Merge pull request #8 from AlexKucera/obsidian-bot-review

Update ESLint rules and resolve bot review feedback
This commit was merged in pull request #8.
This commit is contained in:
AlexKucera authored and GitHub committed 2025-11-09 12:06:31 +01:00
commit b70ad772f3
42 files changed
+4603 -1100

No files matched your search

+1 -1
View File
@@ -169,7 +169,7 @@ Go to the plugin settings and click **Check Dependencies** to ensure all require
- **Obsidian**: Version 1.9.12 or higher - **Obsidian**: Version 1.9.12 or higher
- **Platform**: Desktop only (Windows, macOS, Linux) - I develop this on macOS, but it should in theory work on Windows and Linux. I just have no way to test it. - **Platform**: Desktop only (Windows, macOS, Linux) - I develop this on macOS, but it should in theory work on Windows and Linux. I just have no way to test it.
- **Node.js**: Version 16+ (for development) - **Node.js**: Version 18.20+ (for development)
### External Dependencies ### External Dependencies
+79 -36
View File
@@ -1,57 +1,100 @@
// @ts-check // @ts-check
import eslint from '@eslint/js'; import js from '@eslint/js';
import globals from 'globals';
import tseslint from 'typescript-eslint'; import tseslint from 'typescript-eslint';
import obsidianmd from 'eslint-plugin-obsidianmd';
import importPlugin from 'eslint-plugin-import';
import globals from 'globals';
export default tseslint.config( export default tseslint.config(
// Apply ESLint recommended rules // Base JavaScript recommended rules
eslint.configs.recommended, js.configs.recommended,
// Apply TypeScript-ESLint recommended rules
...tseslint.configs.recommended, // TypeScript recommended type-checked rules
...tseslint.configs.recommendedTypeChecked,
// Obsidian-specific configuration
{ {
// Configure language options plugins: {
obsidianmd: obsidianmd,
import: importPlugin,
},
languageOptions: { languageOptions: {
globals: { globals: {
...globals.node, ...globals.node,
...globals.es2022, ...globals.browser,
NodeJS: 'readonly', // TypeScript global namespace
}, },
parserOptions: { parserOptions: {
sourceType: 'module', projectService: true,
ecmaVersion: 2022, tsconfigRootDir: import.meta.dirname,
}, },
}, },
// Configure files to lint // Apply Obsidian plugin recommended rules (manually specified)
files: ['**/*.ts', '**/*.js', 'main.ts'],
// Configure rules - incorporating Obsidian sample plugin settings
rules: { rules: {
// Disable base ESLint no-unused-vars in favor of TypeScript version // Obsidian command rules
'obsidianmd/commands/no-command-in-command-id': 'error',
'obsidianmd/commands/no-command-in-command-name': 'error',
'obsidianmd/commands/no-default-hotkeys': 'error',
'obsidianmd/commands/no-plugin-id-in-command-id': 'error',
'obsidianmd/commands/no-plugin-name-in-command-name': 'error',
// Settings tab rules
'obsidianmd/settings-tab/no-manual-html-headings': 'error',
'obsidianmd/settings-tab/no-problematic-settings-headings': 'error',
// Other Obsidian rules
'obsidianmd/vault/iterate': 'error',
'obsidianmd/detach-leaves': 'error',
'obsidianmd/hardcoded-config-path': 'error',
'obsidianmd/no-forbidden-elements': 'error',
'obsidianmd/no-plugin-as-component': 'error',
'obsidianmd/no-sample-code': 'error',
'obsidianmd/no-tfile-tfolder-cast': 'error',
'obsidianmd/no-view-references-in-plugin': 'error',
'obsidianmd/no-static-styles-assignment': 'error',
'obsidianmd/object-assign': 'error',
'obsidianmd/platform': 'error',
'obsidianmd/prefer-file-manager-trash-file': 'warn',
'obsidianmd/prefer-abstract-input-suggest': 'error',
'obsidianmd/regex-lookbehind': 'error',
'obsidianmd/sample-names': 'error',
'obsidianmd/validate-manifest': 'error',
'obsidianmd/validate-license': 'error',
'obsidianmd/ui/sentence-case': ['warn', { enforceCamelCaseLower: true }],
// General ESLint rules from Obsidian recommended
'no-unused-vars': 'off', 'no-unused-vars': 'off',
'no-prototype-builtins': 'off',
'no-self-compare': 'warn',
'no-eval': 'error',
'no-implied-eval': 'error',
'prefer-const': 'off',
'no-implicit-globals': 'error',
'no-console': ['error', { allow: ['warn', 'error', 'debug'] }],
'no-alert': 'error',
'no-undef': 'error',
// TypeScript rules from Obsidian recommended
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/no-deprecated': 'error',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/no-explicit-any': ['error', { fixToUnknown: true }],
// Downgrade strict type checking rules to warnings
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
'@typescript-eslint/no-unsafe-call': 'warn',
'@typescript-eslint/no-unsafe-return': 'warn',
// Unused vars with underscore prefix
'@typescript-eslint/no-unused-vars': ['warn', { args: 'none', varsIgnorePattern: '^_', argsIgnorePattern: '^_' }], '@typescript-eslint/no-unused-vars': ['warn', { args: 'none', varsIgnorePattern: '^_', argsIgnorePattern: '^_' }],
// Allow @ts-ignore comments (useful for Obsidian API quirks) // Import rules
'@typescript-eslint/ban-ts-comment': 'off', 'import/no-extraneous-dependencies': 'error',
// Allow prototype builtins usage
'no-prototype-builtins': 'off',
// Allow empty functions (common in plugin architecture)
'@typescript-eslint/no-empty-function': 'off',
// Allow require() imports (Node.js environment with mixed modules)
'@typescript-eslint/no-require-imports': 'off',
'@typescript-eslint/no-var-requires': 'off',
// Obsidian plugins often use 'any' type for API flexibility
'@typescript-eslint/no-explicit-any': 'warn',
// Allow lexical declarations in case blocks
'no-case-declarations': 'off',
// Prefer const is good but not critical for existing code
'prefer-const': 'warn',
}, },
}, },
{ {
+10 -6
View File
@@ -11,6 +11,7 @@ import {
Notice, Notice,
MarkdownView MarkdownView
} from 'obsidian'; } from 'obsidian';
import { shell } from 'electron';
import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS } from './src/core/settings'; import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS } from './src/core/settings';
import { DependencyChecker } from './src/core/DependencyChecker'; import { DependencyChecker } from './src/core/DependencyChecker';
@@ -78,6 +79,7 @@ export class obsidianTypstPDFExport extends Plugin {
`); `);
// Add ribbon icon using custom icon // Add ribbon icon using custom icon
// eslint-disable-next-line obsidianmd/ui/sentence-case -- "PDF" is an acronym and "Typst" is a proper noun
this.addRibbonIcon('typst-pdf-export', 'Export to PDF with Typst', (event: MouseEvent) => { this.addRibbonIcon('typst-pdf-export', 'Export to PDF with Typst', (event: MouseEvent) => {
this.eventHandlers.handleRibbonClick(event); this.eventHandlers.handleRibbonClick(event);
}); });
@@ -177,8 +179,8 @@ export class obsidianTypstPDFExport extends Plugin {
); );
} }
async checkDependenciesAsync(): Promise<void> { checkDependenciesOnStartup(): void {
return DependencyChecker.checkDependenciesAsync( DependencyChecker.checkDependenciesOnStartup(
this.settings.pandocPath, this.settings.pandocPath,
this.settings.typstPath, this.settings.typstPath,
this.settings.executablePaths?.imagemagickPath, this.settings.executablePaths?.imagemagickPath,
@@ -212,8 +214,7 @@ export class obsidianTypstPDFExport extends Plugin {
* Open a PDF file in the default viewer * Open a PDF file in the default viewer
*/ */
openPDF(pdfPath: string): void { openPDF(pdfPath: string): void {
const { shell } = require('electron'); void shell.openPath(pdfPath);
shell.openPath(pdfPath);
} }
async loadSettings() { async loadSettings() {
@@ -238,9 +239,12 @@ export class obsidianTypstPDFExport extends Plugin {
} }
onunload() { // Obsidian supports async onunload and will await it properly, even though
// the Plugin type definition shows void return. This ensures cleanup completes.
// eslint-disable-next-line @typescript-eslint/no-misused-promises
async onunload(): Promise<void> {
// Use lifecycle manager for cleanup // Use lifecycle manager for cleanup
this.lifecycle.cleanup(); await this.lifecycle.cleanup();
} }
} }
+194
View File
@@ -0,0 +1,194 @@
### Required
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/main.ts#L81-L81)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/mmandRegistry.ts#L37-L37)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L23-L23)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L38-L38)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L56-L56)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L325-L325)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L31-L31)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L50-L50)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L57-L57)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L65-L65)
[11](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L67-L67)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L80-L80)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L82-L82)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L94-L94)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L95-L95)
[16](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L97-L97)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L134-L134)
[18](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L138-L138)
[19](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L160-L160)
[20](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L179-L179)
[21](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L182-L182)
[22](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L232-L232)
[23](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L296-L296)
[24](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L138-L138)
[25](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L222-L222)
[26](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/BehaviorSection.ts#L14-L14)
[27](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/neralSection.ts#L21-L21)
[28](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/GeneralSection.ts#L75-L75)
[29](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/GeneralSection.ts#L78-L78)
[30](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/youtSection.ts#L16-L16)
[31](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/PageSetupSection.ts#L16-L16)
[32](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/PageSetupSection.ts#L72-L72)
[33](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L166-L166)
[34](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L167-L167)
[35](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L174-L174)
[36](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L194-L194)
[37](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L195-L195)
[38](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L199-L199)
[39](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L200-L200)
[40](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L201-L201)
Use sentence case for UI text.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/main.ts#L215-L215)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/naryLocator.ts#L154-L154)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L38-L38)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L115-L115)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L183-L183)
[6](https://github.com/exKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L61-L61)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ageOptimizer.ts#L111-L111)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L236-L236)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L252-L252)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ageOptimizer.ts#L264-L264)
[11](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/PdfCliExecutor.ts#L114-L114)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/PdfCliExecutor.ts#L115-L115)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L35-L35)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L46-L46)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L103-L103)
[16](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L118-L118)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L144-L144)
[18](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L188-L188)
[19](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/eprocessors/FrontmatterProcessor.ts#L208-L208)
[20](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L233-L233)
[21](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L51-L51)
[22](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ecutableChecker.ts#L128-L128)
[23](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L158-L158)
[24](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L215-L215)
[25](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/PathUtils.ts#L115-L115)
[26](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EmbedProcessor.ts#L164-L164)
[27](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/bedProcessor.ts#L165-L165)
[28](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/FontManager.ts#L19-L19)
[29](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PathResolver.ts#L29-L29)
A `require()` style import is forbidden.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/MarkdownPreprocessor.ts#L117-L117)
Async method 'process' has no 'await' expression.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/PandocTypstConverter.ts#L138-L138)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/c/plugin/CommandRegistry.ts#L21-L21)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/CommandRegistry.ts#L30-L30)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/CommandRegistry.ts#L39-L39)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L26-L26)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L41-L41)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/entHandlers.ts#L59-L59)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L68-L68)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L95-L95)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L104-L104)
[11](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L56-L56)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/uginLifecycle.ts#L59-L59)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L72-L80)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L88-L101)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L86-L86)
[16](https://github.com/AlexKucerabsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L122-L122)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L19-L19)
Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/PandocTypstConverter.ts#L180-L180)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/c/converters/PandocTypstConverter.ts#L187-L187)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/BinaryLocator.ts#L33-L33)
Obsidian's configuration folder is not necessarily `.obsidian`, can be configured by the user. Use `Vault#configDir` to get the current value
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L35-L35)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L103-L103)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L118-L118)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L144-L144)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L188-L188)
[6](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L208-L208)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L233-L233)
'js-yaml' should be listed in the project's dependencies. n 'npm i -S js-yaml' to add it
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L49-L49)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L50-L50)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L155-L155)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L156-L156)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExportErrorHandler.ts#L64-L64)
Unexpected console statement. Only these console methods are allowed: warn, error, debug.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L275-L275)
'value' will use Object's default stringification format ('[object Object]') when ringified.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/DependencyChecker.ts#L122-L122)
Static async method 'checkDependenciesAsync' has no 'await' expression.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ModalSettingsHelper.ts#L72-L72)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/dal/sections/PageSetupSection.ts#L60-L60)
The two values in this comparison do not have a shared enum type.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/SecurityUtils.ts#L56-L56)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/curityUtils.ts#L117-L117)
Unexpected undescribed directive comment. Include descriptions to explain why the comment is necessary.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L51-L51)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/portOrchestrator.ts#L322-L322)
A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object. Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an intended `this` value. If a function does not access `this`, it can be annotated with `this: void`.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L89-L91)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ugin/ExportOrchestrator.ts#L124-L126)
Promise returned in function argument where a void return was expected.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L160-L160)
`noticeEl` is deprecated. Use `messageEl` instead
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L31-L31)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L50-L50)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L134-L134)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L232-L232)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L296-L296)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L366-L366)
For a consistent UI use `new Setting(containerEl).setName(...).setHeading()` instead of creating HTML heading elements directly.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/templates/TemplateManager.ts#L132-L132)
Unexpected lexical declaration in case block.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L50-L50)
Promise-returning function provided to property where a void return was expected.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L152-L152)
Unexpected `await` of a non-Promise (non-"Thenable") value.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L260-L260)
Creating and attaching "style" elements is not allowed. For loading CSS, use a "styles.css" file instead, which sidian loads for you.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/state/ModalState.ts#L192-L192)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/uiodal/state/ModalState.ts#L203-L203)
Unexpected use of 'localStorage'. Prefer `App#saveLocalStorage` / `App#loadLocalStorage` functions to write / read localStorage data that's unique to a vault.
### Optional
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L92-L92)
'_result' is assigned a value but never used.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L124-L124)
'_progressPercent' is assigned a value but never used.
+3637 -455
View File
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -24,17 +24,25 @@
], ],
"author": "Alexander Kucera", "author": "Alexander Kucera",
"license": "MIT", "license": "MIT",
"engines": {
"node": ">=18.20.0"
},
"devDependencies": { "devDependencies": {
"@eslint/eslintrc": "^3.3.1", "@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.34.0", "@eslint/js": "^9.34.0",
"@types/js-yaml": "^4.0.9",
"@types/node": "^20.19.24", "@types/node": "^20.19.24",
"@typescript-eslint/eslint-plugin": "5.29.0", "@typescript-eslint/eslint-plugin": "^8.46.3",
"@typescript-eslint/parser": "5.29.0", "@typescript-eslint/parser": "^8.46.3",
"@typescript-eslint/utils": "^8.46.3",
"@vitest/coverage-v8": "^4.0.6", "@vitest/coverage-v8": "^4.0.6",
"@vitest/ui": "^4.0.6", "@vitest/ui": "^4.0.6",
"archiver": "^7.0.1", "archiver": "^7.0.1",
"builtin-modules": "3.3.0", "builtin-modules": "3.3.0",
"electron": "^33.3.0",
"esbuild": "0.17.3", "esbuild": "0.17.3",
"eslint": "^9.39.1",
"eslint-plugin-obsidianmd": "^0.1.8",
"globals": "^16.3.0", "globals": "^16.3.0",
"happy-dom": "^20.0.10", "happy-dom": "^20.0.10",
"obsidian": "latest", "obsidian": "latest",
@@ -45,6 +53,7 @@
}, },
"dependencies": { "dependencies": {
"gray-matter": "^4.0.3", "gray-matter": "^4.0.3",
"js-yaml": "^4.1.0",
"pdf-to-img": "^4.5.0" "pdf-to-img": "^4.5.0"
} }
} }
+7 -8
View File
@@ -202,7 +202,7 @@ export interface MarkdownPreprocessorConfig {
* *
* // Process markdown * // Process markdown
* const obsidianMarkdown = '# My Note\n\n[[internal-link]]\n\n![[image.png]]'; * const obsidianMarkdown = '# My Note\n\n[[internal-link]]\n\n![[image.png]]';
* const result = await preprocessor.process(obsidianMarkdown); * const result = preprocessor.process(obsidianMarkdown);
* *
* console.log(result.content); // Standard markdown * console.log(result.content); // Standard markdown
* console.log(result.metadata.imageEmbeds); // Image processing info * console.log(result.metadata.imageEmbeds); // Image processing info
@@ -218,7 +218,7 @@ export interface MarkdownPreprocessorConfig {
* }); * });
* *
* // Process with new configuration * // Process with new configuration
* const newResult = await preprocessor.process(markdown); * const newResult = preprocessor.process(markdown);
* ``` * ```
*/ */
export class MarkdownPreprocessor { export class MarkdownPreprocessor {
@@ -268,7 +268,6 @@ export class MarkdownPreprocessor {
* in the correct order, aggregates metadata from each stage, and returns a complete * in the correct order, aggregates metadata from each stage, and returns a complete
* result with processed content and comprehensive metadata. * result with processed content and comprehensive metadata.
* *
* The method is async to support future extensions (though current processors are sync).
* Processing is stateless - each call operates independently on the provided content. * Processing is stateless - each call operates independently on the provided content.
* *
* Processing Order (critical for avoiding conflicts): * Processing Order (critical for avoiding conflicts):
@@ -300,7 +299,7 @@ export class MarkdownPreprocessor {
* Callout: > [!note] This is important * Callout: > [!note] This is important
* `; * `;
* *
* const result = await preprocessor.process(markdown); * const result = preprocessor.process(markdown);
* *
* // Check for errors * // Check for errors
* if (result.errors.length > 0) { * if (result.errors.length > 0) {
@@ -320,7 +319,7 @@ export class MarkdownPreprocessor {
* ```typescript * ```typescript
* // Handle remote images * // Handle remote images
* const markdown = '![Remote](https://example.com/image.png)'; * const markdown = '![Remote](https://example.com/image.png)';
* const result = await preprocessor.process(markdown); * const result = preprocessor.process(markdown);
* *
* // Remote images are queued for download * // Remote images are queued for download
* result.metadata.imageEmbeds.forEach(embed => { * result.metadata.imageEmbeds.forEach(embed => {
@@ -329,7 +328,7 @@ export class MarkdownPreprocessor {
* }); * });
* ``` * ```
*/ */
public async process(content: string): Promise<PreprocessingResult> { public process(content: string): PreprocessingResult {
const result: PreprocessingResult = { const result: PreprocessingResult = {
content: content, content: content,
metadata: { metadata: {
@@ -506,7 +505,7 @@ export class MarkdownPreprocessor {
* }); * });
* *
* // Process note with web-friendly links * // Process note with web-friendly links
* const result = await preprocessor.process(markdown); * const result = preprocessor.process(markdown);
* // Links will use the new base URL * // Links will use the new base URL
* ``` * ```
* *
@@ -521,7 +520,7 @@ export class MarkdownPreprocessor {
* }); * });
* *
* // Process with HTML-style links * // Process with HTML-style links
* const result = await preprocessor.process(markdown); * const result = preprocessor.process(markdown);
* // [[note]] becomes [note](note.html) * // [[note]] becomes [note](note.html)
* ``` * ```
* *
+20 -54
View File
@@ -11,13 +11,14 @@
* - Error handling * - Error handling
* *
* The converter supports both file-based and content-based conversions, automatically * The converter supports both file-based and content-based conversions, automatically
* managing temporary directories and cleanup on process termination. * managing temporary directories with cleanup via the plugin lifecycle.
*/ */
import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes'; import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { TempDirectoryManager } from '../core/TempDirectoryManager'; import { TempDirectoryManager } from '../core/TempDirectoryManager';
import { PathUtils } from '../core/PathUtils'; import { PathUtils } from '../core/PathUtils';
import { promises as fs } from 'fs';
import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder'; import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
import { PandocExecutor } from './pandoc/PandocExecutor'; import { PandocExecutor } from './pandoc/PandocExecutor';
@@ -32,7 +33,7 @@ import { PandocExecutor } from './pandoc/PandocExecutor';
* Key features: * Key features:
* - File and content-based conversion support * - File and content-based conversion support
* - Automatic temporary directory management * - Automatic temporary directory management
* - Process cleanup on termination (exit, SIGINT, SIGTERM, exceptions) * - Cleanup via plugin lifecycle (onunload)
* - Progress callback support for UI updates * - Progress callback support for UI updates
* - Configurable Pandoc and Typst settings * - Configurable Pandoc and Typst settings
* *
@@ -40,8 +41,8 @@ import { PandocExecutor } from './pandoc/PandocExecutor';
* 1. Constructor initializes command builder and executor * 1. Constructor initializes command builder and executor
* 2. Conversion methods create temp directories and build commands * 2. Conversion methods create temp directories and build commands
* 3. Executor runs Pandoc with Typst engine * 3. Executor runs Pandoc with Typst engine
* 4. Cleanup automatically removes temporary files * 4. Plugin unload calls dispose() to remove temporary files
* 5. dispose() for manual cleanup when done * 5. dispose() can also be called manually for cleanup when done
* *
* @example * @example
* ```typescript * ```typescript
@@ -74,15 +75,14 @@ export class PandocTypstConverter {
private plugin: obsidianTypstPDFExport; private plugin: obsidianTypstPDFExport;
private commandBuilder: PandocCommandBuilder; private commandBuilder: PandocCommandBuilder;
private pandocExecutor: PandocExecutor; private pandocExecutor: PandocExecutor;
private processCleanupHandler: (() => void) | null = null;
private isDisposed = false; private isDisposed = false;
/** /**
* Creates a new PandocTypstConverter instance with configuration. * Creates a new PandocTypstConverter instance with configuration.
* *
* Initializes the converter with the plugin instance and configuration options * Initializes the converter with the plugin instance and configuration options
* for both Pandoc and Typst. Sets up cleanup handlers to ensure temporary * for both Pandoc and Typst. Temporary files are cleaned up via dispose()
* files are removed on process termination. * which is called during plugin unload.
* *
* @param plugin - The main plugin instance for accessing app and settings * @param plugin - The main plugin instance for accessing app and settings
* @param pandocOptions - Configuration options for Pandoc conversion (template, variables, etc.) * @param pandocOptions - Configuration options for Pandoc conversion (template, variables, etc.)
@@ -115,8 +115,6 @@ export class PandocTypstConverter {
this.plugin = plugin; this.plugin = plugin;
this.commandBuilder = new PandocCommandBuilder(plugin); this.commandBuilder = new PandocCommandBuilder(plugin);
this.pandocExecutor = new PandocExecutor(plugin); this.pandocExecutor = new PandocExecutor(plugin);
// Set up cleanup handlers for process termination
this.setupCleanup();
} }
/** /**
@@ -254,7 +252,8 @@ export class PandocTypstConverter {
const pathUtils = new PathUtils(this.plugin.app); const pathUtils = new PathUtils(this.plugin.app);
const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`); const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`);
await this.plugin.app.vault.adapter.write(tempInputPath, content); // Use fs.writeFile for temp files since external tools (Pandoc) need absolute paths
await fs.writeFile(tempInputPath, content, 'utf-8');
// Merge options // Merge options
this.pandocOptions = { ...this.pandocOptions, ...options }; this.pandocOptions = { ...this.pandocOptions, ...options };
@@ -264,7 +263,8 @@ export class PandocTypstConverter {
// Cleanup temp file // Cleanup temp file
try { try {
await this.plugin.app.vault.adapter.remove(tempInputPath); // Use fs.unlink for temp files since they're in external temp directories
await fs.unlink(tempInputPath);
} catch (error) { } catch (error) {
console.warn('Failed to cleanup temp file:', error); console.warn('Failed to cleanup temp file:', error);
} }
@@ -279,38 +279,6 @@ export class PandocTypstConverter {
} }
} }
/**
* Sets up automatic cleanup handlers for process termination events.
*
* Registers the cleanup method to run on various process termination events
* to ensure temporary files are removed even if the process exits unexpectedly.
* Handlers are registered for:
* - Normal exit
* - SIGINT (Ctrl+C)
* - SIGTERM (kill command)
*
* Note: Handlers are stored and removed on dispose() to prevent listener leaks.
* The uncaughtException handler is NOT registered to avoid swallowing errors.
*
* @private
*/
private setupCleanup(): void {
// Store handler reference so we can remove it later
this.processCleanupHandler = () => {
// Only cleanup if not already disposed to avoid double-cleanup
if (!this.isDisposed) {
this.cleanup();
}
};
// Register cleanup handlers - these will be removed on dispose()
process.on('exit', this.processCleanupHandler);
process.on('SIGINT', this.processCleanupHandler);
process.on('SIGTERM', this.processCleanupHandler);
// Note: uncaughtException handler removed to avoid swallowing errors
}
/** /**
* Cleans up temporary files and directories. * Cleans up temporary files and directories.
* *
@@ -318,7 +286,7 @@ export class PandocTypstConverter {
* directory created by the converter. Cleanup failures are logged but don't throw * directory created by the converter. Cleanup failures are logged but don't throw
* to avoid interfering with normal operation or other cleanup operations. * to avoid interfering with normal operation or other cleanup operations.
* *
* Called automatically on process termination or manually via dispose(). * Called via dispose() during plugin unload.
* *
* @private * @private
* @returns Promise that resolves when cleanup is complete * @returns Promise that resolves when cleanup is complete
@@ -364,14 +332,20 @@ export class PandocTypstConverter {
if (!this.tempDir) { if (!this.tempDir) {
if (this.pandocOptions.vaultBasePath) { if (this.pandocOptions.vaultBasePath) {
// Use TempDirectoryManager for plugin temp directories // Use TempDirectoryManager for plugin temp directories
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian'; const configDir = this.plugin?.app?.vault?.configDir;
if (!configDir) {
throw new Error('Unable to access vault configuration directory. Plugin may not be properly initialized.');
}
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app); const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
this.tempDir = await tempManager.ensureTempDir('pandoc'); this.tempDir = await tempManager.ensureTempDir('pandoc');
} else { } else {
// Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback // Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback
const pathUtils = new PathUtils(this.plugin.app); const pathUtils = new PathUtils(this.plugin.app);
const vaultPath = pathUtils.getVaultPath(); const vaultPath = pathUtils.getVaultPath();
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian'; const configDir = this.plugin?.app?.vault?.configDir;
if (!configDir) {
throw new Error('Unable to access vault configuration directory. Plugin may not be properly initialized.');
}
const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app }); const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app });
this.tempDir = await tempManager.ensureTempDir('pandoc'); this.tempDir = await tempManager.ensureTempDir('pandoc');
} }
@@ -410,14 +384,6 @@ export class PandocTypstConverter {
this.isDisposed = true; this.isDisposed = true;
// Remove process event listeners to prevent memory leaks
if (this.processCleanupHandler) {
process.off('exit', this.processCleanupHandler);
process.off('SIGINT', this.processCleanupHandler);
process.off('SIGTERM', this.processCleanupHandler);
this.processCleanupHandler = null;
}
// Cleanup temporary files and resources // Cleanup temporary files and resources
await this.cleanup(); await this.cleanup();
} }
+3 -2
View File
@@ -413,10 +413,11 @@ export class PdfToImageConverter {
}; };
} }
// Ensure output directory exists // Ensure output directory exists (convert absolute path to vault-relative for vault.adapter)
if (this.plugin?.app) { if (this.plugin?.app) {
const pathUtils = new PathUtils(this.plugin.app); const pathUtils = new PathUtils(this.plugin.app);
await pathUtils.ensureDir(outputDir); const relativeOutputDir = pathUtils.toVaultRelative(outputDir);
await pathUtils.ensureDir(relativeOutputDir);
} }
// Generate expected output file name for the first page // Generate expected output file name for the first page
@@ -201,10 +201,6 @@ export class PandocCommandBuilder {
// Enable standalone mode (required for PDF output) // Enable standalone mode (required for PDF output)
args.push('--standalone'); args.push('--standalone');
// Disable citeproc to prevent automatic bibliography processing
// This prevents "document does not contain a bibliography" errors when
// Pandoc detects citation-like patterns but no bibliography file is provided
args.push('--no-citeproc');
// Embed resources (images, etc.) directly into the output // Embed resources (images, etc.) directly into the output
args.push('--embed-resources'); args.push('--embed-resources');
+8 -3
View File
@@ -3,6 +3,7 @@
* Handles discovery of pdf2img and other CLI tools in the Obsidian environment. * Handles discovery of pdf2img and other CLI tools in the Obsidian environment.
*/ */
import { promises as fs } from 'fs';
import * as path from 'path'; import * as path from 'path';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils'; import { PathUtils } from '../../core/PathUtils';
@@ -29,8 +30,13 @@ export class BinaryLocator {
// Get the plugin directory - need to handle Obsidian's environment // Get the plugin directory - need to handle Obsidian's environment
// In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path // In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path
// Try multiple strategies to find the plugin directory // Try multiple strategies to find the plugin directory
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export'; // Extract just the plugin folder name from manifest.dir (e.g., "typst-pdf-export" from ".obsidian/plugins/typst-pdf-export")
const configDir = plugin?.app.vault.configDir || '.obsidian'; const fullManifestDir = plugin?.manifest?.dir || 'typst-pdf-export';
const pluginDirName = path.basename(fullManifestDir);
const configDir = plugin?.app.vault.configDir;
if (!configDir) {
throw new Error('Unable to determine Obsidian configuration directory');
}
const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir); const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir);
// Find the first directory that exists and has node_modules // Find the first directory that exists and has node_modules
@@ -154,7 +160,6 @@ export class BinaryLocator {
try { try {
if (!plugin?.app) { if (!plugin?.app) {
// This should not happen in normal plugin operation, but provide fallback // This should not happen in normal plugin operation, but provide fallback
const fs = require('fs').promises;
await fs.access(binaryPath); await fs.access(binaryPath);
return true; return true;
} }
+2 -4
View File
@@ -3,6 +3,7 @@
* Handles filename pattern matching when pdf2img generates files with different names. * Handles filename pattern matching when pdf2img generates files with different names.
*/ */
import { promises as fs } from 'fs';
import * as path from 'path'; import * as path from 'path';
import { PathUtils } from '../../core/PathUtils'; import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
@@ -35,7 +36,6 @@ export class FileDiscovery {
if (!plugin?.app) { if (!plugin?.app) {
// Fallback to path for external tool output directories // Fallback to path for external tool output directories
const expectedOutputPath = path.join(outputDir, expectedFileName); const expectedOutputPath = path.join(outputDir, expectedFileName);
const fs = require('fs').promises;
try { try {
await fs.access(expectedOutputPath); await fs.access(expectedOutputPath);
return { return {
@@ -112,8 +112,7 @@ export class FileDiscovery {
files = dirList.files.map(f => path.basename(f)); files = dirList.files.map(f => path.basename(f));
} else { } else {
// Use filesystem fallback for absolute/external paths // Use filesystem fallback for absolute/external paths
const fs = require('fs').promises; files = await fs.readdir(outputDir);
files = await fs.readdir(outputDir);
} }
// Look for any image files that might match // Look for any image files that might match
@@ -180,7 +179,6 @@ export class FileDiscovery {
expectedOutputPath: string expectedOutputPath: string
): Promise<FileDiscoveryResult> { ): Promise<FileDiscoveryResult> {
try { try {
const fs = require('fs').promises;
// Debug: List what files are actually in the output directory // Debug: List what files are actually in the output directory
const files = await fs.readdir(outputDir); const files = await fs.readdir(outputDir);
+17 -23
View File
@@ -3,6 +3,8 @@
* Handles format conversion, quality management, and dimension detection. * Handles format conversion, quality management, and dimension detection.
*/ */
import { spawn } from 'child_process';
import { promises as fs } from 'fs';
import * as path from 'path'; import * as path from 'path';
import { PathUtils } from '../../core/PathUtils'; import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
@@ -58,7 +60,6 @@ export class ImageOptimizer {
quality: number = 90 quality: number = 90
): Promise<{success: boolean; error?: string}> { ): Promise<{success: boolean; error?: string}> {
try { try {
const { spawn } = require('child_process');
// Use ImageMagick to convert PNG to JPEG // Use ImageMagick to convert PNG to JPEG
const convertProcess = spawn('magick', [ const convertProcess = spawn('magick', [
@@ -108,7 +109,6 @@ export class ImageOptimizer {
fallbackDimensions: ImageDimensions = { width: 800, height: 600 } fallbackDimensions: ImageDimensions = { width: 800, height: 600 }
): Promise<{dimensions: ImageDimensions; success: boolean; error?: string}> { ): Promise<{dimensions: ImageDimensions; success: boolean; error?: string}> {
try { try {
const { spawn } = require('child_process');
// Use ImageMagick identify to get image dimensions // Use ImageMagick identify to get image dimensions
const identifyProcess = spawn('magick', [ const identifyProcess = spawn('magick', [
@@ -218,22 +218,10 @@ export class ImageOptimizer {
// Clean up the original PNG if conversion succeeded // Clean up the original PNG if conversion succeeded
try { try {
if (plugin?.app) { if (plugin?.app) {
// Convert absolute path to vault-relative path for adapter.remove()
const pathUtils = new PathUtils(plugin.app); const pathUtils = new PathUtils(plugin.app);
const vaultBasePath = pathUtils.getVaultPath(); const relativePath = pathUtils.toVaultRelative(inputImagePath);
let relativePath = inputImagePath;
if (inputImagePath.startsWith(vaultBasePath)) {
// Remove vault base path and leading separator
relativePath = inputImagePath.substring(vaultBasePath.length);
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
relativePath = relativePath.substring(1);
}
}
await plugin.app.vault.adapter.remove(relativePath); await plugin.app.vault.adapter.remove(relativePath);
} else { } else {
const fs = require('fs').promises;
await fs.unlink(inputImagePath); await fs.unlink(inputImagePath);
} }
} catch (unlinkError) { } catch (unlinkError) {
@@ -245,11 +233,14 @@ export class ImageOptimizer {
// Just rename the file to PNG format // Just rename the file to PNG format
const pngFinalPath = finalOutputPath.replace(/\.jpeg?$/, '.png'); const pngFinalPath = finalOutputPath.replace(/\.jpeg?$/, '.png');
if (plugin?.app) { if (plugin?.app) {
const content = await plugin.app.vault.adapter.readBinary(inputImagePath); const pathUtils = new PathUtils(plugin.app);
await plugin.app.vault.adapter.writeBinary(pngFinalPath, content); const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
await plugin.app.vault.adapter.remove(inputImagePath); const relativePngPath = pathUtils.toVaultRelative(pngFinalPath);
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
await plugin.app.vault.adapter.writeBinary(relativePngPath, content);
await plugin.app.vault.adapter.remove(relativeInputPath);
} else { } else {
const fs = require('fs').promises;
await fs.rename(inputImagePath, pngFinalPath); await fs.rename(inputImagePath, pngFinalPath);
} }
actualImagePath = pngFinalPath; actualImagePath = pngFinalPath;
@@ -257,11 +248,14 @@ export class ImageOptimizer {
} else { } else {
// Keep as PNG, just rename to final location // Keep as PNG, just rename to final location
if (plugin?.app) { if (plugin?.app) {
const content = await plugin.app.vault.adapter.readBinary(inputImagePath); const pathUtils = new PathUtils(plugin.app);
await plugin.app.vault.adapter.writeBinary(finalOutputPath, content); const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
await plugin.app.vault.adapter.remove(inputImagePath); const relativeFinalPath = pathUtils.toVaultRelative(finalOutputPath);
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
await plugin.app.vault.adapter.writeBinary(relativeFinalPath, content);
await plugin.app.vault.adapter.remove(relativeInputPath);
} else { } else {
const fs = require('fs').promises;
await fs.rename(inputImagePath, finalOutputPath); await fs.rename(inputImagePath, finalOutputPath);
} }
actualImagePath = finalOutputPath; actualImagePath = finalOutputPath;
+4 -4
View File
@@ -3,11 +3,15 @@
* Executes external pdf2img binary to convert PDF pages to images. * Executes external pdf2img binary to convert PDF pages to images.
*/ */
import { exec } from 'child_process';
import { promisify } from 'util';
import * as path from 'path'; import * as path from 'path';
import { BinaryLocator } from './BinaryLocator'; import { BinaryLocator } from './BinaryLocator';
import { EnvironmentUtils } from './EnvironmentUtils'; import { EnvironmentUtils } from './EnvironmentUtils';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
const execAsync = promisify(exec);
export interface PdfCliOptions { export interface PdfCliOptions {
/** Scale factor for the rendered image */ /** Scale factor for the rendered image */
scale: number; scale: number;
@@ -111,10 +115,6 @@ export class PdfCliExecutor {
plugin?: obsidianTypstPDFExport plugin?: obsidianTypstPDFExport
): Promise<PdfCliResult> { ): Promise<PdfCliResult> {
try { try {
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
// Get augmented environment for CLI execution // Get augmented environment for CLI execution
const env = EnvironmentUtils.getAugmentedEnvironment(plugin?.settings); const env = EnvironmentUtils.getAugmentedEnvironment(plugin?.settings);
@@ -3,6 +3,8 @@
* Extracted from MarkdownPreprocessor for better code organization * Extracted from MarkdownPreprocessor for better code organization
*/ */
import * as yaml from 'js-yaml';
import matter from 'gray-matter';
import { PreprocessingResult } from '../MarkdownPreprocessor'; import { PreprocessingResult } from '../MarkdownPreprocessor';
export interface FrontmatterProcessorConfig { export interface FrontmatterProcessorConfig {
@@ -32,7 +34,6 @@ export class FrontmatterProcessor {
if (!this.FRONTMATTER_PATTERN.test(content)) { if (!this.FRONTMATTER_PATTERN.test(content)) {
// No frontmatter found - add title frontmatter if we have a noteTitle // No frontmatter found - add title frontmatter if we have a noteTitle
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle; result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle }; result.metadata.frontmatter = { title: this.noteTitle };
@@ -43,22 +44,24 @@ export class FrontmatterProcessor {
} }
// Use gray-matter for robust frontmatter parsing // Use gray-matter for robust frontmatter parsing
const matter = require('gray-matter');
// Add debugging to see what's being parsed // Add debugging to see what's being parsed
console.log('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected'); console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected', `(content length: ${content.length})`);
console.log('First 200 chars:', content.substring(0, 200));
const parsed = matter(content); const parsed = matter(content);
if (parsed.data && Object.keys(parsed.data).length > 0) { if (parsed.data && Object.keys(parsed.data).length > 0) {
// Replace frontmatter title with filename if noteTitle is provided // Sanitize frontmatter first to prevent citation fields from leaking to downstream consumers
const sanitizedFrontmatter = this.stripCitationFields(parsed.data);
// Store sanitized frontmatter in metadata (with title override if needed)
if (this.noteTitle) { if (this.noteTitle) {
const frontmatterCopy = { ...parsed.data }; result.metadata.frontmatter = {
frontmatterCopy.title = this.noteTitle; ...sanitizedFrontmatter,
result.metadata.frontmatter = frontmatterCopy; title: this.noteTitle
};
} else { } else {
result.metadata.frontmatter = parsed.data; result.metadata.frontmatter = sanitizedFrontmatter;
} }
// Extract tags from frontmatter if they exist // Extract tags from frontmatter if they exist
@@ -93,14 +96,11 @@ export class FrontmatterProcessor {
result.metadata.title = parsed.data.title.trim(); result.metadata.title = parsed.data.title.trim();
} }
// Handle frontmatter preservation and display options // Use the sanitized frontmatter from metadata for writing
const finalFrontmatter = this.noteTitle ? const finalFrontmatter = result.metadata.frontmatter;
{ ...parsed.data, title: this.noteTitle } :
parsed.data;
if (this.preserveFrontmatter) { if (this.preserveFrontmatter) {
// Keep the frontmatter in the content, but reconstruct it with the modified title // Keep the frontmatter in the content, but reconstruct it with the modified title
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(finalFrontmatter); const newFrontmatter = yaml.dump(finalFrontmatter);
let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`; let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`;
@@ -115,7 +115,6 @@ export class FrontmatterProcessor {
// Return content without frontmatter, but add title as frontmatter for Pandoc // Return content without frontmatter, but add title as frontmatter for Pandoc
let processedContent: string; let processedContent: string;
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`; processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
} else { } else {
@@ -141,7 +140,6 @@ export class FrontmatterProcessor {
} else { } else {
// No frontmatter found - add title frontmatter if we have a noteTitle // No frontmatter found - add title frontmatter if we have a noteTitle
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle; result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle }; result.metadata.frontmatter = { title: this.noteTitle };
@@ -152,8 +150,7 @@ export class FrontmatterProcessor {
} }
} catch (error: unknown) { } catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
console.log('FrontmatterProcessor: gray-matter failed with error:', errorMessage); console.error('FrontmatterProcessor: gray-matter failed with error:', errorMessage, `(content length: ${content.length})`);
console.log('Content being parsed (first 500 chars):', content.substring(0, 500));
result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`); result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`);
// Fallback to simple regex-based parsing // Fallback to simple regex-based parsing
@@ -185,7 +182,6 @@ export class FrontmatterProcessor {
if (this.preserveFrontmatter) { if (this.preserveFrontmatter) {
// Reconstruct frontmatter with modified title // Reconstruct frontmatter with modified title
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(frontmatter); const newFrontmatter = yaml.dump(frontmatter);
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`); let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
@@ -205,7 +201,6 @@ export class FrontmatterProcessor {
} else { } else {
// Add title as frontmatter for Pandoc even when not preserving original // Add title as frontmatter for Pandoc even when not preserving original
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`); let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
@@ -230,7 +225,6 @@ export class FrontmatterProcessor {
} else { } else {
// No frontmatter pattern found, but gray-matter failed - treat as file without frontmatter // No frontmatter pattern found, but gray-matter failed - treat as file without frontmatter
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle; result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle }; result.metadata.frontmatter = { title: this.noteTitle };
@@ -242,6 +236,20 @@ export class FrontmatterProcessor {
} }
} }
/**
* Strip citation-related fields from frontmatter to prevent Pandoc bibliography processing
*/
private stripCitationFields(frontmatter: Record<string, unknown>): Record<string, unknown> {
const citationFields = ['bibliography', 'references', 'csl', 'citation-style', 'nocite', 'link-citations', 'reference-section-title'];
const sanitized = { ...frontmatter };
for (const field of citationFields) {
delete sanitized[field];
}
return sanitized;
}
/** /**
* Format frontmatter as a readable display block * Format frontmatter as a readable display block
*/ */
@@ -265,13 +273,19 @@ export class FrontmatterProcessor {
if (Array.isArray(value)) { if (Array.isArray(value)) {
// For arrays, put each item on its own line if there are many items // For arrays, put each item on its own line if there are many items
if (value.length > 3) { if (value.length > 3) {
formattedValue = '\n\n' + value.map(item => `- ${item}`).join('\n') + '\n'; formattedValue = '\n\n' + value.map(item => {
const itemStr = typeof item === 'object' ? JSON.stringify(item) : String(item);
return `- ${itemStr}`;
}).join('\n') + '\n';
} else { } else {
formattedValue = value.join(', '); formattedValue = value.map(item =>
typeof item === 'object' ? JSON.stringify(item) : String(item)
).join(', ');
} }
} else if (typeof value === 'object') { } else if (typeof value === 'object' && value !== null) {
formattedValue = JSON.stringify(value); formattedValue = JSON.stringify(value);
} else { } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
// Handle primitive values
const valueStr = String(value); const valueStr = String(value);
// If the value is very long (like email lists), break it up // If the value is very long (like email lists), break it up
if (valueStr.length > 80 && valueStr.includes(',')) { if (valueStr.length > 80 && valueStr.includes(',')) {
@@ -308,6 +322,10 @@ export class FrontmatterProcessor {
} else { } else {
formattedValue = valueStr; formattedValue = valueStr;
} }
} else {
// Handle null, undefined, or any other unexpected types
console.debug('FrontmatterProcessor: Unexpected type in frontmatter display formatting', `key: ${key}, type: ${typeof value}`);
formattedValue = '';
} }
// Add line break after the property label, then the value // Add line break after the property label, then the value
+3 -4
View File
@@ -321,7 +321,6 @@ ${dependencyResult.allAvailable
* @param typstPath - Optional custom path to Typst executable * @param typstPath - Optional custom path to Typst executable
* @param imagemagickPath - Optional custom path to ImageMagick convert executable * @param imagemagickPath - Optional custom path to ImageMagick convert executable
* @param additionalPaths - Additional directories to search for executables * @param additionalPaths - Additional directories to search for executables
* @returns Promise that resolves when the check is complete
* *
* @example * @example
* ```typescript * ```typescript
@@ -331,7 +330,7 @@ ${dependencyResult.allAvailable
* await this.loadSettings(); * await this.loadSettings();
* *
* // Silent startup check - only shows notice if problems exist * // Silent startup check - only shows notice if problems exist
* await DependencyChecker.checkDependenciesAsync( * DependencyChecker.checkDependenciesOnStartup(
* this.settings.pandocPath, * this.settings.pandocPath,
* this.settings.typstPath, * this.settings.typstPath,
* this.settings.imagemagickPath, * this.settings.imagemagickPath,
@@ -348,12 +347,12 @@ ${dependencyResult.allAvailable
* // Run 'Check Dependencies' command for details." * // Run 'Check Dependencies' command for details."
* ``` * ```
*/ */
public static async checkDependenciesAsync( public static checkDependenciesOnStartup(
pandocPath?: string, pandocPath?: string,
typstPath?: string, typstPath?: string,
imagemagickPath?: string, imagemagickPath?: string,
additionalPaths: string[] = [] additionalPaths: string[] = []
): Promise<void> { ): void {
// Check dependencies silently on startup // Check dependencies silently on startup
try { try {
const missingDeps = this.checkDependenciesSync( const missingDeps = this.checkDependenciesSync(
+1 -8
View File
@@ -9,6 +9,7 @@
* - Cross-platform path handling (Unix and Windows) * - Cross-platform path handling (Unix and Windows)
*/ */
import { spawn, spawnSync } from 'child_process';
import { DEPENDENCY_CONSTANTS } from './constants'; import { DEPENDENCY_CONSTANTS } from './constants';
import * as path from 'path'; import * as path from 'path';
@@ -140,8 +141,6 @@ export class ExecutableChecker {
* ``` * ```
*/ */
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> { private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
const { spawn } = require('child_process');
try { try {
const stdout = await new Promise<string>((resolve, reject) => { const stdout = await new Promise<string>((resolve, reject) => {
const env = this.getAugmentedEnv(additionalPaths); const env = this.getAugmentedEnv(additionalPaths);
@@ -259,8 +258,6 @@ export class ExecutableChecker {
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName; const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
// Try to find the executable using which command synchronously // Try to find the executable using which command synchronously
const { spawnSync } = require('child_process');
// Use platform-specific command: 'where' on Windows, 'which' on Unix // Use platform-specific command: 'where' on Windows, 'which' on Unix
const whichCommand = process.platform === 'win32' ? 'where' : 'which'; const whichCommand = process.platform === 'win32' ? 'where' : 'which';
@@ -323,8 +320,6 @@ export class ExecutableChecker {
versionCommand: string, versionCommand: string,
versionRegex: RegExp versionRegex: RegExp
): Promise<DependencyInfo> { ): Promise<DependencyInfo> {
const { spawn } = require('child_process');
try { try {
// 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) => {
@@ -396,8 +391,6 @@ export class ExecutableChecker {
* ``` * ```
*/ */
public static checkDependencySync(executablePath: string, versionCommand: string): boolean { public static checkDependencySync(executablePath: string, versionCommand: string): boolean {
const { spawnSync } = require('child_process');
try { try {
const result = spawnSync(executablePath, versionCommand.split(' '), { const result = spawnSync(executablePath, versionCommand.split(' '), {
encoding: 'utf8', encoding: 'utf8',
+4 -4
View File
@@ -9,7 +9,7 @@
* - Consistent error messaging and logging * - Consistent error messaging and logging
* - Batch export result tracking and reporting * - Batch export result tracking and reporting
* - User-facing notices with appropriate durations * - User-facing notices with appropriate durations
* - Support for different log levels (error, warn, info) * - Support for different log levels (error, warn, debug)
* - Specialized handlers for different error types (dependency, processing, validation) * - Specialized handlers for different error types (dependency, processing, validation)
*/ */
@@ -43,7 +43,7 @@ export interface ExportError {
operation: string; operation: string;
error: Error | string; error: Error | string;
shouldShowNotice?: boolean; shouldShowNotice?: boolean;
logLevel?: 'error' | 'warn' | 'info'; logLevel?: 'error' | 'warn' | 'debug';
} }
/** /**
@@ -180,8 +180,8 @@ export class ExportErrorHandler {
case 'warn': case 'warn':
console.warn(`${operation}:`, error); console.warn(`${operation}:`, error);
break; break;
case 'info': case 'debug':
console.info(`${operation}:`, error); console.debug(`${operation}:`, error);
break; break;
} }
+2 -2
View File
@@ -14,7 +14,7 @@
*/ */
import { TFile } from 'obsidian'; import { TFile } from 'obsidian';
import { obsidianTypstPDFExportSettings } from './settings'; import { obsidianTypstPDFExportSettings, ExportFormat } from './settings';
import { ExportConfigModalSettings } from '../ui/modal/modalTypes'; import { ExportConfigModalSettings } from '../ui/modal/modalTypes';
/** /**
@@ -180,7 +180,7 @@ export class ModalSettingsHelper {
// Auto-adjust width for single-page landscape mode // Auto-adjust width for single-page landscape mode
const landscapeAdjustment = settings.pageSetup.orientation === 'landscape' const landscapeAdjustment = settings.pageSetup.orientation === 'landscape'
&& settings.exportDefaults.format === 'single-page' && settings.exportDefaults.format === ExportFormat.SinglePage
? { width: 'auto' } ? { width: 'auto' }
: {}; : {};
+42 -3
View File
@@ -1,6 +1,7 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations // ABOUTME: Centralized path utilities for safe Obsidian API operations
// ABOUTME: Handles vault paths, plugin directories, and file operations // ABOUTME: Handles vault paths, plugin directories, and file operations
import { promises as fs } from 'fs';
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian'; import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
import type { App, PluginManifest } from 'obsidian'; import type { App, PluginManifest } from 'obsidian';
import * as path from 'path'; import * as path from 'path';
@@ -105,6 +106,11 @@ export class PathUtils {
return ''; return '';
} }
const result = path.join(...filtered); const result = path.join(...filtered);
// Don't use normalizePath on absolute paths as it strips the leading slash
// Only normalize vault-relative paths
if (path.isAbsolute(result)) {
return result;
}
return normalizePath(result); return normalizePath(result);
} }
@@ -132,8 +138,10 @@ export class PathUtils {
await this.app.vault.adapter.mkdir(normalizedPath); await this.app.vault.adapter.mkdir(normalizedPath);
} }
} catch (error) { } catch (error) {
new Notice(`Failed to create directory: ${normalizedPath}`); const errorMessage = error instanceof Error ? error.message : String(error);
throw error; const userMessage = `Failed to create output directory "${normalizedPath}". ${errorMessage.includes('parent') || errorMessage.includes('ENOENT') ? 'The parent directory may not exist or you may not have write permissions.' : 'You may not have write permissions or the path is invalid.'}`;
new Notice(userMessage);
throw new Error(userMessage);
} }
} }
@@ -238,7 +246,6 @@ export class PathUtils {
if (isAbsolutePath) { if (isAbsolutePath) {
try { try {
const fs = require('fs').promises;
await fs.access(path); await fs.access(path);
return true; return true;
} catch { } catch {
@@ -248,4 +255,36 @@ export class PathUtils {
return false; return false;
} }
/**
* Converts an absolute path to a vault-relative path.
*
* This method is used to convert absolute filesystem paths to vault-relative
* paths suitable for use with Obsidian's vault adapter operations. If the path
* does not start with the vault base path, it is returned unchanged.
*
* @param absolutePath - The absolute path to convert
* @returns The vault-relative path (without leading slash) or the original path if not within vault
*
* @example
* ```typescript
* const pathUtils = new PathUtils(app);
* const vaultPath = '/Users/name/vault';
* const absolutePath = '/Users/name/vault/folder/file.md';
* const relative = pathUtils.toVaultRelative(absolutePath);
* // Returns: 'folder/file.md'
* ```
*/
toVaultRelative(absolutePath: string): string {
const vaultBasePath = this.getVaultPath();
if (!absolutePath.startsWith(vaultBasePath)) {
return absolutePath;
}
let relativePath = absolutePath.substring(vaultBasePath.length);
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
relativePath = relativePath.substring(1);
}
return relativePath;
}
} }
+15 -5
View File
@@ -117,8 +117,12 @@ export class SecurityUtils {
return false; return false;
} }
// Normalize and resolve the path to detect traversal attempts // Normalize path (reject absolute paths so exports stay inside the vault)
const normalizedPath = path.normalize(outputFolder.trim()); const trimmed = outputFolder.trim();
if (path.isAbsolute(trimmed)) {
return false;
}
const normalizedPath = path.normalize(trimmed);
// Check for path traversal attempts // Check for path traversal attempts
if (normalizedPath.includes('..') || if (normalizedPath.includes('..') ||
@@ -218,7 +222,7 @@ export class SecurityUtils {
// Check for command injection attempts // Check for command injection attempts
const dangerousPatterns = [ const dangerousPatterns = [
/[;&|`$<>]/, // Shell metacharacters that can't appear in safe paths /[;&|`$<>]/, // Shell metacharacters that can't appear in safe paths
// eslint-disable-next-line no-control-regex // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
/\x00/, // Null bytes /\x00/, // Null bytes
/\n|\r/, // Newlines /\n|\r/, // Newlines
/\s*[;&|]\s*/, // Command separators with whitespace /\s*[;&|]\s*/, // Command separators with whitespace
@@ -281,7 +285,12 @@ export class SecurityUtils {
return 'Output folder is required'; return 'Output folder is required';
} }
const normalizedPath = path.normalize(outputFolder.trim()); // Normalize path (reject absolute paths so exports stay inside the vault)
const trimmed = outputFolder.trim();
if (path.isAbsolute(trimmed)) {
return 'Absolute paths are not allowed - use relative paths from vault root';
}
const normalizedPath = path.normalize(trimmed);
if (normalizedPath.includes('..')) { if (normalizedPath.includes('..')) {
return 'Path traversal attempts (..) are not allowed'; return 'Path traversal attempts (..) are not allowed';
@@ -374,7 +383,8 @@ export class SecurityUtils {
if (/[;&|`$<>]/.test(normalizedPath)) { if (/[;&|`$<>]/.test(normalizedPath)) {
return 'Shell metacharacters are not allowed in executable paths'; return 'Shell metacharacters are not allowed in executable paths';
} }
if (/\x00/.test(normalizedPath)) { // eslint-disable-line no-control-regex // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
if (/\x00/.test(normalizedPath)) {
return 'Null bytes are not allowed in paths'; return 'Null bytes are not allowed in paths';
} }
if (/\n|\r/.test(normalizedPath)) { if (/\n|\r/.test(normalizedPath)) {
+22 -9
View File
@@ -24,6 +24,7 @@ import { PLUGIN_DIRS } from './constants';
import { normalizePath } from 'obsidian'; import { normalizePath } from 'obsidian';
import type { App } from 'obsidian'; import type { App } from 'obsidian';
import * as path from 'path'; import * as path from 'path';
import { promises as fs } from 'fs';
/** /**
* Configuration options for TempDirectoryManager initialization. * Configuration options for TempDirectoryManager initialization.
@@ -167,7 +168,8 @@ export class TempDirectoryManager {
private getPluginDir(): string { private getPluginDir(): string {
// path.join automatically handles absolute paths correctly // path.join automatically handles absolute paths correctly
const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName); const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
return normalizePath(result); // Don't normalize absolute paths as normalizePath strips the leading slash
return path.isAbsolute(result) ? result : normalizePath(result);
} }
/** /**
@@ -207,7 +209,8 @@ export class TempDirectoryManager {
// Use path.join to properly handle absolute paths // Use path.join to properly handle absolute paths
const result = path.join(pluginDir, dirName); const result = path.join(pluginDir, dirName);
return normalizePath(result); // Don't normalize absolute paths as normalizePath strips the leading slash
return path.isAbsolute(result) ? result : normalizePath(result);
} }
/** /**
@@ -253,9 +256,13 @@ export class TempDirectoryManager {
public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> { public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> {
const tempDir = this.getTempDir(type); const tempDir = this.getTempDir(type);
const exists = await this.app.vault.adapter.exists(tempDir); // Use fs.mkdir for temp directories since external tools (pdf2img, ImageMagick)
if (!exists) { // need to write to them directly with absolute paths
await this.app.vault.adapter.mkdir(tempDir); try {
await fs.access(tempDir);
} catch {
// Directory doesn't exist, create it with recursive option
await fs.mkdir(tempDir, { recursive: true });
} }
return tempDir; return tempDir;
@@ -302,13 +309,19 @@ export class TempDirectoryManager {
public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> { public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> {
const tempDir = this.getTempDir(type); const tempDir = this.getTempDir(type);
// Use fs for temp directory cleanup since these directories contain
// files created by external tools
try { try {
const exists = await this.app.vault.adapter.exists(tempDir); const exists = await fs.access(tempDir).then(() => true).catch(() => false);
if (exists) { if (exists) {
const list = await this.app.vault.adapter.list(tempDir); const files = await fs.readdir(tempDir);
// Remove only files, not subdirectories (matching current pattern) // Remove only files, not subdirectories (matching current pattern)
for (const file of list.files) { for (const file of files) {
await this.app.vault.adapter.remove(file); const filePath = path.join(tempDir, file);
const stat = await fs.stat(filePath);
if (stat.isFile()) {
await fs.unlink(filePath);
}
} }
} }
return true; return true;
+17 -5
View File
@@ -3,7 +3,7 @@
* Handles registration of all plugin commands and their callbacks * Handles registration of all plugin commands and their callbacks
*/ */
import { Editor, MarkdownView } from 'obsidian'; import { Editor, MarkdownView, Notice } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
export class CommandRegistry { export class CommandRegistry {
@@ -18,7 +18,11 @@ export class CommandRegistry {
id: 'export-current-note', id: 'export-current-note',
name: 'Export current note(s)', name: 'Export current note(s)',
editorCallback: (editor: Editor, view: MarkdownView) => { editorCallback: (editor: Editor, view: MarkdownView) => {
this.plugin.exportCurrentNote(view); this.plugin.exportCurrentNote(view).catch(error => {
console.error('Failed to export current note:', error);
const errorMessage = error?.message ?? String(error);
new Notice(`Failed to export current note: ${errorMessage}`);
});
} }
}); });
@@ -27,16 +31,24 @@ export class CommandRegistry {
id: 'export-with-config', id: 'export-with-config',
name: 'Export with configuration…', name: 'Export with configuration…',
editorCallback: (editor: Editor, view: MarkdownView) => { editorCallback: (editor: Editor, view: MarkdownView) => {
this.plugin.showExportModal(view); this.plugin.showExportModal(view).catch(error => {
console.error('Failed to show export modal:', error);
const errorMessage = error?.message ?? String(error);
new Notice(`Failed to show export modal: ${errorMessage}`);
});
} }
}); });
// Check dependencies command // Check dependencies command
this.plugin.addCommand({ this.plugin.addCommand({
id: 'check-dependencies', id: 'check-dependencies',
name: 'Check Pandoc and Typst dependencies', name: 'Check pandoc and typst dependencies',
callback: () => { callback: () => {
this.plugin.showDependencyStatus(); this.plugin.showDependencyStatus().catch(error => {
console.error('Failed to show dependency status:', error);
const errorMessage = error?.message ?? String(error);
new Notice(`Failed to show dependency status: ${errorMessage}`);
});
} }
}); });
} }
+67 -39
View File
@@ -3,6 +3,8 @@
* Handles processing of PDF, image, and file embeds for PDF export * Handles processing of PDF, image, and file embeds for PDF export
*/ */
import { exec } from 'child_process';
import * as util from 'util';
import { TFile } from 'obsidian'; import { TFile } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import type { PreprocessingResult } from '../converters/MarkdownPreprocessor'; import type { PreprocessingResult } from '../converters/MarkdownPreprocessor';
@@ -12,6 +14,8 @@ import * as path from 'path';
import * as https from 'https'; import * as https from 'https';
import * as http from 'http'; import * as http from 'http';
const execAsync = util.promisify(exec);
export class EmbedProcessor { export class EmbedProcessor {
private readonly pathUtils: PathUtils; private readonly pathUtils: PathUtils;
@@ -19,6 +23,44 @@ export class EmbedProcessor {
this.pathUtils = new PathUtils(plugin.app); this.pathUtils = new PathUtils(plugin.app);
} }
/**
* Handle completion of image download and write to vault.
* @param chunks Downloaded image data chunks
* @param outputPath Absolute path where the image should be written
* @param resolve Promise resolver to call with result
*/
private async handleDownloadComplete(
chunks: Buffer[],
outputPath: string,
resolve: (value: string | null) => void
): Promise<void> {
try {
// Check if file already exists to avoid overwriting
const exists = await this.pathUtils.fileExists(outputPath);
if (exists) {
console.warn(`Export: Image file already exists, using existing: ${outputPath}`);
resolve(outputPath);
return;
}
// Combine chunks and write using vault adapter
const buffer = Buffer.concat(chunks);
// Convert Buffer to ArrayBuffer for vault adapter
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
// Convert absolute path to vault-relative for adapter operations
const relativeOutputPath = this.pathUtils.toVaultRelative(outputPath);
await this.plugin.app.vault.adapter.writeBinary(relativeOutputPath, arrayBuffer);
console.debug(`Export:Successfully downloaded image to: ${outputPath}`);
resolve(outputPath);
} catch (err) {
console.error(`Export: Error writing image file: ${err.message}`);
resolve(null);
}
}
/** /**
* Resolve a local file path using Obsidian's API and filesystem fallbacks * Resolve a local file path using Obsidian's API and filesystem fallbacks
* @param decodedPath The decoded (non-URL-encoded) path to resolve * @param decodedPath The decoded (non-URL-encoded) path to resolve
@@ -86,7 +128,7 @@ export class EmbedProcessor {
* Returns the local path if successful, null if failed * Returns the local path if successful, null if failed
*/ */
private async downloadRemoteImage(imageUrl: string, tempDir: string): Promise<string | null> { private async downloadRemoteImage(imageUrl: string, tempDir: string): Promise<string | null> {
return new Promise((resolve) => { return new Promise((resolve, reject) => {
try { try {
// Parse URL to get filename // Parse URL to get filename
const urlObj = new URL(imageUrl); const urlObj = new URL(imageUrl);
@@ -108,7 +150,7 @@ export class EmbedProcessor {
// Select appropriate protocol based on parsed URL (handles case-insensitive schemes) // Select appropriate protocol based on parsed URL (handles case-insensitive schemes)
const protocol = urlObj.protocol === 'https:' ? https : http; const protocol = urlObj.protocol === 'https:' ? https : http;
console.log(`Export: Downloading remote image: ${imageUrl}`); console.debug(`Export:Downloading remote image: ${imageUrl}`);
// Use parsed URL object for the request to ensure correct protocol handling // Use parsed URL object for the request to ensure correct protocol handling
const request = protocol.get(urlObj, (response) => { const request = protocol.get(urlObj, (response) => {
@@ -120,9 +162,9 @@ export class EmbedProcessor {
// This handles both absolute URLs (e.g., "https://example.com/img.png") // This handles both absolute URLs (e.g., "https://example.com/img.png")
// and relative URLs (e.g., "/assets/img.png" or "../img.png") // and relative URLs (e.g., "/assets/img.png" or "../img.png")
const absoluteRedirectUrl = new URL(redirectUrl, imageUrl).href; const absoluteRedirectUrl = new URL(redirectUrl, imageUrl).href;
console.log(`Export: Following redirect to: ${absoluteRedirectUrl}`); console.debug(`Export:Following redirect to: ${absoluteRedirectUrl}`);
// Recursively follow redirect with resolved absolute URL // Recursively follow redirect with resolved absolute URL
this.downloadRemoteImage(absoluteRedirectUrl, tempDir).then(resolve); this.downloadRemoteImage(absoluteRedirectUrl, tempDir).then(resolve).catch(reject);
return; return;
} }
} }
@@ -141,29 +183,9 @@ export class EmbedProcessor {
chunks.push(chunk); chunks.push(chunk);
}); });
response.on('end', async () => { response.on('end', () => {
try { void this.handleDownloadComplete(chunks, outputPath, resolve);
// Check if file already exists to avoid overwriting });
const exists = await this.pathUtils.fileExists(outputPath);
if (exists) {
console.warn(`Export: Image file already exists, using existing: ${outputPath}`);
resolve(outputPath);
return;
}
// Combine chunks and write using vault adapter
const buffer = Buffer.concat(chunks);
// Convert Buffer to ArrayBuffer for vault adapter
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
await this.plugin.app.vault.adapter.writeBinary(outputPath, arrayBuffer);
console.log(`Export: Successfully downloaded image to: ${outputPath}`);
resolve(outputPath);
} catch (err) {
console.error(`Export: Error writing image file: ${err.message}`);
resolve(null);
}
});
response.on('error', (err) => { response.on('error', (err) => {
console.error(`Export: Error receiving image data: ${err.message}`); console.error(`Export: Error receiving image data: ${err.message}`);
@@ -295,13 +317,13 @@ export class EmbedProcessor {
if (isRemoteUrl) { if (isRemoteUrl) {
// Try to download the remote image // Try to download the remote image
console.log(`Export: Attempting to download remote image: ${decodedPath}`); console.debug(`Export:Attempting to download remote image: ${decodedPath}`);
const downloadedPath = await this.downloadRemoteImage(decodedPath, tempDir); const downloadedPath = await this.downloadRemoteImage(decodedPath, tempDir);
if (downloadedPath) { if (downloadedPath) {
// Successfully downloaded, use it as a local image // Successfully downloaded, use it as a local image
fullImagePath = downloadedPath; fullImagePath = downloadedPath;
console.log(`Export: Successfully downloaded and will embed remote image`); console.debug(`Export:Successfully downloaded and will embed remote image`);
} else { } else {
// Download failed, use placeholder // Download failed, use placeholder
console.warn(`Export: Failed to download remote image: ${decodedPath}`); console.warn(`Export: Failed to download remote image: ${decodedPath}`);
@@ -338,15 +360,14 @@ export class EmbedProcessor {
// Convert WebP to PNG using ImageMagick // Convert WebP to PNG using ImageMagick
const originalImageName = path.basename(fullImagePath); const originalImageName = path.basename(fullImagePath);
const pngFileName = originalImageName.replace(/\.webp$/i, '.png'); const pngFileName = originalImageName.replace(/\.webp$/i, '.png');
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images'); // Use vault-relative path for ensureDir (it uses vault.adapter)
await this.pathUtils.ensureDir(vaultTempImagesDir); const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultRelativeTempDir);
// But use absolute path for ImageMagick
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName); const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
try { try {
// Use PathResolver to get the correct ImageMagick path // Use PathResolver to get the correct ImageMagick path
const { PathResolver } = await import('./PathResolver'); const { PathResolver } = await import('./PathResolver');
@@ -523,8 +544,11 @@ export class EmbedProcessor {
vaultBasePath: string vaultBasePath: string
): Promise<{ relativeImagePath: string; relativePdfPath: string }> { ): Promise<{ relativeImagePath: string; relativePdfPath: string }> {
// Copy image to vault temp directory for access // Copy image to vault temp directory for access
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images'); // Use vault-relative path for ensureDir (it uses vault.adapter)
await this.pathUtils.ensureDir(vaultTempImagesDir); const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultRelativeTempDir);
// But use absolute path for file operations
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
// Sanitize the basename for use in filename - replace problematic characters // Sanitize the basename for use in filename - replace problematic characters
const sanitizedBaseName = baseName const sanitizedBaseName = baseName
@@ -536,8 +560,12 @@ export class EmbedProcessor {
const vaultImagePath = this.pathUtils.joinPath(vaultTempImagesDir, imageFileName); const vaultImagePath = this.pathUtils.joinPath(vaultTempImagesDir, imageFileName);
// Copy file using vault adapter // Copy file using vault adapter
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(imagePath); // Convert absolute paths to vault-relative paths for adapter operations
await this.plugin.app.vault.adapter.writeBinary(vaultImagePath, sourceBuffer); const relativeSourcePath = this.pathUtils.toVaultRelative(imagePath);
const relativeVaultImagePath = this.pathUtils.toVaultRelative(vaultImagePath);
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(relativeSourcePath);
await this.plugin.app.vault.adapter.writeBinary(relativeVaultImagePath, sourceBuffer);
// Get relative paths from vault base // Get relative paths from vault base
const relativeImagePath = path.relative(vaultBasePath, vaultImagePath); const relativeImagePath = path.relative(vaultBasePath, vaultImagePath);
+22 -10
View File
@@ -20,10 +20,12 @@ export class EventHandlers {
if (file.extension === 'md') { if (file.extension === 'md') {
menu.addItem((item) => { menu.addItem((item) => {
item item
.setTitle('Export to PDF (Typst)') .setTitle('Export to PDF')
.setIcon('file-output') .setIcon('file-output')
.onClick(() => { .onClick(() => {
this.plugin.exportFile(file); this.plugin.exportFile(file).catch(error => {
console.error('Failed to export file:', error);
});
}); });
}); });
} }
@@ -35,10 +37,12 @@ export class EventHandlers {
this.plugin.app.workspace.on('editor-menu', (menu: Menu, editor: Editor, view: MarkdownView) => { this.plugin.app.workspace.on('editor-menu', (menu: Menu, editor: Editor, view: MarkdownView) => {
menu.addItem((item) => { menu.addItem((item) => {
item item
.setTitle('Export to PDF (Typst)') .setTitle('Export to PDF')
.setIcon('file-output') .setIcon('file-output')
.onClick(() => { .onClick(() => {
this.plugin.exportCurrentNote(view); this.plugin.exportCurrentNote(view).catch(error => {
console.error('Failed to export current note:', error);
});
}); });
}); });
}) })
@@ -48,15 +52,17 @@ export class EventHandlers {
this.plugin.registerEvent( this.plugin.registerEvent(
this.plugin.app.workspace.on('files-menu', (menu: Menu, files: TAbstractFile[]) => { this.plugin.app.workspace.on('files-menu', (menu: Menu, files: TAbstractFile[]) => {
// Filter for markdown files only // Filter for markdown files only
const markdownFiles = files.filter(this.plugin.isMarkdownFile); const markdownFiles = files.filter((file) => this.plugin.isMarkdownFile(file));
if (markdownFiles.length > 0) { if (markdownFiles.length > 0) {
menu.addItem((item) => { menu.addItem((item) => {
item item
.setTitle(`Export to PDF (Typst)`) .setTitle(`Export to PDF`)
.setIcon('file-output') .setIcon('file-output')
.onClick(() => { .onClick(() => {
this.plugin.exportFiles(markdownFiles); this.plugin.exportFiles(markdownFiles).catch(error => {
console.error('Failed to export files:', error);
});
}); });
}); });
@@ -65,7 +71,9 @@ export class EventHandlers {
.setTitle(`Export with configuration...`) .setTitle(`Export with configuration...`)
.setIcon('settings') .setIcon('settings')
.onClick(() => { .onClick(() => {
this.plugin.showExportModalForFiles(markdownFiles); this.plugin.showExportModalForFiles(markdownFiles).catch(error => {
console.error('Failed to show export modal for files:', error);
});
}); });
}); });
} }
@@ -92,7 +100,9 @@ export class EventHandlers {
.setTitle('Export current note(s)') .setTitle('Export current note(s)')
.setIcon('file-output') .setIcon('file-output')
.onClick(() => { .onClick(() => {
this.plugin.exportFile(activeView.file!); this.plugin.exportFile(activeView.file!).catch(error => {
console.error('Failed to export file:', error);
});
}) })
); );
@@ -101,7 +111,9 @@ export class EventHandlers {
.setTitle('Export with configuration…') .setTitle('Export with configuration…')
.setIcon('settings') .setIcon('settings')
.onClick(() => { .onClick(() => {
this.plugin.showExportModal(activeView); this.plugin.showExportModal(activeView).catch(error => {
console.error('Failed to show export modal:', error);
});
}) })
); );
+10 -9
View File
@@ -143,7 +143,7 @@ export class ExportOrchestrator {
this.plugin.currentExportController = new AbortController(); this.plugin.currentExportController = new AbortController();
try { try {
// Create temp directory for conversion // Create temp directories for conversion
const tempManager = new TempDirectoryManager({ const tempManager = new TempDirectoryManager({
vaultPath: vaultPath, vaultPath: vaultPath,
configDir: this.plugin.app.vault.configDir, configDir: this.plugin.app.vault.configDir,
@@ -151,20 +151,21 @@ export class ExportOrchestrator {
pluginName: this.plugin.manifest.id pluginName: this.plugin.manifest.id
}); });
const tempDir = await tempManager.ensureTempDir('pandoc'); const tempDir = await tempManager.ensureTempDir('pandoc');
const tempImagesDir = await tempManager.ensureTempDir('images');
// Load file content // Load file content
const content = await this.plugin.app.vault.read(file); const content = await this.plugin.app.vault.read(file);
// Create progress notice with cancel button // Create progress notice with cancel button
const progressNotice = new Notice('', 0); const progressNotice = new Notice('', 0);
const cancelButton = progressNotice.noticeEl.createEl('button', { const cancelButton = progressNotice.messageEl.createEl('button', {
text: 'Cancel', text: 'Cancel',
cls: 'mod-warning' cls: 'mod-warning'
}); });
cancelButton.addEventListener('click', () => this.cancelExport()); cancelButton.addEventListener('click', () => this.cancelExport());
progressNotice.setMessage('Preprocessing markdown content...'); progressNotice.setMessage('Preprocessing Markdown content...');
// Preprocess markdown // Preprocess Markdown
const preprocessor = new MarkdownPreprocessor({ const preprocessor = new MarkdownPreprocessor({
vaultPath: vaultPath, vaultPath: vaultPath,
options: { options: {
@@ -179,7 +180,7 @@ export class ExportOrchestrator {
noteTitle: file.basename noteTitle: file.basename
}); });
const processedResult = await preprocessor.process(content); const processedResult = preprocessor.process(content);
if (processedResult.errors.length > 0) { if (processedResult.errors.length > 0) {
console.warn('Preprocessing errors:', processedResult.errors); console.warn('Preprocessing errors:', processedResult.errors);
@@ -191,12 +192,12 @@ export class ExportOrchestrator {
// Process PDF embeds if any were found // Process PDF embeds if any were found
if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) { if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) {
const embedPdfFiles = config.embedPdfFiles ?? this.plugin.settings.behavior.embedPdfFiles; const embedPdfFiles = config.embedPdfFiles ?? this.plugin.settings.behavior.embedPdfFiles;
await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempDir, file, embedPdfFiles); await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempImagesDir, file, embedPdfFiles);
} }
// Process image embeds if any were found // Process image embeds if any were found
if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) { if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) {
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempDir, file); await this.plugin.processImageEmbeds(processedResult, vaultPath, tempImagesDir, file);
} }
// Process file embeds if any were found // Process file embeds if any were found
@@ -319,10 +320,10 @@ export class ExportOrchestrator {
*/ */
async handleFolderExport(folder: TFolder): Promise<void> { async handleFolderExport(folder: TFolder): Promise<void> {
// Get all markdown files in the folder // Get all markdown files in the folder
const markdownFiles = folder.children.filter(this.plugin.isMarkdownFile); const markdownFiles = folder.children.filter((file) => this.plugin.isMarkdownFile(file));
if (markdownFiles.length === 0) { if (markdownFiles.length === 0) {
new Notice('No markdown files found in this folder'); new Notice('No Markdown files found in this folder');
return; return;
} }
+1 -2
View File
@@ -3,6 +3,7 @@
* Handles font discovery, caching, and retrieval for the plugin * Handles font discovery, caching, and retrieval for the plugin
*/ */
import { spawn } from 'child_process';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { ExportErrorHandler } from '../core/ExportErrorHandler'; import { ExportErrorHandler } from '../core/ExportErrorHandler';
import { FALLBACK_FONTS } from '../core/constants'; import { FALLBACK_FONTS } from '../core/constants';
@@ -16,8 +17,6 @@ export class FontManager {
*/ */
async cacheAvailableFonts(): Promise<void> { async cacheAvailableFonts(): Promise<void> {
try { try {
const { spawn } = require('child_process');
const typstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst'); const typstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
// Use spawn instead of exec for security - arguments passed separately // Use spawn instead of exec for security - arguments passed separately
+12 -7
View File
@@ -3,6 +3,7 @@
* Handles executable path resolution and output path preparation * Handles executable path resolution and output path preparation
*/ */
import { spawnSync } from 'child_process';
import { TFile } from 'obsidian'; import { TFile } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { SecurityUtils } from '../core/SecurityUtils'; import { SecurityUtils } from '../core/SecurityUtils';
@@ -26,8 +27,6 @@ export class PathResolver {
} }
// Try to find the executable using which command // Try to find the executable using which command
const { spawnSync } = require('child_process');
// Use platform-specific command: 'where' on Windows, 'which' on Unix // Use platform-specific command: 'where' on Windows, 'which' on Unix
const whichCommand = process.platform === 'win32' ? 'where' : 'which'; const whichCommand = process.platform === 'win32' ? 'where' : 'which';
@@ -60,16 +59,21 @@ export class PathResolver {
* Prepare the output path for a file * Prepare the output path for a file
*/ */
async prepareOutputPath(file: TFile, outputFolder: string): Promise<string> { async prepareOutputPath(file: TFile, outputFolder: string): Promise<string> {
// Check if output folder is set
if (!outputFolder || outputFolder.trim() === '') {
throw new Error('Output folder is not set. Please configure the output folder in plugin settings.');
}
// Validate output folder for security // Validate output folder for security
if (!SecurityUtils.validateOutputPath(outputFolder)) { if (!SecurityUtils.validateOutputPath(outputFolder)) {
throw new Error(`Invalid output folder path: ${outputFolder}. Path contains invalid characters or traversal attempts.`); throw new Error(`Invalid output folder path: "${outputFolder}". Path contains invalid characters or traversal attempts.`);
} }
const vaultPath = this.pathUtils.getVaultPath(); const vaultPath = this.pathUtils.getVaultPath();
const outputDir = this.pathUtils.joinPath(vaultPath, outputFolder); const outputDir = this.pathUtils.joinPath(vaultPath, outputFolder);
// Create output directory if it doesn't exist // Create output directory if it doesn't exist (use vault-relative path for vault adapter)
await this.pathUtils.ensureDir(outputDir); await this.pathUtils.ensureDir(outputFolder);
// Preserve folder structure if configured // Preserve folder structure if configured
let relativePath = ''; let relativePath = '';
@@ -77,8 +81,9 @@ export class PathResolver {
const folderPath = path.dirname(file.path); const folderPath = path.dirname(file.path);
if (folderPath !== '.') { if (folderPath !== '.') {
relativePath = folderPath; relativePath = folderPath;
const fullOutputDir = this.pathUtils.joinPath(outputDir, relativePath); // Use vault-relative path for vault adapter
await this.pathUtils.ensureDir(fullOutputDir); const vaultRelativeOutputDir = this.pathUtils.joinPath(outputFolder, relativePath);
await this.pathUtils.ensureDir(vaultRelativeOutputDir);
} }
} }
+19 -16
View File
@@ -52,32 +52,35 @@ export class PluginLifecycle {
// Clean up any leftover temp directories from previous sessions // Clean up any leftover temp directories from previous sessions
this.cleanupStartupTempDirectories(); this.cleanupStartupTempDirectories();
// Check dependencies on startup (async, don't await) // Check dependencies on startup
this.plugin.checkDependenciesAsync(); this.plugin.checkDependenciesOnStartup();
// Cache available fonts (async, don't await) // Cache available fonts (async, don't await)
this.plugin.cacheAvailableFonts(); void this.plugin.cacheAvailableFonts();
} }
/** /**
* Clean up resources during onunload * Clean up resources during onunload
*/ */
cleanup(): void { async cleanup(): Promise<void> {
// Cancel any ongoing exports // Cancel any ongoing exports
if (this.plugin.currentExportController) { if (this.plugin.currentExportController) {
this.plugin.currentExportController.abort(); this.plugin.currentExportController.abort();
} }
// Clean up temp directories on plugin unload (fire-and-forget async) // Dispose converter to clean up its temp directories
(async () => { if (this.plugin.converter) {
try { await this.plugin.converter.dispose();
const vaultPath = this.pathUtils.getVaultPath(); }
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
await cleanupManager.cleanupAllTempDirs(); // Clean up temp directories on plugin unload
} catch (error) { try {
console.warn('Export: Failed to clean up temp directories during unload:', error); const vaultPath = this.pathUtils.getVaultPath();
} const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
})(); await cleanupManager.cleanupAllTempDirs();
} catch (error) {
console.warn('Export: Failed to clean up temp directories during unload:', error);
}
} }
/** /**
@@ -85,11 +88,11 @@ export class PluginLifecycle {
*/ */
private cleanupStartupTempDirectories(): void { private cleanupStartupTempDirectories(): void {
// Clean up temp directories (fire-and-forget async) // Clean up temp directories (fire-and-forget async)
(async () => { void (async () => {
try { try {
const vaultPath = this.pathUtils.getVaultPath(); const vaultPath = this.pathUtils.getVaultPath();
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app); const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
const _result = await cleanupManager.cleanupAllTempDirs(); await cleanupManager.cleanupAllTempDirs();
if (this.plugin.settings.behavior.debugMode) { if (this.plugin.settings.behavior.debugMode) {
// Debug logging was here but empty in original // Debug logging was here but empty in original
+30 -20
View File
@@ -9,6 +9,7 @@ import {
Setting, Setting,
normalizePath normalizePath
} from 'obsidian'; } from 'obsidian';
import * as path from 'path';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { ExportFormat } from '../core/settings'; import { ExportFormat } from '../core/settings';
import { SecurityUtils } from '../core/SecurityUtils'; import { SecurityUtils } from '../core/SecurityUtils';
@@ -28,8 +29,6 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
const { containerEl } = this; const { containerEl } = this;
containerEl.empty(); containerEl.empty();
containerEl.createEl('h2', { text: 'Typst PDF Export Settings' });
// Executable paths section // Executable paths section
this.createExecutablePathsSection(containerEl); this.createExecutablePathsSection(containerEl);
@@ -47,14 +46,16 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createExecutablePathsSection(containerEl: HTMLElement): void { private createExecutablePathsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Executable Paths' }); new Setting(containerEl)
.setName('Executable paths')
.setHeading();
// Add dependency check button // Add dependency check button
new Setting(containerEl) new Setting(containerEl)
.setName('Dependencies') .setName('Dependencies')
.setDesc('Check the status of external dependencies') .setDesc('Check the status of external dependencies')
.addButton(button => button .addButton(button => button
.setButtonText('Check Dependencies') .setButtonText('Check dependencies')
.setCta() .setCta()
.onClick(async () => { .onClick(async () => {
await this.plugin.showDependencyStatus(); await this.plugin.showDependencyStatus();
@@ -62,9 +63,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
new Setting(containerEl) new Setting(containerEl)
.setName('Pandoc path') .setName('Pandoc path')
.setDesc('Path to pandoc executable (leave empty to use system PATH)') .setDesc('Path to pandoc executable (leave empty to use system path)')
.addText(text => text .addText(text => text
.setPlaceholder('pandoc') .setPlaceholder('Pandoc')
.setValue(this.plugin.settings.pandocPath) .setValue(this.plugin.settings.pandocPath)
.onChange(async (value) => { .onChange(async (value) => {
if (!SecurityUtils.validateExecutablePath(value)) { if (!SecurityUtils.validateExecutablePath(value)) {
@@ -77,9 +78,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
new Setting(containerEl) new Setting(containerEl)
.setName('Typst path') .setName('Typst path')
.setDesc('Path to typst executable (leave empty to use system PATH)') .setDesc('Path to typst executable (leave empty to use system path)')
.addText(text => text .addText(text => text
.setPlaceholder('typst') .setPlaceholder('Typst')
.setValue(this.plugin.settings.typstPath) .setValue(this.plugin.settings.typstPath)
.onChange(async (value) => { .onChange(async (value) => {
if (!SecurityUtils.validateExecutablePath(value)) { if (!SecurityUtils.validateExecutablePath(value)) {
@@ -91,10 +92,10 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
})); }));
new Setting(containerEl) new Setting(containerEl)
.setName('ImageMagick path') .setName('Imagemagick path')
.setDesc('Path to ImageMagick 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('magick') .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)) {
@@ -131,11 +132,13 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createExportDefaultsSection(containerEl: HTMLElement): void { private createExportDefaultsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Export Defaults' }); new Setting(containerEl)
.setName('Export defaults')
.setHeading();
new Setting(containerEl) new Setting(containerEl)
.setName('Default template') .setName('Default template')
.setDesc('Default Typst template for exports') .setDesc('Default typst template for exports')
.addDropdown(async (dropdown) => { .addDropdown(async (dropdown) => {
try { try {
const templates = await this.plugin.templateManager.getAvailableTemplates(); const templates = await this.plugin.templateManager.getAvailableTemplates();
@@ -157,7 +160,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} catch (error) { } catch (error) {
console.error('Failed to load templates:', error); console.error('Failed to load templates:', error);
// Fallback to text input // Fallback to text input
dropdown.addOption('default.typ', 'default.typ'); dropdown.addOption('default.typ', 'Default.typ');
dropdown.setValue(this.plugin.settings.exportDefaults.template); dropdown.setValue(this.plugin.settings.exportDefaults.template);
} }
}); });
@@ -176,13 +179,14 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
new Setting(containerEl) new Setting(containerEl)
.setName('Output folder') .setName('Output folder')
.setDesc('Default folder for exported PDFs (relative to vault root)') .setDesc('Folder for exported pdfs (relative to vault root)')
.addText(text => { .addText(text => {
text text
.setPlaceholder('exports') .setPlaceholder('Exports')
.setValue(this.plugin.settings.outputFolder) .setValue(this.plugin.settings.outputFolder)
.onChange(async (value) => { .onChange(async (value) => {
const normalizedValue = normalizePath(value); // Don't normalize absolute paths as normalizePath strips the leading slash
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
if (!SecurityUtils.validateOutputPath(normalizedValue)) { if (!SecurityUtils.validateOutputPath(normalizedValue)) {
ExportErrorHandler.showValidationError('output folder', SecurityUtils.getPathValidationError(normalizedValue)); ExportErrorHandler.showValidationError('output folder', SecurityUtils.getPathValidationError(normalizedValue));
return; return;
@@ -229,7 +233,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createTypographyDefaultsSection(containerEl: HTMLElement): void { private createTypographyDefaultsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Typography Defaults' }); new Setting(containerEl)
.setName('Typography defaults')
.setHeading();
// Use helper method for all three font dropdowns // Use helper method for all three font dropdowns
this.createFontDropdown( this.createFontDropdown(
@@ -293,7 +299,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createPageSetupSection(containerEl: HTMLElement): void { private createPageSetupSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Page Setup' }); new Setting(containerEl)
.setName('Page setup')
.setHeading();
new Setting(containerEl) new Setting(containerEl)
.setName('Page size') .setName('Page size')
@@ -363,7 +371,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createBehaviorSection(containerEl: HTMLElement): void { private createBehaviorSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Behavior' }); new Setting(containerEl)
.setName('Behavior')
.setHeading();
new Setting(containerEl) new Setting(containerEl)
.setName('Open after export') .setName('Open after export')
+3 -10
View File
@@ -36,15 +36,7 @@ export class TemplateManager {
} }
// Read directory contents - convert absolute path to vault-relative // Read directory contents - convert absolute path to vault-relative
const vaultBasePath = this.pathUtils.getVaultPath(); const vaultRelativePath = this.pathUtils.toVaultRelative(this.templatesPath);
let vaultRelativePath = this.templatesPath;
// Convert absolute path to vault-relative path
if (this.templatesPath.startsWith(vaultBasePath)) {
vaultRelativePath = this.templatesPath.substring(vaultBasePath.length);
// Remove leading separators
vaultRelativePath = vaultRelativePath.replace(/^[/\\]+/, '');
}
const list = await this.plugin.app.vault.adapter.list(vaultRelativePath); const list = await this.plugin.app.vault.adapter.list(vaultRelativePath);
const files = list.files.map(filePath => path.basename(filePath)); const files = list.files.map(filePath => path.basename(filePath));
@@ -127,11 +119,12 @@ export class TemplateManager {
case 'version': case 'version':
metadata.version = value; metadata.version = value;
break; break;
case 'variable': case 'variable': {
// Parse variable definition (e.g., @variable: font:string:Body font family) // Parse variable definition (e.g., @variable: font:string:Body font family)
const [name, type, description] = value.split(':'); const [name, type, description] = value.split(':');
metadata.variables.push({ name, type, description }); metadata.variables.push({ name, type, description });
break; break;
}
} }
} }
+6 -4
View File
@@ -57,8 +57,9 @@ export class EmbeddedTemplateManager {
} }
try { try {
// Ensure templates directory exists // Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
await this.pathUtils.ensureDir(this.templatesDir); const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
await this.pathUtils.ensureDir(relativeTemplatesDir);
// Extract template content // Extract template content
const content = extractTemplate(templateName, filePath); const content = extractTemplate(templateName, filePath);
@@ -105,8 +106,9 @@ export class EmbeddedTemplateManager {
const embeddedNames = getAllTemplateNames(); const embeddedNames = getAllTemplateNames();
// Ensure templates directory exists // Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
await this.pathUtils.ensureDir(this.templatesDir); const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
await this.pathUtils.ensureDir(relativeTemplatesDir);
for (const templateName of embeddedNames) { for (const templateName of embeddedNames) {
try { try {
+5 -5
View File
@@ -20,7 +20,7 @@ export class ExportConfigModal extends Modal {
plugin: obsidianTypstPDFExport; plugin: obsidianTypstPDFExport;
private state: ModalState; private state: ModalState;
private sections: Map<string, ModalSection> = new Map(); private sections: Map<string, ModalSection> = new Map();
private onSubmit: (config: ExportConfig) => void; private onSubmit: (config: ExportConfig) => void | Promise<void>;
private onCancel?: () => void; private onCancel?: () => void;
private renderer: ModalRenderer; private renderer: ModalRenderer;
private validator: ModalValidator; private validator: ModalValidator;
@@ -29,7 +29,7 @@ export class ExportConfigModal extends Modal {
app: App, app: App,
plugin: obsidianTypstPDFExport, plugin: obsidianTypstPDFExport,
settings: Partial<ExportConfigModalSettings>, settings: Partial<ExportConfigModalSettings>,
onSubmit: (config: ExportConfig) => void, onSubmit: (config: ExportConfig) => void | Promise<void>,
onCancel?: () => void onCancel?: () => void
) { ) {
super(app); super(app);
@@ -38,7 +38,7 @@ export class ExportConfigModal extends Modal {
this.onCancel = onCancel; this.onCancel = onCancel;
// Initialize state // Initialize state
this.state = new ModalState(settings); this.state = new ModalState(settings, app);
// Register sections // Register sections
this.registerSections(); this.registerSections();
@@ -83,7 +83,7 @@ export class ExportConfigModal extends Modal {
this.renderer.initialize(contentContainer); this.renderer.initialize(contentContainer);
// Load available templates // Load available templates
this.loadAvailableTemplates(); void this.loadAvailableTemplates();
} }
private async loadAvailableTemplates(): Promise<void> { private async loadAvailableTemplates(): Promise<void> {
@@ -119,7 +119,7 @@ export class ExportConfigModal extends Modal {
this.renderer.refreshSections(); this.renderer.refreshSections();
// Reload templates to update the dropdown // Reload templates to update the dropdown
this.loadAvailableTemplates(); void this.loadAvailableTemplates();
ExportErrorHandler.showSettingsReset(); ExportErrorHandler.showSettingsReset();
} }
+18 -243
View File
@@ -10,7 +10,7 @@ import { ModalSection } from './modalTypes';
export interface ModalRendererCallbacks { export interface ModalRendererCallbacks {
onReset: () => void; onReset: () => void;
onCancel: () => void; onCancel: () => void;
onSubmit: () => void; onSubmit: () => void | Promise<void>;
} }
export class ModalRenderer { export class ModalRenderer {
@@ -47,7 +47,6 @@ export class ModalRenderer {
initialize(contentContainer: HTMLElement): void { initialize(contentContainer: HTMLElement): void {
this.contentContainer = contentContainer; this.contentContainer = contentContainer;
this.setupInitialLayout(); this.setupInitialLayout();
this.addModalStyles();
} }
/** /**
@@ -121,7 +120,7 @@ export class ModalRenderer {
this.progressBar = progressBarContainer.createDiv('export-progress-bar'); this.progressBar = progressBarContainer.createDiv('export-progress-bar');
// Progress percentage // Progress percentage
const _progressPercent = this.progressContainer.createEl('div', { this.progressContainer.createEl('div', {
cls: 'export-progress-percent', cls: 'export-progress-percent',
text: '0%' text: '0%'
}); });
@@ -135,7 +134,7 @@ export class ModalRenderer {
// Reset button (left side) // Reset button (left side)
this.resetButton = buttonContainer.createEl('button', { this.resetButton = buttonContainer.createEl('button', {
text: 'Reset to Defaults', text: 'Reset to defaults',
cls: 'mod-muted' cls: 'mod-muted'
}); });
this.resetButton.addEventListener('click', () => this.callbacks.onReset()); this.resetButton.addEventListener('click', () => this.callbacks.onReset());
@@ -155,7 +154,20 @@ export class ModalRenderer {
text: 'Export', text: 'Export',
cls: 'mod-cta' cls: 'mod-cta'
}); });
this.submitButton.addEventListener('click', () => this.callbacks.onSubmit()); this.submitButton.addEventListener('click', () => {
this.setExportingState(true);
Promise.resolve(this.callbacks.onSubmit()).catch(err => {
// Log the error for debugging
console.error('Export submission failed:', err);
// Show user-facing error feedback
const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred during export';
this.showValidationErrors([errorMessage]);
// Re-enable buttons so user can try again or cancel
this.setExportingState(false);
});
});
} }
/** /**
@@ -219,7 +231,7 @@ export class ModalRenderer {
} }
const errorContainer = this.formContainer.createDiv('validation-errors'); const errorContainer = this.formContainer.createDiv('validation-errors');
errorContainer.createEl('h4', { text: 'Validation Errors', cls: 'error-title' }); errorContainer.createEl('h4', { text: 'Validation errors', cls: 'error-title' });
const errorList = errorContainer.createEl('ul'); const errorList = errorContainer.createEl('ul');
errors.forEach(error => { errors.forEach(error => {
@@ -251,241 +263,4 @@ export class ModalRenderer {
// Remove after 5 seconds // Remove after 5 seconds
setTimeout(() => warningContainer.remove(), 5000); setTimeout(() => warningContainer.remove(), 5000);
} }
/**
* Add custom CSS styles for the modal
*/
private addModalStyles(): void {
// Add custom styles for the modal
const style = document.createElement('style');
style.textContent = `
.export-config-modal {
width: 90vw;
max-width: 520px;
height: 80vh;
max-height: 600px;
}
.export-config-container {
display: flex;
flex-direction: column;
height: 100%;
}
.export-config-header {
padding: 16px 24px 8px 24px;
border-bottom: 1px solid var(--background-modifier-border);
flex-shrink: 0;
}
.export-config-header h2 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.export-note-title {
margin: 0;
font-size: 14px;
color: var(--text-muted);
opacity: 0.8;
}
.export-config-form {
flex: 1;
overflow-y: auto;
padding: 16px 24px;
}
.export-config-section {
margin-bottom: 24px;
}
.export-config-section:last-child {
margin-bottom: 0;
}
.export-config-section-title {
font-weight: 600;
margin-bottom: 12px;
padding-bottom: 4px;
border-bottom: 1px solid var(--background-modifier-border-hover);
}
.export-config-buttons {
padding: 16px 24px;
border-top: 1px solid var(--background-modifier-border);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
.export-config-buttons .right-buttons {
display: flex;
gap: 8px;
}
/* Progress styles */
.export-progress-container {
padding: 24px;
text-align: center;
}
.export-progress-container.export-hidden {
display: none;
}
.export-progress-container.export-progress-visible {
display: block;
}
.export-form-hidden {
display: none !important;
}
.export-progress-text {
margin-bottom: 16px;
font-size: 14px;
color: var(--text-muted);
}
.export-progress-bar-container {
width: 100%;
height: 8px;
background-color: var(--background-modifier-border);
border-radius: 4px;
margin-bottom: 8px;
overflow: hidden;
}
.export-progress-bar {
height: 100%;
background-color: var(--interactive-accent);
border-radius: 4px;
width: var(--progress-width, 0%);
transition: width 0.3s ease;
}
.export-progress-percent {
font-size: 12px;
color: var(--text-muted);
}
/* Form field styles */
.export-setting-item {
margin-bottom: 16px;
}
.export-setting-item-info {
margin-bottom: 6px;
}
.export-setting-item-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-setting-item-description {
font-size: 12px;
color: var(--text-muted);
}
.export-setting-item-control {
display: flex;
align-items: center;
}
.export-setting-item-control input,
.export-setting-item-control select {
flex: 1;
}
/* Folder suggest styles */
.export-folder-suggest-container {
position: relative;
}
.export-folder-suggest-input {
width: 100%;
padding: 6px 8px;
border: 1px solid var(--background-modifier-border);
border-radius: 4px;
background: var(--background-primary);
color: var(--text-normal);
}
.export-folder-suggest-input:focus {
border-color: var(--interactive-accent);
outline: none;
}
/* Validation styles */
.validation-errors, .validation-warnings {
background: var(--background-modifier-error);
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.validation-warnings {
background: var(--background-modifier-warning);
}
.error-title {
color: var(--text-error);
margin: 0 0 10px 0;
}
.warning-title {
color: var(--text-warning);
margin: 0 0 10px 0;
}
.validation-errors ul, .validation-warnings ul {
margin: 0;
padding-left: 20px;
}
.export-validation-error {
color: var(--text-error);
font-size: 12px;
margin-top: 4px;
}
.export-validation-warning {
color: var(--text-warning);
font-size: 12px;
margin-top: 4px;
}
/* Template variable styles */
.export-template-variables {
margin-top: 12px;
}
.export-template-variable {
margin-bottom: 8px;
padding: 8px;
background: var(--background-secondary);
border-radius: 4px;
font-size: 12px;
}
.export-template-variable-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-template-variable-description {
color: var(--text-muted);
font-style: italic;
}
`;
if (!document.head.querySelector('style[data-export-config-modal]')) {
style.setAttribute('data-export-config-modal', 'true');
document.head.appendChild(style);
}
}
} }
+3 -1
View File
@@ -11,7 +11,9 @@ export class BehaviorSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void { render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Export Behavior' }); new Setting(this.container)
.setName('Export behavior')
.setHeading();
this.createBehaviorToggles(state); this.createBehaviorToggles(state);
} }
+13 -7
View File
@@ -4,6 +4,7 @@
*/ */
import { Setting, App, normalizePath, DropdownComponent } from 'obsidian'; import { Setting, App, normalizePath, DropdownComponent } from 'obsidian';
import * as path from 'path';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { ExportFormat } from '../../../core/settings'; import { ExportFormat } from '../../../core/settings';
import { FolderSuggest } from '../../components/FolderSuggest'; import { FolderSuggest } from '../../components/FolderSuggest';
@@ -18,7 +19,9 @@ export class GeneralSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState, app?: App): void { render(containerEl: HTMLElement, state: ModalState, app?: App): void {
if (app) this.app = app; if (app) this.app = app;
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'General Settings' }); new Setting(this.container)
.setName('General settings')
.setHeading();
this.createTemplateSelection(state); this.createTemplateSelection(state);
this.createFormatSelection(state); this.createFormatSelection(state);
@@ -72,13 +75,14 @@ export class GeneralSection implements ModalSection {
new Setting(this.container) new Setting(this.container)
.setName('Output folder') .setName('Output folder')
.setDesc('Folder where PDFs will be saved (relative to vault root)') .setDesc('Location for exported PDF files (relative to vault root or absolute path)')
.addText(text => { .addText(text => {
const input = text const input = text
.setPlaceholder('exports') .setPlaceholder('PDF exports')
.setValue(state.settings.outputFolder || 'exports') .setValue(state.settings.outputFolder || 'exports')
.onChange(value => { .onChange(value => {
const normalizedValue = normalizePath(value); // Don't normalize absolute paths as normalizePath strips the leading slash
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
state.updateSettings({ outputFolder: normalizedValue }); state.updateSettings({ outputFolder: normalizedValue });
}); });
this.outputFolderInput = input.inputEl; this.outputFolderInput = input.inputEl;
@@ -102,9 +106,11 @@ export class GeneralSection implements ModalSection {
// Validate output folder // Validate output folder
if (this.outputFolderInput) { if (this.outputFolderInput) {
const value = normalizePath(this.outputFolderInput.value.trim()); const rawValue = this.outputFolderInput.value.trim();
if (!SecurityUtils.validateOutputPath(value)) { // Don't normalize absolute paths as normalizePath strips the leading slash
errors.push(SecurityUtils.getPathValidationError(value)); const normalizedValue = path.isAbsolute(rawValue) ? rawValue : normalizePath(rawValue);
if (!SecurityUtils.validateOutputPath(normalizedValue)) {
errors.push(SecurityUtils.getPathValidationError(normalizedValue));
} }
} }
+3 -1
View File
@@ -13,7 +13,9 @@ export class LayoutSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void { render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Layout' }); new Setting(this.container)
.setName('Page layout')
.setHeading();
this.createPageSizeSettings(state); this.createPageSizeSettings(state);
this.createOrientationSettings(state); this.createOrientationSettings(state);
+6 -3
View File
@@ -6,6 +6,7 @@
import { Setting } from 'obsidian'; import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper'; import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper';
import { ExportFormat } from '../../../core/settings';
export class PageSetupSection implements ModalSection { export class PageSetupSection implements ModalSection {
private container: HTMLElement | null = null; private container: HTMLElement | null = null;
@@ -13,7 +14,9 @@ export class PageSetupSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void { render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Setup' }); new Setting(this.container)
.setName('Page setup')
.setHeading();
this.createPageSizeSettings(state); this.createPageSizeSettings(state);
this.createOrientationSettings(state); this.createOrientationSettings(state);
@@ -57,7 +60,7 @@ export class PageSetupSection implements ModalSection {
orientation: value, orientation: value,
flipped: isLandscape, flipped: isLandscape,
// Auto-adjust width for single-page mode when flipped // Auto-adjust width for single-page mode when flipped
...(isLandscape && state.settings.format === 'single-page' ...(isLandscape && state.settings.format === ExportFormat.SinglePage
? { width: 'auto' } ? { width: 'auto' }
: {}) : {})
}); });
@@ -69,7 +72,7 @@ export class PageSetupSection implements ModalSection {
if (!this.container) return; if (!this.container) return;
const marginsContainer = this.container.createDiv('margins-container'); const marginsContainer = this.container.createDiv('margins-container');
marginsContainer.createEl('h4', { text: 'Text Margins' }); marginsContainer.createEl('h4', { text: 'Text margins' });
marginsContainer.createEl('p', { marginsContainer.createEl('p', {
text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")', text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")',
cls: 'setting-item-description' cls: 'setting-item-description'
+13 -49
View File
@@ -3,7 +3,7 @@
* Handles font selection and size configuration * Handles font selection and size configuration
*/ */
import { Setting, App, DropdownComponent } from 'obsidian'; import { Setting, App } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
export class TypographySection implements ModalSection { export class TypographySection implements ModalSection {
@@ -13,11 +13,16 @@ export class TypographySection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState, app?: App): void { render(containerEl: HTMLElement, state: ModalState, app?: App): void {
if (app) this.app = app; if (app) this.app = app;
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Typography' }); new Setting(this.container)
.setName('Typography')
.setHeading();
// Create font settings asynchronously // Create font settings asynchronously with explicit error handling
this.createFontSettings(state); // Font size settings are created after font dropdowns to preserve logical ordering
this.createFontSizeSettings(state); this.createFontSettings(state).catch(error => {
console.error('Failed to create font settings:', error);
// If font loading fails, getAvailableFonts will use hardcoded fallback fonts
});
} }
private async createFontSettings(state: ModalState): Promise<void> { private async createFontSettings(state: ModalState): Promise<void> {
@@ -100,6 +105,9 @@ export class TypographySection implements ModalSection {
state.updateTemplateVariables({ monospaceFont: value }); state.updateTemplateVariables({ monospaceFont: value });
}); });
}); });
// Create font size settings after font dropdowns for logical ordering
this.createFontSizeSettings(state);
} }
private createFontSizeSettings(state: ModalState): void { private createFontSizeSettings(state: ModalState): void {
@@ -161,50 +169,6 @@ export class TypographySection implements ModalSection {
} }
} }
private addFallbackBodyFonts(dropdown: DropdownComponent, state: ModalState, fontType: 'body' | 'heading'): void {
dropdown
.addOption('Concourse OT', 'Concourse OT')
.addOption('Times New Roman', 'Times New Roman')
.addOption('Georgia', 'Georgia')
.addOption('Arial', 'Arial')
.addOption('Helvetica', 'Helvetica')
.addOption('Calibri', 'Calibri')
.addOption('Cambria', 'Cambria')
.addOption('Palatino', 'Palatino')
.addOption('Book Antiqua', 'Book Antiqua');
// Set the appropriate value based on font type
const currentValue = fontType === 'body'
? state.templateVariables.bodyFont
: state.templateVariables.headingFont;
dropdown
.setValue(String(currentValue || 'Concourse OT'))
.onChange((value: string) => {
if (fontType === 'body') {
state.updateTemplateVariables({ bodyFont: value });
} else {
state.updateTemplateVariables({ headingFont: value });
}
});
}
private addFallbackMonospaceFonts(dropdown: DropdownComponent, state: ModalState): void {
dropdown
.addOption('Source Code Pro', 'Source Code Pro')
.addOption('Courier New', 'Courier New')
.addOption('Monaco', 'Monaco')
.addOption('Consolas', 'Consolas')
.addOption('Menlo', 'Menlo')
.addOption('DejaVu Sans Mono', 'DejaVu Sans Mono')
.addOption('Liberation Mono', 'Liberation Mono')
.addOption('Ubuntu Mono', 'Ubuntu Mono')
.setValue(String(state.templateVariables.monospaceFont || 'Source Code Pro'))
.onChange((value: string) => {
state.updateTemplateVariables({ monospaceFont: value });
});
}
validate(): ValidationResult { validate(): ValidationResult {
const errors: string[] = []; const errors: string[] = [];
const warnings: string[] = []; const warnings: string[] = [];
+8 -7
View File
@@ -3,6 +3,7 @@
* Centralized state management for the Export Configuration Modal * Centralized state management for the Export Configuration Modal
*/ */
import { App } from 'obsidian';
import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes'; import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes';
import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/settings'; import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/settings';
@@ -13,7 +14,7 @@ export class ModalState implements IModalState {
private changeListeners: Set<() => void> = new Set(); private changeListeners: Set<() => void> = new Set();
private static readonly STORAGE_KEY = 'typst-export-modal-state'; private static readonly STORAGE_KEY = 'typst-export-modal-state';
constructor(initialSettings: Partial<ExportConfigModalSettings>) { constructor(initialSettings: Partial<ExportConfigModalSettings>, private app: App) {
// Load from localStorage if available // Load from localStorage if available
const savedState = this.loadFromStorage(); const savedState = this.loadFromStorage();
@@ -174,7 +175,7 @@ export class ModalState implements IModalState {
} }
/** /**
* Save current state to localStorage * Save current state to vault-specific storage
*/ */
private saveToStorage(): void { private saveToStorage(): void {
const stateToSave = { const stateToSave = {
@@ -189,23 +190,23 @@ export class ModalState implements IModalState {
}; };
try { try {
localStorage.setItem(ModalState.STORAGE_KEY, JSON.stringify(stateToSave)); this.app.saveLocalStorage(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
} catch (error) { } catch (error) {
console.warn('Failed to save modal state to localStorage:', error); console.warn('Failed to save modal state to vault storage:', error);
} }
} }
/** /**
* Load state from localStorage * Load state from vault-specific storage
*/ */
private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, string | number | boolean> } | null { private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, string | number | boolean> } | null {
try { try {
const saved = localStorage.getItem(ModalState.STORAGE_KEY); const saved = this.app.loadLocalStorage(ModalState.STORAGE_KEY);
if (saved) { if (saved) {
return JSON.parse(saved); return JSON.parse(saved);
} }
} catch (error) { } catch (error) {
console.warn('Failed to load modal state from localStorage:', error); console.warn('Failed to load modal state from vault storage:', error);
} }
return null; return null;
} }
+220
View File
@@ -134,3 +134,223 @@
.export-form-hidden { .export-form-hidden {
display: none !important; display: none !important;
} }
/* Export config modal styles */
.export-config-modal {
width: 90vw;
max-width: 520px;
height: 80vh;
max-height: 600px;
}
.export-config-container {
display: flex;
flex-direction: column;
height: 100%;
}
.export-config-header {
padding: 16px 24px 8px 24px;
border-bottom: 1px solid var(--background-modifier-border);
flex-shrink: 0;
}
.export-config-header h2 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.export-note-title {
margin: 0;
font-size: 14px;
color: var(--text-muted);
opacity: 0.8;
}
.export-config-form {
flex: 1;
overflow-y: auto;
padding: 16px 24px;
}
.export-config-section {
margin-bottom: 24px;
}
.export-config-section:last-child {
margin-bottom: 0;
}
.export-config-section-title {
font-weight: 600;
margin-bottom: 12px;
padding-bottom: 4px;
border-bottom: 1px solid var(--background-modifier-border-hover);
}
.export-config-buttons {
padding: 16px 24px;
border-top: 1px solid var(--background-modifier-border);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
.export-config-buttons .right-buttons {
display: flex;
gap: 8px;
}
/* Progress styles */
.export-progress-container {
padding: 24px;
text-align: center;
}
.export-progress-container.export-hidden {
display: none;
}
.export-progress-container.export-progress-visible {
display: block;
}
.export-progress-text {
margin-bottom: 16px;
font-size: 14px;
color: var(--text-muted);
}
.export-progress-bar-container {
width: 100%;
height: 8px;
background-color: var(--background-modifier-border);
border-radius: 4px;
margin-bottom: 8px;
overflow: hidden;
}
.export-progress-bar {
height: 100%;
background-color: var(--interactive-accent);
border-radius: 4px;
width: var(--progress-width, 0%);
transition: width 0.3s ease;
}
.export-progress-percent {
font-size: 12px;
color: var(--text-muted);
}
/* Form field styles */
.export-setting-item {
margin-bottom: 16px;
}
.export-setting-item-info {
margin-bottom: 6px;
}
.export-setting-item-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-setting-item-description {
font-size: 12px;
color: var(--text-muted);
}
.export-setting-item-control {
display: flex;
align-items: center;
}
.export-setting-item-control input,
.export-setting-item-control select {
flex: 1;
}
/* Folder suggest styles */
.export-folder-suggest-container {
position: relative;
}
.export-folder-suggest-input {
width: 100%;
padding: 6px 8px;
border: 1px solid var(--background-modifier-border);
border-radius: 4px;
background: var(--background-primary);
color: var(--text-normal);
}
.export-folder-suggest-input:focus {
border-color: var(--interactive-accent);
outline: none;
}
/* Validation styles */
.validation-errors, .validation-warnings {
background: var(--background-modifier-error);
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.validation-warnings {
background: var(--background-modifier-warning);
}
.error-title {
color: var(--text-error);
margin: 0 0 10px 0;
}
.warning-title {
color: var(--text-warning);
margin: 0 0 10px 0;
}
.validation-errors ul, .validation-warnings ul {
margin: 0;
padding-left: 20px;
}
.export-validation-error {
color: var(--text-error);
font-size: 12px;
margin-top: 4px;
}
.export-validation-warning {
color: var(--text-warning);
font-size: 12px;
margin-top: 4px;
}
/* Template variable styles */
.export-template-variables {
margin-top: 12px;
}
.export-template-variable {
margin-bottom: 8px;
padding: 8px;
background: var(--background-secondary);
border-radius: 4px;
font-size: 12px;
}
.export-template-variable-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-template-variable-description {
color: var(--text-muted);
font-style: italic;
}
+2
View File
@@ -11,6 +11,8 @@
"importHelpers": true, "importHelpers": true,
"isolatedModules": true, "isolatedModules": true,
"strictNullChecks": true, "strictNullChecks": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"lib": [ "lib": [
"DOM", "DOM",
"ES5", "ES5",