Modal settings now persist to the vault; submit handlers may be async.
Improved embed, image and temp-file handling for more reliable exports.
Pandoc will perform citation processing by default during export.
Bug Fixes
Added robust error handling for export flows and reduced noisy console output.
Improved path validation and folder handling to prevent permission/absolute-path issues.
Style
Standardized UI text/capitalization and replaced static headings with native Setting headings.
Export modal styling and progress UI enhancements.
Chores
Tooling/dependency updates and TypeScript config tweaks.
Documentation
Updated README Node.js requirement to 18.20+.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit
* **New Features**
* Modal settings now persist to the vault; submit handlers may be async.
* Improved embed, image and temp-file handling for more reliable exports.
* Pandoc will perform citation processing by default during export.
* **Bug Fixes**
* Added robust error handling for export flows and reduced noisy console output.
* Improved path validation and folder handling to prevent permission/absolute-path issues.
* **Style**
* Standardized UI text/capitalization and replaced static headings with native Setting headings.
* Export modal styling and progress UI enhancements.
* **Chores**
* Tooling/dependency updates and TypeScript config tweaks.
* **Documentation**
* Updated README Node.js requirement to 18.20+.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Consolidates dynamic requires into top-level imports, migrates many vault/file ops to Node fs.promises with vault-relative handling, converts selected async APIs to synchronous or Promise-capable forms, moves modal state to vault-local storage, standardizes modal headings to Setting components, and adds guarded error handling for prior fire-and-forget calls.
Rename and make startup dependency check synchronous (checkDependenciesOnStartup); make MarkdownPreprocessor.process synchronous; change PluginLifecycle.cleanup to async Promise<void>; make main.onunload async and await lifecycle cleanup.
Move temp/template creation and cleanup to Node fs.promises (mkdir/access/readdir/unlink); ensure directories, use vault-relative paths via PathUtils.toVaultRelative; tie cleanup to plugin lifecycle (dispose/unload).
Add tempImagesDir, convert many adapter ops to use vault-relative paths, perform conversions with absolute paths when required, centralize remote-download completion handling, improve error propagation and debug logging, and treat preprocessor.process as synchronous.
Minor log-level/type change (info → debug), error message tweaks/quoting, switch-case scoping fix, README Node version bumped to >=18.20.0, consolidate template path usage with PathUtils.toVaultRelative.
Sequence Diagram(s)
sequenceDiagram
participant Plugin as Plugin (startup)
participant Main as main.ts
participant Checker as DependencyChecker
participant Notice as Obsidian Notice
Plugin->>Main: initialize
Main->>Checker: checkDependenciesOnStartup() -- synchronous
Note right of Checker `#DDDDFF`: runs checkDependenciesSync internally
alt dependency missing / error
Checker->>Notice: show notice
end
sequenceDiagram
participant UI as Export Modal
participant State as ModalState
participant Vault as App Vault API
UI->>State: new ModalState(settings, app)
State->>Vault: loadLocalStorage(key)
Vault-->>State: saved state
State-->>UI: merged initialized state
UI->>UI: void loadAvailableTemplates() -- async ignored by caller
UI->>State: onSubmit(config)
alt onSubmit returns Promise
State->>Vault: saveLocalStorage(key, data)
else sync
State->>Vault: saveLocalStorage(key, data)
end
Vault-->>State: confirm
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
Focus areas for review:
Async↔sync API changes and all call sites (DependencyChecker, MarkdownPreprocessor, PluginLifecycle, ExportOrchestrator).
🐰 I hop through imports, neat and spry, Promises shortened, some waved goodbye, Vault keeps my things safe, snug, and sound, Headings now Settings, tidy and round, A refactor nibble — a carrot I found!
Pre-merge checks and finishing touches
✅ Passed checks (3 passed)
Check name
Status
Explanation
Description Check
✅ Passed
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
✅ Passed
The title accurately summarizes the main changes: ESLint configuration updates and resolution of bot-identified issues across multiple files.
Docstring Coverage
✅ Passed
No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Create PR with unit tests
Post copyable unit tests in a comment
Commit unit tests in branch obsidian-bot-review
📜 Recent review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between d6d31afb16 and efbff4e172.
src/**/*.ts: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
Add user-facing commands via this.addCommand(...) and use stable command IDs
Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
Prefer async/await over promise chains and handle errors gracefully
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
The removal of DropdownComponent is appropriate since Setting provides the addDropdown method.
16-18: LGTM: Proper use of Setting component for section heading.
This aligns with Obsidian UI patterns and is more consistent with the framework's approach to modal headings.
20-26: LGTM: Error handling properly implemented.
The addition of .catch() with explicit error logging addresses the previous review feedback. Moving createFontSizeSettings inside createFontSettings (line 110) ensures proper UI ordering.
28-111: LGTM: Font settings creation is well-structured.
The method correctly handles font dropdown creation with defensive logic to ensure the current font is always available as an option, even if not in the cached list.
113-127: LGTM: Font size settings implemented correctly.
The slider configuration with 8-16pt range and 0.5pt increments is reasonable and provides good UX with the dynamic tooltip.
172-188: LGTM: Validation and identifier methods are correct.
The validation appropriately returns no errors for dropdowns with predefined options, and the section identifier is unique.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
src/templates/TemplateManager.ts (1)
8-8: Eliminate Node.js path module dependency in favor of Obsidian API.
The file imports and uses Node.js's path module (line 8) with path.basename() at line 50. Per previous learnings from this codebase, the obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules and instead stick to Obsidian API calls for path operations.
Replace path.basename() with a simple string operation that extracts the filename from the path:
-import { obsidianTypstPDFExport } from '../../main';
-import { PathUtils } from '../core/PathUtils';
-import * as path from 'path';
+import { obsidianTypstPDFExport } from '../../main';
+import { PathUtils } from '../core/PathUtils';
220-228: Replace ESLint pragma with Biome directive.
Biome still errors on the /\x00/ regex because // eslint-disable-next-line no-control-regex is ignored by Biome after the recent tooling switch. This keeps the lint pipeline red. Swap the pragma for the Biome equivalent so the intentional null-byte check passes lint while retaining the security guard. Suggested fix:
- // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally checking for null byte character for security validation
376-384: Same Biome pragma issue as above.
This second null-byte check hits the same Biome rule and will also fail lint until we replace the ESLint directive with the Biome-specific ignore. Please apply the same adjustment here:
- // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally checking for null byte character for security validation
src/ui/modal/ExportConfigModal.ts (1)
150-164: Bring the form back after a failed export
showProgress adds the export-progress-visible and export-form-hidden classes. In the catch block we only re-enable the buttons, so after a failure the modal stays stuck on the progress view and the form never becomes visible again. Users can’t adjust settings to retry without closing and reopening the modal. Please remove those classes (e.g., a hideProgress() helper that restores the form) before re-enabling the controls.
The addition of esModuleInterop and allowSyntheticDefaultImports properly supports the ES module import patterns being adopted throughout the codebase.
Consider enabling full TypeScript strict mode by adding "strict": true to replace the individual strict flags. This would provide more comprehensive type safety guarantees. As per coding guidelines.
src/converters/pdf/PdfCliExecutor.ts (1)
116-116: Consider promisifying at module level.
The promisified exec is currently created on each call to executeCommand. For better performance, consider moving this to module level:
+const execAsync = promisify(exec);
+
export class PdfCliExecutor {
Then use execAsync directly without recreating it on each invocation.
src/core/DependencyChecker.ts (1)
351-356: Consider renaming method to match synchronous behavior.
The method name checkDependenciesAsync suggests asynchronous behavior, but it now returns void instead of Promise<void>. This naming mismatch could confuse future maintainers.
Consider renaming to better reflect the synchronous, fire-and-forget nature:
- public static checkDependenciesAsync(
+ public static checkDependenciesOnStartup(
Alternatively, if maintaining the current name for backward compatibility, add a JSDoc note clarifying the synchronous nature and fire-and-forget usage pattern.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 39d66607af and 2c4076f3c9.
⛔ Files ignored due to path filters (1)
package-lock.json is excluded by !**/package-lock.json
src/**/*.ts: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
Add user-facing commands via this.addCommand(...) and use stable command IDs
Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
Prefer async/await over promise chains and handle errors gracefully
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)
📚 Learning: 2025-09-25T14:14:57.437Z
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.437Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.
Applied to files:
src/converters/pdf/ImageOptimizer.ts
📚 Learning: 2025-09-25T14:27:31.837Z
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
Applied to files:
src/converters/pdf/ImageOptimizer.ts
src/plugin/FontManager.ts
src/plugin/PathResolver.ts
src/converters/PandocTypstConverter.ts
src/plugin/EmbedProcessor.ts
src/core/ModalSettingsHelper.ts
main.ts
src/core/PathUtils.ts
src/plugin/EventHandlers.ts
src/core/ExecutableChecker.ts
src/converters/pdf/PdfCliExecutor.ts
src/converters/pdf/BinaryLocator.ts
src/converters/pdf/FileDiscovery.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to esbuild.config.mjs : Use esbuild for bundling (this sample relies on esbuild.config.mjs)
Applied to files:
package.json
eslint.config.mjs
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
Applied to files:
src/ui/modal/sections/GeneralSection.ts
src/ui/modal/state/ModalState.ts
src/core/ModalSettingsHelper.ts
src/plugin/SettingsTab.ts
src/ui/modal/sections/PageSetupSection.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Prefer async/await over promise chains and handle errors gracefully
[error] 378-378: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
🔇 Additional comments (33)
src/templates/TemplateManager.ts (1)
130-135: Block scope wrapping in switch case is correct.
The wrapping of the "variable" case in block scope { } is the correct JavaScript pattern for isolating variable declarations within switch cases. This prevents variable hoisting issues and improves code clarity.
src/plugin/FontManager.ts (1)
6-6: LGTM: Top-level import migration.
The change from dynamic require to top-level import of spawn is a best practice and aligns with the broader PR objective to modernize import patterns.
src/plugin/PathResolver.ts (1)
6-6: LGTM: Top-level import migration.
The change from dynamic require to top-level import of spawnSync follows best practices and maintains consistency with the broader refactoring across the codebase.
src/converters/pdf/FileDiscovery.ts (1)
6-6: LGTM: Standardizing to fs.promises.
The migration to top-level import of fs.promises is a best practice and aligns with similar changes across the codebase (BinaryLocator.ts, ImageOptimizer.ts, PathUtils.ts).
src/converters/pdf/PdfCliExecutor.ts (1)
6-7: LGTM: Top-level imports adopted.
The migration to top-level imports for exec and promisify follows best practices and aligns with the broader refactoring.
package.json (1)
30-30: LGTM: Tooling and dependency updates.
The additions support the broader refactoring objectives:
js-yaml and @types/js-yaml enable YAML parsing capabilities
Updated TypeScript ESLint packages (^8.46.3) provide improved linting
eslint and eslint-plugin-obsidianmd enhance code quality checks
electron supports development environment requirements
Also applies to: 32-34, 39-39, 41-42, 53-53
src/plugin/SettingsTab.ts (2)
31-33: LGTM: Migrating to Setting API for headings.
The change from static HTML to programmatic Setting components with setHeading() follows Obsidian's recommended API patterns and aligns with similar UI migrations across the codebase.
52-54: LGTM: Consistent heading and text normalization.
All section headings now use the Setting API with setHeading(), providing consistent UI structure. The button text change from "Check Dependencies" to "Check dependencies" maintains text consistency with other sections.
Also applies to: 61-61, 138-140, 238-240, 304-306, 376-378
src/converters/pdf/BinaryLocator.ts (2)
6-6: LGTM!
The top-level import of fs.promises aligns with the PR-wide pattern of replacing dynamic requires with static imports, improving bundling and maintainability.
34-37: Good defensive programming!
Throwing an error when configDir is undefined is the correct approach, as Obsidian's configuration directory can be user-configured and should not be hardcoded. The error is properly caught and returned as a descriptive error message in the BinaryLocation result.
src/plugin/PluginLifecycle.ts (3)
54-59: LGTM!
The explicit void wrapping correctly marks these as intentional fire-and-forget operations, satisfying the ESLint @typescript-eslint/no-floating-promises rule while maintaining the desired non-blocking startup behavior.
The void-wrapped async IIFE correctly implements non-blocking cleanup during plugin unload, with proper error handling to prevent exceptions from disrupting the shutdown process.
88-92: LGTM!
The fire-and-forget startup cleanup correctly wraps the async operations with void, while properly awaiting the internal cleanupAllTempDirs() call to ensure cleanup completes before the IIFE exits.
src/converters/pdf/ImageOptimizer.ts (1)
6-7: LGTM!
The migration to top-level static imports for child_process and fs aligns with the PR-wide pattern of replacing dynamic requires, improving bundling efficiency and enabling better static analysis.
src/plugin/EmbedProcessor.ts (3)
6-7: LGTM!
The top-level imports for exec and util align with the PR-wide pattern and enable the promisified exec usage later in the file.
113-113: Good logging hygiene!
Switching to console.debug for download and remote image processing messages appropriately reduces console noise while maintaining observability for debugging. This aligns with the ESLint no-console rule that permits debug, warn, and error.
Also applies to: 125-125, 162-162, 300-300, 306-306
348-349: LGTM!
The promisified exec is correctly implemented using the top-level imported util.promisify, providing a cleaner promise-based interface for command execution.
main.ts (3)
14-14: LGTM!
The top-level electron shell import aligns with the PR-wide pattern of replacing dynamic requires with static imports.
181-188: Consistent with DependencyChecker refactor.
The signature change from async returning Promise<void> to synchronous returning void correctly aligns with the refactored DependencyChecker.checkDependenciesAsync, which now performs synchronous checks and shows notices only when dependencies are missing.
216-216: LGTM!
The void operator correctly marks the shell.openPath call as an intentional fire-and-forget operation, appropriate for launching an external PDF viewer.
obsidianreviewbot-feedback.md (1)
1-191: Feedback documentation file.
This file documents linting feedback and guidance for the PR. No code review is necessary as it serves as a reference for the changes made to address ESLint and Obsidian-specific plugin issues.
eslint.config.mjs (2)
3-7: LGTM!
The ESLint configuration correctly integrates the Obsidian plugin and follows the modern flat config pattern with appropriate base configurations for JavaScript and TypeScript.
Also applies to: 10-14
37-98: Comprehensive and well-balanced rule configuration.
The ESLint rules appropriately enforce Obsidian-specific best practices while downgrading strict type-checking rules to warnings for gradual adoption. The @typescript-eslint/require-await: 'off' setting explains why some async methods without await expressions are not flagged.
src/ui/modal/sections/TypographySection.ts (2)
16-18: LGTM: Consistent heading style
The migration from static HTML to Setting-based heading aligns with the broader UI consistency changes across modal sections.
21-21: Review concerns are partially overstated but UX delay remains a valid consideration
The code shows defensive implementations that mitigate the stated risks:
Empty dropdowns concern: Font dropdowns won't be visible until createFontSettings() completes; they don't briefly appear empty. Font size controls (synchronous) ARE visible immediately, providing immediate UI feedback.
Race conditions: The container null check at line 26 prevents errors if the modal closes before font loading completes.
State inconsistencies: Same null check prevents state updates after modal closure.
However, a legitimate UX consideration remains: the three font dropdowns will have a visible delay before appearing, with no loading indicator to explain the UI gap. The fallback fonts (lines 134–146) ensure the dropdowns populate with reasonable defaults even if cache fails, but this doesn't address the initial delay.
This pattern is consistent throughout the codebase (cacheAvailableFonts, loadAvailableTemplates), suggesting it's intentional. Whether the delay is acceptable depends on typical cache availability and UX expectations—this warrants manual verification.
src/ui/modal/sections/LayoutSection.ts (1)
16-18: LGTM: Consistent heading style
The migration to Setting-based heading matches the pattern applied across other modal sections (GeneralSection, TypographySection, BehaviorSection, PageSetupSection) for UI consistency.
src/core/PathUtils.ts (1)
4-4: LGTM: Cleaner import pattern while maintaining Obsidian API preference
The change from dynamic require to top-level import is a good modernization. The fs module is only used as a fallback for absolute paths outside the vault (after trying Obsidian's vault adapter first), which aligns with the project's preference for Obsidian APIs.
Replacing the string literal 'single-page' with ExportFormat.SinglePage improves type safety and maintainability. This aligns with similar updates in PageSetupSection.ts.
src/ui/modal/sections/PageSetupSection.ts (3)
17-19: LGTM: Consistent heading style
Setting-based heading aligns with the UI consistency changes across all modal sections.
59-66: LGTM: Type-safe format check and concise conditional spread
The change from string comparison to ExportFormat.SinglePage constant improves type safety. The conditional spread pattern cleanly handles the width adjustment for landscape single-page mode.
75-75: LGTM: Sentence case aligns with UI guidelines
The change from "Text Margins" to "Text margins" follows sentence-case conventions for subheadings, consistent with modern UI design patterns.
styles.css (1)
138-356: LGTM: Well-structured modal styles with theme compatibility
The new styles for the export configuration modal follow good practices:
Uses Obsidian CSS variables for theme compatibility
Provides clear visual hierarchy with appropriate spacing
Includes accessible focus states for interactive elements
Uses flexbox for responsive layout
Properly scopes classes with export- prefix to avoid conflicts
The styles integrate cleanly without modifying existing rules.
src/converters/MarkdownPreprocessor.ts (1)
331-331: No action required—all call sites correctly updated
Verification confirms the method signature change from async to sync is complete and correct. The single call site in ExportOrchestrator.ts at line 182 properly invokes preprocessor.process(content) synchronously without await. No other instantiations or usages exist in the codebase.
**Actionable comments posted: 8**
> [!CAUTION]
> Some comments are outside the diff and can’t be posted inline due to platform limitations.
>
>
>
> <details>
> <summary>⚠️ Outside diff range comments (4)</summary><blockquote>
>
> <details>
> <summary>src/templates/TemplateManager.ts (1)</summary><blockquote>
>
> `8-8`: **Eliminate Node.js `path` module dependency in favor of Obsidian API.**
>
> The file imports and uses Node.js's `path` module (line 8) with `path.basename()` at line 50. Per previous learnings from this codebase, the obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules and instead stick to Obsidian API calls for path operations.
>
> Replace `path.basename()` with a simple string operation that extracts the filename from the path:
>
>
>
>
> ```diff
> -import { obsidianTypstPDFExport } from '../../main';
> -import { PathUtils } from '../core/PathUtils';
> -import * as path from 'path';
>
> +import { obsidianTypstPDFExport } from '../../main';
> +import { PathUtils } from '../core/PathUtils';
> ```
>
> Then update line 50:
>
> ```diff
> - const files = list.files.map(filePath => path.basename(filePath));
> + const files = list.files.map(filePath => filePath.split(/[/\\]/).pop() || filePath);
> ```
>
> Based on learnings from PR #5.
>
>
>
> Also applies to: 50-50
>
> </blockquote></details>
> <details>
> <summary>src/core/SecurityUtils.ts (2)</summary><blockquote>
>
> `220-228`: **Replace ESLint pragma with Biome directive.**
>
> Biome still errors on the `/\x00/` regex because `// eslint-disable-next-line no-control-regex` is ignored by Biome after the recent tooling switch. This keeps the lint pipeline red. Swap the pragma for the Biome equivalent so the intentional null-byte check passes lint while retaining the security guard. Suggested fix:
>
> ```diff
> - // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
> + // biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally checking for null byte character for security validation
> ```
>
> ---
>
> `376-384`: **Same Biome pragma issue as above.**
>
> This second null-byte check hits the same Biome rule and will also fail lint until we replace the ESLint directive with the Biome-specific ignore. Please apply the same adjustment here:
>
> ```diff
> - // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
> + // biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally checking for null byte character for security validation
> ```
>
> </blockquote></details>
> <details>
> <summary>src/ui/modal/ExportConfigModal.ts (1)</summary><blockquote>
>
> `150-164`: **Bring the form back after a failed export**
>
> `showProgress` adds the `export-progress-visible` and `export-form-hidden` classes. In the catch block we only re-enable the buttons, so after a failure the modal stays stuck on the progress view and the form never becomes visible again. Users can’t adjust settings to retry without closing and reopening the modal. Please remove those classes (e.g., a `hideProgress()` helper that restores the form) before re-enabling the controls.
>
> ```diff
> this.renderer.showProgress(`Export failed: ${error.message}`, -1);
> this.renderer.setExportingState(false);
> + this.renderer.hideProgress();
> ```
>
> </blockquote></details>
>
> </blockquote></details>
<details>
<summary>🧹 Nitpick comments (3)</summary><blockquote>
<details>
<summary>tsconfig.json (1)</summary><blockquote>
`14-15`: **LGTM: ES module interop enabled.**
The addition of `esModuleInterop` and `allowSyntheticDefaultImports` properly supports the ES module import patterns being adopted throughout the codebase.
Consider enabling full TypeScript strict mode by adding `"strict": true` to replace the individual strict flags. This would provide more comprehensive type safety guarantees. As per coding guidelines.
</blockquote></details>
<details>
<summary>src/converters/pdf/PdfCliExecutor.ts (1)</summary><blockquote>
`116-116`: **Consider promisifying at module level.**
The promisified `exec` is currently created on each call to `executeCommand`. For better performance, consider moving this to module level:
```diff
+const execAsync = promisify(exec);
+
export class PdfCliExecutor {
```
Then use `execAsync` directly without recreating it on each invocation.
</blockquote></details>
<details>
<summary>src/core/DependencyChecker.ts (1)</summary><blockquote>
`351-356`: **Consider renaming method to match synchronous behavior.**
The method name `checkDependenciesAsync` suggests asynchronous behavior, but it now returns `void` instead of `Promise<void>`. This naming mismatch could confuse future maintainers.
Consider renaming to better reflect the synchronous, fire-and-forget nature:
```diff
- public static checkDependenciesAsync(
+ public static checkDependenciesOnStartup(
```
Alternatively, if maintaining the current name for backward compatibility, add a JSDoc note clarifying the synchronous nature and fire-and-forget usage pattern.
</blockquote></details>
</blockquote></details>
<details>
<summary>📜 Review details</summary>
**Configuration used**: CodeRabbit UI
**Review profile**: CHILL
**Plan**: Pro
<details>
<summary>📥 Commits</summary>
Reviewing files that changed from the base of the PR and between 39d66607afcdb87535597b49d1df4a7030c1cb29 and 2c4076f3c9201b6336c94b76dad48c864c703e8a.
</details>
<details>
<summary>⛔ Files ignored due to path filters (1)</summary>
* `package-lock.json` is excluded by `!**/package-lock.json`
</details>
<details>
<summary>📒 Files selected for processing (36)</summary>
* `eslint.config.mjs` (2 hunks)
* `main.ts` (3 hunks)
* `obsidianreviewbot-feedback.md` (1 hunks)
* `package.json` (2 hunks)
* `src/converters/MarkdownPreprocessor.ts` (7 hunks)
* `src/converters/PandocTypstConverter.ts` (2 hunks)
* `src/converters/pdf/BinaryLocator.ts` (2 hunks)
* `src/converters/pdf/FileDiscovery.ts` (2 hunks)
* `src/converters/pdf/ImageOptimizer.ts` (1 hunks)
* `src/converters/pdf/PdfCliExecutor.ts` (1 hunks)
* `src/converters/preprocessors/FrontmatterProcessor.ts` (8 hunks)
* `src/core/DependencyChecker.ts` (1 hunks)
* `src/core/ExecutableChecker.ts` (1 hunks)
* `src/core/ExportErrorHandler.ts` (1 hunks)
* `src/core/ModalSettingsHelper.ts` (2 hunks)
* `src/core/PathUtils.ts` (1 hunks)
* `src/core/SecurityUtils.ts` (2 hunks)
* `src/plugin/CommandRegistry.ts` (3 hunks)
* `src/plugin/EmbedProcessor.ts` (6 hunks)
* `src/plugin/EventHandlers.ts` (6 hunks)
* `src/plugin/ExportOrchestrator.ts` (3 hunks)
* `src/plugin/FontManager.ts` (1 hunks)
* `src/plugin/PathResolver.ts` (1 hunks)
* `src/plugin/PluginLifecycle.ts` (3 hunks)
* `src/plugin/SettingsTab.ts` (6 hunks)
* `src/templates/TemplateManager.ts` (1 hunks)
* `src/ui/modal/ExportConfigModal.ts` (5 hunks)
* `src/ui/modal/ModalRenderer.ts` (4 hunks)
* `src/ui/modal/sections/BehaviorSection.ts` (1 hunks)
* `src/ui/modal/sections/GeneralSection.ts` (1 hunks)
* `src/ui/modal/sections/LayoutSection.ts` (1 hunks)
* `src/ui/modal/sections/PageSetupSection.ts` (3 hunks)
* `src/ui/modal/sections/TypographySection.ts` (1 hunks)
* `src/ui/modal/state/ModalState.ts` (4 hunks)
* `styles.css` (1 hunks)
* `tsconfig.json` (1 hunks)
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>📓 Path-based instructions (4)</summary>
<details>
<summary>src/**/*.ts</summary>
**📄 CodeRabbit inference engine (AGENTS.md)**
> `src/**/*.ts`: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
> Add user-facing commands via this.addCommand(...) and use stable command IDs
> Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
> Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
> Prefer async/await over promise chains and handle errors gracefully
Files:
- `src/templates/TemplateManager.ts`
- `src/converters/pdf/ImageOptimizer.ts`
- `src/plugin/FontManager.ts`
- `src/plugin/ExportOrchestrator.ts`
- `src/plugin/PathResolver.ts`
- `src/converters/PandocTypstConverter.ts`
- `src/core/ExportErrorHandler.ts`
- `src/plugin/CommandRegistry.ts`
- `src/plugin/EmbedProcessor.ts`
- `src/ui/modal/sections/TypographySection.ts`
- `src/ui/modal/sections/GeneralSection.ts`
- `src/ui/modal/state/ModalState.ts`
- `src/core/ModalSettingsHelper.ts`
- `src/ui/modal/ModalRenderer.ts`
- `src/ui/modal/sections/BehaviorSection.ts`
- `src/converters/MarkdownPreprocessor.ts`
- `src/plugin/SettingsTab.ts`
- `src/core/PathUtils.ts`
- `src/ui/modal/sections/PageSetupSection.ts`
- `src/plugin/EventHandlers.ts`
- `src/ui/modal/sections/LayoutSection.ts`
- `src/core/ExecutableChecker.ts`
- `src/converters/pdf/PdfCliExecutor.ts`
- `src/core/DependencyChecker.ts`
- `src/converters/pdf/BinaryLocator.ts`
- `src/core/SecurityUtils.ts`
- `src/converters/preprocessors/FrontmatterProcessor.ts`
- `src/plugin/PluginLifecycle.ts`
- `src/converters/pdf/FileDiscovery.ts`
- `src/ui/modal/ExportConfigModal.ts`
</details>
<details>
<summary>{manifest.json,main.js,styles.css}</summary>
**📄 CodeRabbit inference engine (AGENTS.md)**
> Release artifacts must include main.js and manifest.json, and styles.css if present, at the top level
Files:
- `styles.css`
</details>
<details>
<summary>package.json</summary>
**📄 CodeRabbit inference engine (AGENTS.md)**
> Use npm as the package manager (project scripts and deps defined in package.json)
Files:
- `package.json`
</details>
<details>
<summary>tsconfig.json</summary>
**📄 CodeRabbit inference engine (AGENTS.md)**
> Enable TypeScript strict mode ("strict": true preferred)
Files:
- `tsconfig.json`
</details>
</details><details>
<summary>🧠 Learnings (8)</summary>
<details>
<summary>📓 Common learnings</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
```
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)
```
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:14:57.437Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.437Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.
```
**Applied to files:**
- `src/converters/pdf/ImageOptimizer.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:27:31.837Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
```
**Applied to files:**
- `src/converters/pdf/ImageOptimizer.ts`
- `src/plugin/FontManager.ts`
- `src/plugin/PathResolver.ts`
- `src/converters/PandocTypstConverter.ts`
- `src/plugin/EmbedProcessor.ts`
- `src/core/ModalSettingsHelper.ts`
- `main.ts`
- `src/core/PathUtils.ts`
- `src/plugin/EventHandlers.ts`
- `src/core/ExecutableChecker.ts`
- `src/converters/pdf/PdfCliExecutor.ts`
- `src/converters/pdf/BinaryLocator.ts`
- `src/converters/pdf/FileDiscovery.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to esbuild.config.mjs : Use esbuild for bundling (this sample relies on esbuild.config.mjs)
```
**Applied to files:**
- `package.json`
- `eslint.config.mjs`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
```
**Applied to files:**
- `src/plugin/CommandRegistry.ts`
- `src/plugin/PluginLifecycle.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to tsconfig.json : Enable TypeScript strict mode ("strict": true preferred)
```
**Applied to files:**
- `tsconfig.json`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
```
**Applied to files:**
- `src/ui/modal/sections/GeneralSection.ts`
- `src/ui/modal/state/ModalState.ts`
- `src/core/ModalSettingsHelper.ts`
- `src/plugin/SettingsTab.ts`
- `src/ui/modal/sections/PageSetupSection.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Prefer async/await over promise chains and handle errors gracefully
```
**Applied to files:**
- `src/plugin/EventHandlers.ts`
- `src/core/DependencyChecker.ts`
</details>
</details><details>
<summary>🧬 Code graph analysis (13)</summary>
<details>
<summary>src/converters/PandocTypstConverter.ts (2)</summary><blockquote>
<details>
<summary>src/core/TempDirectoryManager.ts (1)</summary>
* `TempDirectoryManager` (117-458)
</details>
<details>
<summary>src/core/PathUtils.ts (1)</summary>
* `PathUtils` (30-251)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/sections/TypographySection.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Setting` (17-24)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/sections/GeneralSection.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Setting` (17-24)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/state/ModalState.ts (2)</summary><blockquote>
<details>
<summary>src/ui/modal/modalTypes.ts (2)</summary>
* `ExportConfigModalSettings` (29-46)
* `ModalState` (60-70)
</details>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `App` (54-65)
</details>
</blockquote></details>
<details>
<summary>main.ts (1)</summary><blockquote>
<details>
<summary>src/core/DependencyChecker.ts (1)</summary>
* `DependencyChecker` (75-378)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/sections/BehaviorSection.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Setting` (17-24)
</details>
</blockquote></details>
<details>
<summary>src/converters/MarkdownPreprocessor.ts (1)</summary><blockquote>
<details>
<summary>src/converters/preprocessors/EmbedProcessor.ts (1)</summary>
* `PreprocessingResult` (14-52)
</details>
</blockquote></details>
<details>
<summary>src/plugin/SettingsTab.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Setting` (17-24)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/sections/PageSetupSection.ts (3)</summary><blockquote>
<details>
<summary>src/ui/modal/modalTypes.ts (2)</summary>
* `ModalSection` (48-52)
* `ModalState` (60-70)
</details>
<details>
<summary>src/ui/modal/state/ModalState.ts (1)</summary>
* `ModalState` (10-213)
</details>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Setting` (17-24)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/sections/LayoutSection.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Setting` (17-24)
</details>
</blockquote></details>
<details>
<summary>src/plugin/PluginLifecycle.ts (1)</summary><blockquote>
<details>
<summary>src/core/TempDirectoryManager.ts (1)</summary>
* `TempDirectoryManager` (117-458)
</details>
</blockquote></details>
<details>
<summary>src/converters/pdf/FileDiscovery.ts (2)</summary><blockquote>
<details>
<summary>esbuild.config.mjs (1)</summary>
* `files` (30-30)
</details>
<details>
<summary>scripts/package-plugin.js (1)</summary>
* `fs` (11-11)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/ExportConfigModal.ts (2)</summary><blockquote>
<details>
<summary>src/ui/modal/modalTypes.ts (2)</summary>
* `ExportConfig` (8-27)
* `ModalState` (60-70)
</details>
<details>
<summary>src/ui/modal/state/ModalState.ts (1)</summary>
* `ModalState` (10-213)
</details>
</blockquote></details>
</details><details>
<summary>🪛 Biome (2.1.2)</summary>
<details>
<summary>src/core/SecurityUtils.ts</summary>
[error] 378-378: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
</details>
</details>
</details>
<details>
<summary>🔇 Additional comments (33)</summary><blockquote>
<details>
<summary>src/templates/TemplateManager.ts (1)</summary><blockquote>
`130-135`: **Block scope wrapping in switch case is correct.**
The wrapping of the "variable" case in block scope `{ }` is the correct JavaScript pattern for isolating variable declarations within switch cases. This prevents variable hoisting issues and improves code clarity.
</blockquote></details>
<details>
<summary>src/plugin/FontManager.ts (1)</summary><blockquote>
`6-6`: **LGTM: Top-level import migration.**
The change from dynamic require to top-level import of `spawn` is a best practice and aligns with the broader PR objective to modernize import patterns.
</blockquote></details>
<details>
<summary>src/plugin/PathResolver.ts (1)</summary><blockquote>
`6-6`: **LGTM: Top-level import migration.**
The change from dynamic require to top-level import of `spawnSync` follows best practices and maintains consistency with the broader refactoring across the codebase.
</blockquote></details>
<details>
<summary>src/converters/pdf/FileDiscovery.ts (1)</summary><blockquote>
`6-6`: **LGTM: Standardizing to fs.promises.**
The migration to top-level import of `fs.promises` is a best practice and aligns with similar changes across the codebase (BinaryLocator.ts, ImageOptimizer.ts, PathUtils.ts).
</blockquote></details>
<details>
<summary>src/converters/pdf/PdfCliExecutor.ts (1)</summary><blockquote>
`6-7`: **LGTM: Top-level imports adopted.**
The migration to top-level imports for `exec` and `promisify` follows best practices and aligns with the broader refactoring.
</blockquote></details>
<details>
<summary>package.json (1)</summary><blockquote>
`30-30`: **LGTM: Tooling and dependency updates.**
The additions support the broader refactoring objectives:
- `js-yaml` and `@types/js-yaml` enable YAML parsing capabilities
- Updated TypeScript ESLint packages (^8.46.3) provide improved linting
- `eslint` and `eslint-plugin-obsidianmd` enhance code quality checks
- `electron` supports development environment requirements
Also applies to: 32-34, 39-39, 41-42, 53-53
</blockquote></details>
<details>
<summary>src/plugin/SettingsTab.ts (2)</summary><blockquote>
`31-33`: **LGTM: Migrating to Setting API for headings.**
The change from static HTML to programmatic `Setting` components with `setHeading()` follows Obsidian's recommended API patterns and aligns with similar UI migrations across the codebase.
---
`52-54`: **LGTM: Consistent heading and text normalization.**
All section headings now use the `Setting` API with `setHeading()`, providing consistent UI structure. The button text change from "Check Dependencies" to "Check dependencies" maintains text consistency with other sections.
Also applies to: 61-61, 138-140, 238-240, 304-306, 376-378
</blockquote></details>
<details>
<summary>src/converters/pdf/BinaryLocator.ts (2)</summary><blockquote>
`6-6`: **LGTM!**
The top-level import of `fs.promises` aligns with the PR-wide pattern of replacing dynamic requires with static imports, improving bundling and maintainability.
---
`34-37`: **Good defensive programming!**
Throwing an error when `configDir` is undefined is the correct approach, as Obsidian's configuration directory can be user-configured and should not be hardcoded. The error is properly caught and returned as a descriptive error message in the `BinaryLocation` result.
</blockquote></details>
<details>
<summary>src/plugin/PluginLifecycle.ts (3)</summary><blockquote>
`54-59`: **LGTM!**
The explicit `void` wrapping correctly marks these as intentional fire-and-forget operations, satisfying the ESLint `@typescript-eslint/no-floating-promises` rule while maintaining the desired non-blocking startup behavior.
---
`72-80`: **Appropriate fire-and-forget cleanup pattern.**
The void-wrapped async IIFE correctly implements non-blocking cleanup during plugin unload, with proper error handling to prevent exceptions from disrupting the shutdown process.
---
`88-92`: **LGTM!**
The fire-and-forget startup cleanup correctly wraps the async operations with `void`, while properly awaiting the internal `cleanupAllTempDirs()` call to ensure cleanup completes before the IIFE exits.
</blockquote></details>
<details>
<summary>src/converters/pdf/ImageOptimizer.ts (1)</summary><blockquote>
`6-7`: **LGTM!**
The migration to top-level static imports for `child_process` and `fs` aligns with the PR-wide pattern of replacing dynamic requires, improving bundling efficiency and enabling better static analysis.
</blockquote></details>
<details>
<summary>src/plugin/EmbedProcessor.ts (3)</summary><blockquote>
`6-7`: **LGTM!**
The top-level imports for `exec` and `util` align with the PR-wide pattern and enable the promisified exec usage later in the file.
---
`113-113`: **Good logging hygiene!**
Switching to `console.debug` for download and remote image processing messages appropriately reduces console noise while maintaining observability for debugging. This aligns with the ESLint `no-console` rule that permits `debug`, `warn`, and `error`.
Also applies to: 125-125, 162-162, 300-300, 306-306
---
`348-349`: **LGTM!**
The promisified `exec` is correctly implemented using the top-level imported `util.promisify`, providing a cleaner promise-based interface for command execution.
</blockquote></details>
<details>
<summary>main.ts (3)</summary><blockquote>
`14-14`: **LGTM!**
The top-level `electron` shell import aligns with the PR-wide pattern of replacing dynamic requires with static imports.
---
`181-188`: **Consistent with DependencyChecker refactor.**
The signature change from `async` returning `Promise<void>` to synchronous returning `void` correctly aligns with the refactored `DependencyChecker.checkDependenciesAsync`, which now performs synchronous checks and shows notices only when dependencies are missing.
---
`216-216`: **LGTM!**
The `void` operator correctly marks the `shell.openPath` call as an intentional fire-and-forget operation, appropriate for launching an external PDF viewer.
</blockquote></details>
<details>
<summary>obsidianreviewbot-feedback.md (1)</summary><blockquote>
`1-191`: **Feedback documentation file.**
This file documents linting feedback and guidance for the PR. No code review is necessary as it serves as a reference for the changes made to address ESLint and Obsidian-specific plugin issues.
</blockquote></details>
<details>
<summary>eslint.config.mjs (2)</summary><blockquote>
`3-7`: **LGTM!**
The ESLint configuration correctly integrates the Obsidian plugin and follows the modern flat config pattern with appropriate base configurations for JavaScript and TypeScript.
Also applies to: 10-14
---
`37-98`: **Comprehensive and well-balanced rule configuration.**
The ESLint rules appropriately enforce Obsidian-specific best practices while downgrading strict type-checking rules to warnings for gradual adoption. The `@typescript-eslint/require-await: 'off'` setting explains why some async methods without await expressions are not flagged.
</blockquote></details>
<details>
<summary>src/ui/modal/sections/TypographySection.ts (2)</summary><blockquote>
`16-18`: **LGTM: Consistent heading style**
The migration from static HTML to Setting-based heading aligns with the broader UI consistency changes across modal sections.
---
`21-21`: **Review concerns are partially overstated but UX delay remains a valid consideration**
The code shows defensive implementations that mitigate the stated risks:
- **Empty dropdowns concern**: Font dropdowns won't be visible until `createFontSettings()` completes; they don't briefly appear empty. Font size controls (synchronous) ARE visible immediately, providing immediate UI feedback.
- **Race conditions**: The container null check at line 26 prevents errors if the modal closes before font loading completes.
- **State inconsistencies**: Same null check prevents state updates after modal closure.
However, a legitimate UX consideration remains: the three font dropdowns will have a visible delay before appearing, with no loading indicator to explain the UI gap. The fallback fonts (lines 134–146) ensure the dropdowns populate with reasonable defaults even if cache fails, but this doesn't address the initial delay.
This pattern is consistent throughout the codebase (`cacheAvailableFonts`, `loadAvailableTemplates`), suggesting it's intentional. Whether the delay is acceptable depends on typical cache availability and UX expectations—this warrants manual verification.
</blockquote></details>
<details>
<summary>src/ui/modal/sections/LayoutSection.ts (1)</summary><blockquote>
`16-18`: **LGTM: Consistent heading style**
The migration to Setting-based heading matches the pattern applied across other modal sections (GeneralSection, TypographySection, BehaviorSection, PageSetupSection) for UI consistency.
</blockquote></details>
<details>
<summary>src/core/PathUtils.ts (1)</summary><blockquote>
`4-4`: **LGTM: Cleaner import pattern while maintaining Obsidian API preference**
The change from dynamic `require` to top-level import is a good modernization. The fs module is only used as a fallback for absolute paths outside the vault (after trying Obsidian's vault adapter first), which aligns with the project's preference for Obsidian APIs.
Based on learnings.
Also applies to: 242-242
</blockquote></details>
<details>
<summary>src/core/ModalSettingsHelper.ts (1)</summary><blockquote>
`182-183`: **LGTM: Type-safe constant replaces magic string**
Replacing the string literal `'single-page'` with `ExportFormat.SinglePage` improves type safety and maintainability. This aligns with similar updates in PageSetupSection.ts.
</blockquote></details>
<details>
<summary>src/ui/modal/sections/PageSetupSection.ts (3)</summary><blockquote>
`17-19`: **LGTM: Consistent heading style**
Setting-based heading aligns with the UI consistency changes across all modal sections.
---
`59-66`: **LGTM: Type-safe format check and concise conditional spread**
The change from string comparison to `ExportFormat.SinglePage` constant improves type safety. The conditional spread pattern cleanly handles the width adjustment for landscape single-page mode.
---
`75-75`: **LGTM: Sentence case aligns with UI guidelines**
The change from "Text Margins" to "Text margins" follows sentence-case conventions for subheadings, consistent with modern UI design patterns.
</blockquote></details>
<details>
<summary>styles.css (1)</summary><blockquote>
`138-356`: **LGTM: Well-structured modal styles with theme compatibility**
The new styles for the export configuration modal follow good practices:
- Uses Obsidian CSS variables for theme compatibility
- Provides clear visual hierarchy with appropriate spacing
- Includes accessible focus states for interactive elements
- Uses flexbox for responsive layout
- Properly scopes classes with `export-` prefix to avoid conflicts
The styles integrate cleanly without modifying existing rules.
</blockquote></details>
<details>
<summary>src/converters/MarkdownPreprocessor.ts (1)</summary><blockquote>
`331-331`: **No action required—all call sites correctly updated**
Verification confirms the method signature change from async to sync is complete and correct. The single call site in `ExportOrchestrator.ts` at line 182 properly invokes `preprocessor.process(content)` synchronously without `await`. No other instantiations or usages exist in the codebase.
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
The configuration correctly uses projectService with import.meta.dirname for TypeScript parser configuration. Note that import.meta.dirname requires Node.js 20.11+ or a polyfill in earlier versions.
Verify that the project's minimum Node.js version supports import.meta.dirname:
🏁 Script executed:
#!/bin/bash
# Check package.json for Node.js version requirementsif[ -f package.json ];thenecho"=== Checking Node.js version requirements ==="
jq -r '.engines.node // "Not specified"' package.json
fi
Length of output: 59
🏁 Script executed:
#!/bin/bash
# Check for Node.js version specification filesecho"=== Checking for version specification files ==="
fd -e nvmrc -e tool-versions | head -20
echo""echo"=== Checking README for Node.js version info ==="if[ -f README.md ];then
grep -i "node.*version\|node.*20\|node.*18" README.md | head -10
fiecho""echo"=== Checking GitHub Actions or CI configs for Node.js version ==="
fd -e yml -e yaml | xargs grep -l "node-version\|node_version" 2>/dev/null | head -5
Length of output: 210
Node.js version incompatibility with import.meta.dirname.
The code uses import.meta.dirname (line 31), which requires Node.js 20.11+ or 18.20+. However, the README specifies "Node.js: Version 16+" for development, creating a compatibility gap. Developers on Node.js 16 or 17.x versions cannot run this configuration.
Update the minimum Node.js version requirement to 18.20+ or 20.11+ in README.md and package.json, or replace import.meta.dirname with an alternative that supports Node.js 16+ (e.g., dirname(fileURLToPath(import.meta.url))).
🤖 Prompt for AI Agents
In eslint.config.mjs around lines 18 to 33 the config uses import.meta.dirname
which requires Node 18.20+/20.11+, causing incompatibility with the project's
stated minimum Node 16; either update the project's minimum Node version in
README.md and package.json to 18.20+ (or 20.11+) so import.meta.dirname is
supported, or replace import.meta.dirname with a Node-16-compatible alternative:
import { fileURLToPath } from 'url' and import { dirname } from 'path' then
derive tsconfigRootDir via dirname(fileURLToPath(import.meta.url)); make the
chosen change consistently (update docs, package.json engines if bumping Node)
and run lint to verify the config loads correctly.
_⚠️ Potential issue_ | _🔴 Critical_
<details>
<summary>🧩 Analysis chain</summary>
**Modern ESLint configuration pattern.**
The configuration correctly uses `projectService` with `import.meta.dirname` for TypeScript parser configuration. Note that `import.meta.dirname` requires Node.js 20.11+ or a polyfill in earlier versions.
Verify that the project's minimum Node.js version supports `import.meta.dirname`:
---
🏁 Script executed:
```shell
#!/bin/bash
# Check package.json for Node.js version requirements
if [ -f package.json ]; then
echo "=== Checking Node.js version requirements ==="
jq -r '.engines.node // "Not specified"' package.json
fi
```
Length of output: 59
---
🏁 Script executed:
```shell
#!/bin/bash
# Check for Node.js version specification files
echo "=== Checking for version specification files ==="
fd -e nvmrc -e tool-versions | head -20
echo ""
echo "=== Checking README for Node.js version info ==="
if [ -f README.md ]; then
grep -i "node.*version\|node.*20\|node.*18" README.md | head -10
fi
echo ""
echo "=== Checking GitHub Actions or CI configs for Node.js version ==="
fd -e yml -e yaml | xargs grep -l "node-version\|node_version" 2>/dev/null | head -5
```
Length of output: 210
---
</details>
**Node.js version incompatibility with `import.meta.dirname`.**
The code uses `import.meta.dirname` (line 31), which requires Node.js 20.11+ or 18.20+. However, the README specifies "Node.js: Version 16+" for development, creating a compatibility gap. Developers on Node.js 16 or 17.x versions cannot run this configuration.
Update the minimum Node.js version requirement to 18.20+ or 20.11+ in README.md and package.json, or replace `import.meta.dirname` with an alternative that supports Node.js 16+ (e.g., `dirname(fileURLToPath(import.meta.url))`).
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In eslint.config.mjs around lines 18 to 33 the config uses import.meta.dirname
which requires Node 18.20+/20.11+, causing incompatibility with the project's
stated minimum Node 16; either update the project's minimum Node version in
README.md and package.json to 18.20+ (or 20.11+) so import.meta.dirname is
supported, or replace import.meta.dirname with a Node-16-compatible alternative:
import { fileURLToPath } from 'url' and import { dirname } from 'path' then
derive tsconfigRootDir via dirname(fileURLToPath(import.meta.url)); make the
chosen change consistently (update docs, package.json engines if bumping Node)
and run lint to verify the config loads correctly.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
Fire-and-forget cleanup won't complete on process termination.
Process event handlers like 'exit', 'SIGINT', and 'SIGTERM' are synchronous and terminate immediately without waiting for promises. Calling void this.cleanup() means the async file removal operations in cleanup() (line 340) will likely not complete before the process exits, leaving temporary files behind.
Consider using Obsidian's plugin lifecycle methods (onunload) for cleanup instead of Node.js process events, as plugin unload hooks are better suited for async cleanup operations.
Apply this diff to document the limitation:
this.processCleanupHandler = () => {
// Only cleanup if not already disposed to avoid double-cleanup
if (!this.isDisposed) {
+ // Note: Async cleanup may not complete before process exit
void this.cleanup();
}
};
🤖 Prompt for AI Agents
In src/converters/PandocTypstConverter.ts around line 302, the code calls void
this.cleanup() from process event handlers which is fire-and-forget and will not
complete on process termination; replace these process-level handlers with the
plugin lifecycle unload hook (onunload) so cleanup() can be awaited and finish
async file removals, or if you must keep process handlers, make them synchronous
by performing sync removal or spawn a blocking cleanup before exit; remove or
stop using void this.cleanup() in process events and register/await cleanup
inside the plugin's onunload handler instead.
_⚠️ Potential issue_ | _🟠 Major_
**Fire-and-forget cleanup won't complete on process termination.**
Process event handlers like 'exit', 'SIGINT', and 'SIGTERM' are synchronous and terminate immediately without waiting for promises. Calling `void this.cleanup()` means the async file removal operations in `cleanup()` (line 340) will likely not complete before the process exits, leaving temporary files behind.
Consider using Obsidian's plugin lifecycle methods (`onunload`) for cleanup instead of Node.js process events, as plugin unload hooks are better suited for async cleanup operations.
Apply this diff to document the limitation:
```diff
this.processCleanupHandler = () => {
// Only cleanup if not already disposed to avoid double-cleanup
if (!this.isDisposed) {
+ // Note: Async cleanup may not complete before process exit
void this.cleanup();
}
};
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/converters/PandocTypstConverter.ts around line 302, the code calls void
this.cleanup() from process event handlers which is fire-and-forget and will not
complete on process termination; replace these process-level handlers with the
plugin lifecycle unload hook (onunload) so cleanup() can be awaited and finish
async file removals, or if you must keep process handlers, make them synchronous
by performing sync removal or spawn a blocking cleanup before exit; remove or
stop using void this.cleanup() in process events and register/await cleanup
inside the plugin's onunload handler instead.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
Provide default value for potentially undefined configDir.
Lines 367 and 374 use optional chaining that can result in undefined, but TempDirectoryManager.create() (line 368) and the TempDirectoryManager constructor (line 375) expect configDir: string according to the relevant code snippets. Passing undefined will cause type errors or runtime failures in path resolution.
In src/converters/PandocTypstConverter.ts around lines 367-368 and 374-375,
optional chaining is allowing configDir to be undefined but
TempDirectoryManager.create()/constructor require a string; update the calls to
supply a safe string fallback when configDir is undefined (for example use a
sensible default path or the empty string) so the argument is always a string;
ensure you compute a local const configDirStr =
(this.plugin?.app?.vault?.configDir ?? '<fallback>') and pass configDirStr into
TempDirectoryManager.create() and the TempDirectoryManager constructor to
satisfy types and avoid runtime path errors.
_⚠️ Potential issue_ | _🔴 Critical_
**Provide default value for potentially undefined configDir.**
Lines 367 and 374 use optional chaining that can result in `undefined`, but `TempDirectoryManager.create()` (line 368) and the `TempDirectoryManager` constructor (line 375) expect `configDir: string` according to the relevant code snippets. Passing `undefined` will cause type errors or runtime failures in path resolution.
Restore the default value to ensure type safety:
Apply this diff:
```diff
- const configDir = this.plugin?.app?.vault?.configDir;
+ const configDir = this.plugin?.app?.vault?.configDir ?? '.obsidian';
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
```
```diff
- const configDir = this.plugin?.app?.vault?.configDir;
+ const configDir = this.plugin?.app?.vault?.configDir ?? '.obsidian';
const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app });
```
Also applies to: 374-375
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/converters/PandocTypstConverter.ts around lines 367-368 and 374-375,
optional chaining is allowing configDir to be undefined but
TempDirectoryManager.create()/constructor require a string; update the calls to
supply a safe string fallback when configDir is undefined (for example use a
sensible default path or the empty string) so the argument is always a string;
ensure you compute a local const configDirStr =
(this.plugin?.app?.vault?.configDir ?? '<fallback>') and pass configDirStr into
TempDirectoryManager.create() and the TempDirectoryManager constructor to
satisfy types and avoid runtime path errors.
```
</details>
<!-- This is an auto-generated reply by CodeRabbit -->
Remove raw-content logging from diagnostics.
These new console.debug/console.error statements dump the first 200–500 characters of user notes directly to the developer console. Even in debug builds this is sensitive content (frontmatter often includes titles, tags, authors, etc.), so shipping this logging materially increases the risk of leaking private vault data. Please strip the raw-content logging (or gate it behind an explicit opt-in) before release.
Also applies to: 152-154
🤖 Prompt for AI Agents
In src/converters/preprocessors/FrontmatterProcessor.ts around lines 49-51 (and
likewise remove similar logging at 152-154), remove the console.debug calls that
print the raw content snippet to avoid leaking sensitive user data; instead
either delete those debug statements entirely or replace them with non-sensitive
diagnostics (e.g., log only that frontmatter was detected and the content length
or a redacted/hashed preview), and if you need full-content logging keep it
strictly behind an explicit opt-in debug flag or environment variable checked
before printing.
_⚠️ Potential issue_ | _🟠 Major_
**Remove raw-content logging from diagnostics.**
These new `console.debug`/`console.error` statements dump the first 200–500 characters of user notes directly to the developer console. Even in debug builds this is sensitive content (frontmatter often includes titles, tags, authors, etc.), so shipping this logging materially increases the risk of leaking private vault data. Please strip the raw-content logging (or gate it behind an explicit opt-in) before release.
Also applies to: 152-154
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/converters/preprocessors/FrontmatterProcessor.ts around lines 49-51 (and
likewise remove similar logging at 152-154), remove the console.debug calls that
print the raw content snippet to avoid leaking sensitive user data; instead
either delete those debug statements entirely or replace them with non-sensitive
diagnostics (e.g., log only that frontmatter was detected and the content length
or a redacted/hashed preview), and if you need full-content logging keep it
strictly behind an explicit opt-in debug flag or environment variable checked
before printing.
```
</details>
<!-- fingerprinting:phantom:medusa:sabertoothed -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
Align logLevel parameter with actual logging behavior.
The logLevel parameter accepts 'info' per the interface definition (line 46), but the implementation now uses console.debug() instead of console.info(). This creates a semantic mismatch where callers specify 'info' but receive debug-level logging.
Consider one of these options:
Revert to console.info() if info-level logging is the intended behavior, OR
Update the interface to accept 'debug' instead of 'info' to match the implementation
Option 1: Revert to console.info
case 'info':
- console.debug(`${operation}:`, error);
+ console.info(`${operation}:`, error);
break;
‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
case 'info':
console.info(`${operation}:`, error);
break;
🤖 Prompt for AI Agents
In src/core/ExportErrorHandler.ts around lines 183 to 185, the method accepts a
logLevel of 'info' per the interface but calls console.debug(), creating a
mismatch; either change the implementation to call console.info() to match the
declared 'info' logLevel, or update the interface and any docs to accept 'debug'
(replace 'info' with 'debug' where the type/interface and comments mention it)
and ensure all callers using 'info' are updated to 'debug' or adjusted
accordingly.
_⚠️ Potential issue_ | _🟡 Minor_
**Align logLevel parameter with actual logging behavior.**
The `logLevel` parameter accepts `'info'` per the interface definition (line 46), but the implementation now uses `console.debug()` instead of `console.info()`. This creates a semantic mismatch where callers specify `'info'` but receive debug-level logging.
Consider one of these options:
1. **Revert to `console.info()`** if info-level logging is the intended behavior, OR
2. **Update the interface** to accept `'debug'` instead of `'info'` to match the implementation
**Option 1: Revert to console.info**
```diff
case 'info':
- console.debug(`${operation}:`, error);
+ console.info(`${operation}:`, error);
break;
```
**Option 2: Update interface and documentation**
```diff
export interface ExportError {
fileName?: string;
operation: string;
error: Error | string;
shouldShowNotice?: boolean;
- logLevel?: 'error' | 'warn' | 'info';
+ logLevel?: 'error' | 'warn' | 'debug';
}
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
case 'info':
console.info(`${operation}:`, error);
break;
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/core/ExportErrorHandler.ts around lines 183 to 185, the method accepts a
logLevel of 'info' per the interface but calls console.debug(), creating a
mismatch; either change the implementation to call console.info() to match the
declared 'info' logLevel, or update the interface and any docs to accept 'debug'
(replace 'info' with 'debug' where the type/interface and comments mention it)
and ensure all callers using 'info' are updated to 'debug' or adjusted
accordingly.
```
</details>
<!-- This is an auto-generated reply by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
<!-- This is an auto-generated comment by CodeRabbit -->
Error handling should notify users, not just log to console
When a user-initiated command fails, logging to console provides no feedback to the user. They won't know why the export didn't happen. Consider showing a Notice with the error message so users understand what went wrong.
Apply this pattern for user-facing error handling:
- this.plugin.exportCurrentNote(view).catch(error => {
- console.error('Failed to export current note:', error);
- });
+ this.plugin.exportCurrentNote(view).catch(error => {
+ console.error('Failed to export current note:', error);
+ new Notice(`Export failed: ${error.message}`);
+ });
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/plugin/CommandRegistry.ts around lines 21 to 23, the catch currently only
logs the error to console which gives no user feedback; instead import and use
Obsidian's Notice to show a user-facing message (e.g., new Notice(`Failed to
export current note: ${error?.message ?? String(error)}`)) and optionally retain
console.error for debugging; ensure Notice is imported from 'obsidian' and that
the error is safely stringified so users see a readable explanation.
_⚠️ Potential issue_ | _🟠 Major_
**Error handling should notify users, not just log to console**
When a user-initiated command fails, logging to console provides no feedback to the user. They won't know why the export didn't happen. Consider showing a Notice with the error message so users understand what went wrong.
Apply this pattern for user-facing error handling:
```diff
- this.plugin.exportCurrentNote(view).catch(error => {
- console.error('Failed to export current note:', error);
- });
+ this.plugin.exportCurrentNote(view).catch(error => {
+ console.error('Failed to export current note:', error);
+ new Notice(`Export failed: ${error.message}`);
+ });
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/plugin/CommandRegistry.ts around lines 21 to 23, the catch currently only
logs the error to console which gives no user feedback; instead import and use
Obsidian's Notice to show a user-facing message (e.g., new Notice(`Failed to
export current note: ${error?.message ?? String(error)}`)) and optionally retain
console.error for debugging; ensure Notice is imported from 'obsidian' and that
the error is safely stringified so users see a readable explanation.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
Error handling should notify users, not just log to console
Similar to the export command, users should be notified when the modal fails to open rather than failing silently.
- this.plugin.showExportModal(view).catch(error => {
- console.error('Failed to show export modal:', error);
- });
+ this.plugin.showExportModal(view).catch(error => {
+ console.error('Failed to show export modal:', error);
+ new Notice(`Failed to open export dialog: ${error.message}`);
+ });
📝 Committable suggestion
‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
this.plugin.showExportModal(view).catch(error => {
console.error('Failed to show export modal:', error);
new Notice(`Failed to open export dialog: ${error.message}`);
});
🤖 Prompt for AI Agents
In src/plugin/CommandRegistry.ts around lines 32–34, the catch block for
this.plugin.showExportModal currently only logs to console; change it to notify
the user via the app notification system and include error details (e.g., call
this.plugin.app.notifications.create or create a Notice with a clear message
like "Failed to open export modal" plus the error message), while optionally
still logging the error for debugging. Ensure the notification is user-friendly,
includes the error text, and preserves the promise chain by keeping the .catch
handler.
_⚠️ Potential issue_ | _🟠 Major_
**Error handling should notify users, not just log to console**
Similar to the export command, users should be notified when the modal fails to open rather than failing silently.
```diff
- this.plugin.showExportModal(view).catch(error => {
- console.error('Failed to show export modal:', error);
- });
+ this.plugin.showExportModal(view).catch(error => {
+ console.error('Failed to show export modal:', error);
+ new Notice(`Failed to open export dialog: ${error.message}`);
+ });
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
this.plugin.showExportModal(view).catch(error => {
console.error('Failed to show export modal:', error);
new Notice(`Failed to open export dialog: ${error.message}`);
});
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/plugin/CommandRegistry.ts around lines 32–34, the catch block for
this.plugin.showExportModal currently only logs to console; change it to notify
the user via the app notification system and include error details (e.g., call
this.plugin.app.notifications.create or create a Notice with a clear message
like "Failed to open export modal" plus the error message), while optionally
still logging the error for debugging. Ensure the notification is user-friendly,
includes the error text, and preserves the promise chain by keeping the .catch
handler.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
Error handling should notify users, not just log to console
The dependency status check is a user-initiated command and should show errors via Notice.
- this.plugin.showDependencyStatus().catch(error => {
- console.error('Failed to show dependency status:', error);
- });
+ this.plugin.showDependencyStatus().catch(error => {
+ console.error('Failed to show dependency status:', error);
+ new Notice(`Failed to check dependencies: ${error.message}`);
+ });
Note: You'll need to import Notice from 'obsidian' at the top of the file.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/plugin/CommandRegistry.ts around lines 43-45, the catch currently only
logs errors to the console; import Notice from 'obsidian' at the top of the file
and replace the console.error call with a user-facing notification (e.g. new
Notice(`Failed to show dependency status: ${error?.message || error}`)); you may
still log the full error to console for debugging, but ensure the user sees the
Notice so the command surfaces failures to the UI.
_⚠️ Potential issue_ | _🟠 Major_
**Error handling should notify users, not just log to console**
The dependency status check is a user-initiated command and should show errors via Notice.
```diff
- this.plugin.showDependencyStatus().catch(error => {
- console.error('Failed to show dependency status:', error);
- });
+ this.plugin.showDependencyStatus().catch(error => {
+ console.error('Failed to show dependency status:', error);
+ new Notice(`Failed to check dependencies: ${error.message}`);
+ });
```
Note: You'll need to import `Notice` from 'obsidian' at the top of the file.
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/plugin/CommandRegistry.ts around lines 43-45, the catch currently only
logs errors to the console; import Notice from 'obsidian' at the top of the file
and replace the console.error call with a user-facing notification (e.g. new
Notice(`Failed to show dependency status: ${error?.message || error}`)); you may
still log the full error to console for debugging, but ensure the user sees the
Notice so the command surfaces failures to the UI.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
@coderabbitai ObsidianReviewBot specifically has an issue with this:
Obsidian's configuration folder is not necessarily .obsidian, it can be configured by the user. Use Vault#configDir to get the current value
@coderabbitai ObsidianReviewBot specifically has an issue with this:
> Obsidian's configuration folder is not necessarily .obsidian, it can be configured by the user. Use Vault#configDir to get the current value
#!/bin/bash
# Find TempDirectoryManager class definition and check its constructor/create method signatures
ast-grep --pattern $'class TempDirectoryManager {
$$$
}'
echo "=== Searching for TempDirectoryManager.create method ==="
ast-grep --pattern $'static create($$$) {
$$$
}'
echo "=== Searching for TempDirectoryManager constructor ==="
ast-grep --pattern $'constructor($$$) {
$$$
}'
echo "=== Using rg to find TempDirectoryManager definition ==="
rg -A 30 "class TempDirectoryManager" --type ts
Length of output: 26660
@AlexKucera You're absolutely right! The ObsidianReviewBot feedback is correct — we shouldn't hardcode .obsidian as a fallback since users can configure a different config directory.
Looking at the pattern already established in your codebase (specifically in BinaryLocator.ts from the AI summary), the proper solution is to throw an error when configDir cannot be accessed rather than falling back to a hardcoded value.
Here's the corrected approach:
privateasyncensureTempDirectory():Promise<string>{if(!this.tempDir){if(this.pandocOptions.vaultBasePath){// Use TempDirectoryManager for plugin temp directories
constconfigDir=this.plugin?.app?.vault?.configDir;if(!configDir){thrownewError('Unable to access vault configuration directory. Plugin may not be properly initialized.');}consttempManager=TempDirectoryManager.create(this.pandocOptions.vaultBasePath,configDir,undefined,this.plugin?.app);this.tempDir=awaittempManager.ensureTempDir('pandoc');}else{// Fallback to system temp if plugin folder not available
constpathUtils=newPathUtils(this.plugin.app);constvaultPath=pathUtils.getVaultPath();constconfigDir=this.plugin?.app?.vault?.configDir;if(!configDir){thrownewError('Unable to access vault configuration directory. Plugin may not be properly initialized.');}consttempManager=newTempDirectoryManager({vaultPath,configDir,app: this.plugin.app});this.tempDir=awaittempManager.ensureTempDir('pandoc');}}returnthis.tempDir;}
This approach:
✅ Respects the user's configured config directory by using vault.configDir
✅ Doesn't hardcode .obsidian
✅ Follows the existing pattern in BinaryLocator.ts
✅ Provides a clear error message if the vault isn't accessible
✅ Satisfies TypeScript's type checking for TempDirectoryManager
The error throw is appropriate here because if the plugin/app/vault isn't accessible, something is fundamentally wrong with the initialization, and the conversion can't proceed safely anyway.
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
<details>
<summary>🧩 Analysis chain</summary>
🏁 Script executed:
```
#!/bin/bash
# Find TempDirectoryManager class definition and check its constructor/create method signatures
ast-grep --pattern $'class TempDirectoryManager {
$$$
}'
echo "=== Searching for TempDirectoryManager.create method ==="
ast-grep --pattern $'static create($$$) {
$$$
}'
echo "=== Searching for TempDirectoryManager constructor ==="
ast-grep --pattern $'constructor($$$) {
$$$
}'
echo "=== Using rg to find TempDirectoryManager definition ==="
rg -A 30 "class TempDirectoryManager" --type ts
```
Length of output: 26660
---
</details>
@AlexKucera You're absolutely right! The ObsidianReviewBot feedback is correct — we shouldn't hardcode `.obsidian` as a fallback since users can configure a different config directory.
Looking at the pattern already established in your codebase (specifically in `BinaryLocator.ts` from the AI summary), the proper solution is to **throw an error when `configDir` cannot be accessed** rather than falling back to a hardcoded value.
Here's the corrected approach:
```typescript
private async ensureTempDirectory(): Promise<string> {
if (!this.tempDir) {
if (this.pandocOptions.vaultBasePath) {
// Use TempDirectoryManager for plugin temp directories
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);
this.tempDir = await tempManager.ensureTempDir('pandoc');
} else {
// Fallback to system temp if plugin folder not available
const pathUtils = new PathUtils(this.plugin.app);
const vaultPath = pathUtils.getVaultPath();
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 });
this.tempDir = await tempManager.ensureTempDir('pandoc');
}
}
return this.tempDir;
}
```
This approach:
1. ✅ Respects the user's configured config directory by using `vault.configDir`
2. ✅ Doesn't hardcode `.obsidian`
3. ✅ Follows the existing pattern in `BinaryLocator.ts`
4. ✅ Provides a clear error message if the vault isn't accessible
5. ✅ Satisfies TypeScript's type checking for `TempDirectoryManager`
The error throw is appropriate here because if the plugin/app/vault isn't accessible, something is fundamentally wrong with the initialization, and the conversion can't proceed safely anyway.
---
<details>
<summary>🧬 Code Graph Analysis Results</summary>
[src/converters/PandocTypstConverter.ts] ensureTempDirectory - snippet
- File: src/converters/PandocTypstConverter.ts
- Context: Method that creates a temporary directory for conversion, using Vault configDir to locate plugin temp space.
const configDir = this.plugin?.app?.vault?.configDir;
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
this.tempDir = await tempManager.ensureTempDir('pandoc');
[src/core/TempDirectoryManager.ts] getPluginDir - snippet
- File: src/core/TempDirectoryManager.ts
- Context: Internal helper that computes the absolute path to the plugin directory within the vault, using vaultPath, configDir, and pluginName.
private getPluginDir(): string {
// path.join automatically handles absolute paths correctly
const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
return normalizePath(result);
}
</details>
---
<details>
<summary>🧠 Learnings used</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
```
</details>
<!-- <agentComponentType>chat-answer</agentComponentType> -->
<!-- <rawResChunk><answer><details>
<summary>🧩 Analysis chain</summary>
🏁 Script executed:
```
#!/bin/bash
# Find TempDirectoryManager class definition and check its constructor/create method signatures
ast-grep --pattern $'class TempDirectoryManager {
$$$
}'
echo "=== Searching for TempDirectoryManager.create method ==="
ast-grep --pattern $'static create($$$) {
$$$
}'
echo "=== Searching for TempDirectoryManager constructor ==="
ast-grep --pattern $'constructor($$$) {
$$$
}'
echo "=== Using rg to find TempDirectoryManager definition ==="
rg -A 30 "class TempDirectoryManager" --type ts
```
Length of output: 26660
---
</details>
@AlexKucera You're absolutely right! The ObsidianReviewBot feedback is correct — we shouldn't hardcode `.obsidian` as a fallback since users can configure a different config directory.
Looking at the pattern already established in your codebase (specifically in `BinaryLocator.ts` from the AI summary), the proper solution is to **throw an error when `configDir` cannot be accessed** rather than falling back to a hardcoded value.
Here's the corrected approach:
```typescript
private async ensureTempDirectory(): Promise<string> {
if (!this.tempDir) {
if (this.pandocOptions.vaultBasePath) {
// Use TempDirectoryManager for plugin temp directories
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);
this.tempDir = await tempManager.ensureTempDir('pandoc');
} else {
// Fallback to system temp if plugin folder not available
const pathUtils = new PathUtils(this.plugin.app);
const vaultPath = pathUtils.getVaultPath();
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 });
this.tempDir = await tempManager.ensureTempDir('pandoc');
}
}
return this.tempDir;
}
```
This approach:
1. ✅ Respects the user's configured config directory by using `vault.configDir`
2. ✅ Doesn't hardcode `.obsidian`
3. ✅ Follows the existing pattern in `BinaryLocator.ts`
4. ✅ Provides a clear error message if the vault isn't accessible
5. ✅ Satisfies TypeScript's type checking for `TempDirectoryManager`
The error throw is appropriate here because if the plugin/app/vault isn't accessible, something is fundamentally wrong with the initialization, and the conversion can't proceed safely anyway.
---
<details>
<summary>🧬 Code Graph Analysis Results</summary>
[src/converters/PandocTypstConverter.ts] ensureTempDirectory - snippet
- File: src/converters/PandocTypstConverter.ts
- Context: Method that creates a temporary directory for conversion, using Vault configDir to locate plugin temp space.
const configDir = this.plugin?.app?.vault?.configDir;
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
this.tempDir = await tempManager.ensureTempDir('pandoc');
[src/core/TempDirectoryManager.ts] getPluginDir - snippet
- File: src/core/TempDirectoryManager.ts
- Context: Internal helper that computes the absolute path to the plugin directory within the vault, using vaultPath, configDir, and pluginName.
private getPluginDir(): string {
// path.join automatically handles absolute paths correctly
const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
return normalizePath(result);
}
</details>
---
<details>
<summary>🧠 Learnings used</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
```
</details>
</answer></rawResChunk> -->
<!-- This is an auto-generated reply by CodeRabbit -->
#!/bin/bash
# Search for any code using logLevel with 'info' value
rg -n "logLevel.*['\"]info['\"]" --type ts
Length of output: 72
🏁 Script executed:
#!/bin/bash
# Also search for the ExportError interface usage to find all places where logLevel might be specified
rg -n "ExportError|handleExportError" --type ts -C3
Length of output: 28847
@AlexKucera, thank you for clarifying! That makes sense—ObsidianReviewBot's restriction to only console.warn, console.error, and console.debug means we need to align the interface with the implementation.
Since no code in the codebase is currently using logLevel: 'info' (confirmed by the search), you only need to update:
Line 46 - Update the ExportError interface:
logLevel?:'error'|'warn'|'debug';
Line 39 - Update the JSDoc comment above the interface:
(This is fine as-is, but you could optionally clarify it accepts 'error' | 'warn' | 'debug')
Line 165 in the example comment, change:
*logLevel:'warn'
to remain as 'warn' (already correct), but the comment text that mentions "info" in the example doesn't exist, so you're good there.
The change from console.info() to console.debug() is the right approach given the ObsidianReviewBot constraint. Just update the interface definition to match! 🎯
🧬 Code Graph Analysis Results
tests/mocks/obsidian.ts
At lines 4-6:
```
export class Notice {
constructor(message: string) {}
}
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
<details>
<summary>🧩 Analysis chain</summary>
🏁 Script executed:
```
#!/bin/bash
# Search for any code using logLevel with 'info' value
rg -n "logLevel.*['\"]info['\"]" --type ts
```
Length of output: 72
---
🏁 Script executed:
```
#!/bin/bash
# Also search for the ExportError interface usage to find all places where logLevel might be specified
rg -n "ExportError|handleExportError" --type ts -C3
```
Length of output: 28847
---
</details>
@AlexKucera, thank you for clarifying! That makes sense—ObsidianReviewBot's restriction to only `console.warn`, `console.error`, and `console.debug` means we need to align the interface with the implementation.
Since no code in the codebase is currently using `logLevel: 'info'` (confirmed by the search), you only need to update:
1. **Line 46** - Update the `ExportError` interface:
```typescript
logLevel?: 'error' | 'warn' | 'debug';
```
2. **Line 39** - Update the JSDoc comment above the interface:
```typescript
* @property logLevel - Logging severity level (default: 'error')
```
(This is fine as-is, but you could optionally clarify it accepts 'error' | 'warn' | 'debug')
3. **Line 165** in the example comment, change:
```typescript
* logLevel: 'warn'
```
to remain as 'warn' (already correct), but the comment text that mentions "info" in the example doesn't exist, so you're good there.
The change from `console.info()` to `console.debug()` is the right approach given the ObsidianReviewBot constraint. Just update the interface definition to match! 🎯
---
<details>
<summary>🧬 Code Graph Analysis Results</summary>
<filename>tests/__mocks__/obsidian.ts</filename>
<snippet>
At lines 4-6:
```
export class Notice {
constructor(message: string) {}
}
```
</snippet>
<filename>src/core/constants.ts</filename>
<snippet>
At lines 122-128:
```
export const EXPORT_CONSTANTS = {
DEFAULT_TIMEOUT: 120000, // 2 minutes
NOTICE_DURATION: {
SHORT: 5000,
LONG: 12000
}
} as const;
```
</snippet>
</details>
---
<details>
<summary>✏️ Learnings added</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
```
> Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings).
</details>
<!-- <agentComponentType>chat-answer</agentComponentType> -->
<!-- <rawResChunk><answer><details>
<summary>🧩 Analysis chain</summary>
🏁 Script executed:
```
#!/bin/bash
# Search for any code using logLevel with 'info' value
rg -n "logLevel.*['\"]info['\"]" --type ts
```
Length of output: 72
---
🏁 Script executed:
```
#!/bin/bash
# Also search for the ExportError interface usage to find all places where logLevel might be specified
rg -n "ExportError|handleExportError" --type ts -C3
```
Length of output: 28847
---
</details>
@AlexKucera, thank you for clarifying! That makes sense—ObsidianReviewBot's restriction to only `console.warn`, `console.error`, and `console.debug` means we need to align the interface with the implementation.
Since no code in the codebase is currently using `logLevel: 'info'` (confirmed by the search), you only need to update:
1. **Line 46** - Update the `ExportError` interface:
```typescript
logLevel?: 'error' | 'warn' | 'debug';
```
2. **Line 39** - Update the JSDoc comment above the interface:
```typescript
* @property logLevel - Logging severity level (default: 'error')
```
(This is fine as-is, but you could optionally clarify it accepts 'error' | 'warn' | 'debug')
3. **Line 165** in the example comment, change:
```typescript
* logLevel: 'warn'
```
to remain as 'warn' (already correct), but the comment text that mentions "info" in the example doesn't exist, so you're good there.
The change from `console.info()` to `console.debug()` is the right approach given the ObsidianReviewBot constraint. Just update the interface definition to match! 🎯
---
<details>
<summary>🧬 Code Graph Analysis Results</summary>
<filename>tests/__mocks__/obsidian.ts</filename>
<snippet>
At lines 4-6:
```
export class Notice {
constructor(message: string) {}
}
```
</snippet>
<filename>src/core/constants.ts</filename>
<snippet>
At lines 122-128:
```
export const EXPORT_CONSTANTS = {
DEFAULT_TIMEOUT: 120000, // 2 minutes
NOTICE_DURATION: {
SHORT: 5000,
LONG: 12000
}
} as const;
```
</snippet>
</details>
---
<details>
<summary>✏️ Learnings added</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
```
> Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings).
</details>
</answer></rawResChunk> -->
<!-- This is an auto-generated reply by CodeRabbit -->
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/plugin/PathResolver.ts (1)
11-11: Add a dirname method to PathUtils and use it in PathResolver instead of importing Node.js path directly.
PathUtils does not currently provide a dirname equivalent method. Line 81 in PathResolver.ts uses path.dirname(file.path) after importing Node.js path module. This violates the project preference to avoid direct Node.js imports.
Since PathUtils already centralizes path operations and uses the Node.js path module internally, add a dirname method to PathUtils (following the same pattern as joinPath) and update PathResolver to use it instead of the direct import.
Also applies to: 11-11
♻️ Duplicate comments (7)
eslint.config.mjs (1)
23-33: Critical: Node.js version incompatibility persists.
The past review flagged that import.meta.dirname (line 31) requires Node.js 20.11+ or 18.20+, creating incompatibility with the project's documented Node.js 16+ minimum. This issue remains unresolved.
You must either:
Update README.md and package.json to require Node.js 18.20+ or 20.11+, or
Replace import.meta.dirname with a Node-16-compatible alternative:
49-50: CRITICAL: Remove raw content logging to prevent data leakage.
These debug statements log the first 200 characters of user vault content, which can contain sensitive information like titles, tags, authors, and other PII. This was flagged in a previous review but remains unaddressed.
Apply this diff to remove the sensitive logging:
- console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
- console.debug('First 200 chars:', content.substring(0, 200));
+ console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
If you need diagnostics, log non-sensitive metadata like content length:
152-154: CRITICAL: Remove raw content logging from error path.
The error handler logs the first 500 characters of vault content, which presents the same privacy risk as the debug logging above. This was also flagged in the previous review.
21-45: Error handling still needs user-facing notifications.
All three command error handlers only log to console, providing no feedback to users when commands fail. This was flagged in previous reviews but remains unaddressed.
Import Notice from 'obsidian' and update all three error handlers:
+import { Editor, MarkdownView, Notice } from 'obsidian';
-import { Editor, MarkdownView } from 'obsidian';
this.plugin.exportCurrentNote(view).catch(error => {
console.error('Failed to export current note:', error);
+ new Notice(`Export failed: ${error?.message ?? 'Unknown error'}`);
});
this.plugin.showExportModal(view).catch(error => {
console.error('Failed to show export modal:', error);
+ new Notice(`Failed to open export dialog: ${error?.message ?? 'Unknown error'}`);
});
this.plugin.showDependencyStatus().catch(error => {
console.error('Failed to show dependency status:', error);
+ new Notice(`Failed to check dependencies: ${error?.message ?? 'Unknown error'}`);
});
All six error handlers only log to console, giving users no feedback when operations fail.
Import Notice and add user notifications in each .catch() block. For example:
this.plugin.exportFile(file).catch(error => {
console.error('Failed to export file:', error);
+ new Notice(`Export failed: ${error?.message ?? 'Unknown error'}`);
});
Apply similar patterns to all other .catch() blocks in this file.
Also applies to: 43-45, 63-65, 74-76, 103-105, 114-116
src/converters/PandocTypstConverter.ts (2)
302-312: Async cleanup still won’t finish during process exit.
void this.cleanup() inside the process handlers means the async temp-file removal continues in the background while Node is already exiting, so the work is almost guaranteed to be cut off. Please drop the process.on(...) handlers and instead hook into the plugin lifecycle (e.g., register an unload handler that awaits cleanup()) so cleanup can actually complete. (deepwiki.com)
370-379: Guard against missing configDir before creating temp manager.
this.plugin?.app?.vault?.configDir can evaluate to undefined (tests, early plugin startup, etc.). Passing that into TempDirectoryManager.create(...) / constructor will throw because path.join rejects undefined. Add an explicit check and either throw a clear error or short‑circuit before calling the manager so we never reach path operations with an undefined config directory.
and likewise in the fallback branch before instantiating TempDirectoryManager.
🧹 Nitpick comments (7)
eslint.config.mjs (1)
68-78: Consider redundancy of no-undef with TypeScript.
Line 78 enables no-undef as an error. With TypeScript's type checking already active (via recommendedTypeChecked), this rule is largely redundant since TypeScript will catch undefined variables. However, it's not harmful and may catch edge cases in JavaScript files.
You can optionally disable this rule since TypeScript provides superior checking:
-'no-undef': 'error',
+'no-undef': 'off', // TypeScript handles this
Lines 277-279 contain unnecessarily complex chaining: value.join('\n').split('\n').map(...) essentially just maps each item. This can be simplified for better readability.
Apply this diff to simplify the logic:
if (Array.isArray(value)) {
// For arrays, put each item on its own line if there are many items
if (value.length > 3) {
- formattedValue = '\n\n' + value.map(item =>
- typeof item === 'object' ? JSON.stringify(item) : String(item)
- ).join('\n').split('\n').map(line => `- ${line}`).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 {
formattedValue = value.map(item =>
typeof item === 'object' ? JSON.stringify(item) : String(item)
).join(', ');
}
src/ui/modal/sections/GeneralSection.ts (1)
7-7: Reconsider using Node.js path module.
The codebase has previously preferred to avoid Node.js built-in modules like path in favor of Obsidian API calls for path operations. The path.isAbsolute() check on line 85 can be replaced with a simple check like value.startsWith('/') or a utility function.
Based on learnings.
Consider this alternative:
-import * as path from 'path';
And replace line 85:
- const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
+ const normalizedValue = value.startsWith('/') ? value : normalizePath(value);
src/plugin/EmbedProcessor.ts (3)
162-172: Extract duplicate path conversion logic to a helper method.
This path-to-vault-relative conversion logic is duplicated three times in the changed code (here and at lines 559-565, 567-573). Consider extracting it to a helper method in PathUtils:
// In PathUtils class:
publictoVaultRelativePath(absolutePath: string):string{constvaultBasePath=this.getVaultPath();if(!absolutePath.startsWith(vaultBasePath)){returnabsolutePath;}letrelativePath=absolutePath.substring(vaultBasePath.length);if(relativePath.startsWith('/')||relativePath.startsWith('\\')){relativePath=relativePath.substring(1);}returnrelativePath;}
364-364: Move util.promisify(exec) to module level for efficiency.
util.promisify(exec) is currently called inside the function for each WebP image that needs conversion. While promisify is lightweight, defining it once at the module level would be cleaner and more efficient:
At the top of the file, after the imports:
import * as https from 'https';
import * as http from 'http';
+
+const execAsync = util.promisify(exec);
export class EmbedProcessor {
Then remove line 364 and use execAsync directly at line 380.
src/plugin/SettingsTab.ts (1)
12-12: Consider avoiding Node.js path module per project preferences.
The import of the Node.js path module conflicts with the established preference to avoid Node.js built-in modules in favor of Obsidian API calls. Since path.isAbsolute() is only used once (line 189), consider implementing a simple check instead.
Based on learnings.
Apply this diff to remove the dependency:
-import * as path from 'path';
Then update line 189 to:
- const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
+ // Check if path is absolute (starts with / or Windows drive letter)
+ const isAbsolute = /^([a-zA-Z]:)?[\/\\]/.test(value);
+ const normalizedValue = isAbsolute ? value : normalizePath(value);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 2c4076f3c9 and 87f3894bf1.
src/**/*.ts: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
Add user-facing commands via this.addCommand(...) and use stable command IDs
Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
Prefer async/await over promise chains and handle errors gracefully
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to esbuild.config.mjs : Use esbuild for bundling (this sample relies on esbuild.config.mjs)
Applied to files:
eslint.config.mjs
📚 Learning: 2025-09-25T14:27:31.837Z
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
Applied to files:
src/core/TempDirectoryManager.ts
src/plugin/EventHandlers.ts
src/core/PathUtils.ts
src/plugin/EmbedProcessor.ts
src/converters/PdfToImageConverter.ts
src/converters/pdf/ImageOptimizer.ts
src/plugin/PathResolver.ts
src/converters/PandocTypstConverter.ts
src/ui/modal/sections/GeneralSection.ts
src/plugin/SettingsTab.ts
src/plugin/ExportOrchestrator.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Prefer async/await over promise chains and handle errors gracefully
Applied to files:
src/plugin/EventHandlers.ts
📚 Learning: 2025-11-05T14:17:36.572Z
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.437Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.
Applied to files:
src/converters/pdf/ImageOptimizer.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
Applied to files:
src/ui/modal/sections/GeneralSection.ts
src/plugin/SettingsTab.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Add user-facing commands via this.addCommand(...) and use stable command IDs
Applied to files:
src/plugin/CommandRegistry.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
The ESM imports are properly structured and all plugins are correctly imported for use in the configuration.
10-14: Appropriate base configuration with type checking.
The configuration correctly layers JavaScript recommended rules with TypeScript type-checked rules, which will provide comprehensive static analysis for the codebase.
18-21: Plugins correctly registered.
The Obsidian and import plugins are properly configured in the flat config format.
37-66: Comprehensive Obsidian plugin rules.
The rule set covers all major Obsidian plugin best practices including command naming, settings UI, vault operations, and platform compatibility. The mixed severities (error/warn) are appropriately balanced.
80-94: Pragmatic TypeScript rule configuration.
The TypeScript rules strike a good balance:
Strict any usage with fixToUnknown (line 84) encourages proper typing
Type safety rules downgraded to warnings (lines 87-91) allow gradual improvement
Underscore prefix pattern (line 94) for unused variables is a widely-accepted convention
97-97: Import validation enabled.
The import/no-extraneous-dependencies rule will help catch packages used in code but not declared in package.json.
100-110: Appropriate ignore patterns.
The ignore list correctly excludes build artifacts, dependencies, and generated files from linting. The inclusion of main.js aligns with the project's bundling strategy.
The updated signature allows onSubmit to be async, which is appropriate for operations that may involve asynchronous work. However, ensure that error handling is properly implemented where this callback is invoked (see comment on line 157).
137-137: LGTM - Consistent sentence case.
The button text change from "Reset to Defaults" to "Reset to defaults" follows sentence case convention, improving UI consistency.
221-221: LGTM - Consistent sentence case.
The header text change from "Validation Errors" to "Validation errors" follows sentence case convention, consistent with the button text change at line 137.
The citation field stripping and title override logic is well-structured and addresses a common issue where Pandoc auto-processes bibliography fields.
240-252: LGTM: Citation field removal is correctly implemented.
The method properly strips bibliographic fields to prevent Pandoc from automatically processing citations. The immutable approach (copying before mutation) is good practice.
src/plugin/CommandRegistry.ts (1)
41-41: LGTM!
Lowercase styling for tool names improves consistency.
src/plugin/EventHandlers.ts (2)
55-55: LGTM! Fixes potential binding issue.
Wrapping isMarkdownFile in an arrow function ensures correct this binding.
23-23: LGTM! Cleaner UI text.
Removing "(Typst)" simplifies menu items without losing clarity.
Also applies to: 40-40, 60-60
src/plugin/ExportOrchestrator.ts (5)
161-165: Verify cancel button renders correctly on messageEl.
Attaching the cancel button to messageEl instead of noticeEl changes where the button appears. Confirm this produces the intended UI layout.
146-154: LGTM! Proper separation of temp directories.
Creating separate tempImagesDir for image/PDF processing and tempDir for Pandoc operations improves organization. The cleanup at line 259 properly handles both via cleanupAllTempDirs().
Also applies to: 195-200
323-323: LGTM! Fixes potential binding issue.
The explicit arrow function ensures correct this binding for isMarkdownFile.
166-166: LGTM! Consistent capitalization.
Capitalizing "Markdown" throughout improves consistency with standard naming conventions.
Also applies to: 168-168, 326-326
183-183: Verification confirmed: preprocessor.process() is synchronous and correctly called without await.
The process() method signature at line 331 is public process(content: string): PreprocessingResult { with no async keyword, confirming it returns PreprocessingResult directly rather than a Promise. The removal of await at line 183 is correct. Additionally, the cancel button attachment to progressNotice.messageEl follows standard Obsidian Notice patterns and is appropriately placed.
src/converters/pdf/ImageOptimizer.ts (1)
6-7: LGTM!
Top-level imports for spawn and fs.promises properly replace inline require() calls, improving code organization and aligning with ESLint best practices.
src/core/PathUtils.ts (3)
4-4: LGTM!
Top-level import of fs.promises properly replaces inline require() and supports the fileExists fallback for paths outside the vault.
109-114: LGTM!
Correctly preserves absolute paths by skipping normalization, which would incorrectly strip the leading slash. The conditional ensures only vault-relative paths are normalized.
141-144: LGTM!
Enhanced error message provides actionable context to users by detecting parent directory and permission issues, improving the user experience during directory creation failures.
src/core/TempDirectoryManager.ts (4)
27-27: LGTM!
Top-level import of fs.promises consolidates filesystem operations for temporary directories, replacing inline usage and improving code organization.
171-172: LGTM!
Correctly preserves absolute paths by skipping normalization. The comments clearly explain that normalizePath would incorrectly strip the leading slash from absolute paths.
Also applies to: 212-213
259-266: LGTM!
The switch from vault.adapter.mkdir to fs.mkdir is appropriate for temporary directories. The comment correctly explains that external tools (pdf2img, ImageMagick) need direct filesystem access with absolute paths rather than vault-relative paths.
Based on learnings
314-331: LGTM!
The migration from vault.adapter to fs.promises for temp directory cleanup is well-justified. External tools write directly to these directories with absolute paths, so fs operations are more appropriate than vault.adapter. The error handling properly logs warnings and returns boolean status without throwing.
Based on learnings
src/ui/modal/sections/GeneralSection.ts (2)
22-24: LGTM! Improved heading consistency.
Replacing the static heading with a Setting component improves UI consistency and accessibility, aligning with the broader refactoring mentioned in the PR summary.
81-81: LGTM! More specific placeholder.
The updated placeholder "PDF exports" provides a clearer example for users.
Moving exec and util imports to the top level is a best practice and aligns with the PR objective of consolidating dynamic runtime requires.
113-113: LGTM! Appropriate log level for debug messages.
Changing these informational messages from console.log to console.debug is appropriate for non-critical tracing and keeps the console cleaner.
Also applies to: 125-125, 174-174, 313-313, 319-319
127-127: LGTM! Recursive redirect handling is correctly implemented.
The use of .then(resolve).catch(reject) properly chains the recursive promise to the outer promise executor, ensuring both successful results and errors are correctly propagated.
542-546: LGTM! Proper vault-relative path handling for adapter operations.
The code correctly uses PathUtils.joinPath() and converts paths to vault-relative format before calling vault.adapter.readBinary() and writeBinary(). The comments explaining the vault-relative vs absolute path distinction are helpful.
Note: The path conversion logic at lines 559-573 is covered by the earlier refactoring suggestion at lines 162-172.
Also applies to: 575-576
src/plugin/PathResolver.ts (4)
6-6: LGTM: Appropriate use of Node.js built-in for executable resolution.
The top-level import of spawnSync and its usage to resolve executable paths is necessary and appropriate. While the plugin generally prefers Obsidian APIs, there's no Obsidian equivalent for executable path resolution, making this an acceptable exception.
Based on learnings.
Also applies to: 39-42
63-65: LGTM: Good defensive validation.
The early validation of the output folder setting with a clear error message is excellent defensive programming. This prevents undefined behavior and provides helpful guidance to the user.
69-69: LGTM: Improved error message clarity.
Adding quotation marks around the path in the error message improves readability and helps users identify the problematic value.
76-76: LGTM: Correct vault-relative path handling.
The changes to use vault-relative paths (outputFolder and vaultRelativeOutputDir) with ensureDir are correct. Obsidian's vault adapter operates on vault-relative paths, while the final return value (line 94) correctly uses the full filesystem path needed by external tools like Typst.
Also applies to: 85-86
src/plugin/SettingsTab.ts (1)
49-51: LGTM: Proper use of Setting components for headings.
The conversion from static HTML headings to Setting components with setHeading() follows Obsidian's standard pattern for settings UI and improves consistency with the native interface.
Also applies to: 135-137, 236-238, 302-304, 374-376
**Actionable comments posted: 7**
> [!CAUTION]
> Some comments are outside the diff and can’t be posted inline due to platform limitations.
>
>
>
> <details>
> <summary>⚠️ Outside diff range comments (1)</summary><blockquote>
>
> <details>
> <summary>src/plugin/PathResolver.ts (1)</summary><blockquote>
>
> `11-11`: **Add a `dirname` method to PathUtils and use it in PathResolver instead of importing Node.js `path` directly.**
>
> PathUtils does not currently provide a `dirname` equivalent method. Line 81 in PathResolver.ts uses `path.dirname(file.path)` after importing Node.js `path` module. This violates the project preference to avoid direct Node.js imports.
>
> Since PathUtils already centralizes path operations and uses the Node.js `path` module internally, add a `dirname` method to PathUtils (following the same pattern as `joinPath`) and update PathResolver to use it instead of the direct import.
>
> Also applies to: 11-11
>
> </blockquote></details>
>
> </blockquote></details>
<details>
<summary>♻️ Duplicate comments (7)</summary><blockquote>
<details>
<summary>eslint.config.mjs (1)</summary><blockquote>
`23-33`: **Critical: Node.js version incompatibility persists.**
The past review flagged that `import.meta.dirname` (line 31) requires Node.js 20.11+ or 18.20+, creating incompatibility with the project's documented Node.js 16+ minimum. This issue remains unresolved.
You must either:
1. Update README.md and package.json to require Node.js 18.20+ or 20.11+, or
2. Replace `import.meta.dirname` with a Node-16-compatible alternative:
```diff
+import { fileURLToPath } from 'url';
+import { dirname } from 'path';
+
import js from '@eslint/js';
// ... other imports
export default tseslint.config(
// ... config
{
languageOptions: {
// ...
parserOptions: {
projectService: true,
- tsconfigRootDir: import.meta.dirname,
+ tsconfigRootDir: dirname(fileURLToPath(import.meta.url)),
},
},
}
);
```
</blockquote></details>
<details>
<summary>src/converters/preprocessors/FrontmatterProcessor.ts (2)</summary><blockquote>
`49-50`: **CRITICAL: Remove raw content logging to prevent data leakage.**
These debug statements log the first 200 characters of user vault content, which can contain sensitive information like titles, tags, authors, and other PII. This was flagged in a previous review but remains unaddressed.
Apply this diff to remove the sensitive logging:
```diff
- console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
- console.debug('First 200 chars:', content.substring(0, 200));
+ console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
```
If you need diagnostics, log non-sensitive metadata like content length:
```typescript
console.debug('FrontmatterProcessor: Parsing content (length:', content.length, 'bytes)');
```
---
`152-154`: **CRITICAL: Remove raw content logging from error path.**
The error handler logs the first 500 characters of vault content, which presents the same privacy risk as the debug logging above. This was also flagged in the previous review.
Apply this diff:
```diff
- console.error('FrontmatterProcessor: gray-matter failed with error:', errorMessage);
- console.error('Content being parsed (first 500 chars):', content.substring(0, 500));
+ console.error('FrontmatterProcessor: gray-matter parsing failed:', errorMessage);
+ console.debug('Content length:', content.length, 'bytes, has frontmatter pattern:', this.FRONTMATTER_PATTERN.test(content));
```
</blockquote></details>
<details>
<summary>src/plugin/CommandRegistry.ts (1)</summary><blockquote>
`21-45`: **Error handling still needs user-facing notifications.**
All three command error handlers only log to console, providing no feedback to users when commands fail. This was flagged in previous reviews but remains unaddressed.
Import `Notice` from 'obsidian' and update all three error handlers:
```diff
+import { Editor, MarkdownView, Notice } from 'obsidian';
-import { Editor, MarkdownView } from 'obsidian';
```
```diff
this.plugin.exportCurrentNote(view).catch(error => {
console.error('Failed to export current note:', error);
+ new Notice(`Export failed: ${error?.message ?? 'Unknown error'}`);
});
```
```diff
this.plugin.showExportModal(view).catch(error => {
console.error('Failed to show export modal:', error);
+ new Notice(`Failed to open export dialog: ${error?.message ?? 'Unknown error'}`);
});
```
```diff
this.plugin.showDependencyStatus().catch(error => {
console.error('Failed to show dependency status:', error);
+ new Notice(`Failed to check dependencies: ${error?.message ?? 'Unknown error'}`);
});
```
</blockquote></details>
<details>
<summary>src/plugin/EventHandlers.ts (1)</summary><blockquote>
`26-28`: **Error handling lacks user-facing notifications.**
All six error handlers only log to console, giving users no feedback when operations fail.
Import `Notice` and add user notifications in each `.catch()` block. For example:
```diff
this.plugin.exportFile(file).catch(error => {
console.error('Failed to export file:', error);
+ new Notice(`Export failed: ${error?.message ?? 'Unknown error'}`);
});
```
Apply similar patterns to all other `.catch()` blocks in this file.
Also applies to: 43-45, 63-65, 74-76, 103-105, 114-116
</blockquote></details>
<details>
<summary>src/converters/PandocTypstConverter.ts (2)</summary><blockquote>
`302-312`: **Async cleanup still won’t finish during process exit.**
`void this.cleanup()` inside the process handlers means the async temp-file removal continues in the background while Node is already exiting, so the work is almost guaranteed to be cut off. Please drop the `process.on(...)` handlers and instead hook into the plugin lifecycle (e.g., register an unload handler that awaits `cleanup()`) so cleanup can actually complete. ([deepwiki.com](https://deepwiki.com/obsidianmd/obsidian-api/3-plugin-development?utm_source=openai))
---
`370-379`: **Guard against missing `configDir` before creating temp manager.**
`this.plugin?.app?.vault?.configDir` can evaluate to `undefined` (tests, early plugin startup, etc.). Passing that into `TempDirectoryManager.create(...)` / constructor will throw because `path.join` rejects `undefined`. Add an explicit check and either throw a clear error or short‑circuit before calling the manager so we never reach path operations with an undefined config directory.
```diff
- const configDir = this.plugin?.app?.vault?.configDir;
- const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
+ const configDir = this.plugin?.app?.vault?.configDir;
+ if (!configDir) {
+ throw new Error('Unable to resolve vault config directory for temp export workspace.');
+ }
+ const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
```
and likewise in the fallback branch before instantiating `TempDirectoryManager`.
</blockquote></details>
</blockquote></details>
<details>
<summary>🧹 Nitpick comments (7)</summary><blockquote>
<details>
<summary>eslint.config.mjs (1)</summary><blockquote>
`68-78`: **Consider redundancy of `no-undef` with TypeScript.**
Line 78 enables `no-undef` as an error. With TypeScript's type checking already active (via `recommendedTypeChecked`), this rule is largely redundant since TypeScript will catch undefined variables. However, it's not harmful and may catch edge cases in JavaScript files.
You can optionally disable this rule since TypeScript provides superior checking:
```diff
-'no-undef': 'error',
+'no-undef': 'off', // TypeScript handles this
```
</blockquote></details>
<details>
<summary>src/converters/preprocessors/FrontmatterProcessor.ts (1)</summary><blockquote>
`277-283`: **Simplify array formatting logic.**
Lines 277-279 contain unnecessarily complex chaining: `value.join('\n').split('\n').map(...)` essentially just maps each item. This can be simplified for better readability.
Apply this diff to simplify the logic:
```diff
if (Array.isArray(value)) {
// For arrays, put each item on its own line if there are many items
if (value.length > 3) {
- formattedValue = '\n\n' + value.map(item =>
- typeof item === 'object' ? JSON.stringify(item) : String(item)
- ).join('\n').split('\n').map(line => `- ${line}`).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 {
formattedValue = value.map(item =>
typeof item === 'object' ? JSON.stringify(item) : String(item)
).join(', ');
}
```
</blockquote></details>
<details>
<summary>src/ui/modal/sections/GeneralSection.ts (1)</summary><blockquote>
`7-7`: **Reconsider using Node.js `path` module.**
The codebase has previously preferred to avoid Node.js built-in modules like `path` in favor of Obsidian API calls for path operations. The `path.isAbsolute()` check on line 85 can be replaced with a simple check like `value.startsWith('/')` or a utility function.
Based on learnings.
Consider this alternative:
```diff
-import * as path from 'path';
```
And replace line 85:
```diff
- const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
+ const normalizedValue = value.startsWith('/') ? value : normalizePath(value);
```
</blockquote></details>
<details>
<summary>src/plugin/EmbedProcessor.ts (3)</summary><blockquote>
`162-172`: **Extract duplicate path conversion logic to a helper method.**
This path-to-vault-relative conversion logic is duplicated three times in the changed code (here and at lines 559-565, 567-573). Consider extracting it to a helper method in `PathUtils`:
```typescript
// In PathUtils class:
public toVaultRelativePath(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;
}
```
Then replace all three occurrences with:
```typescript
const relativeOutputPath = this.pathUtils.toVaultRelativePath(outputPath);
```
---
`146-181`: **Consider extracting the async IIFE to a named function for clarity.**
The async IIFE pattern works but could be more readable. Consider extracting it to a named async function:
```typescript
private async handleDownloadComplete(
chunks: Buffer[],
outputPath: string,
resolve: (value: string | null) => void
): Promise<void> {
try {
const exists = await this.pathUtils.fileExists(outputPath);
if (exists) {
console.warn(`Export: Image file already exists, using existing: ${outputPath}`);
resolve(outputPath);
return;
}
const buffer = Buffer.concat(chunks);
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
const relativeOutputPath = this.pathUtils.toVaultRelativePath(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);
}
}
```
Then call it:
```typescript
response.on('end', () => {
void this.handleDownloadComplete(chunks, outputPath, resolve);
});
```
---
`364-364`: **Move `util.promisify(exec)` to module level for efficiency.**
`util.promisify(exec)` is currently called inside the function for each WebP image that needs conversion. While promisify is lightweight, defining it once at the module level would be cleaner and more efficient:
At the top of the file, after the imports:
```diff
import * as https from 'https';
import * as http from 'http';
+
+const execAsync = util.promisify(exec);
export class EmbedProcessor {
```
Then remove line 364 and use `execAsync` directly at line 380.
</blockquote></details>
<details>
<summary>src/plugin/SettingsTab.ts (1)</summary><blockquote>
`12-12`: **Consider avoiding Node.js path module per project preferences.**
The import of the Node.js `path` module conflicts with the established preference to avoid Node.js built-in modules in favor of Obsidian API calls. Since `path.isAbsolute()` is only used once (line 189), consider implementing a simple check instead.
Based on learnings.
Apply this diff to remove the dependency:
```diff
-import * as path from 'path';
```
Then update line 189 to:
```diff
- const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
+ // Check if path is absolute (starts with / or Windows drive letter)
+ const isAbsolute = /^([a-zA-Z]:)?[\/\\]/.test(value);
+ const normalizedValue = isAbsolute ? value : normalizePath(value);
```
</blockquote></details>
</blockquote></details>
<details>
<summary>📜 Review details</summary>
**Configuration used**: CodeRabbit UI
**Review profile**: CHILL
**Plan**: Pro
<details>
<summary>📥 Commits</summary>
Reviewing files that changed from the base of the PR and between 2c4076f3c9201b6336c94b76dad48c864c703e8a and 87f3894bf17a57107d5c67377e53b83338618dd6.
</details>
<details>
<summary>📒 Files selected for processing (18)</summary>
* `eslint.config.mjs` (2 hunks)
* `src/converters/PandocTypstConverter.ts` (5 hunks)
* `src/converters/PdfToImageConverter.ts` (1 hunks)
* `src/converters/pandoc/PandocCommandBuilder.ts` (0 hunks)
* `src/converters/pdf/BinaryLocator.ts` (2 hunks)
* `src/converters/pdf/ImageOptimizer.ts` (2 hunks)
* `src/converters/preprocessors/FrontmatterProcessor.ts` (10 hunks)
* `src/core/PathUtils.ts` (3 hunks)
* `src/core/TempDirectoryManager.ts` (5 hunks)
* `src/plugin/CommandRegistry.ts` (2 hunks)
* `src/plugin/EmbedProcessor.ts` (10 hunks)
* `src/plugin/EventHandlers.ts` (6 hunks)
* `src/plugin/ExportOrchestrator.ts` (4 hunks)
* `src/plugin/PathResolver.ts` (2 hunks)
* `src/plugin/SettingsTab.ts` (11 hunks)
* `src/templates/embeddedTemplates.ts` (2 hunks)
* `src/ui/modal/ModalRenderer.ts` (5 hunks)
* `src/ui/modal/sections/GeneralSection.ts` (3 hunks)
</details>
<details>
<summary>💤 Files with no reviewable changes (1)</summary>
* src/converters/pandoc/PandocCommandBuilder.ts
</details>
<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary>
* src/converters/pdf/BinaryLocator.ts
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>📓 Path-based instructions (1)</summary>
<details>
<summary>src/**/*.ts</summary>
**📄 CodeRabbit inference engine (AGENTS.md)**
> `src/**/*.ts`: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
> Add user-facing commands via this.addCommand(...) and use stable command IDs
> Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
> Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
> Prefer async/await over promise chains and handle errors gracefully
Files:
- `src/core/TempDirectoryManager.ts`
- `src/plugin/EventHandlers.ts`
- `src/core/PathUtils.ts`
- `src/plugin/EmbedProcessor.ts`
- `src/ui/modal/ModalRenderer.ts`
- `src/converters/preprocessors/FrontmatterProcessor.ts`
- `src/converters/PdfToImageConverter.ts`
- `src/converters/pdf/ImageOptimizer.ts`
- `src/plugin/PathResolver.ts`
- `src/converters/PandocTypstConverter.ts`
- `src/ui/modal/sections/GeneralSection.ts`
- `src/plugin/SettingsTab.ts`
- `src/templates/embeddedTemplates.ts`
- `src/plugin/CommandRegistry.ts`
- `src/plugin/ExportOrchestrator.ts`
</details>
</details><details>
<summary>🧠 Learnings (9)</summary>
<details>
<summary>📓 Common learnings</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
```
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)
```
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to esbuild.config.mjs : Use esbuild for bundling (this sample relies on esbuild.config.mjs)
```
**Applied to files:**
- `eslint.config.mjs`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:27:31.837Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
```
**Applied to files:**
- `src/core/TempDirectoryManager.ts`
- `src/plugin/EventHandlers.ts`
- `src/core/PathUtils.ts`
- `src/plugin/EmbedProcessor.ts`
- `src/converters/PdfToImageConverter.ts`
- `src/converters/pdf/ImageOptimizer.ts`
- `src/plugin/PathResolver.ts`
- `src/converters/PandocTypstConverter.ts`
- `src/ui/modal/sections/GeneralSection.ts`
- `src/plugin/SettingsTab.ts`
- `src/plugin/ExportOrchestrator.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Prefer async/await over promise chains and handle errors gracefully
```
**Applied to files:**
- `src/plugin/EventHandlers.ts`
</details>
<details>
<summary>📚 Learning: 2025-11-05T14:17:36.572Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
```
**Applied to files:**
- `src/converters/preprocessors/FrontmatterProcessor.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:14:57.437Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.437Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.
```
**Applied to files:**
- `src/converters/pdf/ImageOptimizer.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
```
**Applied to files:**
- `src/ui/modal/sections/GeneralSection.ts`
- `src/plugin/SettingsTab.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Add user-facing commands via this.addCommand(...) and use stable command IDs
```
**Applied to files:**
- `src/plugin/CommandRegistry.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
```
**Applied to files:**
- `src/plugin/CommandRegistry.ts`
</details>
</details><details>
<summary>🧬 Code graph analysis (9)</summary>
<details>
<summary>src/core/TempDirectoryManager.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `normalizePath` (47-49)
</details>
</blockquote></details>
<details>
<summary>src/core/PathUtils.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Notice` (4-6)
</details>
</blockquote></details>
<details>
<summary>src/converters/PdfToImageConverter.ts (1)</summary><blockquote>
<details>
<summary>src/core/PathUtils.ts (1)</summary>
* `PathUtils` (30-258)
</details>
</blockquote></details>
<details>
<summary>src/converters/pdf/ImageOptimizer.ts (1)</summary><blockquote>
<details>
<summary>src/core/PathUtils.ts (1)</summary>
* `PathUtils` (30-258)
</details>
</blockquote></details>
<details>
<summary>src/plugin/PathResolver.ts (1)</summary><blockquote>
<details>
<summary>src/core/SecurityUtils.ts (1)</summary>
* `SecurityUtils` (77-393)
</details>
</blockquote></details>
<details>
<summary>src/converters/PandocTypstConverter.ts (2)</summary><blockquote>
<details>
<summary>src/core/TempDirectoryManager.ts (1)</summary>
* `TempDirectoryManager` (118-471)
</details>
<details>
<summary>src/core/PathUtils.ts (1)</summary>
* `PathUtils` (30-258)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/sections/GeneralSection.ts (2)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (2)</summary>
* `Setting` (17-24)
* `normalizePath` (47-49)
</details>
<details>
<summary>scripts/package-plugin.js (1)</summary>
* `path` (12-12)
</details>
</blockquote></details>
<details>
<summary>src/plugin/SettingsTab.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (2)</summary>
* `Setting` (17-24)
* `normalizePath` (47-49)
</details>
</blockquote></details>
<details>
<summary>src/plugin/ExportOrchestrator.ts (2)</summary><blockquote>
<details>
<summary>src/core/TempDirectoryManager.ts (1)</summary>
* `TempDirectoryManager` (118-471)
</details>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Notice` (4-6)
</details>
</blockquote></details>
</details>
</details>
<details>
<summary>🔇 Additional comments (40)</summary><blockquote>
<details>
<summary>eslint.config.mjs (7)</summary><blockquote>
`3-7`: **LGTM: Clean plugin imports.**
The ESM imports are properly structured and all plugins are correctly imported for use in the configuration.
---
`10-14`: **Appropriate base configuration with type checking.**
The configuration correctly layers JavaScript recommended rules with TypeScript type-checked rules, which will provide comprehensive static analysis for the codebase.
---
`18-21`: **Plugins correctly registered.**
The Obsidian and import plugins are properly configured in the flat config format.
---
`37-66`: **Comprehensive Obsidian plugin rules.**
The rule set covers all major Obsidian plugin best practices including command naming, settings UI, vault operations, and platform compatibility. The mixed severities (error/warn) are appropriately balanced.
---
`80-94`: **Pragmatic TypeScript rule configuration.**
The TypeScript rules strike a good balance:
- Strict `any` usage with fixToUnknown (line 84) encourages proper typing
- Type safety rules downgraded to warnings (lines 87-91) allow gradual improvement
- Underscore prefix pattern (line 94) for unused variables is a widely-accepted convention
---
`97-97`: **Import validation enabled.**
The `import/no-extraneous-dependencies` rule will help catch packages used in code but not declared in package.json.
---
`100-110`: **Appropriate ignore patterns.**
The ignore list correctly excludes build artifacts, dependencies, and generated files from linting. The inclusion of `main.js` aligns with the project's bundling strategy.
Based on learnings
</blockquote></details>
<details>
<summary>src/ui/modal/ModalRenderer.ts (3)</summary><blockquote>
`13-13`: **LGTM - Signature change enables async operations.**
The updated signature allows `onSubmit` to be async, which is appropriate for operations that may involve asynchronous work. However, ensure that error handling is properly implemented where this callback is invoked (see comment on line 157).
---
`137-137`: **LGTM - Consistent sentence case.**
The button text change from "Reset to Defaults" to "Reset to defaults" follows sentence case convention, improving UI consistency.
---
`221-221`: **LGTM - Consistent sentence case.**
The header text change from "Validation Errors" to "Validation errors" follows sentence case convention, consistent with the button text change at line 137.
</blockquote></details>
<details>
<summary>src/converters/preprocessors/FrontmatterProcessor.ts (3)</summary><blockquote>
`6-7`: **LGTM: Top-level imports follow PR objectives.**
The consolidation of YAML parsing dependencies into top-level imports aligns with the PR's goal to eliminate dynamic runtime requires.
---
`97-100`: **LGTM: Frontmatter sanitization prevents unwanted Pandoc bibliography processing.**
The citation field stripping and title override logic is well-structured and addresses a common issue where Pandoc auto-processes bibliography fields.
---
`240-252`: **LGTM: Citation field removal is correctly implemented.**
The method properly strips bibliographic fields to prevent Pandoc from automatically processing citations. The immutable approach (copying before mutation) is good practice.
</blockquote></details>
<details>
<summary>src/plugin/CommandRegistry.ts (1)</summary><blockquote>
`41-41`: **LGTM!**
Lowercase styling for tool names improves consistency.
</blockquote></details>
<details>
<summary>src/plugin/EventHandlers.ts (2)</summary><blockquote>
`55-55`: **LGTM! Fixes potential binding issue.**
Wrapping `isMarkdownFile` in an arrow function ensures correct `this` binding.
---
`23-23`: **LGTM! Cleaner UI text.**
Removing "(Typst)" simplifies menu items without losing clarity.
Also applies to: 40-40, 60-60
</blockquote></details>
<details>
<summary>src/plugin/ExportOrchestrator.ts (5)</summary><blockquote>
`161-165`: **Verify cancel button renders correctly on messageEl.**
Attaching the cancel button to `messageEl` instead of `noticeEl` changes where the button appears. Confirm this produces the intended UI layout.
---
`146-154`: **LGTM! Proper separation of temp directories.**
Creating separate `tempImagesDir` for image/PDF processing and `tempDir` for Pandoc operations improves organization. The cleanup at line 259 properly handles both via `cleanupAllTempDirs()`.
Also applies to: 195-200
---
`323-323`: **LGTM! Fixes potential binding issue.**
The explicit arrow function ensures correct `this` binding for `isMarkdownFile`.
---
`166-166`: **LGTM! Consistent capitalization.**
Capitalizing "Markdown" throughout improves consistency with standard naming conventions.
Also applies to: 168-168, 326-326
---
`183-183`: **Verification confirmed: preprocessor.process() is synchronous and correctly called without await.**
The `process()` method signature at line 331 is `public process(content: string): PreprocessingResult {` with no `async` keyword, confirming it returns `PreprocessingResult` directly rather than a Promise. The removal of `await` at line 183 is correct. Additionally, the cancel button attachment to `progressNotice.messageEl` follows standard Obsidian Notice patterns and is appropriately placed.
</blockquote></details>
<details>
<summary>src/converters/pdf/ImageOptimizer.ts (1)</summary><blockquote>
`6-7`: **LGTM!**
Top-level imports for `spawn` and `fs.promises` properly replace inline `require()` calls, improving code organization and aligning with ESLint best practices.
</blockquote></details>
<details>
<summary>src/core/PathUtils.ts (3)</summary><blockquote>
`4-4`: **LGTM!**
Top-level import of `fs.promises` properly replaces inline `require()` and supports the fileExists fallback for paths outside the vault.
---
`109-114`: **LGTM!**
Correctly preserves absolute paths by skipping normalization, which would incorrectly strip the leading slash. The conditional ensures only vault-relative paths are normalized.
---
`141-144`: **LGTM!**
Enhanced error message provides actionable context to users by detecting parent directory and permission issues, improving the user experience during directory creation failures.
</blockquote></details>
<details>
<summary>src/core/TempDirectoryManager.ts (4)</summary><blockquote>
`27-27`: **LGTM!**
Top-level import of `fs.promises` consolidates filesystem operations for temporary directories, replacing inline usage and improving code organization.
---
`171-172`: **LGTM!**
Correctly preserves absolute paths by skipping normalization. The comments clearly explain that `normalizePath` would incorrectly strip the leading slash from absolute paths.
Also applies to: 212-213
---
`259-266`: **LGTM!**
The switch from `vault.adapter.mkdir` to `fs.mkdir` is appropriate for temporary directories. The comment correctly explains that external tools (pdf2img, ImageMagick) need direct filesystem access with absolute paths rather than vault-relative paths.
Based on learnings
---
`314-331`: **LGTM!**
The migration from vault.adapter to fs.promises for temp directory cleanup is well-justified. External tools write directly to these directories with absolute paths, so fs operations are more appropriate than vault.adapter. The error handling properly logs warnings and returns boolean status without throwing.
Based on learnings
</blockquote></details>
<details>
<summary>src/ui/modal/sections/GeneralSection.ts (2)</summary><blockquote>
`22-24`: **LGTM! Improved heading consistency.**
Replacing the static heading with a Setting component improves UI consistency and accessibility, aligning with the broader refactoring mentioned in the PR summary.
---
`81-81`: **LGTM! More specific placeholder.**
The updated placeholder "PDF exports" provides a clearer example for users.
</blockquote></details>
<details>
<summary>src/plugin/EmbedProcessor.ts (4)</summary><blockquote>
`6-7`: **LGTM! Top-level imports improve maintainability.**
Moving `exec` and `util` imports to the top level is a best practice and aligns with the PR objective of consolidating dynamic runtime requires.
---
`113-113`: **LGTM! Appropriate log level for debug messages.**
Changing these informational messages from `console.log` to `console.debug` is appropriate for non-critical tracing and keeps the console cleaner.
Also applies to: 125-125, 174-174, 313-313, 319-319
---
`127-127`: **LGTM! Recursive redirect handling is correctly implemented.**
The use of `.then(resolve).catch(reject)` properly chains the recursive promise to the outer promise executor, ensuring both successful results and errors are correctly propagated.
---
`542-546`: **LGTM! Proper vault-relative path handling for adapter operations.**
The code correctly uses `PathUtils.joinPath()` and converts paths to vault-relative format before calling `vault.adapter.readBinary()` and `writeBinary()`. The comments explaining the vault-relative vs absolute path distinction are helpful.
Note: The path conversion logic at lines 559-573 is covered by the earlier refactoring suggestion at lines 162-172.
Also applies to: 575-576
</blockquote></details>
<details>
<summary>src/plugin/PathResolver.ts (4)</summary><blockquote>
`6-6`: **LGTM: Appropriate use of Node.js built-in for executable resolution.**
The top-level import of `spawnSync` and its usage to resolve executable paths is necessary and appropriate. While the plugin generally prefers Obsidian APIs, there's no Obsidian equivalent for executable path resolution, making this an acceptable exception.
Based on learnings.
Also applies to: 39-42
---
`63-65`: **LGTM: Good defensive validation.**
The early validation of the output folder setting with a clear error message is excellent defensive programming. This prevents undefined behavior and provides helpful guidance to the user.
---
`69-69`: **LGTM: Improved error message clarity.**
Adding quotation marks around the path in the error message improves readability and helps users identify the problematic value.
---
`76-76`: **LGTM: Correct vault-relative path handling.**
The changes to use vault-relative paths (`outputFolder` and `vaultRelativeOutputDir`) with `ensureDir` are correct. Obsidian's vault adapter operates on vault-relative paths, while the final return value (line 94) correctly uses the full filesystem path needed by external tools like Typst.
Also applies to: 85-86
</blockquote></details>
<details>
<summary>src/plugin/SettingsTab.ts (1)</summary><blockquote>
`49-51`: **LGTM: Proper use of Setting components for headings.**
The conversion from static HTML headings to Setting components with `setHeading()` follows Obsidian's standard pattern for settings UI and improves consistency with the native interface.
Also applies to: 135-137, 236-238, 302-304, 374-376
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
Extract duplicated path conversion logic to PathUtils helper.
This vault-relative path conversion pattern is duplicated across multiple files (ImageOptimizer.ts, embeddedTemplates.ts, and here). Consolidating to a PathUtils helper method would reduce duplication and improve maintainability.
See the detailed suggestion in the review comment for src/converters/pdf/ImageOptimizer.ts lines 247-304. The same pathUtils.toVaultRelative() helper would simplify this code:
if (this.plugin?.app) {
const pathUtils = new PathUtils(this.plugin.app);
- const vaultPath = pathUtils.getVaultPath();
- // Convert absolute path to vault-relative
- let relativeOutputDir = outputDir;
- if (outputDir.startsWith(vaultPath)) {
- relativeOutputDir = outputDir.substring(vaultPath.length);
- if (relativeOutputDir.startsWith('/') || relativeOutputDir.startsWith('\\')) {
- relativeOutputDir = relativeOutputDir.substring(1);
- }
- }
+ const relativeOutputDir = pathUtils.toVaultRelative(outputDir);
await pathUtils.ensureDir(relativeOutputDir);
}
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/converters/PdfToImageConverter.ts around lines 416 to 428, the
vault-relative path conversion logic is duplicated and should be moved into
PathUtils; add a PathUtils.toVaultRelative(outputDir) (or similar) method that
returns the vault-relative path (trimming leading separators when needed) and
replace the inline conversion here with: const relativeOutputDir =
pathUtils.toVaultRelative(outputDir); then call await
pathUtils.ensureDir(relativeOutputDir); ensuring behavior matches existing
trimming and only converts when outputDir starts with the vault path.
_🛠️ Refactor suggestion_ | _🟠 Major_
**Extract duplicated path conversion logic to PathUtils helper.**
This vault-relative path conversion pattern is duplicated across multiple files (ImageOptimizer.ts, embeddedTemplates.ts, and here). Consolidating to a PathUtils helper method would reduce duplication and improve maintainability.
See the detailed suggestion in the review comment for `src/converters/pdf/ImageOptimizer.ts` lines 247-304. The same `pathUtils.toVaultRelative()` helper would simplify this code:
```diff
if (this.plugin?.app) {
const pathUtils = new PathUtils(this.plugin.app);
- const vaultPath = pathUtils.getVaultPath();
- // Convert absolute path to vault-relative
- let relativeOutputDir = outputDir;
- if (outputDir.startsWith(vaultPath)) {
- relativeOutputDir = outputDir.substring(vaultPath.length);
- if (relativeOutputDir.startsWith('/') || relativeOutputDir.startsWith('\\')) {
- relativeOutputDir = relativeOutputDir.substring(1);
- }
- }
+ const relativeOutputDir = pathUtils.toVaultRelative(outputDir);
await pathUtils.ensureDir(relativeOutputDir);
}
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/converters/PdfToImageConverter.ts around lines 416 to 428, the
vault-relative path conversion logic is duplicated and should be moved into
PathUtils; add a PathUtils.toVaultRelative(outputDir) (or similar) method that
returns the vault-relative path (trimming leading separators when needed) and
replace the inline conversion here with: const relativeOutputDir =
pathUtils.toVaultRelative(outputDir); then call await
pathUtils.ensureDir(relativeOutputDir); ensuring behavior matches existing
trimming and only converts when outputDir starts with the vault path.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
Extract duplicated path conversion logic to PathUtils helper.
The vault-relative path conversion pattern (stripping vault base path and leading separators) is duplicated three times in this file (lines 220-234, 247-271, 280-304). This code duplication increases maintenance burden and the risk of inconsistencies.
Consider adding a helper method to PathUtils:
// In PathUtils.ts
publictoVaultRelative(absolutePath: string):string{constvaultBasePath=this.getVaultPath();if(!absolutePath.startsWith(vaultBasePath)){returnabsolutePath;}letrelativePath=absolutePath.substring(vaultBasePath.length);if(relativePath.startsWith('/')||relativePath.startsWith('\\')){relativePath=relativePath.substring(1);}returnrelativePath;}
Then replace the duplicated blocks:
if (plugin?.app) {
- // Convert absolute paths to vault-relative paths for adapter operations
const pathUtils = new PathUtils(plugin.app);
- const vaultBasePath = pathUtils.getVaultPath();
-
- let relativeInputPath = inputImagePath;
- if (inputImagePath.startsWith(vaultBasePath)) {
- // Remove vault base path and leading separator
- relativeInputPath = inputImagePath.substring(vaultBasePath.length);
- if (relativeInputPath.startsWith('/') || relativeInputPath.startsWith('\\')) {
- relativeInputPath = relativeInputPath.substring(1);
- }
- }
-
- let relativePngPath = pngFinalPath;
- if (pngFinalPath.startsWith(vaultBasePath)) {
- // Remove vault base path and leading separator
- relativePngPath = pngFinalPath.substring(vaultBasePath.length);
- if (relativePngPath.startsWith('/') || relativePngPath.startsWith('\\')) {
- relativePngPath = relativePngPath.substring(1);
- }
- }
+ const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
+ const relativePngPath = pathUtils.toVaultRelative(pngFinalPath);
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
🤖 Prompt for AI Agents
In src/converters/pdf/ImageOptimizer.ts around lines 247-304 (and also the
similar occurrences at ~220-234 and ~280-304), duplicate logic strips the vault
base path and leading separators; extract this into PathUtils.toVaultRelative
and replace the three duplicated blocks with calls to that helper. Add a public
toVaultRelative(absolutePath: string) method on PathUtils that returns the
original path if it does not start with getVaultPath(), otherwise removes the
vault base prefix and any leading '/' or '\' and returns the result; then in
ImageOptimizer create a PathUtils(plugin.app) instance and call toVaultRelative
for inputImagePath, pngFinalPath and finalOutputPath before passing them to
plugin.app.vault.adapter.readBinary/writeBinary/remove, removing the inline
substring/startsWith logic so behavior remains identical.
_🛠️ Refactor suggestion_ | _🟠 Major_
**Extract duplicated path conversion logic to PathUtils helper.**
The vault-relative path conversion pattern (stripping vault base path and leading separators) is duplicated three times in this file (lines 220-234, 247-271, 280-304). This code duplication increases maintenance burden and the risk of inconsistencies.
Consider adding a helper method to PathUtils:
```typescript
// In PathUtils.ts
public 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;
}
```
Then replace the duplicated blocks:
```diff
if (plugin?.app) {
- // Convert absolute paths to vault-relative paths for adapter operations
const pathUtils = new PathUtils(plugin.app);
- const vaultBasePath = pathUtils.getVaultPath();
-
- let relativeInputPath = inputImagePath;
- if (inputImagePath.startsWith(vaultBasePath)) {
- // Remove vault base path and leading separator
- relativeInputPath = inputImagePath.substring(vaultBasePath.length);
- if (relativeInputPath.startsWith('/') || relativeInputPath.startsWith('\\')) {
- relativeInputPath = relativeInputPath.substring(1);
- }
- }
-
- let relativePngPath = pngFinalPath;
- if (pngFinalPath.startsWith(vaultBasePath)) {
- // Remove vault base path and leading separator
- relativePngPath = pngFinalPath.substring(vaultBasePath.length);
- if (relativePngPath.startsWith('/') || relativePngPath.startsWith('\\')) {
- relativePngPath = relativePngPath.substring(1);
- }
- }
+ const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
+ const relativePngPath = pathUtils.toVaultRelative(pngFinalPath);
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/converters/pdf/ImageOptimizer.ts around lines 247-304 (and also the
similar occurrences at ~220-234 and ~280-304), duplicate logic strips the vault
base path and leading separators; extract this into PathUtils.toVaultRelative
and replace the three duplicated blocks with calls to that helper. Add a public
toVaultRelative(absolutePath: string) method on PathUtils that returns the
original path if it does not start with getVaultPath(), otherwise removes the
vault base prefix and any leading '/' or '\' and returns the result; then in
ImageOptimizer create a PathUtils(plugin.app) instance and call toVaultRelative
for inputImagePath, pngFinalPath and finalOutputPath before passing them to
plugin.app.vault.adapter.readBinary/writeBinary/remove, removing the inline
substring/startsWith logic so behavior remains identical.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
The comment states that normalizePath strips the leading slash from absolute paths, but this should be verified. The Obsidian API documentation or actual testing should confirm this behavior before bypassing normalization.
Run the following script to check the actual behavior of normalizePath with various path patterns:
🏁 Script executed:
#!/bin/bash
# Description: Search for other usages of normalizePath with absolute paths to understand current behavior# Search for normalizePath usage patterns
rg -n -C3 'normalizePath\(' --type=ts
# Look for any path handling tests or documentation
fd -e ts -e md | xargs rg -l 'normalizePath|absolute.*path|path.*absolute' -i
Length of output: 7180
Now I need to verify the inconsistency at line 109 in GeneralSection.ts where `normalizePath` is called directly without checking `isAbsolute()` first:
**The normalizePath behavior claim in the comment is correct and verified.**
The Obsidian API's `normalizePath` function converts Unix-style absolute paths (like "/users/username/folder/file.md") to relative paths by stripping the leading slash. The defensive check using `path.isAbsolute()` before calling `normalizePath` is therefore necessary and appropriate—it prevents user-provided absolute paths from being incorrectly converted to relative paths during settings storage.
The code and comment are accurate.
[resolve_review_comment]
---
🌐 Web query:
```web
Obsidian API normalizePath function documentation behavior absolute paths
💡 Result:
Short answer: normalizePath is for vault-relative paths — it normalizes separators, removes leading/trailing slashes (so a leading "/" is stripped) and converts backslashes to "/" (Windows). It will therefore turn an OS-style absolute path (or a path starting with "/") into a vault-relative path. Use it for paths inside the vault; don’t use it if you need to keep an OS absolute path. [1][2][3]
Obsidian typings / examples (shows leading "/" is removed and backslashes normalized). [2]
Obsidian forum discussion confirming normalizePath removes leading "/" and is intended for vault-internal paths. [3]
The normalizePath behavior claim is verified as correct, but a critical inconsistency was found during verification.
The Obsidian normalizePath function does remove leading slashes from absolute paths and converts backslashes to forward slashes, making the code's defensive check necessary and appropriate. The comment is accurate.
However, an inconsistency exists in src/ui/modal/sections/GeneralSection.ts:
Lines 82-87 (onChange handler): Conditionally applies normalizePath only to relative paths, preserving absolute paths for storage
Line 109 (validation): Unconditionally applies normalizePath to validate the path
This means validation and storage operate on different path states. If a user enters an absolute path like /exports, it gets stored as /exports but validated as exports, potentially allowing invalid states or bypassing security checks.
Apply the same defensive check at line 109 to ensure validation and storage are consistent:
const value = path.isAbsolute(this.outputFolderInput.value.trim())
? this.outputFolderInput.value.trim()
: normalizePath(this.outputFolderInput.value.trim());
🤖 Prompt for AI Agents
In src/plugin/SettingsTab.ts around lines 188-189, the code defends against
normalizePath stripping leading slashes by preserving absolute paths before
normalization, but the validator elsewhere applies normalizePath unconditionally
causing inconsistent validation vs storage; update the validation path
computation to mirror the storage logic by first trimming the raw input and then
using path.isAbsolute(trimmed) ? trimmed : normalizePath(trimmed) so both
validation and storage see the same path form.
_⚠️ Potential issue_ | _🔴 Critical_
<details>
<summary>🧩 Analysis chain</summary>
**Verify the normalizePath behavior claim.**
The comment states that `normalizePath` strips the leading slash from absolute paths, but this should be verified. The Obsidian API documentation or actual testing should confirm this behavior before bypassing normalization.
Run the following script to check the actual behavior of normalizePath with various path patterns:
---
🏁 Script executed:
```shell
#!/bin/bash
# Description: Search for other usages of normalizePath with absolute paths to understand current behavior
# Search for normalizePath usage patterns
rg -n -C3 'normalizePath\(' --type=ts
# Look for any path handling tests or documentation
fd -e ts -e md | xargs rg -l 'normalizePath|absolute.*path|path.*absolute' -i
```
Length of output: 7180
---
```
Now I need to verify the inconsistency at line 109 in GeneralSection.ts where `normalizePath` is called directly without checking `isAbsolute()` first:
**The normalizePath behavior claim in the comment is correct and verified.**
The Obsidian API's `normalizePath` function converts Unix-style absolute paths (like "/users/username/folder/file.md") to relative paths by stripping the leading slash. The defensive check using `path.isAbsolute()` before calling `normalizePath` is therefore necessary and appropriate—it prevents user-provided absolute paths from being incorrectly converted to relative paths during settings storage.
The code and comment are accurate.
[resolve_review_comment]
---
🌐 Web query:
```web
Obsidian API normalizePath function documentation behavior absolute paths
```
💡 Result:
Short answer: normalizePath is for vault-relative paths — it normalizes separators, removes leading/trailing slashes (so a leading "/" is stripped) and converts backslashes to "/" (Windows). It will therefore turn an OS-style absolute path (or a path starting with "/") into a vault-relative path. Use it for paths inside the vault; don’t use it if you need to keep an OS absolute path. [1][2][3]
Sources:
- Obsidian plugin docs (normalizePath behavior & guidance). [1]
- Obsidian typings / examples (shows leading "/" is removed and backslashes normalized). [2]
- Obsidian forum discussion confirming normalizePath removes leading "/" and is intended for vault-internal paths. [3]
---
</details>
**The normalizePath behavior claim is verified as correct, but a critical inconsistency was found during verification.**
The Obsidian `normalizePath` function does remove leading slashes from absolute paths and converts backslashes to forward slashes, making the code's defensive check necessary and appropriate. The comment is accurate.
However, an inconsistency exists in `src/ui/modal/sections/GeneralSection.ts`:
- **Lines 82-87** (onChange handler): Conditionally applies normalizePath only to relative paths, preserving absolute paths for storage
- **Line 109** (validation): Unconditionally applies normalizePath to validate the path
This means validation and storage operate on different path states. If a user enters an absolute path like `/exports`, it gets stored as `/exports` but validated as `exports`, potentially allowing invalid states or bypassing security checks.
**Apply the same defensive check at line 109** to ensure validation and storage are consistent:
```
const value = path.isAbsolute(this.outputFolderInput.value.trim())
? this.outputFolderInput.value.trim()
: normalizePath(this.outputFolderInput.value.trim());
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/plugin/SettingsTab.ts around lines 188-189, the code defends against
normalizePath stripping leading slashes by preserving absolute paths before
normalization, but the validator elsewhere applies normalizePath unconditionally
causing inconsistent validation vs storage; update the validation path
computation to mirror the storage logic by first trimming the raw input and then
using path.isAbsolute(trimmed) ? trimmed : normalizePath(trimmed) so both
validation and storage see the same path form.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
Extract duplicated path conversion logic to PathUtils helper.
The vault-relative path conversion is duplicated both within this file (lines 60-69 and 116-125) and across other files in this PR. This is the same duplication issue identified in ImageOptimizer.ts and PdfToImageConverter.ts.
Add a toVaultRelative() helper to PathUtils (see detailed suggestion in ImageOptimizer.ts review), then simplify both locations:
_🛠️ Refactor suggestion_ | _🟠 Major_
**Extract duplicated path conversion logic to PathUtils helper.**
The vault-relative path conversion is duplicated both within this file (lines 60-69 and 116-125) and across other files in this PR. This is the same duplication issue identified in ImageOptimizer.ts and PdfToImageConverter.ts.
Add a `toVaultRelative()` helper to PathUtils (see detailed suggestion in ImageOptimizer.ts review), then simplify both locations:
```diff
try {
- // Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
- const vaultPath = this.pathUtils.getVaultPath();
- let relativeTemplatesDir = this.templatesDir;
- if (this.templatesDir.startsWith(vaultPath)) {
- relativeTemplatesDir = this.templatesDir.substring(vaultPath.length);
- if (relativeTemplatesDir.startsWith('/') || relativeTemplatesDir.startsWith('\\')) {
- relativeTemplatesDir = relativeTemplatesDir.substring(1);
- }
- }
+ const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
await this.pathUtils.ensureDir(relativeTemplatesDir);
```
Also applies to: 116-125
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
Handle potential promise rejection from async onSubmit.
The void operator correctly discards the promise, but if onSubmit is async and throws an error, it will result in an unhandled promise rejection. This could lead to unexpected behavior or silent failures.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/ui/modal/ModalRenderer.ts around line 157, the click handler currently
calls this.callbacks.onSubmit() with the void operator which discards the
returned promise and can create unhandled promise rejections if onSubmit is
async; change the handler to capture the promise and attach error handling
(e.g., call Promise.resolve(this.callbacks.onSubmit()).catch(err => { /*
handle/log error and update UI state */ })) or wrap the invocation in an async
function with try/catch so any thrown/rejected error is caught and handled
appropriately (log the error and provide user-facing feedback or disable the
submit button as needed).
_⚠️ Potential issue_ | _🟠 Major_
**Handle potential promise rejection from async onSubmit.**
The `void` operator correctly discards the promise, but if `onSubmit` is async and throws an error, it will result in an unhandled promise rejection. This could lead to unexpected behavior or silent failures.
Apply this diff to add proper error handling:
```diff
- this.submitButton.addEventListener('click', () => void this.callbacks.onSubmit());
+ this.submitButton.addEventListener('click', async () => {
+ try {
+ await this.callbacks.onSubmit();
+ } catch (error) {
+ console.error('Export failed:', error);
+ // Optionally show error to user via validation errors
+ this.showValidationErrors([`Export failed: ${error instanceof Error ? error.message : String(error)}`]);
+ }
+ });
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/ui/modal/ModalRenderer.ts around line 157, the click handler currently
calls this.callbacks.onSubmit() with the void operator which discards the
returned promise and can create unhandled promise rejections if onSubmit is
async; change the handler to capture the promise and attach error handling
(e.g., call Promise.resolve(this.callbacks.onSubmit()).catch(err => { /*
handle/log error and update UI state */ })) or wrap the invocation in an async
function with try/catch so any thrown/rejected error is caught and handled
appropriately (log the error and provide user-facing feedback or disable the
submit button as needed).
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
The description states "relative to vault root", but the code on lines 84-85 now accepts and preserves absolute paths. Either update the description to clarify that absolute paths are supported, or remove the absolute path handling to match the description.
If absolute paths are intended, consider updating the description:
- .setDesc('Location for exported PDF files (relative to vault root)')
+ .setDesc('Location for exported PDF files (relative to vault root, or absolute path)')
🤖 Prompt for AI Agents
In src/ui/modal/sections/GeneralSection.ts around line 78, the UI description
currently reads "Location for exported PDF files (relative to vault root)" but
the code now accepts and preserves absolute paths; update the description to
accurately reflect that both relative paths (resolved against vault root) and
absolute paths are supported (e.g., "Location for exported PDF files (relative
to vault root or absolute path)") or, if absolute paths are not intended, remove
the absolute-path handling in the code so the behavior matches the original
"relative" wording; ensure text is concise and consistent with the actual path
handling logic.
_⚠️ Potential issue_ | _🟡 Minor_
**Description contradicts absolute path handling.**
The description states "relative to vault root", but the code on lines 84-85 now accepts and preserves absolute paths. Either update the description to clarify that absolute paths are supported, or remove the absolute path handling to match the description.
If absolute paths are intended, consider updating the description:
```diff
- .setDesc('Location for exported PDF files (relative to vault root)')
+ .setDesc('Location for exported PDF files (relative to vault root, or absolute path)')
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/ui/modal/sections/GeneralSection.ts around line 78, the UI description
currently reads "Location for exported PDF files (relative to vault root)" but
the code now accepts and preserves absolute paths; update the description to
accurately reflect that both relative paths (resolved against vault root) and
absolute paths are supported (e.g., "Location for exported PDF files (relative
to vault root or absolute path)") or, if absolute paths are not intended, remove
the absolute-path handling in the code so the behavior matches the original
"relative" wording; ensure text is concise and consistent with the actual path
handling logic.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
Inconsistent path handling between onChange and validate.
The onChange handler preserves absolute paths (line 85), but the validate() method always normalizes paths including absolute ones (line 109). This inconsistency could cause validation to incorrectly handle absolute paths that were previously accepted.
Apply this diff to make validation consistent:
// Validate output folder
if (this.outputFolderInput) {
- const value = normalizePath(this.outputFolderInput.value.trim());
+ const rawValue = this.outputFolderInput.value.trim();
+ const value = rawValue.startsWith('/') ? rawValue : normalizePath(rawValue);
if (!SecurityUtils.validateOutputPath(value)) {
errors.push(SecurityUtils.getPathValidationError(value));
}
}
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/ui/modal/sections/GeneralSection.ts around lines 84-86 and 109,
validation is inconsistent: onChange preserves absolute paths but validate()
always normalizes them. Update validate() to mirror onChange by checking
path.isAbsolute(value) and using the raw value for absolute paths, otherwise
passing normalizePath(value); then run the existing validation logic against
that normalizedValue so absolute paths are treated consistently between onChange
and validate.
_⚠️ Potential issue_ | _🟠 Major_
**Inconsistent path handling between onChange and validate.**
The onChange handler preserves absolute paths (line 85), but the validate() method always normalizes paths including absolute ones (line 109). This inconsistency could cause validation to incorrectly handle absolute paths that were previously accepted.
Apply this diff to make validation consistent:
```diff
// Validate output folder
if (this.outputFolderInput) {
- const value = normalizePath(this.outputFolderInput.value.trim());
+ const rawValue = this.outputFolderInput.value.trim();
+ const value = rawValue.startsWith('/') ? rawValue : normalizePath(rawValue);
if (!SecurityUtils.validateOutputPath(value)) {
errors.push(SecurityUtils.getPathValidationError(value));
}
}
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/ui/modal/sections/GeneralSection.ts around lines 84-86 and 109,
validation is inconsistent: onChange preserves absolute paths but validate()
always normalizes them. Update validate() to mirror onChange by checking
path.isAbsolute(value) and using the raw value for absolute paths, otherwise
passing normalizePath(value); then run the existing validation logic against
that normalizedValue so absolute paths are treated consistently between onChange
and validate.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/ui/modal/sections/TypographySection.ts (1)
166-214: Remove unused helper methodsaddFallbackBodyFonts and addFallbackMonospaceFonts.
The ripgrep search confirms these private methods are never called anywhere in the codebase (only their definitions at lines 166 and 197). Since createFontSettings already uses getAvailableFonts() directly, delete both methods to reduce maintenance burden and complexity.
src/core/SecurityUtils.ts (1)
121-156: Explicitly reject absolute paths across platforms
path.isAbsolute(trimmed) returning true should short-circuit to false, otherwise Windows drive-letter paths (e.g., C:\tmp) sail through—contradicting the documented “relative-only” guarantee and letting exports escape the vault. Reject absolutes up front, then normalize.
53-101: Sanitized metadata still leaks citation fields
You strip citation keys before writing back to the note, but result.metadata.frontmatter still points to the raw parsed.data. Downstream consumers read from this metadata object, so the bibliography/citation fields you meant to drop remain available and can reappear later in the pipeline, defeating the new sanitization. Please store the sanitized copy in metadata before constructing finalFrontmatter.
Promise.resolve(this.callbacks.onSubmit()) still executes onSubmit before the promise wrapper is created, so any synchronous throw escapes and bubbles as an uncaught error. Wrap the handler in an async function (or capture the return value before resolving) so both sync and async failures hit the catch block.
- this.submitButton.addEventListener('click', () => {
- this.setExportingState(true);
- Promise.resolve(this.callbacks.onSubmit()).catch(err => {
+ this.submitButton.addEventListener('click', async () => {
+ this.setExportingState(true);
+ try {
+ await 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);
- });
+ }
});
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 87f3894bf1 and c1c02ee553.
src/**/*.ts: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
Add user-facing commands via this.addCommand(...) and use stable command IDs
Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
Prefer async/await over promise chains and handle errors gracefully
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
Applied to files:
src/converters/pdf/PdfCliExecutor.ts
src/converters/pdf/ImageOptimizer.ts
src/converters/PdfToImageConverter.ts
src/core/PathUtils.ts
src/converters/PandocTypstConverter.ts
src/plugin/EmbedProcessor.ts
main.ts
📚 Learning: 2025-09-25T14:14:57.437Z
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.437Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.
Applied to files:
src/converters/pdf/ImageOptimizer.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to esbuild.config.mjs : Use esbuild for bundling (this sample relies on esbuild.config.mjs)
Applied to files:
package.json
📚 Learning: 2025-11-05T14:17:36.572Z
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
Applied to files:
src/converters/PandocTypstConverter.ts
main.ts
src/plugin/PluginLifecycle.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)
Applied to files:
main.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
Applied to files:
main.ts
📚 Learning: 2025-09-25T14:48:20.040Z
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Prefer async/await over promise chains and handle errors gracefully
[error] 381-381: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
🔇 Additional comments (11)
package.json (5)
27-29: Establishing Node 18.20.0 as minimum version.
The engine constraint aligns with Node's maintenance timeline and enables access to modern JavaScript features (async/await, top-level await, ES2020+). Confirm this floor is compatible with your intended plugin users' Obsidian setups.
33-33: Verify js-yaml is used as a runtime dependency.
js-yaml has been added as a runtime dependency alongside its TypeScript definitions. Per the PR summary, code now consolidates "runtime requires into top-level imports," so this is justifiable if modules like FrontmatterProcessor or template handlers import it directly at runtime. Verify that js-yaml is actually imported in runtime code (not just build scripts).
Also applies to: 56-56
35-37: TypeScript-ESLint versions are aligned.
All three @typescript-eslint/* packages are pinned to ^8.46.3, ensuring consistent AST parsing and rule behavior across the linting pipeline. This is good practice.
44-45: Verify eslint-plugin-obsidianmd compatibility with ESLint 9.
eslint has been updated to ^9.39.1 and eslint-plugin-obsidianmd@^0.1.8 is introduced. Confirm the plugin is compatible with ESLint 9's flat config format and does not introduce peer dependency conflicts.
42-42: Clarify the need for electron as a devDependency.
electron was updated to ^33.3.0. For an Obsidian plugin project, electron is typically only needed if you're building/testing desktop integration at dev-time. If this was added as a transitive dependency of another package, consider documenting this. If explicitly needed for the build, confirm its necessity in the PR description or docs.
src/core/ExportErrorHandler.ts (3)
12-12: Documentation correctly updated to reflect debug log level.
The documentation now accurately lists the supported log levels as (error, warn, debug), which aligns with both the interface definition and the implementation.
46-46: Interface properly aligned with implementation.
The logLevel type now correctly includes 'debug' instead of 'info', matching the console.debug() call in the implementation. This resolves the semantic mismatch identified in the previous review.
183-185: Implementation correctly uses console.debug() per ObsidianReviewBot requirements.
The switch case now uses 'debug' with console.debug(), which complies with ObsidianReviewBot's restriction to only console.warn(), console.error(), and console.debug(). This properly aligns with the updated interface definition.
Based on learnings.
src/converters/pdf/PdfCliExecutor.ts (1)
6-14: LGTM! Clean refactoring to top-level imports.
Moving the child_process and util imports to the top level and creating execAsync once at module scope is more efficient and idiomatic than runtime requires. This eliminates the overhead of recreating the promisified function on each executeCommand call while maintaining the same public API.
src/ui/modal/sections/TypographySection.ts (2)
167-169: ESLint disable blocks are properly scoped and justified.
The ESLint disable/enable comments correctly scope the exception to the specific font name declarations that require it. The explanatory comment clearly states why the rule must be disabled (font names are proper nouns).
Note: If the helper methods containing these blocks are determined to be unused (per the previous comment), they should be removed along with the ESLint directives.
Also applies to: 179-179, 198-199, 213-213
16-18: ✗ setHeading() is a legitimate Obsidian API method used consistently throughout the codebase.
The original concern about test mock compatibility is incorrect. setHeading() appears in 10+ locations across the codebase (TypographySection, LayoutSection, GeneralSection, BehaviorSection, PageSetupSection, and SettingsTab), confirming it's a real Obsidian API method. The test mock not including it is a mock limitation, not a code issue.
The code change at lines 16-18 is valid and follows the established pattern used elsewhere in the project.
**Actionable comments posted: 2**
> [!CAUTION]
> Some comments are outside the diff and can’t be posted inline due to platform limitations.
>
>
>
> <details>
> <summary>⚠️ Outside diff range comments (3)</summary><blockquote>
>
> <details>
> <summary>src/ui/modal/sections/TypographySection.ts (1)</summary><blockquote>
>
> `166-214`: **Remove unused helper methods** `addFallbackBodyFonts` and `addFallbackMonospaceFonts`.
>
> The ripgrep search confirms these private methods are never called anywhere in the codebase (only their definitions at lines 166 and 197). Since `createFontSettings` already uses `getAvailableFonts()` directly, delete both methods to reduce maintenance burden and complexity.
>
> </blockquote></details>
> <details>
> <summary>src/core/SecurityUtils.ts (1)</summary><blockquote>
>
> `121-156`: **Explicitly reject absolute paths across platforms**
>
> `path.isAbsolute(trimmed)` returning true should short-circuit to `false`, otherwise Windows drive-letter paths (e.g., `C:\tmp`) sail through—contradicting the documented “relative-only” guarantee and letting exports escape the vault. Reject absolutes up front, then normalize.
>
> ```diff
> - // Normalize path, but preserve absolute paths (mirrors SettingsTab storage logic)
> - const trimmed = outputFolder.trim();
> - const normalizedPath = path.isAbsolute(trimmed) ? trimmed : path.normalize(trimmed);
> + // Normalize path (reject absolute paths so exports stay inside the vault)
> + const trimmed = outputFolder.trim();
> + if (path.isAbsolute(trimmed)) {
> + return false;
> + }
> + const normalizedPath = path.normalize(trimmed);
> ```
>
> </blockquote></details>
> <details>
> <summary>src/converters/preprocessors/FrontmatterProcessor.ts (1)</summary><blockquote>
>
> `53-101`: **Sanitized metadata still leaks citation fields**
>
> You strip citation keys before writing back to the note, but `result.metadata.frontmatter` still points to the raw `parsed.data`. Downstream consumers read from this metadata object, so the bibliography/citation fields you meant to drop remain available and can reappear later in the pipeline, defeating the new sanitization. Please store the sanitized copy in metadata before constructing `finalFrontmatter`.
>
>
>
> ```diff
> - if (this.noteTitle) {
> - const frontmatterCopy = { ...parsed.data };
> - frontmatterCopy.title = this.noteTitle;
> - result.metadata.frontmatter = frontmatterCopy;
> - } else {
> - result.metadata.frontmatter = parsed.data;
> - }
> + const sanitizedFrontmatter = this.stripCitationFields(parsed.data);
> + if (this.noteTitle) {
> + result.metadata.frontmatter = {
> + ...sanitizedFrontmatter,
> + title: this.noteTitle
> + };
> + } else {
> + result.metadata.frontmatter = sanitizedFrontmatter;
> + }
> …
> - const sanitizedFrontmatter = this.stripCitationFields(parsed.data);
> - const finalFrontmatter = this.noteTitle ?
> - { ...sanitizedFrontmatter, title: this.noteTitle } :
> - sanitizedFrontmatter;
> + const finalFrontmatter = result.metadata.frontmatter;
> ```
>
> </blockquote></details>
>
> </blockquote></details>
<details>
<summary>♻️ Duplicate comments (1)</summary><blockquote>
<details>
<summary>src/ui/modal/ModalRenderer.ts (1)</summary><blockquote>
`157-169`: **Catch synchronous `onSubmit` failures**
`Promise.resolve(this.callbacks.onSubmit())` still executes `onSubmit` before the promise wrapper is created, so any synchronous throw escapes and bubbles as an uncaught error. Wrap the handler in an `async` function (or capture the return value before resolving) so both sync and async failures hit the catch block.
```diff
- this.submitButton.addEventListener('click', () => {
- this.setExportingState(true);
- Promise.resolve(this.callbacks.onSubmit()).catch(err => {
+ this.submitButton.addEventListener('click', async () => {
+ this.setExportingState(true);
+ try {
+ await 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);
- });
+ }
});
```
</blockquote></details>
</blockquote></details>
<details>
<summary>📜 Review details</summary>
**Configuration used**: CodeRabbit UI
**Review profile**: CHILL
**Plan**: Pro
<details>
<summary>📥 Commits</summary>
Reviewing files that changed from the base of the PR and between 87f3894bf17a57107d5c67377e53b83338618dd6 and c1c02ee553e64bc9b28372cd3de0ae9bece7b89e.
</details>
<details>
<summary>📒 Files selected for processing (20)</summary>
* `README.md` (1 hunks)
* `main.ts` (5 hunks)
* `package.json` (2 hunks)
* `src/converters/PandocTypstConverter.ts` (7 hunks)
* `src/converters/PdfToImageConverter.ts` (1 hunks)
* `src/converters/pdf/ImageOptimizer.ts` (3 hunks)
* `src/converters/pdf/PdfCliExecutor.ts` (1 hunks)
* `src/converters/preprocessors/FrontmatterProcessor.ts` (10 hunks)
* `src/core/DependencyChecker.ts` (2 hunks)
* `src/core/ExportErrorHandler.ts` (3 hunks)
* `src/core/PathUtils.ts` (4 hunks)
* `src/core/SecurityUtils.ts` (4 hunks)
* `src/plugin/CommandRegistry.ts` (3 hunks)
* `src/plugin/EmbedProcessor.ts` (10 hunks)
* `src/plugin/PluginLifecycle.ts` (1 hunks)
* `src/templates/TemplateManager.ts` (2 hunks)
* `src/templates/embeddedTemplates.ts` (2 hunks)
* `src/ui/modal/ModalRenderer.ts` (5 hunks)
* `src/ui/modal/sections/GeneralSection.ts` (4 hunks)
* `src/ui/modal/sections/TypographySection.ts` (5 hunks)
</details>
<details>
<summary>✅ Files skipped from review due to trivial changes (1)</summary>
* README.md
</details>
<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (3)</summary>
* src/ui/modal/sections/GeneralSection.ts
* src/core/DependencyChecker.ts
* src/plugin/CommandRegistry.ts
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>📓 Path-based instructions (2)</summary>
<details>
<summary>src/**/*.ts</summary>
**📄 CodeRabbit inference engine (AGENTS.md)**
> `src/**/*.ts`: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
> Add user-facing commands via this.addCommand(...) and use stable command IDs
> Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
> Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
> Prefer async/await over promise chains and handle errors gracefully
Files:
- `src/templates/embeddedTemplates.ts`
- `src/converters/pdf/PdfCliExecutor.ts`
- `src/converters/pdf/ImageOptimizer.ts`
- `src/converters/PdfToImageConverter.ts`
- `src/core/PathUtils.ts`
- `src/templates/TemplateManager.ts`
- `src/core/ExportErrorHandler.ts`
- `src/converters/PandocTypstConverter.ts`
- `src/plugin/EmbedProcessor.ts`
- `src/ui/modal/sections/TypographySection.ts`
- `src/converters/preprocessors/FrontmatterProcessor.ts`
- `src/ui/modal/ModalRenderer.ts`
- `src/plugin/PluginLifecycle.ts`
- `src/core/SecurityUtils.ts`
</details>
<details>
<summary>package.json</summary>
**📄 CodeRabbit inference engine (AGENTS.md)**
> Use npm as the package manager (project scripts and deps defined in package.json)
Files:
- `package.json`
</details>
</details><details>
<summary>🧠 Learnings (8)</summary>
<details>
<summary>📚 Learning: 2025-09-25T14:27:31.837Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
```
**Applied to files:**
- `src/converters/pdf/PdfCliExecutor.ts`
- `src/converters/pdf/ImageOptimizer.ts`
- `src/converters/PdfToImageConverter.ts`
- `src/core/PathUtils.ts`
- `src/converters/PandocTypstConverter.ts`
- `src/plugin/EmbedProcessor.ts`
- `main.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:14:57.437Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.437Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.
```
**Applied to files:**
- `src/converters/pdf/ImageOptimizer.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to esbuild.config.mjs : Use esbuild for bundling (this sample relies on esbuild.config.mjs)
```
**Applied to files:**
- `package.json`
</details>
<details>
<summary>📚 Learning: 2025-11-05T14:17:36.572Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
```
**Applied to files:**
- `src/core/ExportErrorHandler.ts`
- `src/converters/preprocessors/FrontmatterProcessor.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
```
**Applied to files:**
- `src/converters/PandocTypstConverter.ts`
- `main.ts`
- `src/plugin/PluginLifecycle.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)
```
**Applied to files:**
- `main.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
```
**Applied to files:**
- `main.ts`
</details>
<details>
<summary>📚 Learning: 2025-09-25T14:48:20.040Z</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/**/*.ts : Prefer async/await over promise chains and handle errors gracefully
```
**Applied to files:**
- `src/ui/modal/ModalRenderer.ts`
</details>
</details><details>
<summary>🧬 Code graph analysis (8)</summary>
<details>
<summary>src/converters/pdf/ImageOptimizer.ts (1)</summary><blockquote>
<details>
<summary>src/core/PathUtils.ts (1)</summary>
* `PathUtils` (30-290)
</details>
</blockquote></details>
<details>
<summary>src/converters/PdfToImageConverter.ts (1)</summary><blockquote>
<details>
<summary>src/core/PathUtils.ts (1)</summary>
* `PathUtils` (30-290)
</details>
</blockquote></details>
<details>
<summary>src/core/PathUtils.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Notice` (4-6)
</details>
</blockquote></details>
<details>
<summary>src/converters/PandocTypstConverter.ts (2)</summary><blockquote>
<details>
<summary>src/core/TempDirectoryManager.ts (1)</summary>
* `TempDirectoryManager` (118-471)
</details>
<details>
<summary>src/core/PathUtils.ts (1)</summary>
* `PathUtils` (30-290)
</details>
</blockquote></details>
<details>
<summary>src/plugin/EmbedProcessor.ts (1)</summary><blockquote>
<details>
<summary>src/core/PathUtils.ts (1)</summary>
* `PathUtils` (30-290)
</details>
</blockquote></details>
<details>
<summary>src/ui/modal/sections/TypographySection.ts (1)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Setting` (17-24)
</details>
</blockquote></details>
<details>
<summary>main.ts (1)</summary><blockquote>
<details>
<summary>src/core/DependencyChecker.ts (1)</summary>
* `DependencyChecker` (75-377)
</details>
</blockquote></details>
<details>
<summary>src/plugin/PluginLifecycle.ts (1)</summary><blockquote>
<details>
<summary>src/core/TempDirectoryManager.ts (1)</summary>
* `TempDirectoryManager` (118-471)
</details>
</blockquote></details>
</details><details>
<summary>🪛 Biome (2.1.2)</summary>
<details>
<summary>src/core/SecurityUtils.ts</summary>
[error] 381-381: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
</details>
</details>
</details>
<details>
<summary>🔇 Additional comments (11)</summary><blockquote>
<details>
<summary>package.json (5)</summary><blockquote>
`27-29`: **Establishing Node 18.20.0 as minimum version.**
The engine constraint aligns with Node's maintenance timeline and enables access to modern JavaScript features (async/await, top-level await, ES2020+). Confirm this floor is compatible with your intended plugin users' Obsidian setups.
---
`33-33`: **Verify js-yaml is used as a runtime dependency.**
`js-yaml` has been added as a runtime dependency alongside its TypeScript definitions. Per the PR summary, code now consolidates "runtime requires into top-level imports," so this is justifiable if modules like `FrontmatterProcessor` or template handlers import it directly at runtime. Verify that `js-yaml` is actually imported in runtime code (not just build scripts).
Also applies to: 56-56
---
`35-37`: **TypeScript-ESLint versions are aligned.**
All three `@typescript-eslint/*` packages are pinned to `^8.46.3`, ensuring consistent AST parsing and rule behavior across the linting pipeline. This is good practice.
---
`44-45`: **Verify eslint-plugin-obsidianmd compatibility with ESLint 9.**
`eslint` has been updated to `^9.39.1` and `eslint-plugin-obsidianmd@^0.1.8` is introduced. Confirm the plugin is compatible with ESLint 9's flat config format and does not introduce peer dependency conflicts.
---
`42-42`: **Clarify the need for electron as a devDependency.**
`electron` was updated to `^33.3.0`. For an Obsidian plugin project, electron is typically only needed if you're building/testing desktop integration at dev-time. If this was added as a transitive dependency of another package, consider documenting this. If explicitly needed for the build, confirm its necessity in the PR description or docs.
</blockquote></details>
<details>
<summary>src/core/ExportErrorHandler.ts (3)</summary><blockquote>
`12-12`: **Documentation correctly updated to reflect debug log level.**
The documentation now accurately lists the supported log levels as `(error, warn, debug)`, which aligns with both the interface definition and the implementation.
---
`46-46`: **Interface properly aligned with implementation.**
The `logLevel` type now correctly includes `'debug'` instead of `'info'`, matching the `console.debug()` call in the implementation. This resolves the semantic mismatch identified in the previous review.
---
`183-185`: **Implementation correctly uses console.debug() per ObsidianReviewBot requirements.**
The switch case now uses `'debug'` with `console.debug()`, which complies with ObsidianReviewBot's restriction to only `console.warn()`, `console.error()`, and `console.debug()`. This properly aligns with the updated interface definition.
Based on learnings.
</blockquote></details>
<details>
<summary>src/converters/pdf/PdfCliExecutor.ts (1)</summary><blockquote>
`6-14`: **LGTM! Clean refactoring to top-level imports.**
Moving the `child_process` and `util` imports to the top level and creating `execAsync` once at module scope is more efficient and idiomatic than runtime requires. This eliminates the overhead of recreating the promisified function on each `executeCommand` call while maintaining the same public API.
</blockquote></details>
<details>
<summary>src/ui/modal/sections/TypographySection.ts (2)</summary><blockquote>
`167-169`: **ESLint disable blocks are properly scoped and justified.**
The ESLint disable/enable comments correctly scope the exception to the specific font name declarations that require it. The explanatory comment clearly states why the rule must be disabled (font names are proper nouns).
Note: If the helper methods containing these blocks are determined to be unused (per the previous comment), they should be removed along with the ESLint directives.
Also applies to: 179-179, 198-199, 213-213
---
`16-18`: **✗ setHeading() is a legitimate Obsidian API method used consistently throughout the codebase.**
The original concern about test mock compatibility is incorrect. `setHeading()` appears in 10+ locations across the codebase (TypographySection, LayoutSection, GeneralSection, BehaviorSection, PageSetupSection, and SettingsTab), confirming it's a real Obsidian API method. The test mock not including it is a mock limitation, not a code issue.
The code change at lines 16-18 is valid and follows the established pattern used elsewhere in the project.
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
Importing electron at module scope breaks the plugin on mobile builds (and any runtime without Electron) because the module cannot be resolved during load. Keep the dynamic require inside openPDF instead.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In main.ts around lines 14-15, importing { shell } from 'electron' at module
scope breaks non-Electron targets; move the import into the openPDF function as
a dynamic require. Replace the top-level import by removing it, and inside
openPDF use const { shell } = require('electron') (or a try/catch around require
to handle non-Electron runtimes) so the module is only loaded at call time and
does not prevent mobile builds from loading the module.
_⚠️ Potential issue_ | _🔴 Critical_
**Avoid top-level Electron import**
Importing `electron` at module scope breaks the plugin on mobile builds (and any runtime without Electron) because the module cannot be resolved during load. Keep the dynamic `require` inside `openPDF` instead.
```diff
-import { shell } from 'electron';
@@
openPDF(pdfPath: string): void {
- void shell.openPath(pdfPath);
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const { shell } = require('electron') as typeof import('electron');
+ void shell.openPath(pdfPath);
}
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In main.ts around lines 14-15, importing { shell } from 'electron' at module
scope breaks non-Electron targets; move the import into the openPDF function as
a dynamic require. Replace the top-level import by removing it, and inside
openPDF use const { shell } = require('electron') (or a try/catch around require
to handle non-Electron runtimes) so the module is only loaded at call time and
does not prevent mobile builds from loading the module.
```
</details>
<!-- fingerprinting:phantom:medusa:sabertoothed -->
<!-- This is an auto-generated reply by CodeRabbit -->
Add error handling for fire-and-forget async call.
The void operator suppresses the promise without error handling, violating the coding guideline to "handle errors gracefully". If createFontSettings fails, errors will be silently swallowed. Additionally, this creates a UI ordering issue where the font size settings render before the font dropdowns, which may confuse users.
-void this.createFontSettings(state);
+void this.createFontSettings(state).catch(error => {
+ console.error('Failed to create font settings:', error);
+ // Optionally show user-facing error
+});
As per coding guidelines.
📝 Committable suggestion
‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
void this.createFontSettings(state).catch(error => {
console.error('Failed to create font settings:', error);
// Optionally show user-facing error
});
🤖 Prompt for AI Agents
In src/ui/modal/sections/TypographySection.ts around line 21, the call "void
this.createFontSettings(state);" suppresses errors and causes font-size to
render before font dropdowns; either make render async and await
this.createFontSettings(state) so errors propagate and ordering is preserved
(update the render signature and all call sites accordingly), or keep the
fire-and-forget but attach explicit error handling like
this.createFontSettings(state).catch(err => /* log/report error */) and ensure
any ordering dependent UI updates wait for completion; implement one of these
fixes and remove the void operator.
_⚠️ Potential issue_ | _🟠 Major_
**Add error handling for fire-and-forget async call.**
The `void` operator suppresses the promise without error handling, violating the coding guideline to "handle errors gracefully". If `createFontSettings` fails, errors will be silently swallowed. Additionally, this creates a UI ordering issue where the font size settings render before the font dropdowns, which may confuse users.
Consider one of these approaches:
**Option 1: Await the font settings creation**
```diff
-void this.createFontSettings(state);
-this.createFontSizeSettings(state);
+await this.createFontSettings(state);
+this.createFontSizeSettings(state);
```
Then change the `render` method signature to:
```diff
-render(containerEl: HTMLElement, state: ModalState, app?: App): void {
+async render(containerEl: HTMLElement, state: ModalState, app?: App): Promise<void> {
```
**Option 2: Add error handling with void operator**
```diff
-void this.createFontSettings(state);
+void this.createFontSettings(state).catch(error => {
+ console.error('Failed to create font settings:', error);
+ // Optionally show user-facing error
+});
```
As per coding guidelines.
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
void this.createFontSettings(state).catch(error => {
console.error('Failed to create font settings:', error);
// Optionally show user-facing error
});
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/ui/modal/sections/TypographySection.ts around line 21, the call "void
this.createFontSettings(state);" suppresses errors and causes font-size to
render before font dropdowns; either make render async and await
this.createFontSettings(state) so errors propagate and ordering is preserved
(update the render signature and all call sites accordingly), or keep the
fire-and-forget but attach explicit error handling like
this.createFontSettings(state).catch(err => /* log/report error */) and ensure
any ordering dependent UI updates wait for completion; implement one of these
fixes and remove the void operator.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits 5219ef7 to d6d31af
@AlexKucera, understood! Since this plugin is desktop-only, the top-level electron import is perfectly fine. Thank you for clarifying the deployment target.
✏️ Learnings added
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: main.ts:14-15
Timestamp: 2025-11-08T18:51:00.473Z
Learning: The obsidian-typst-pdf-export plugin is a desktop-only release and does not target mobile platforms, so Electron dependencies and desktop-specific APIs can be used without mobile compatibility concerns.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
🧠 Learnings used
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
@AlexKucera, understood! Since this plugin is desktop-only, the top-level `electron` import is perfectly fine. Thank you for clarifying the deployment target.
---
<details>
<summary>✏️ Learnings added</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: main.ts:14-15
Timestamp: 2025-11-08T18:51:00.473Z
Learning: The obsidian-typst-pdf-export plugin is a desktop-only release and does not target mobile platforms, so Electron dependencies and desktop-specific APIs can be used without mobile compatibility concerns.
```
> Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings).
</details>
---
<details>
<summary>🧠 Learnings used</summary>
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)
```
---
```
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
```
</details>
<!-- This is an auto-generated reply by CodeRabbit -->
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/ui/modal/sections/TypographySection.ts (1)
20-26: Good error handling, but clarify the comment.
The .catch() block successfully addresses the previous review concern about error handling. However, the comment on line 24 is misleading: if createFontSettings fails completely (e.g., due to an exception), no font settings will be created—not a "fallback to default fonts." The actual fallback behavior occurs when getAvailableFonts fails, which returns hardcoded fonts.
Consider clarifying the comment:
- // Font settings will fall back to default fonts if this fails
+ // If font loading fails, getAvailableFonts will use hardcoded fallback fonts
256-344: Consider logging unexpected types in formatFrontmatterForDisplay.
The method has comprehensive type handling, which is excellent. However, the else clause at lines 325-328 silently returns an empty string for unexpected types. While this is safe (and line 267 already filters most edge cases), consider logging a debug message when an unexpected type is encountered to aid future debugging.
Apply this diff to add debug logging for unexpected types:
} else {
- // Handle null, undefined, or any other unexpected types
+ // Handle null, undefined, or any other unexpected types
+ console.debug('FrontmatterProcessor: Unexpected type in frontmatter display formatting', `key: ${key}, type: ${typeof value}`);
formattedValue = '';
}
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between c1c02ee553 and d6d31afb16.
src/**/*.ts: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
Add user-facing commands via this.addCommand(...) and use stable command IDs
Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
Prefer async/await over promise chains and handle errors gracefully
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
Applied to files:
src/core/SecurityUtils.ts
📚 Learning: 2025-11-05T14:17:36.572Z
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
[error] 387-387: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
🔇 Additional comments (11)
src/core/SecurityUtils.ts (3)
119-126: LGTM! Strong security improvement.
The explicit absolute path check before normalization is the correct approach. Checking path.isAbsolute() on the raw trimmed input prevents potential bypasses where normalization might mask absolute path patterns.
287-293: LGTM! Consistent error handling.
The error message logic correctly mirrors the validation logic in validateOutputPath, providing users with specific, actionable feedback about absolute path rejection.
225-226: LGTM! Appropriate security validation.
The ESLint disable comments clearly document that the null byte checks (\x00) are intentional security validations, not accidental control characters. These checks are critical for preventing path injection attacks.
Note: Biome is flagging line 387 as containing a control character in the regex. This is a false positive since the null byte check is intentional. If you want to suppress Biome's warning as well, you may need to add a Biome-specific comment (e.g., // biome-ignore lint/suspicious/noControlCharactersInRegex: <reason>), as it doesn't respect ESLint directives.
Using the Setting component with .setHeading() is the recommended approach for modal section headings and provides better consistency with the rest of the Obsidian UI.
109-110: Font size settings now coupled to async font loading flow.
Moving createFontSizeSettings inside the async function successfully preserves the visual ordering (font dropdowns appear before font size controls). However, this means if createFontSettings encounters an early failure, font size settings also won't render.
This is acceptable since createFontSettings has robust error handling (container check, getAvailableFonts fallback), but be aware of this dependency if you later need font size settings to always appear regardless of font loading status.
Moving from inline require() to top-level imports follows ES6 best practices and makes dependencies explicit.
49-49: LGTM: Privacy concern addressed.
The debug logging now only includes content length rather than raw content snippets, properly addressing the previous review feedback about sensitive data leakage.
54-65: LGTM: Sanitization prevents citation field leakage.
The approach of sanitizing frontmatter before storing it in metadata is sound and prevents bibliography/citation fields from affecting downstream Pandoc processing. The sequencing is correct: sanitize first, then apply title overrides.
71-90: LGTM: Comprehensive tag extraction.
The tag extraction logic properly handles both array and string representations, includes type safety checks, and correctly merges with existing tags while avoiding duplicates.
153-153: LGTM: Error logging respects privacy.
The error logging correctly uses console.error() (which is allowed) and only logs the error message and content length, avoiding any sensitive data leakage.
239-251: LGTM: Citation field sanitization is well-implemented.
The stripCitationFields method correctly uses a shallow copy and removes a comprehensive list of citation-related fields to prevent Pandoc bibliography processing.
**Actionable comments posted: 1**
<details>
<summary>🧹 Nitpick comments (2)</summary><blockquote>
<details>
<summary>src/ui/modal/sections/TypographySection.ts (1)</summary><blockquote>
`20-26`: **Good error handling, but clarify the comment.**
The `.catch()` block successfully addresses the previous review concern about error handling. However, the comment on line 24 is misleading: if `createFontSettings` fails completely (e.g., due to an exception), no font settings will be created—not a "fallback to default fonts." The actual fallback behavior occurs when `getAvailableFonts` fails, which returns hardcoded fonts.
Consider clarifying the comment:
```diff
- // Font settings will fall back to default fonts if this fails
+ // If font loading fails, getAvailableFonts will use hardcoded fallback fonts
```
As per coding guidelines.
</blockquote></details>
<details>
<summary>src/converters/preprocessors/FrontmatterProcessor.ts (1)</summary><blockquote>
`256-344`: **Consider logging unexpected types in formatFrontmatterForDisplay.**
The method has comprehensive type handling, which is excellent. However, the else clause at lines 325-328 silently returns an empty string for unexpected types. While this is safe (and line 267 already filters most edge cases), consider logging a debug message when an unexpected type is encountered to aid future debugging.
Apply this diff to add debug logging for unexpected types:
```diff
} else {
- // Handle null, undefined, or any other unexpected types
+ // Handle null, undefined, or any other unexpected types
+ console.debug('FrontmatterProcessor: Unexpected type in frontmatter display formatting', `key: ${key}, type: ${typeof value}`);
formattedValue = '';
}
```
</blockquote></details>
</blockquote></details>
<details>
<summary>📜 Review details</summary>
**Configuration used**: CodeRabbit UI
**Review profile**: CHILL
**Plan**: Pro
<details>
<summary>📥 Commits</summary>
Reviewing files that changed from the base of the PR and between c1c02ee553e64bc9b28372cd3de0ae9bece7b89e and d6d31afb16e8ece4926824c3b97ca36ff837295a.
</details>
<details>
<summary>📒 Files selected for processing (3)</summary>
* `src/converters/preprocessors/FrontmatterProcessor.ts` (10 hunks)
* `src/core/SecurityUtils.ts` (4 hunks)
* `src/ui/modal/sections/TypographySection.ts` (3 hunks)
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>📓 Path-based instructions (1)</summary>
<details>
<summary>src/**/*.ts</summary>
**📄 CodeRabbit inference engine (AGENTS.md)**
> `src/**/*.ts`: Organize code into multiple files under src/ (commands/, ui/, utils/, etc.) rather than putting everything in main.ts
> Add user-facing commands via this.addCommand(...) and use stable command IDs
> Persist settings using this.loadData()/this.saveData() and provide sensible defaults via a settings tab
> Register and clean up all DOM, app, and interval listeners using this.register* helpers for safe unload
> Prefer async/await over promise chains and handle errors gracefully
Files:
- `src/core/SecurityUtils.ts`
- `src/converters/preprocessors/FrontmatterProcessor.ts`
- `src/ui/modal/sections/TypographySection.ts`
</details>
</details><details>
<summary>🧠 Learnings (2)</summary>
<details>
<summary>📚 Learning: 2025-09-25T14:27:31.837Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.837Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.
```
**Applied to files:**
- `src/core/SecurityUtils.ts`
</details>
<details>
<summary>📚 Learning: 2025-11-05T14:17:36.572Z</summary>
```
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().
```
**Applied to files:**
- `src/converters/preprocessors/FrontmatterProcessor.ts`
</details>
</details><details>
<summary>🧬 Code graph analysis (1)</summary>
<details>
<summary>src/ui/modal/sections/TypographySection.ts (3)</summary><blockquote>
<details>
<summary>tests/__mocks__/obsidian.ts (1)</summary>
* `Setting` (17-24)
</details>
<details>
<summary>src/ui/modal/state/ModalState.ts (1)</summary>
* `ModalState` (10-213)
</details>
<details>
<summary>src/ui/modal/modalTypes.ts (1)</summary>
* `ModalState` (60-70)
</details>
</blockquote></details>
</details><details>
<summary>🪛 Biome (2.1.2)</summary>
<details>
<summary>src/core/SecurityUtils.ts</summary>
[error] 387-387: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
</details>
</details>
</details>
<details>
<summary>🔇 Additional comments (11)</summary><blockquote>
<details>
<summary>src/core/SecurityUtils.ts (3)</summary><blockquote>
`119-126`: **LGTM! Strong security improvement.**
The explicit absolute path check before normalization is the correct approach. Checking `path.isAbsolute()` on the raw trimmed input prevents potential bypasses where normalization might mask absolute path patterns.
---
`287-293`: **LGTM! Consistent error handling.**
The error message logic correctly mirrors the validation logic in `validateOutputPath`, providing users with specific, actionable feedback about absolute path rejection.
---
`225-226`: **LGTM! Appropriate security validation.**
The ESLint disable comments clearly document that the null byte checks (`\x00`) are intentional security validations, not accidental control characters. These checks are critical for preventing path injection attacks.
**Note:** Biome is flagging line 387 as containing a control character in the regex. This is a false positive since the null byte check is intentional. If you want to suppress Biome's warning as well, you may need to add a Biome-specific comment (e.g., `// biome-ignore lint/suspicious/noControlCharactersInRegex: <reason>`), as it doesn't respect ESLint directives.
Also applies to: 386-387
</blockquote></details>
<details>
<summary>src/ui/modal/sections/TypographySection.ts (2)</summary><blockquote>
`16-18`: **LGTM! Standardized heading follows Obsidian UI patterns.**
Using the `Setting` component with `.setHeading()` is the recommended approach for modal section headings and provides better consistency with the rest of the Obsidian UI.
---
`109-110`: **Font size settings now coupled to async font loading flow.**
Moving `createFontSizeSettings` inside the async function successfully preserves the visual ordering (font dropdowns appear before font size controls). However, this means if `createFontSettings` encounters an early failure, font size settings also won't render.
This is acceptable since `createFontSettings` has robust error handling (container check, `getAvailableFonts` fallback), but be aware of this dependency if you later need font size settings to always appear regardless of font loading status.
</blockquote></details>
<details>
<summary>src/converters/preprocessors/FrontmatterProcessor.ts (6)</summary><blockquote>
`6-7`: **LGTM: Top-level imports improve code organization.**
Moving from inline `require()` to top-level imports follows ES6 best practices and makes dependencies explicit.
---
`49-49`: **LGTM: Privacy concern addressed.**
The debug logging now only includes content length rather than raw content snippets, properly addressing the previous review feedback about sensitive data leakage.
---
`54-65`: **LGTM: Sanitization prevents citation field leakage.**
The approach of sanitizing frontmatter before storing it in metadata is sound and prevents bibliography/citation fields from affecting downstream Pandoc processing. The sequencing is correct: sanitize first, then apply title overrides.
---
`71-90`: **LGTM: Comprehensive tag extraction.**
The tag extraction logic properly handles both array and string representations, includes type safety checks, and correctly merges with existing tags while avoiding duplicates.
---
`153-153`: **LGTM: Error logging respects privacy.**
The error logging correctly uses `console.error()` (which is allowed) and only logs the error message and content length, avoiding any sensitive data leakage.
---
`239-251`: **LGTM: Citation field sanitization is well-implemented.**
The `stripCitationFields` method correctly uses a shallow copy and removes a comprehensive list of citation-related fields to prevent Pandoc bibliography processing.
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
In src/converters/preprocessors/FrontmatterProcessor.ts around lines 118, 185
and 204, several lines have extra leading whitespace causing inconsistent
indentation; remove the extra leading spaces on each of the affected lines so
they align with the surrounding block indentation (match the same indent level
as neighboring statements), keeping existing spacing within the line intact and
ensuring the file's indentation style remains consistent.
_⚠️ Potential issue_ | _🟡 Minor_
**Fix indentation inconsistencies.**
These lines appear to have extra leading whitespace. Ensure consistent indentation throughout the file.
Apply this diff to fix line 118:
```diff
if (this.noteTitle) {
- const titleFrontmatter = yaml.dump({ title: this.noteTitle });
+ const titleFrontmatter = yaml.dump({ title: this.noteTitle });
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
```
Apply similar fixes to lines 185 and 204:
```diff
if (this.noteTitle) {
- const newFrontmatter = yaml.dump(frontmatter);
+ const newFrontmatter = yaml.dump(frontmatter);
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
```
```diff
if (this.noteTitle) {
- const titleFrontmatter = yaml.dump({ title: this.noteTitle });
+ const titleFrontmatter = yaml.dump({ title: this.noteTitle });
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
```
Also applies to: 185-185, 204-204
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/converters/preprocessors/FrontmatterProcessor.ts around lines 118, 185
and 204, several lines have extra leading whitespace causing inconsistent
indentation; remove the extra leading spaces on each of the affected lines so
they align with the surrounding block indentation (match the same indent level
as neighboring statements), keeping existing spacing within the line intact and
ensuring the file's indentation style remains consistent.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commit efbff4e
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Summary by CodeRabbit
New Features
Bug Fixes
Style
Chores
Documentation
Walkthrough
Consolidates dynamic requires into top-level imports, migrates many vault/file ops to Node fs.promises with vault-relative handling, converts selected async APIs to synchronous or Promise-capable forms, moves modal state to vault-local storage, standardizes modal headings to Setting components, and adds guarded error handling for prior fire-and-forget calls.
Changes
eslint.config.mjs,package.json,tsconfig.jsoneslint-plugin-obsidianmdand import plugin; update/add devDeps (eslint, electron,@typescript-eslint/*, js-yaml, vitest, tslib, typescript); enableesModuleInteropandallowSyntheticDefaultImports.src/core/DependencyChecker.ts,src/converters/MarkdownPreprocessor.ts,src/plugin/PluginLifecycle.ts,main.tscheckDependenciesOnStartup); make MarkdownPreprocessor.process synchronous; change PluginLifecycle.cleanup to asyncPromise<void>; makemain.onunloadasync and await lifecycle cleanup.src/core/ExecutableChecker.ts,src/converters/pdf/PdfCliExecutor.ts,src/converters/pdf/ImageOptimizer.ts,src/plugin/EmbedProcessor.ts,src/plugin/FontManager.ts,src/plugin/PathResolver.ts,src/converters/pdf/FileDiscovery.ts,src/converters/pdf/BinaryLocator.tsrequirecalls with top-level ES imports (child_process spawn/spawnSync/exec, util.promisify,fs.promises) and remove in-function requires.src/core/TempDirectoryManager.ts,src/templates/embeddedTemplates.ts,src/templates/TemplateManager.ts,src/converters/PandocTypstConverter.tsfs.promises(mkdir/access/readdir/unlink); ensure directories, use vault-relative paths viaPathUtils.toVaultRelative; tie cleanup to plugin lifecycle (dispose/unload).src/core/PathUtils.ts,src/core/SecurityUtils.ts,src/converters/PdfToImageConverter.ts,src/converters/pdf/BinaryLocator.ts,src/converters/pdf/FileDiscovery.tsPathUtils.toVaultRelative; preserve absolute paths where appropriate; reject absolute outputs in validators; strengthenconfigDirguards; use top-levelfsfor absolute checks.src/converters/preprocessors/FrontmatterProcessor.tsgray-matterandjs-yaml; sanitize frontmatter (strip citation fields), robust fallback parsing for malformed frontmatter, improved tag merging, formatted display output, and enhanced error handling/logging.src/converters/pdf/ImageOptimizer.ts,src/converters/PdfToImageConverter.ts,src/plugin/EmbedProcessor.ts,src/plugin/ExportOrchestrator.tstempImagesDir, convert many adapter ops to use vault-relative paths, perform conversions with absolute paths when required, centralize remote-download completion handling, improve error propagation and debug logging, and treat preprocessor.process as synchronous.src/converters/pandoc/PandocCommandBuilder.ts--no-citeprocflag so Pandoc uses default citation processing (no citeproc disabling).src/ui/modal/ExportConfigModal.ts,src/ui/modal/ModalRenderer.ts,src/ui/modal/state/ModalState.ts,src/ui/modal/sections/*,src/plugin/SettingsTab.ts,styles.cssSettingheadings; onSubmit callbacks acceptPromise<void>;ModalStatenow acceptsAppand uses vault-local storage APIs; minor text/capitalization edits; add modal styles.src/plugin/CommandRegistry.ts,src/plugin/EventHandlers.ts.catch(...)and/orvoidto handle errors and avoid silent rejections; adjust some command/menu labels.src/core/ExportErrorHandler.ts,src/plugin/PathResolver.ts,obsidianreviewbot-feedback.md,README.md,src/templates/TemplateManager.tsinfo→debug), error message tweaks/quoting, switch-case scoping fix, README Node version bumped to>=18.20.0, consolidate template path usage withPathUtils.toVaultRelative.Sequence Diagram(s)
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches
✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
obsidian-bot-review📜 Recent review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
d6d31afb16andefbff4e172.📒 Files selected for processing (2)
src/converters/preprocessors/FrontmatterProcessor.ts(7 hunks)src/ui/modal/sections/TypographySection.ts(3 hunks)🧰 Additional context used
📓 Path-based instructions (1)
src/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/ui/modal/sections/TypographySection.tssrc/converters/preprocessors/FrontmatterProcessor.ts🧠 Learnings (1)
📚 Learning: 2025-11-05T14:17:36.572Z
Applied to files:
src/converters/preprocessors/FrontmatterProcessor.ts🧬 Code graph analysis (2)
src/ui/modal/sections/TypographySection.ts (3)
src/converters/preprocessors/FrontmatterProcessor.ts (1)
🔇 Additional comments (6)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands and usage tips.Actionable comments posted: 8
🧹 Nitpick comments (3)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
39d66607afand2c4076f3c9.⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json📒 Files selected for processing (36)
eslint.config.mjs(2 hunks)main.ts(3 hunks)obsidianreviewbot-feedback.md(1 hunks)package.json(2 hunks)src/converters/MarkdownPreprocessor.ts(7 hunks)src/converters/PandocTypstConverter.ts(2 hunks)src/converters/pdf/BinaryLocator.ts(2 hunks)src/converters/pdf/FileDiscovery.ts(2 hunks)src/converters/pdf/ImageOptimizer.ts(1 hunks)src/converters/pdf/PdfCliExecutor.ts(1 hunks)src/converters/preprocessors/FrontmatterProcessor.ts(8 hunks)src/core/DependencyChecker.ts(1 hunks)src/core/ExecutableChecker.ts(1 hunks)src/core/ExportErrorHandler.ts(1 hunks)src/core/ModalSettingsHelper.ts(2 hunks)src/core/PathUtils.ts(1 hunks)src/core/SecurityUtils.ts(2 hunks)src/plugin/CommandRegistry.ts(3 hunks)src/plugin/EmbedProcessor.ts(6 hunks)src/plugin/EventHandlers.ts(6 hunks)src/plugin/ExportOrchestrator.ts(3 hunks)src/plugin/FontManager.ts(1 hunks)src/plugin/PathResolver.ts(1 hunks)src/plugin/PluginLifecycle.ts(3 hunks)src/plugin/SettingsTab.ts(6 hunks)src/templates/TemplateManager.ts(1 hunks)src/ui/modal/ExportConfigModal.ts(5 hunks)src/ui/modal/ModalRenderer.ts(4 hunks)src/ui/modal/sections/BehaviorSection.ts(1 hunks)src/ui/modal/sections/GeneralSection.ts(1 hunks)src/ui/modal/sections/LayoutSection.ts(1 hunks)src/ui/modal/sections/PageSetupSection.ts(3 hunks)src/ui/modal/sections/TypographySection.ts(1 hunks)src/ui/modal/state/ModalState.ts(4 hunks)styles.css(1 hunks)tsconfig.json(1 hunks)🧰 Additional context used
📓 Path-based instructions (4)
src/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/templates/TemplateManager.tssrc/converters/pdf/ImageOptimizer.tssrc/plugin/FontManager.tssrc/plugin/ExportOrchestrator.tssrc/plugin/PathResolver.tssrc/converters/PandocTypstConverter.tssrc/core/ExportErrorHandler.tssrc/plugin/CommandRegistry.tssrc/plugin/EmbedProcessor.tssrc/ui/modal/sections/TypographySection.tssrc/ui/modal/sections/GeneralSection.tssrc/ui/modal/state/ModalState.tssrc/core/ModalSettingsHelper.tssrc/ui/modal/ModalRenderer.tssrc/ui/modal/sections/BehaviorSection.tssrc/converters/MarkdownPreprocessor.tssrc/plugin/SettingsTab.tssrc/core/PathUtils.tssrc/ui/modal/sections/PageSetupSection.tssrc/plugin/EventHandlers.tssrc/ui/modal/sections/LayoutSection.tssrc/core/ExecutableChecker.tssrc/converters/pdf/PdfCliExecutor.tssrc/core/DependencyChecker.tssrc/converters/pdf/BinaryLocator.tssrc/core/SecurityUtils.tssrc/converters/preprocessors/FrontmatterProcessor.tssrc/plugin/PluginLifecycle.tssrc/converters/pdf/FileDiscovery.tssrc/ui/modal/ExportConfigModal.ts{manifest.json,main.js,styles.css}
📄 CodeRabbit inference engine (AGENTS.md)
Files:
styles.csspackage.json
📄 CodeRabbit inference engine (AGENTS.md)
Files:
package.jsontsconfig.json
📄 CodeRabbit inference engine (AGENTS.md)
Files:
tsconfig.json🧠 Learnings (8)
📓 Common learnings
📚 Learning: 2025-09-25T14:14:57.437Z
Applied to files:
src/converters/pdf/ImageOptimizer.ts📚 Learning: 2025-09-25T14:27:31.837Z
Applied to files:
src/converters/pdf/ImageOptimizer.tssrc/plugin/FontManager.tssrc/plugin/PathResolver.tssrc/converters/PandocTypstConverter.tssrc/plugin/EmbedProcessor.tssrc/core/ModalSettingsHelper.tsmain.tssrc/core/PathUtils.tssrc/plugin/EventHandlers.tssrc/core/ExecutableChecker.tssrc/converters/pdf/PdfCliExecutor.tssrc/converters/pdf/BinaryLocator.tssrc/converters/pdf/FileDiscovery.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
package.jsoneslint.config.mjs📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/plugin/CommandRegistry.tssrc/plugin/PluginLifecycle.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
tsconfig.json📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/ui/modal/sections/GeneralSection.tssrc/ui/modal/state/ModalState.tssrc/core/ModalSettingsHelper.tssrc/plugin/SettingsTab.tssrc/ui/modal/sections/PageSetupSection.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/plugin/EventHandlers.tssrc/core/DependencyChecker.ts🧬 Code graph analysis (13)
src/converters/PandocTypstConverter.ts (2)
src/ui/modal/sections/TypographySection.ts (1)
src/ui/modal/sections/GeneralSection.ts (1)
src/ui/modal/state/ModalState.ts (2)
main.ts (1)
src/ui/modal/sections/BehaviorSection.ts (1)
src/converters/MarkdownPreprocessor.ts (1)
src/plugin/SettingsTab.ts (1)
src/ui/modal/sections/PageSetupSection.ts (3)
src/ui/modal/sections/LayoutSection.ts (1)
src/plugin/PluginLifecycle.ts (1)
src/converters/pdf/FileDiscovery.ts (2)
src/ui/modal/ExportConfigModal.ts (2)
🪛 Biome (2.1.2)
src/core/SecurityUtils.ts
[error] 378-378: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
🔇 Additional comments (33)
@@ -31,0 +40,4 @@'obsidianmd/commands/no-default-hotkeys': 'error','obsidianmd/commands/no-plugin-id-in-command-id': 'error','obsidianmd/commands/no-plugin-name-in-command-name': 'error',⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
Modern ESLint configuration pattern.
The configuration correctly uses
projectServicewithimport.meta.dirnamefor TypeScript parser configuration. Note thatimport.meta.dirnamerequires Node.js 20.11+ or a polyfill in earlier versions.Verify that the project's minimum Node.js version supports
import.meta.dirname:🏁 Script executed:
Length of output: 59
🏁 Script executed:
Length of output: 210
Node.js version incompatibility with
import.meta.dirname.The code uses
import.meta.dirname(line 31), which requires Node.js 20.11+ or 18.20+. However, the README specifies "Node.js: Version 16+" for development, creating a compatibility gap. Developers on Node.js 16 or 17.x versions cannot run this configuration.Update the minimum Node.js version requirement to 18.20+ or 20.11+ in README.md and package.json, or replace
import.meta.dirnamewith an alternative that supports Node.js 16+ (e.g.,dirname(fileURLToPath(import.meta.url))).🤖 Prompt for AI Agents
⚠️ Potential issue | 🟠 Major
Fire-and-forget cleanup won't complete on process termination.
Process event handlers like 'exit', 'SIGINT', and 'SIGTERM' are synchronous and terminate immediately without waiting for promises. Calling
void this.cleanup()means the async file removal operations incleanup()(line 340) will likely not complete before the process exits, leaving temporary files behind.Consider using Obsidian's plugin lifecycle methods (
onunload) for cleanup instead of Node.js process events, as plugin unload hooks are better suited for async cleanup operations.Apply this diff to document the limitation:
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee⚠️ Potential issue | 🔴 Critical
Provide default value for potentially undefined configDir.
Lines 367 and 374 use optional chaining that can result in
undefined, butTempDirectoryManager.create()(line 368) and theTempDirectoryManagerconstructor (line 375) expectconfigDir: stringaccording to the relevant code snippets. Passingundefinedwill cause type errors or runtime failures in path resolution.Restore the default value to ensure type safety:
Apply this diff:
Also applies to: 374-375
🤖 Prompt for AI Agents
@@ -43,28 +44,30 @@ export class FrontmatterProcessor {}⚠️ Potential issue | 🟠 Major
Remove raw-content logging from diagnostics.
These new
console.debug/console.errorstatements dump the first 200–500 characters of user notes directly to the developer console. Even in debug builds this is sensitive content (frontmatter often includes titles, tags, authors, etc.), so shipping this logging materially increases the risk of leaking private vault data. Please strip the raw-content logging (or gate it behind an explicit opt-in) before release.Also applies to: 152-154
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee@@ -180,8 +180,8 @@ export class ExportErrorHandler {case 'warn':console.warn(`${operation}:`, error);⚠️ Potential issue | 🟡 Minor
Align logLevel parameter with actual logging behavior.
The
logLevelparameter accepts'info'per the interface definition (line 46), but the implementation now usesconsole.debug()instead ofconsole.info(). This creates a semantic mismatch where callers specify'info'but receive debug-level logging.Consider one of these options:
console.info()if info-level logging is the intended behavior, OR'debug'instead of'info'to match the implementationOption 1: Revert to console.info
Option 2: Update interface and documentation
📝 Committable suggestion
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee@@ -29,2 +33,3 @@editorCallback: (editor: Editor, view: MarkdownView) => {this.plugin.showExportModal(view);this.plugin.showExportModal(view).catch(error => {console.error('Failed to show export modal:', error);⚠️ Potential issue | 🟠 Major
Error handling should notify users, not just log to console
When a user-initiated command fails, logging to console provides no feedback to the user. They won't know why the export didn't happen. Consider showing a Notice with the error message so users understand what went wrong.
Apply this pattern for user-facing error handling:
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee⚠️ Potential issue | 🟠 Major
Error handling should notify users, not just log to console
Similar to the export command, users should be notified when the modal fails to open rather than failing silently.
📝 Committable suggestion
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee⚠️ Potential issue | 🟠 Major
Error handling should notify users, not just log to console
The dependency status check is a user-initiated command and should show errors via Notice.
Note: You'll need to import
Noticefrom 'obsidian' at the top of the file.🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee@coderabbitai ObsidianReviewBot specifically has an issue with this:
@@ -180,8 +180,8 @@ export class ExportErrorHandler {case 'warn':console.warn(`${operation}:`, error);@coderabbitai ObsidianReviewBot raised this issue:
🧩 Analysis chain
🏁 Script executed:
Length of output: 26660
@AlexKucera You're absolutely right! The ObsidianReviewBot feedback is correct — we shouldn't hardcode
.obsidianas a fallback since users can configure a different config directory.Looking at the pattern already established in your codebase (specifically in
BinaryLocator.tsfrom the AI summary), the proper solution is to throw an error whenconfigDircannot be accessed rather than falling back to a hardcoded value.Here's the corrected approach:
This approach:
vault.configDir.obsidianBinaryLocator.tsTempDirectoryManagerThe error throw is appropriate here because if the plugin/app/vault isn't accessible, something is fundamentally wrong with the initialization, and the conversion can't proceed safely anyway.
🧬 Code Graph Analysis Results
[src/converters/PandocTypstConverter.ts] ensureTempDirectory - snippet
const configDir = this.plugin?.app?.vault?.configDir;
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
this.tempDir = await tempManager.ensureTempDir('pandoc');
[src/core/TempDirectoryManager.ts] getPluginDir - snippet
private getPluginDir(): string {
// path.join automatically handles absolute paths correctly
const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
return normalizePath(result);
}
🧠 Learnings used
@@ -180,8 +180,8 @@ export class ExportErrorHandler {case 'warn':console.warn(`${operation}:`, error);🧩 Analysis chain
🏁 Script executed:
Length of output: 72
🏁 Script executed:
Length of output: 28847
@AlexKucera, thank you for clarifying! That makes sense—ObsidianReviewBot's restriction to only
console.warn,console.error, andconsole.debugmeans we need to align the interface with the implementation.Since no code in the codebase is currently using
logLevel: 'info'(confirmed by the search), you only need to update:ExportErrorinterface:(This is fine as-is, but you could optionally clarify it accepts 'error' | 'warn' | 'debug')
to remain as 'warn' (already correct), but the comment text that mentions "info" in the example doesn't exist, so you're good there.
The change from
console.info()toconsole.debug()is the right approach given the ObsidianReviewBot constraint. Just update the interface definition to match! 🎯🧬 Code Graph Analysis Results
tests/mocks/obsidian.ts
At lines 4-6: ``` export class Notice { constructor(message: string) {} } ```src/core/constants.ts
At lines 122-128: ``` export const EXPORT_CONSTANTS = { DEFAULT_TIMEOUT: 120000, // 2 minutes NOTICE_DURATION: { SHORT: 5000, LONG: 12000 } } as const; ```✏️ Learnings added
Actionable comments posted: 7
♻️ Duplicate comments (7)
🧹 Nitpick comments (7)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
2c4076f3c9and87f3894bf1.📒 Files selected for processing (18)
eslint.config.mjs(2 hunks)src/converters/PandocTypstConverter.ts(5 hunks)src/converters/PdfToImageConverter.ts(1 hunks)src/converters/pandoc/PandocCommandBuilder.ts(0 hunks)src/converters/pdf/BinaryLocator.ts(2 hunks)src/converters/pdf/ImageOptimizer.ts(2 hunks)src/converters/preprocessors/FrontmatterProcessor.ts(10 hunks)src/core/PathUtils.ts(3 hunks)src/core/TempDirectoryManager.ts(5 hunks)src/plugin/CommandRegistry.ts(2 hunks)src/plugin/EmbedProcessor.ts(10 hunks)src/plugin/EventHandlers.ts(6 hunks)src/plugin/ExportOrchestrator.ts(4 hunks)src/plugin/PathResolver.ts(2 hunks)src/plugin/SettingsTab.ts(11 hunks)src/templates/embeddedTemplates.ts(2 hunks)src/ui/modal/ModalRenderer.ts(5 hunks)src/ui/modal/sections/GeneralSection.ts(3 hunks)💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
🧰 Additional context used
📓 Path-based instructions (1)
src/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/core/TempDirectoryManager.tssrc/plugin/EventHandlers.tssrc/core/PathUtils.tssrc/plugin/EmbedProcessor.tssrc/ui/modal/ModalRenderer.tssrc/converters/preprocessors/FrontmatterProcessor.tssrc/converters/PdfToImageConverter.tssrc/converters/pdf/ImageOptimizer.tssrc/plugin/PathResolver.tssrc/converters/PandocTypstConverter.tssrc/ui/modal/sections/GeneralSection.tssrc/plugin/SettingsTab.tssrc/templates/embeddedTemplates.tssrc/plugin/CommandRegistry.tssrc/plugin/ExportOrchestrator.ts🧠 Learnings (9)
📓 Common learnings
📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
eslint.config.mjs📚 Learning: 2025-09-25T14:27:31.837Z
Applied to files:
src/core/TempDirectoryManager.tssrc/plugin/EventHandlers.tssrc/core/PathUtils.tssrc/plugin/EmbedProcessor.tssrc/converters/PdfToImageConverter.tssrc/converters/pdf/ImageOptimizer.tssrc/plugin/PathResolver.tssrc/converters/PandocTypstConverter.tssrc/ui/modal/sections/GeneralSection.tssrc/plugin/SettingsTab.tssrc/plugin/ExportOrchestrator.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/plugin/EventHandlers.ts📚 Learning: 2025-11-05T14:17:36.572Z
Applied to files:
src/converters/preprocessors/FrontmatterProcessor.ts📚 Learning: 2025-09-25T14:14:57.437Z
Applied to files:
src/converters/pdf/ImageOptimizer.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/ui/modal/sections/GeneralSection.tssrc/plugin/SettingsTab.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/plugin/CommandRegistry.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/plugin/CommandRegistry.ts🧬 Code graph analysis (9)
src/core/TempDirectoryManager.ts (1)
src/core/PathUtils.ts (1)
src/converters/PdfToImageConverter.ts (1)
src/converters/pdf/ImageOptimizer.ts (1)
src/plugin/PathResolver.ts (1)
src/converters/PandocTypstConverter.ts (2)
src/ui/modal/sections/GeneralSection.ts (2)
src/plugin/SettingsTab.ts (1)
src/plugin/ExportOrchestrator.ts (2)
🔇 Additional comments (40)
@@ -413,10 +413,11 @@ export class PdfToImageConverter {};🛠️ Refactor suggestion | 🟠 Major
Extract duplicated path conversion logic to PathUtils helper.
This vault-relative path conversion pattern is duplicated across multiple files (ImageOptimizer.ts, embeddedTemplates.ts, and here). Consolidating to a PathUtils helper method would reduce duplication and improve maintainability.
See the detailed suggestion in the review comment for
src/converters/pdf/ImageOptimizer.tslines 247-304. The samepathUtils.toVaultRelative()helper would simplify this code:🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee@@ -251,3 +242,3 @@await plugin.app.vault.adapter.remove(relativeInputPath);} else {const fs = require('fs').promises;await fs.rename(inputImagePath, pngFinalPath);🛠️ Refactor suggestion | 🟠 Major
Extract duplicated path conversion logic to PathUtils helper.
The vault-relative path conversion pattern (stripping vault base path and leading separators) is duplicated three times in this file (lines 220-234, 247-271, 280-304). This code duplication increases maintenance burden and the risk of inconsistencies.
Consider adding a helper method to PathUtils:
Then replace the duplicated blocks:
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
Verify the normalizePath behavior claim.
The comment states that
normalizePathstrips the leading slash from absolute paths, but this should be verified. The Obsidian API documentation or actual testing should confirm this behavior before bypassing normalization.Run the following script to check the actual behavior of normalizePath with various path patterns:
🏁 Script executed:
Length of output: 7180
💡 Result:
Short answer: normalizePath is for vault-relative paths — it normalizes separators, removes leading/trailing slashes (so a leading "/" is stripped) and converts backslashes to "/" (Windows). It will therefore turn an OS-style absolute path (or a path starting with "/") into a vault-relative path. Use it for paths inside the vault; don’t use it if you need to keep an OS absolute path. [1][2][3]
Sources:
The normalizePath behavior claim is verified as correct, but a critical inconsistency was found during verification.
The Obsidian
normalizePathfunction does remove leading slashes from absolute paths and converts backslashes to forward slashes, making the code's defensive check necessary and appropriate. The comment is accurate.However, an inconsistency exists in
src/ui/modal/sections/GeneralSection.ts:This means validation and storage operate on different path states. If a user enters an absolute path like
/exports, it gets stored as/exportsbut validated asexports, potentially allowing invalid states or bypassing security checks.Apply the same defensive check at line 109 to ensure validation and storage are consistent:
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee@@ -57,8 +57,9 @@ export class EmbeddedTemplateManager {}🛠️ Refactor suggestion | 🟠 Major
Extract duplicated path conversion logic to PathUtils helper.
The vault-relative path conversion is duplicated both within this file (lines 60-69 and 116-125) and across other files in this PR. This is the same duplication issue identified in ImageOptimizer.ts and PdfToImageConverter.ts.
Add a
toVaultRelative()helper to PathUtils (see detailed suggestion in ImageOptimizer.ts review), then simplify both locations:Also applies to: 116-125
✅ Addressed in commits
f0daebctoc1c02ee@@ -155,7 +154,20 @@ export class ModalRenderer {text: 'Export',⚠️ Potential issue | 🟠 Major
Handle potential promise rejection from async onSubmit.
The
voidoperator correctly discards the promise, but ifonSubmitis async and throws an error, it will result in an unhandled promise rejection. This could lead to unexpected behavior or silent failures.Apply this diff to add proper error handling:
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee@@ -72,13 +75,14 @@ export class GeneralSection implements ModalSection {⚠️ Potential issue | 🟡 Minor
Description contradicts absolute path handling.
The description states "relative to vault root", but the code on lines 84-85 now accepts and preserves absolute paths. Either update the description to clarify that absolute paths are supported, or remove the absolute path handling to match the description.
If absolute paths are intended, consider updating the description:
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02ee@@ -102,9 +106,11 @@ export class GeneralSection implements ModalSection {// Validate output folderif (this.outputFolderInput) {⚠️ Potential issue | 🟠 Major
Inconsistent path handling between onChange and validate.
The onChange handler preserves absolute paths (line 85), but the validate() method always normalizes paths including absolute ones (line 109). This inconsistency could cause validation to incorrectly handle absolute paths that were previously accepted.
Apply this diff to make validation consistent:
🤖 Prompt for AI Agents
✅ Addressed in commits
f0daebctoc1c02eeActionable comments posted: 2
♻️ Duplicate comments (1)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
87f3894bf1andc1c02ee553.📒 Files selected for processing (20)
README.md(1 hunks)main.ts(5 hunks)package.json(2 hunks)src/converters/PandocTypstConverter.ts(7 hunks)src/converters/PdfToImageConverter.ts(1 hunks)src/converters/pdf/ImageOptimizer.ts(3 hunks)src/converters/pdf/PdfCliExecutor.ts(1 hunks)src/converters/preprocessors/FrontmatterProcessor.ts(10 hunks)src/core/DependencyChecker.ts(2 hunks)src/core/ExportErrorHandler.ts(3 hunks)src/core/PathUtils.ts(4 hunks)src/core/SecurityUtils.ts(4 hunks)src/plugin/CommandRegistry.ts(3 hunks)src/plugin/EmbedProcessor.ts(10 hunks)src/plugin/PluginLifecycle.ts(1 hunks)src/templates/TemplateManager.ts(2 hunks)src/templates/embeddedTemplates.ts(2 hunks)src/ui/modal/ModalRenderer.ts(5 hunks)src/ui/modal/sections/GeneralSection.ts(4 hunks)src/ui/modal/sections/TypographySection.ts(5 hunks)✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/templates/embeddedTemplates.tssrc/converters/pdf/PdfCliExecutor.tssrc/converters/pdf/ImageOptimizer.tssrc/converters/PdfToImageConverter.tssrc/core/PathUtils.tssrc/templates/TemplateManager.tssrc/core/ExportErrorHandler.tssrc/converters/PandocTypstConverter.tssrc/plugin/EmbedProcessor.tssrc/ui/modal/sections/TypographySection.tssrc/converters/preprocessors/FrontmatterProcessor.tssrc/ui/modal/ModalRenderer.tssrc/plugin/PluginLifecycle.tssrc/core/SecurityUtils.tspackage.json
📄 CodeRabbit inference engine (AGENTS.md)
Files:
package.json🧠 Learnings (8)
📚 Learning: 2025-09-25T14:27:31.837Z
Applied to files:
src/converters/pdf/PdfCliExecutor.tssrc/converters/pdf/ImageOptimizer.tssrc/converters/PdfToImageConverter.tssrc/core/PathUtils.tssrc/converters/PandocTypstConverter.tssrc/plugin/EmbedProcessor.tsmain.ts📚 Learning: 2025-09-25T14:14:57.437Z
Applied to files:
src/converters/pdf/ImageOptimizer.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
package.json📚 Learning: 2025-11-05T14:17:36.572Z
Applied to files:
src/core/ExportErrorHandler.tssrc/converters/preprocessors/FrontmatterProcessor.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/converters/PandocTypstConverter.tsmain.tssrc/plugin/PluginLifecycle.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
main.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
main.ts📚 Learning: 2025-09-25T14:48:20.040Z
Applied to files:
src/ui/modal/ModalRenderer.ts🧬 Code graph analysis (8)
src/converters/pdf/ImageOptimizer.ts (1)
src/converters/PdfToImageConverter.ts (1)
src/core/PathUtils.ts (1)
src/converters/PandocTypstConverter.ts (2)
src/plugin/EmbedProcessor.ts (1)
src/ui/modal/sections/TypographySection.ts (1)
main.ts (1)
src/plugin/PluginLifecycle.ts (1)
🪛 Biome (2.1.2)
src/core/SecurityUtils.ts
[error] 381-381: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
🔇 Additional comments (11)
@@ -12,3 +12,4 @@MarkdownView} from 'obsidian';import { shell } from 'electron';⚠️ Potential issue | 🔴 Critical
Avoid top-level Electron import
Importing
electronat module scope breaks the plugin on mobile builds (and any runtime without Electron) because the module cannot be resolved during load. Keep the dynamicrequireinsideopenPDFinstead.🤖 Prompt for AI Agents
@@ -13,36 +13,41 @@ export class TypographySection implements ModalSection {render(containerEl: HTMLElement, state: ModalState, app?: App): void {⚠️ Potential issue | 🟠 Major
Add error handling for fire-and-forget async call.
The
voidoperator suppresses the promise without error handling, violating the coding guideline to "handle errors gracefully". IfcreateFontSettingsfails, errors will be silently swallowed. Additionally, this creates a UI ordering issue where the font size settings render before the font dropdowns, which may confuse users.Consider one of these approaches:
Option 1: Await the font settings creation
Then change the
rendermethod signature to:Option 2: Add error handling with void operator
As per coding guidelines.
📝 Committable suggestion
🤖 Prompt for AI Agents
✅ Addressed in commits
5219ef7tod6d31af@@ -12,3 +12,4 @@MarkdownView} from 'obsidian';import { shell } from 'electron';@coderabbitai this is a Desktop only release. so Electron is no issue here.
@@ -12,3 +12,4 @@MarkdownView} from 'obsidian';import { shell } from 'electron';@AlexKucera, understood! Since this plugin is desktop-only, the top-level
electronimport is perfectly fine. Thank you for clarifying the deployment target.✏️ Learnings added
🧠 Learnings used
Actionable comments posted: 1
🧹 Nitpick comments (2)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
c1c02ee553andd6d31afb16.📒 Files selected for processing (3)
src/converters/preprocessors/FrontmatterProcessor.ts(10 hunks)src/core/SecurityUtils.ts(4 hunks)src/ui/modal/sections/TypographySection.ts(3 hunks)🧰 Additional context used
📓 Path-based instructions (1)
src/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/core/SecurityUtils.tssrc/converters/preprocessors/FrontmatterProcessor.tssrc/ui/modal/sections/TypographySection.ts🧠 Learnings (2)
📚 Learning: 2025-09-25T14:27:31.837Z
Applied to files:
src/core/SecurityUtils.ts📚 Learning: 2025-11-05T14:17:36.572Z
Applied to files:
src/converters/preprocessors/FrontmatterProcessor.ts🧬 Code graph analysis (1)
src/ui/modal/sections/TypographySection.ts (3)
🪛 Biome (2.1.2)
src/core/SecurityUtils.ts
[error] 387-387: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
🔇 Additional comments (11)
@@ -115,7 +115,6 @@ export class FrontmatterProcessor {// Return content without frontmatter, but add title as frontmatter for Pandoc⚠️ Potential issue | 🟡 Minor
Fix indentation inconsistencies.
These lines appear to have extra leading whitespace. Ensure consistent indentation throughout the file.
Apply this diff to fix line 118:
Apply similar fixes to lines 185 and 204:
Also applies to: 185-185, 204-204
🤖 Prompt for AI Agents
✅ Addressed in commit
efbff4e