Enhances path handling and file resolution #5
@@ -22,12 +22,15 @@ export class FontManager {
|
||||
|
||||
// Use spawn instead of exec for security - arguments passed separately
|
||||
const stdout = await new Promise<string>((resolve, reject) => {
|
||||
const typstProcess = spawn(typstPath, ['fonts'], {
|
||||
// Build platform-specific environment with enhanced PATH
|
||||
const enhancedEnv = {
|
||||
...process.env,
|
||||
PATH: this.buildPlatformSpecificPATH()
|
||||
};
|
||||
|
||||
const typstProcess = spawn(typstPath, ['fonts'], {
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
|
||||
}
|
||||
env: enhancedEnv
|
||||
});
|
||||
|
||||
let output = '';
|
||||
@@ -64,13 +67,14 @@ export class FontManager {
|
||||
const cacheData = {
|
||||
fonts: fonts,
|
||||
timestamp: Date.now(),
|
||||
typstPath: typstPath
|
||||
typstPath: typstPath,
|
||||
platform: process.platform
|
||||
};
|
||||
|
||||
|
||||
const pathUtils = new PathUtils(this.plugin.app);
|
||||
const vaultPath = pathUtils.getVaultPath();
|
||||
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
|
||||
const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json');
|
||||
// Use vault-relative path for adapter operations
|
||||
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
|
||||
await this.plugin.app.vault.adapter.write(fontsCachePath,
|
||||
JSON.stringify(cacheData, null, 2));
|
||||
} catch (error) {
|
||||
@@ -81,51 +85,80 @@ export class FontManager {
|
||||
|
||||
// Create fallback cache file
|
||||
const fallbackFonts = FALLBACK_FONTS;
|
||||
|
||||
|
||||
const cacheData = {
|
||||
fonts: fallbackFonts,
|
||||
timestamp: Date.now(),
|
||||
typstPath: 'fallback',
|
||||
error: error.message
|
||||
platform: process.platform,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
|
||||
|
||||
const pathUtils = new PathUtils(this.plugin.app);
|
||||
const vaultPath = pathUtils.getVaultPath();
|
||||
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
|
||||
const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json');
|
||||
// Use vault-relative path for adapter operations
|
||||
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
|
||||
await this.plugin.app.vault.adapter.write(fontsCachePath,
|
||||
JSON.stringify(cacheData, null, 2));
|
||||
}
|
||||
|
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cached fonts list
|
||||
* Get cached fonts list with improved validation and error recovery
|
||||
*/
|
||||
async getCachedFonts(): Promise<string[]> {
|
||||
try {
|
||||
const pathUtils = new PathUtils(this.plugin.app);
|
||||
const vaultPath = pathUtils.getVaultPath();
|
||||
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
|
||||
const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json');
|
||||
// Use vault-relative path for adapter operations
|
||||
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
|
||||
const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath);
|
||||
|
⚠️ Potential issue | 🟠 Major Use vault-relative paths for vault.adapter I/O (avoid absolute paths). Passing absolute paths to Apply this diff: 📝 Committable suggestion
🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🟠 Major_
**Use vault-relative paths for vault.adapter I/O (avoid absolute paths).**
Passing absolute paths to `vault.adapter.write` is brittle across adapters/OSes. Use the plugin-dir path relative to the vault instead.
Apply this diff:
```diff
- const pathUtils = new PathUtils(this.plugin.app);
- const vaultPath = pathUtils.getVaultPath();
- const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
- const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json');
- await this.plugin.app.vault.adapter.write(fontsCachePath,
+ const pathUtils = new PathUtils(this.plugin.app);
+ const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
+ const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
+ await this.plugin.app.vault.adapter.write(fontsCachePath,
JSON.stringify(cacheData, null, 2));
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
const pathUtils = new PathUtils(this.plugin.app);
const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
await this.plugin.app.vault.adapter.write(fontsCachePath,
JSON.stringify(cacheData, null, 2));
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/plugin/FontManager.ts around lines 70 to 75, the code builds an absolute
path using the vault root and passes it to vault.adapter.write, which is
brittle; change it to use a vault-relative path instead by joining the pluginDir
with 'fonts-cache.json' (e.g. use pathUtils.joinPath(pluginDir,
'fonts-cache.json')) and pass that relative path to
this.plugin.app.vault.adapter.write (ensure no leading slash so the adapter
treats it as vault-relative).
```
</details>
<!-- fingerprinting:phantom:poseidon:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits 24a169d to 2cdc9c3
|
||||
const cacheData = JSON.parse(cacheContent);
|
||||
|
||||
// Check if cache is older than 24 hours or typst path changed
|
||||
const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000;
|
||||
|
||||
let cacheData;
|
||||
try {
|
||||
cacheData = JSON.parse(cacheContent);
|
||||
} catch (parseError) {
|
||||
console.error('Corrupted fonts cache file, regenerating:', parseError);
|
||||
// Remove corrupted cache and regenerate
|
||||
await this.plugin.app.vault.adapter.remove(fontsCachePath);
|
||||
await this.cacheAvailableFonts();
|
||||
return [...FALLBACK_FONTS];
|
||||
}
|
||||
|
||||
// Validate cache structure
|
||||
if (!cacheData || typeof cacheData !== 'object' || !Array.isArray(cacheData.fonts)) {
|
||||
console.warn('Invalid fonts cache structure, regenerating');
|
||||
await this.plugin.app.vault.adapter.remove(fontsCachePath);
|
||||
await this.cacheAvailableFonts();
|
||||
return [...FALLBACK_FONTS];
|
||||
}
|
||||
|
||||
// Check if cache needs refresh
|
||||
const isStale = Date.now() - (cacheData.timestamp || 0) > 24 * 60 * 60 * 1000;
|
||||
const resolvedTypstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
|
||||
const pathChanged = cacheData.typstPath !== resolvedTypstPath;
|
||||
|
||||
if (isStale || pathChanged) {
|
||||
const platformChanged = cacheData.platform !== process.platform;
|
||||
|
||||
if (isStale || pathChanged || platformChanged) {
|
||||
// Refresh cache in background
|
||||
this.cacheAvailableFonts();
|
||||
this.cacheAvailableFonts().catch(error => {
|
||||
console.error('Background font cache refresh failed:', error);
|
||||
});
|
||||
}
|
||||
|
||||
return cacheData.fonts || [];
|
||||
|
||||
// Validate fonts array contains valid strings
|
||||
const validFonts = cacheData.fonts.filter((font: unknown) =>
|
||||
typeof font === 'string' && font.trim().length > 0
|
||||
);
|
||||
|
||||
return validFonts.length > 0 ? validFonts : [...FALLBACK_FONTS];
|
||||
} catch (error) {
|
||||
console.error('Failed to read fonts cache:', error);
|
||||
// Try to recreate cache
|
||||
await this.cacheAvailableFonts();
|
||||
|
||||
this.cacheAvailableFonts().catch(cacheError => {
|
||||
console.error('Failed to recreate fonts cache:', cacheError);
|
||||
});
|
||||
|
||||
// Return fallback fonts
|
||||
|
⚠️ Potential issue | 🟠 Major Same fix in fallback branch: write using vault-relative plugin path. 📝 Committable suggestion
🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🟠 Major_
**Same fix in fallback branch: write using vault-relative plugin path.**
```diff
- const pathUtils = new PathUtils(this.plugin.app);
- const vaultPath = pathUtils.getVaultPath();
- const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
- const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json');
+ const pathUtils = new PathUtils(this.plugin.app);
+ const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
+ const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
await this.plugin.app.vault.adapter.write(fontsCachePath,
JSON.stringify(cacheData, null, 2));
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
const pathUtils = new PathUtils(this.plugin.app);
const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
await this.plugin.app.vault.adapter.write(fontsCachePath,
JSON.stringify(cacheData, null, 2));
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/plugin/FontManager.ts around lines 92 to 97, the fallback branch
currently writes fonts-cache.json using an incorrect path; update the fallback
write to use the vault-relative plugin path like the primary branch: construct
fontsCachePath with pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json')
and call this.plugin.app.vault.adapter.write(fontsCachePath,
JSON.stringify(cacheData, null, 2)) so both branches write to the same
vault-relative location.
```
</details>
<!-- fingerprinting:phantom:poseidon:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits 24a169d to 2cdc9c3
|
||||
return [...FALLBACK_FONTS];
|
||||
}
|
||||
@@ -137,4 +170,60 @@ export class FontManager {
|
||||
async getAvailableFonts(): Promise<string[]> {
|
||||
return await this.getCachedFonts();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build platform-specific PATH environment variable for font discovery
|
||||
* @private
|
||||
*/
|
||||
private buildPlatformSpecificPATH(): string {
|
||||
const currentPath = process.env.PATH || '';
|
||||
const pathSeparator = process.platform === 'win32' ? ';' : ':';
|
||||
|
||||
// Platform-specific common installation paths
|
||||
let additionalPaths: string[] = [];
|
||||
|
||||
switch (process.platform) {
|
||||
case 'darwin': // macOS
|
||||
additionalPaths = [
|
||||
'/opt/homebrew/bin',
|
||||
'/usr/local/bin',
|
||||
'/usr/bin',
|
||||
'/bin',
|
||||
'/opt/local/bin', // MacPorts
|
||||
'/sw/bin' // Fink
|
||||
];
|
||||
break;
|
||||
|
||||
case 'linux':
|
||||
additionalPaths = [
|
||||
'/usr/local/bin',
|
||||
'/usr/bin',
|
||||
'/bin',
|
||||
'/opt/bin',
|
||||
'/snap/bin', // Snap packages
|
||||
'~/.cargo/bin', // Rust/Cargo installations
|
||||
'~/.local/bin' // User local installations
|
||||
];
|
||||
break;
|
||||
|
||||
case 'win32': // Windows
|
||||
additionalPaths = [
|
||||
'C:\\Program Files\\Typst',
|
||||
'C:\\Program Files (x86)\\Typst',
|
||||
process.env.LOCALAPPDATA ? `${process.env.LOCALAPPDATA}\\Programs\\Typst` : '',
|
||||
process.env.APPDATA ? `${process.env.APPDATA}\\Typst` : '',
|
||||
'C:\\tools\\typst', // Chocolatey common path
|
||||
process.env.USERPROFILE ? `${process.env.USERPROFILE}\\.cargo\\bin` : ''
|
||||
].filter(path => path.length > 0);
|
||||
break;
|
||||
|
||||
default:
|
||||
// Fallback for other platforms
|
||||
additionalPaths = ['/usr/local/bin', '/usr/bin', '/bin'];
|
||||
}
|
||||
|
||||
// Combine current PATH with additional paths, avoiding duplicates
|
||||
const allPaths = [...additionalPaths, currentPath].filter(path => path.length > 0);
|
||||
return allPaths.join(pathSeparator);
|
||||
}
|
||||
}
|
||||
⚠️ Potential issue | 🟠 Major
Read cache via vault-relative path too.
📝 Committable suggestion
🤖 Prompt for AI Agents
✅ Addressed in commits
24a169dto2cdc9c3