From 281c02210a2ab0c58586a89ca3248b1fa7875d05 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 5 Nov 2025 08:03:52 +0100 Subject: [PATCH] Add Docstrings --- .gitignore | 2 + package-lock.json | 1793 ++++++++++++++++- package.json | 12 +- src/converters/MarkdownPreprocessor.ts | 454 ++++- src/converters/PandocTypstConverter.ts | 232 ++- src/converters/PdfToImageConverter.ts | 447 +++- src/converters/pandoc/PandocCommandBuilder.ts | 253 ++- src/converters/pandoc/PandocExecutor.ts | 275 ++- src/core/DependencyChecker.ts | 239 ++- src/core/ExecutableChecker.ts | 185 +- src/core/ExportErrorHandler.ts | 339 +++- src/core/ModalSettingsHelper.ts | 184 +- src/core/PathUtils.ts | 138 +- src/core/SecurityUtils.ts | 255 ++- src/core/TempDirectoryManager.ts | 352 +++- src/core/constants.ts | 192 +- src/core/settings.ts | 205 +- 17 files changed, 5380 insertions(+), 177 deletions(-) diff --git a/.gitignore b/.gitignore index 37d7b38..b65516d 100644 --- a/.gitignore +++ b/.gitignore @@ -70,3 +70,5 @@ CLAUDE.md repomix-output.xml guidance.md + +coverage/ diff --git a/package-lock.json b/package-lock.json index 02a85da..812d3d7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "obsidian-typst-pdf-export", - "version": "1.2.0", + "version": "1.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "obsidian-typst-pdf-export", - "version": "1.2.0", + "version": "1.3.0", "license": "MIT", "dependencies": { "gray-matter": "^4.0.3", @@ -15,17 +15,81 @@ "devDependencies": { "@eslint/eslintrc": "^3.3.1", "@eslint/js": "^9.34.0", - "@types/node": "^16.11.6", + "@types/node": "^20.19.24", "@typescript-eslint/eslint-plugin": "5.29.0", "@typescript-eslint/parser": "5.29.0", + "@vitest/coverage-v8": "^4.0.6", + "@vitest/ui": "^4.0.6", "archiver": "^7.0.1", "builtin-modules": "3.3.0", "esbuild": "0.17.3", "globals": "^16.3.0", + "happy-dom": "^20.0.10", "obsidian": "latest", "tslib": "2.4.0", "typescript": "^5.9.2", - "typescript-eslint": "^8.43.0" + "typescript-eslint": "^8.43.0", + "vitest": "^4.0.6" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", + "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", + "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" } }, "node_modules/@codemirror/state": { @@ -53,6 +117,23 @@ "w3c-keyname": "^2.2.4" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/android-arm": { "version": "0.17.3", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.3.tgz", @@ -325,6 +406,23 @@ "node": ">=12" } }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/netbsd-x64": { "version": "0.17.3", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.3.tgz", @@ -342,6 +440,23 @@ "node": ">=12" } }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/openbsd-x64": { "version": "0.17.3", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.3.tgz", @@ -359,6 +474,23 @@ "node": ">=12" } }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/sunos-x64": { "version": "0.17.3", "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.3.tgz", @@ -650,6 +782,34 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@mapbox/node-pre-gyp": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", @@ -728,6 +888,339 @@ "node": ">=14" } }, + "node_modules/@polka/url": { + "version": "1.0.0-next.29", + "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", + "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.52.5.tgz", + "integrity": "sha512-8c1vW4ocv3UOMp9K+gToY5zL2XiiVw3k7f1ksf4yO1FlDFQ1C2u72iACFnSOceJFsWskc2WZNqeRhFRPzv+wtQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.52.5.tgz", + "integrity": "sha512-mQGfsIEFcu21mvqkEKKu2dYmtuSZOBMmAl5CFlPGLY94Vlcm+zWApK7F/eocsNzp8tKmbeBP8yXyAbx0XHsFNA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.52.5.tgz", + "integrity": "sha512-takF3CR71mCAGA+v794QUZ0b6ZSrgJkArC+gUiG6LB6TQty9T0Mqh3m2ImRBOxS2IeYBo4lKWIieSvnEk2OQWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.52.5.tgz", + "integrity": "sha512-W901Pla8Ya95WpxDn//VF9K9u2JbocwV/v75TE0YIHNTbhqUTv9w4VuQ9MaWlNOkkEfFwkdNhXgcLqPSmHy0fA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.52.5.tgz", + "integrity": "sha512-QofO7i7JycsYOWxe0GFqhLmF6l1TqBswJMvICnRUjqCx8b47MTo46W8AoeQwiokAx3zVryVnxtBMcGcnX12LvA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.52.5.tgz", + "integrity": "sha512-jr21b/99ew8ujZubPo9skbrItHEIE50WdV86cdSoRkKtmWa+DDr6fu2c/xyRT0F/WazZpam6kk7IHBerSL7LDQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.52.5.tgz", + "integrity": "sha512-PsNAbcyv9CcecAUagQefwX8fQn9LQ4nZkpDboBOttmyffnInRy8R8dSg6hxxl2Re5QhHBf6FYIDhIj5v982ATQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.52.5.tgz", + "integrity": "sha512-Fw4tysRutyQc/wwkmcyoqFtJhh0u31K+Q6jYjeicsGJJ7bbEq8LwPWV/w0cnzOqR2m694/Af6hpFayLJZkG2VQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.52.5.tgz", + "integrity": "sha512-a+3wVnAYdQClOTlyapKmyI6BLPAFYs0JM8HRpgYZQO02rMR09ZcV9LbQB+NL6sljzG38869YqThrRnfPMCDtZg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.52.5.tgz", + "integrity": "sha512-AvttBOMwO9Pcuuf7m9PkC1PUIKsfaAJ4AYhy944qeTJgQOqJYJ9oVl2nYgY7Rk0mkbsuOpCAYSs6wLYB2Xiw0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.52.5.tgz", + "integrity": "sha512-DkDk8pmXQV2wVrF6oq5tONK6UHLz/XcEVow4JTTerdeV1uqPeHxwcg7aFsfnSm9L+OO8WJsWotKM2JJPMWrQtA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.52.5.tgz", + "integrity": "sha512-W/b9ZN/U9+hPQVvlGwjzi+Wy4xdoH2I8EjaCkMvzpI7wJUs8sWJ03Rq96jRnHkSrcHTpQe8h5Tg3ZzUPGauvAw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.52.5.tgz", + "integrity": "sha512-sjQLr9BW7R/ZiXnQiWPkErNfLMkkWIoCz7YMn27HldKsADEKa5WYdobaa1hmN6slu9oWQbB6/jFpJ+P2IkVrmw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.52.5.tgz", + "integrity": "sha512-hq3jU/kGyjXWTvAh2awn8oHroCbrPm8JqM7RUpKjalIRWWXE01CQOf/tUNWNHjmbMHg/hmNCwc/Pz3k1T/j/Lg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.52.5.tgz", + "integrity": "sha512-gn8kHOrku8D4NGHMK1Y7NA7INQTRdVOntt1OCYypZPRt6skGbddska44K8iocdpxHTMMNui5oH4elPH4QOLrFQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.52.5.tgz", + "integrity": "sha512-hXGLYpdhiNElzN770+H2nlx+jRog8TyynpTVzdlc6bndktjKWyZyiCsuDAlpd+j+W+WNqfcyAWz9HxxIGfZm1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.52.5.tgz", + "integrity": "sha512-arCGIcuNKjBoKAXD+y7XomR9gY6Mw7HnFBv5Rw7wQRvwYLR7gBAgV7Mb2QTyjXfTveBNFAtPt46/36vV9STLNg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.52.5.tgz", + "integrity": "sha512-QoFqB6+/9Rly/RiPjaomPLmR/13cgkIGfA40LHly9zcH1S0bN2HVFYk3a1eAyHQyjs3ZJYlXvIGtcCs5tko9Cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.52.5.tgz", + "integrity": "sha512-w0cDWVR6MlTstla1cIfOGyl8+qb93FlAVutcor14Gf5Md5ap5ySfQ7R9S/NjNaMLSFdUnKGEasmVnu3lCMqB7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.52.5.tgz", + "integrity": "sha512-Aufdpzp7DpOTULJCuvzqcItSGDH73pF3ko/f+ckJhxQyHtp67rHw3HMNxoIdDMUITJESNE6a8uh4Lo4SLouOUg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.52.5.tgz", + "integrity": "sha512-UGBUGPFp1vkj6p8wCRraqNhqwX/4kNQPS57BCFc8wYh0g94iVIW33wJtQAx3G7vrjjNtRaxiMUylM0ktp/TRSQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.52.5.tgz", + "integrity": "sha512-TAcgQh2sSkykPRWLrdyy2AiceMckNf5loITqXxFI5VuQjS5tSuw3WlwdN8qv8vzjLAUTvYaH/mVjSFpbkFbpTg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz", + "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, "node_modules/@types/codemirror": { "version": "5.60.8", "resolved": "https://registry.npmjs.org/@types/codemirror/-/codemirror-5.60.8.tgz", @@ -738,6 +1231,13 @@ "@types/tern": "*" } }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", @@ -753,11 +1253,14 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "16.18.126", - "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz", - "integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==", + "version": "20.19.24", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.24.tgz", + "integrity": "sha512-FE5u0ezmi6y9OZEzlJfg37mqqf6ZDSF2V/NLjUyGrR9uTZ7Sb9F7bLNZ03S4XVUNRWGA7Ck4c1kK+YnuWjl+DA==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } }, "node_modules/@types/tern": { "version": "0.23.9", @@ -769,6 +1272,13 @@ "@types/estree": "*" } }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "5.29.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.29.0.tgz", @@ -1022,6 +1532,171 @@ "license": "ISC", "peer": true }, + "node_modules/@vitest/coverage-v8": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.0.6.tgz", + "integrity": "sha512-cv6pFXj9/Otk7q1Ocoj8k3BUVVwnFr3jqcqpwYrU5LkKClU9DpaMEdX+zptx/RyIJS+/VpoxMWmfISXchmVDPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.0.6", + "ast-v8-to-istanbul": "^0.3.5", + "debug": "^4.4.3", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-lib-source-maps": "^5.0.6", + "istanbul-reports": "^3.2.0", + "magicast": "^0.3.5", + "std-env": "^3.9.0", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.0.6", + "vitest": "4.0.6" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/expect": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.6.tgz", + "integrity": "sha512-5j8UUlBVhOjhj4lR2Nt9sEV8b4WtbcYh8vnfhTNA2Kn5+smtevzjNq+xlBuVhnFGXiyPPNzGrOVvmyHWkS5QGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.0.6", + "@vitest/utils": "4.0.6", + "chai": "^6.0.1", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.0.6.tgz", + "integrity": "sha512-3COEIew5HqdzBFEYN9+u0dT3i/NCwppLnO1HkjGfAP1Vs3vti1Hxm/MvcbC4DAn3Szo1M7M3otiAaT83jvqIjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.0.6", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.19" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.0.6.tgz", + "integrity": "sha512-4vptgNkLIA1W1Nn5X4x8rLJBzPiJwnPc+awKtfBE5hNMVsoAl/JCCPPzNrbf+L4NKgklsis5Yp2gYa+XAS442g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.0.6.tgz", + "integrity": "sha512-trPk5qpd7Jj+AiLZbV/e+KiiaGXZ8ECsRxtnPnCrJr9OW2mLB72Cb824IXgxVz/mVU3Aj4VebY+tDTPn++j1Og==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.0.6", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.0.6.tgz", + "integrity": "sha512-PaYLt7n2YzuvxhulDDu6c9EosiRuIE+FI2ECKs6yvHyhoga+2TBWI8dwBjs+IeuQaMtZTfioa9tj3uZb7nev1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.0.6", + "magic-string": "^0.30.19", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.0.6.tgz", + "integrity": "sha512-g9jTUYPV1LtRPRCQfhbMintW7BTQz1n6WXYQYRQ25qkyffA4bjVXjkROokZnv7t07OqfaFKw1lPzqKGk1hmNuQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/ui": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/ui/-/ui-4.0.6.tgz", + "integrity": "sha512-1ekpBsYNUm0Xv/0YsTvoSRmiRkmzz9Pma7qQ3Ui76sg2gwp2/ewSWqx4W/HfaN5dF0E8iBbidFo1wGaeqXYIrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.0.6", + "fflate": "^0.8.2", + "flatted": "^3.3.3", + "pathe": "^2.0.3", + "sirv": "^3.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "vitest": "4.0.6" + } + }, + "node_modules/@vitest/utils": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.0.6.tgz", + "integrity": "sha512-bG43VS3iYKrMIZXBo+y8Pti0O7uNju3KvNn6DrQWhQQKcLavMB+0NZfO1/QBAEbq0MaQ3QjNsnnXlGQvsh0Z6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.0.6", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -1351,6 +2026,28 @@ "node": ">=8" } }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.8.tgz", + "integrity": "sha512-szgSZqUxI5T8mLKvS7WTjF9is+MVbOeLADU73IseOcrqhxr/VAvy6wfoVE39KnKzA7JRhjF5eUagNlHwvZPlKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^9.0.1" + } + }, "node_modules/async": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", @@ -1506,6 +2203,16 @@ "node": "^18.12.0 || >= 20.9.0" } }, + "node_modules/chai": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.0.tgz", + "integrity": "sha512-aUTnJc/JipRzJrNADXVvpVqi6CO0dn3nx4EVPxijri+fj3LUUDyZQOgVeW54Ob3Y1Xh9Iz8f+CgaCl8v0mn9bA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -1733,9 +2440,9 @@ } }, "node_modules/debug": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", - "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "devOptional": true, "license": "MIT", "dependencies": { @@ -1848,6 +2555,13 @@ "once": "^1.4.0" } }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, "node_modules/esbuild": { "version": "0.17.3", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.3.tgz", @@ -2186,6 +2900,16 @@ "node": ">=4.0" } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -2226,6 +2950,16 @@ "node": ">=6" } }, + "node_modules/expect-type": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.2.2.tgz", + "integrity": "sha512-JhFGDVJ7tmDJItKhYgJCGLOWjuK9vPxiXoUFLwLDc99NlmklilbiQJwoctZtt13+xMw91MCk/REan6MWHqDjyA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/extend-shallow": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", @@ -2307,6 +3041,13 @@ "reusify": "^1.0.4" } }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "dev": true, + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -2373,8 +3114,7 @@ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/foreground-child": { "version": "3.3.1", @@ -2445,6 +3185,21 @@ "devOptional": true, "license": "ISC" }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/functional-red-black-tree": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", @@ -2601,13 +3356,27 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/happy-dom": { + "version": "20.0.10", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.0.10.tgz", + "integrity": "sha512-6umCCHcjQrhP5oXhrHQQvLB0bwb1UzHAHdsXy+FjtKoYjUhmNZsQL8NivwM1vDvNEChJabVrUYxUnp/ZdYmy2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "^20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "whatwg-mimetype": "^3.0.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -2619,6 +3388,13 @@ "license": "ISC", "optional": true }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, "node_modules/https-proxy-agent": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", @@ -2805,6 +3581,76 @@ "dev": true, "license": "ISC" }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report/node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz", + "integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.23", + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/jackspeak": { "version": "3.4.3", "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", @@ -2821,6 +3667,13 @@ "@pkgjs/parseargs": "^0.11.0" } }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, "node_modules/js-yaml": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", @@ -2977,6 +3830,28 @@ "dev": true, "license": "ISC" }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz", + "integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.25.4", + "@babel/types": "^7.25.4", + "source-map-js": "^1.2.0" + } + }, "node_modules/make-dir": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", @@ -3127,6 +4002,16 @@ "node": "*" } }, + "node_modules/mrmime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", + "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -3141,6 +4026,25 @@ "license": "MIT", "optional": true }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, "node_modules/napi-build-utils": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", @@ -3408,6 +4312,13 @@ "node": ">=6" } }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, "node_modules/pdf-to-img": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/pdf-to-img/-/pdf-to-img-4.5.0.tgz", @@ -3491,6 +4402,13 @@ "simple-concat": "^1.0.0" } }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", @@ -3504,6 +4422,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, "node_modules/prebuild-install": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", @@ -3721,6 +4668,48 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/rollup": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.5.tgz", + "integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.52.5", + "@rollup/rollup-android-arm64": "4.52.5", + "@rollup/rollup-darwin-arm64": "4.52.5", + "@rollup/rollup-darwin-x64": "4.52.5", + "@rollup/rollup-freebsd-arm64": "4.52.5", + "@rollup/rollup-freebsd-x64": "4.52.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.52.5", + "@rollup/rollup-linux-arm-musleabihf": "4.52.5", + "@rollup/rollup-linux-arm64-gnu": "4.52.5", + "@rollup/rollup-linux-arm64-musl": "4.52.5", + "@rollup/rollup-linux-loong64-gnu": "4.52.5", + "@rollup/rollup-linux-ppc64-gnu": "4.52.5", + "@rollup/rollup-linux-riscv64-gnu": "4.52.5", + "@rollup/rollup-linux-riscv64-musl": "4.52.5", + "@rollup/rollup-linux-s390x-gnu": "4.52.5", + "@rollup/rollup-linux-x64-gnu": "4.52.5", + "@rollup/rollup-linux-x64-musl": "4.52.5", + "@rollup/rollup-openharmony-arm64": "4.52.5", + "@rollup/rollup-win32-arm64-msvc": "4.52.5", + "@rollup/rollup-win32-ia32-msvc": "4.52.5", + "@rollup/rollup-win32-x64-gnu": "4.52.5", + "@rollup/rollup-win32-x64-msvc": "4.52.5", + "fsevents": "~2.3.2" + } + }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -3820,6 +4809,13 @@ "node": ">=8" } }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", @@ -3872,6 +4868,21 @@ "simple-concat": "^1.0.0" } }, + "node_modules/sirv": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz", + "integrity": "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@polka/url": "^1.0.0-next.24", + "mrmime": "^2.0.0", + "totalist": "^3.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", @@ -3882,12 +4893,36 @@ "node": ">=8" } }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", "license": "BSD-3-Clause" }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, "node_modules/streamx": { "version": "2.22.1", "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.22.1.tgz", @@ -4005,7 +5040,6 @@ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -4087,6 +5121,78 @@ "license": "MIT", "peer": true }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tinyrainbow": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.0.3.tgz", + "integrity": "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -4100,6 +5206,16 @@ "node": ">=8.0" } }, + "node_modules/totalist": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", + "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/tr46": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", @@ -4460,6 +5576,13 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", @@ -4476,6 +5599,619 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, + "node_modules/vite": { + "version": "7.1.12", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.12.tgz", + "integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/vite/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vitest": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.6.tgz", + "integrity": "sha512-gR7INfiVRwnEOkCk47faros/9McCZMp5LM+OMNWGLaDBSvJxIzwjgNFufkuePBNaesGRnLmNfW+ddbUJRZn0nQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.0.6", + "@vitest/mocker": "4.0.6", + "@vitest/pretty-format": "4.0.6", + "@vitest/runner": "4.0.6", + "@vitest/snapshot": "4.0.6", + "@vitest/spy": "4.0.6", + "@vitest/utils": "4.0.6", + "debug": "^4.4.3", + "es-module-lexer": "^1.7.0", + "expect-type": "^1.2.2", + "magic-string": "^0.30.19", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.0.3", + "vite": "^6.0.0 || ^7.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.0.6", + "@vitest/browser-preview": "4.0.6", + "@vitest/browser-webdriverio": "4.0.6", + "@vitest/ui": "4.0.6", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/w3c-keyname": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", @@ -4491,6 +6227,16 @@ "license": "BSD-2-Clause", "optional": true }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", @@ -4518,6 +6264,23 @@ "node": ">= 8" } }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/wide-align": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", diff --git a/package.json b/package.json index 6a84a51..1bbb7bc 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,10 @@ "lint": "eslint src/ main.ts", "dev": "npm run typecheck && node esbuild.config.mjs", "build": "npm run typecheck && npm run lint && node esbuild.config.mjs production", + "test": "vitest run", + "test:watch": "vitest", + "test:ui": "vitest --ui", + "test:coverage": "vitest run --coverage", "package": "node scripts/package-plugin.js", "version": "node version-bump.mjs && git add manifest.json versions.json" }, @@ -23,17 +27,21 @@ "devDependencies": { "@eslint/eslintrc": "^3.3.1", "@eslint/js": "^9.34.0", - "@types/node": "^16.11.6", + "@types/node": "^20.19.24", "@typescript-eslint/eslint-plugin": "5.29.0", "@typescript-eslint/parser": "5.29.0", + "@vitest/coverage-v8": "^4.0.6", + "@vitest/ui": "^4.0.6", "archiver": "^7.0.1", "builtin-modules": "3.3.0", "esbuild": "0.17.3", "globals": "^16.3.0", + "happy-dom": "^20.0.10", "obsidian": "latest", "tslib": "2.4.0", "typescript": "^5.9.2", - "typescript-eslint": "^8.43.0" + "typescript-eslint": "^8.43.0", + "vitest": "^4.0.6" }, "dependencies": { "gray-matter": "^4.0.3", diff --git a/src/converters/MarkdownPreprocessor.ts b/src/converters/MarkdownPreprocessor.ts index 6755ad4..7314783 100644 --- a/src/converters/MarkdownPreprocessor.ts +++ b/src/converters/MarkdownPreprocessor.ts @@ -1,6 +1,35 @@ /** - * MarkdownPreprocessor - Converts Obsidian-specific markdown syntax to standard markdown - * compatible with Pandoc for Typst PDF export + * Markdown preprocessing pipeline for Obsidian-to-Pandoc conversion. + * + * This module provides the central preprocessing system that transforms Obsidian's + * proprietary markdown syntax into standard markdown compatible with Pandoc and Typst. + * It coordinates multiple specialized processors to handle: + * - YAML frontmatter extraction and formatting + * - Wikilink conversion to standard markdown links + * - Obsidian embed syntax (![[...]]) to standard images/includes + * - Callout blocks (>[!note]) to custom Typst environments + * - Email block formatting for email exports + * - Remote image detection and download queue management + * - Metadata extraction (tags, title, frontmatter) + * + * The preprocessor runs in a specific order to avoid conflicts: + * 1. Horizontal rule normalization (prevent YAML delimiter confusion) + * 2. Frontmatter extraction and processing + * 3. Email block formatting + * 4. Unnecessary link filtering (Open: links, Mail.app links) + * 5. Embed processing (![[image]], ![[pdf]]) + * 6. Remote image detection (![](https://...)) + * 7. Wikilink conversion ([[link]] → [link](link.md)) + * 8. Callout block conversion + * 9. Title extraction + * + * Key features: + * - Stateless processing (each call is independent) + * - Comprehensive metadata extraction for export pipeline + * - Configurable wikilink and frontmatter handling + * - Remote resource tracking for download coordination + * - Error and warning reporting for user feedback + * - Modular processor architecture for maintainability */ import { FrontmatterProcessor, FrontmatterProcessorConfig } from './preprocessors/FrontmatterProcessor'; @@ -11,6 +40,13 @@ import { MetadataExtractor } from './preprocessors/MetadataExtractor'; import { HorizontalRuleProcessor } from './preprocessors/HorizontalRuleProcessor'; import * as path from 'path'; +/** + * Configuration options for markdown preprocessing behavior. + * + * @property preserveFrontmatter - Keep YAML frontmatter in output (true) or strip it (false) + * @property baseUrl - Base URL for relative link resolution (optional) + * @property printFrontmatter - Display frontmatter as formatted text at document start (optional) + */ export interface PreprocessorOptions { /** Preserve existing frontmatter */ preserveFrontmatter: boolean; @@ -20,7 +56,24 @@ export interface PreprocessorOptions { printFrontmatter?: boolean; } - +/** + * Result of markdown preprocessing operation. + * + * Contains the processed content, extracted metadata, and any errors or warnings + * encountered during processing. The metadata includes information needed by + * downstream export components like embedded resources and frontmatter data. + * + * @property content - Processed markdown content ready for Pandoc + * @property metadata - Extracted metadata and resource tracking + * @property metadata.tags - Extracted tags from frontmatter and content + * @property metadata.frontmatter - Parsed YAML frontmatter object + * @property metadata.title - Document title (from frontmatter or H1) + * @property metadata.pdfEmbeds - PDF files embedded via ![[file.pdf]] + * @property metadata.imageEmbeds - Images embedded via ![[image.png]] or ![](url) + * @property metadata.fileEmbeds - Other files embedded via ![[file.ext]] + * @property errors - Critical processing errors + * @property warnings - Non-critical processing warnings + */ export interface PreprocessingResult { /** Processed markdown content */ content: string; @@ -61,6 +114,36 @@ export interface PreprocessingResult { warnings: string[]; } +/** + * Configuration for MarkdownPreprocessor initialization. + * + * Provides all settings needed to initialize the preprocessor and its + * constituent processors. This configuration is typically built from plugin + * settings and file context. + * + * @property vaultPath - Absolute path to vault root for file resolution + * @property options - Preprocessing behavior configuration + * @property wikilinkConfig - Wikilink conversion settings + * @property noteTitle - Optional title to prepend as H1 heading + * + * @example + * ```typescript + * const config: MarkdownPreprocessorConfig = { + * vaultPath: '/Users/name/vault', + * options: { + * preserveFrontmatter: true, + * printFrontmatter: false, + * baseUrl: '' + * }, + * wikilinkConfig: { + * format: 'md', + * extension: '.md' + * }, + * noteTitle: 'My Document' + * }; + * const preprocessor = new MarkdownPreprocessor(config); + * ``` + */ export interface MarkdownPreprocessorConfig { /** Vault path for file resolution */ vaultPath: string; @@ -72,6 +155,72 @@ export interface MarkdownPreprocessorConfig { noteTitle?: string; } +/** + * Central markdown preprocessing coordinator for Obsidian-to-Pandoc conversion. + * + * This class orchestrates multiple specialized processors to transform Obsidian's + * proprietary markdown into standard markdown that Pandoc can process. It ensures + * processors run in the correct order to avoid syntax conflicts and maintains + * comprehensive metadata about the conversion. + * + * The preprocessor is stateless - each process() call is independent and doesn't + * affect previous or future calls. Configuration can be updated between calls via + * updateConfig(). + * + * Architecture: + * - Delegates to specialized processors for specific syntax + * - Maintains processing order to prevent conflicts + * - Aggregates metadata from all processors + * - Provides error and warning reporting + * + * Processing Pipeline: + * 1. Horizontal rules (prevent YAML confusion) + * 2. Frontmatter (extract metadata, optionally format) + * 3. Email blocks (custom email formatting) + * 4. Link filtering (remove unnecessary links) + * 5. Embeds (convert ![[...]] syntax) + * 6. Remote images (detect and queue for download) + * 7. Wikilinks (convert [[...]] to standard links) + * 8. Callouts (convert >[!type] blocks) + * 9. Title extraction (from H1 or frontmatter) + * + * @example + * ```typescript + * // Initialize preprocessor + * const preprocessor = new MarkdownPreprocessor({ + * vaultPath: '/path/to/vault', + * options: { + * preserveFrontmatter: true, + * printFrontmatter: false + * }, + * wikilinkConfig: { + * format: 'md', + * extension: '.md' + * }, + * noteTitle: 'My Note' + * }); + * + * // Process markdown + * const obsidianMarkdown = '# My Note\n\n[[internal-link]]\n\n![[image.png]]'; + * const result = await preprocessor.process(obsidianMarkdown); + * + * console.log(result.content); // Standard markdown + * console.log(result.metadata.imageEmbeds); // Image processing info + * console.log(result.errors); // Any errors encountered + * ``` + * + * @example + * ```typescript + * // Update configuration for different export + * preprocessor.updateConfig({ + * options: { preserveFrontmatter: false }, + * noteTitle: 'Different Title' + * }); + * + * // Process with new configuration + * const newResult = await preprocessor.process(markdown); + * ``` + */ export class MarkdownPreprocessor { private vaultPath: string; private options: PreprocessorOptions; @@ -113,7 +262,72 @@ export class MarkdownPreprocessor { } /** - * Main processing method that converts Obsidian markdown to standard markdown + * Processes Obsidian markdown and converts it to standard Pandoc-compatible markdown. + * + * This is the main entry point for preprocessing. It runs all configured processors + * in the correct order, aggregates metadata from each stage, and returns a complete + * result with processed content and comprehensive metadata. + * + * The method is async to support future extensions (though current processors are sync). + * Processing is stateless - each call operates independently on the provided content. + * + * Processing Order (critical for avoiding conflicts): + * 1. Horizontal rules → Prevent YAML delimiter confusion + * 2. Frontmatter → Extract metadata, optionally format + * 3. Email blocks → Custom formatting for email exports + * 4. Link filtering → Remove Open: and Mail.app links + * 5. Embeds → Convert ![[...]] syntax first (before wikilinks add .md) + * 6. Remote images → Detect and queue ![](https://...) for download + * 7. Wikilinks → Convert [[...]] after embeds processed + * 8. Callouts → Convert >[!type] blocks to Typst environments + * 9. Title extraction → From H1 or frontmatter + * + * @param content - Raw Obsidian markdown content to process + * @returns Preprocessing result with converted content, metadata, and diagnostics + * + * @example + * ```typescript + * // Process note with various Obsidian syntax + * const markdown = `--- + * title: My Note + * tags: [export, pdf] + * --- + * + * # My Note + * + * Internal link: [[other-note]] + * Image: ![[screenshot.png]] + * Callout: > [!note] This is important + * `; + * + * const result = await preprocessor.process(markdown); + * + * // Check for errors + * if (result.errors.length > 0) { + * console.error('Processing errors:', result.errors); + * } + * + * // Access processed content + * console.log(result.content); // Standard markdown + * + * // Access extracted metadata + * console.log(result.metadata.title); // "My Note" + * console.log(result.metadata.tags); // ["export", "pdf"] + * console.log(result.metadata.imageEmbeds); // [{originalPath, ...}] + * ``` + * + * @example + * ```typescript + * // Handle remote images + * const markdown = '![Remote](https://example.com/image.png)'; + * const result = await preprocessor.process(markdown); + * + * // Remote images are queued for download + * result.metadata.imageEmbeds.forEach(embed => { + * console.log(`Download: ${embed.originalPath}`); + * // Export pipeline will download and embed these + * }); + * ``` */ public async process(content: string): Promise { const result: PreprocessingResult = { @@ -167,8 +381,51 @@ export class MarkdownPreprocessor { } /** - * Process standard markdown images and track remote URLs for download - * Remote images are marked for later download and embedding + * Processes standard markdown images and queues remote URLs for download. + * + * This method scans the content for standard markdown image syntax `![alt](url)` + * and detects remote images (http:// or https://). Remote images are: + * - Replaced with marker placeholders in the content + * - Added to the imageEmbeds metadata for download by the export pipeline + * - Tracked with a warning message for user visibility + * + * Local images (file paths without http/https) are left unchanged for normal + * processing. This allows the export pipeline to handle them separately from + * remote resources that need downloading. + * + * The marker format is: `IMAGE_EMBED_MARKER:{url}:{baseName}:{alt}` + * This allows the export pipeline to: + * - Download the remote image + * - Replace the marker with the local path + * - Preserve the alt text for accessibility + * + * @param content - Markdown content to process + * @param result - Processing result to update with remote image metadata + * @returns Content with remote images replaced by markers + * @private + * + * @example + * ```typescript + * // Remote image detected and queued + * const markdown = '![Photo](https://example.com/image.png)'; + * const result = { metadata: {}, warnings: [], errors: [] }; + * const processed = this.processStandardMarkdownImages(markdown, result); + * + * // Content has marker: 'IMAGE_EMBED_MARKER:https://...:image:Photo' + * // result.metadata.imageEmbeds has entry for download + * // result.warnings includes "Remote URL image queued for download" + * ``` + * + * @example + * ```typescript + * // Local image left unchanged + * const markdown = '![Local](local-image.png)'; + * const result = { metadata: {}, warnings: [], errors: [] }; + * const processed = this.processStandardMarkdownImages(markdown, result); + * + * // Content unchanged: '![Local](local-image.png)' + * // No entries added to metadata or warnings + * ``` */ private processStandardMarkdownImages(content: string, result: PreprocessingResult): string { // Pattern to match standard markdown images: ![alt](url) @@ -219,7 +476,66 @@ export class MarkdownPreprocessor { } /** - * Update configuration + * Updates the preprocessor configuration dynamically. + * + * This method allows modifying preprocessor settings after initialization without + * creating a new instance. It supports partial updates - only the provided fields + * are changed, leaving others intact. The method also propagates relevant changes + * to dependent processors (WikilinkProcessor, EmbedProcessor) to maintain consistency. + * + * When updating wikilink configuration or base URL, the changes cascade to: + * 1. WikilinkProcessor - Updated with new wikilink settings and base URL + * 2. EmbedProcessor - Receives updated WikilinkProcessor reference + * + * This cascading update ensures that all processors use consistent configuration + * throughout the preprocessing pipeline. + * + * Configuration updates are useful for: + * - Changing export settings between different notes + * - Applying user preference changes without reinitialization + * - Switching between different export contexts (web vs. local) + * - Testing different configuration combinations + * + * @param config - Partial configuration update (only specified fields are changed) + * + * @example + * ```typescript + * // Update base URL for web export + * preprocessor.updateConfig({ + * options: { baseUrl: 'https://example.com/notes' } + * }); + * + * // Process note with web-friendly links + * const result = await preprocessor.process(markdown); + * // Links will use the new base URL + * ``` + * + * @example + * ```typescript + * // Change wikilink format for different export + * preprocessor.updateConfig({ + * wikilinkConfig: { + * format: 'html', + * extension: '.html' + * } + * }); + * + * // Process with HTML-style links + * const result = await preprocessor.process(markdown); + * // [[note]] becomes [note](note.html) + * ``` + * + * @example + * ```typescript + * // Update multiple settings at once + * preprocessor.updateConfig({ + * vaultPath: '/new/vault/path', + * options: { + * preserveFrontmatter: false, + * printFrontmatter: true + * } + * }); + * ``` */ public updateConfig(config: Partial): void { if (config.vaultPath) { @@ -247,7 +563,48 @@ export class MarkdownPreprocessor { } /** - * Get current configuration + * Retrieves the current preprocessor configuration. + * + * This method returns a snapshot of the preprocessor's current settings, + * including vault path, processing options, and wikilink configuration. + * The returned object is a plain data object that can be: + * - Inspected for debugging + * - Serialized for logging or caching + * - Modified and passed to updateConfig() for changes + * - Used to create a new preprocessor with the same settings + * + * Note: The returned configuration does not include the noteTitle field, + * as this is typically set per-export rather than persisted in the + * preprocessor configuration. + * + * @returns Current preprocessor configuration object + * + * @example + * ```typescript + * // Inspect current settings + * const config = preprocessor.getConfig(); + * console.log('Vault path:', config.vaultPath); + * console.log('Preserve frontmatter:', config.options.preserveFrontmatter); + * console.log('Wikilink format:', config.wikilinkConfig.format); + * ``` + * + * @example + * ```typescript + * // Clone preprocessor with same configuration + * const currentConfig = preprocessor.getConfig(); + * const clonedPreprocessor = new MarkdownPreprocessor({ + * ...currentConfig, + * noteTitle: 'Different Title' + * }); + * ``` + * + * @example + * ```typescript + * // Modify and reapply configuration + * const config = preprocessor.getConfig(); + * config.options.baseUrl = 'https://new-url.com'; + * preprocessor.updateConfig(config); + * ``` */ public getConfig(): MarkdownPreprocessorConfig { return { @@ -258,12 +615,91 @@ export class MarkdownPreprocessor { } } -// Default configurations +/** + * Default preprocessor options for standard Markdown processing. + * + * These defaults are designed to work well for most Obsidian-to-Pandoc conversions: + * - **preserveFrontmatter: true** - Keeps YAML frontmatter in the output, allowing + * Pandoc and Typst to access metadata (title, author, date, custom variables). + * Set to false if you want to strip frontmatter entirely. + * - **baseUrl: ''** - Empty base URL means links remain relative to the vault. + * Set this when exporting to web to make links absolute (e.g., 'https://example.com/notes'). + * + * These values are used when creating a new MarkdownPreprocessor without explicit + * options. They can be overridden via the MarkdownPreprocessorConfig constructor + * parameter or modified later via updateConfig(). + * + * @example + * ```typescript + * // Use defaults implicitly + * const preprocessor = new MarkdownPreprocessor({ + * vaultPath: '/vault', + * options: DEFAULT_PREPROCESSOR_OPTIONS, // Explicit use of defaults + * wikilinkConfig: DEFAULT_WIKILINK_CONFIG + * }); + * ``` + * + * @example + * ```typescript + * // Override defaults for web export + * const webOptions = { + * ...DEFAULT_PREPROCESSOR_OPTIONS, + * baseUrl: 'https://blog.example.com/notes' + * }; + * ``` + */ export const DEFAULT_PREPROCESSOR_OPTIONS: PreprocessorOptions = { preserveFrontmatter: true, baseUrl: '' }; +/** + * Default wikilink conversion configuration for Markdown output. + * + * These defaults convert Obsidian wikilinks to standard Markdown links: + * - **format: 'md'** - Convert to Markdown format `[text](link.md)` + * Other possible values: 'html' for `[text](link.html)`, 'wiki' to preserve `[[link]]` + * - **extension: '.md'** - Add .md extension to converted links + * Ensures [[note]] becomes [note](note.md) for proper cross-reference handling + * + * This configuration is passed to WikilinkProcessor during preprocessing and + * ensures consistent link handling throughout the conversion pipeline. + * + * These values work well for Pandoc conversion, as Pandoc expects standard + * Markdown links with file extensions. For web publishing, you might want to + * use format: 'html' and extension: '.html' instead. + * + * @example + * ```typescript + * // Use defaults for standard Markdown output + * const preprocessor = new MarkdownPreprocessor({ + * vaultPath: '/vault', + * options: DEFAULT_PREPROCESSOR_OPTIONS, + * wikilinkConfig: DEFAULT_WIKILINK_CONFIG // [[note]] → [note](note.md) + * }); + * ``` + * + * @example + * ```typescript + * // Override for HTML export + * const htmlWikilinkConfig = { + * ...DEFAULT_WIKILINK_CONFIG, + * format: 'html', + * extension: '.html' + * }; + * // [[note]] → [note](note.html) + * ``` + * + * @example + * ```typescript + * // Preserve wikilinks (no conversion) + * const preserveWikilinks = { + * format: 'wiki', + * extension: '' + * }; + * // [[note]] → [[note]] (unchanged) + * ``` + */ export const DEFAULT_WIKILINK_CONFIG: WikilinkConfig = { format: 'md', extension: '.md' diff --git a/src/converters/PandocTypstConverter.ts b/src/converters/PandocTypstConverter.ts index f34df3f..1413521 100644 --- a/src/converters/PandocTypstConverter.ts +++ b/src/converters/PandocTypstConverter.ts @@ -1,6 +1,17 @@ /** - * Pandoc to Typst PDF Converter - * Handles the conversion of Markdown to PDF using Pandoc with Typst engine + * Pandoc to Typst PDF Converter. + * + * This module provides the main conversion engine for transforming Markdown files + * to PDF documents using the Pandoc → Typst → PDF pipeline. It coordinates all + * aspects of the conversion process including: + * - Temporary file and directory management + * - Command building and execution + * - Progress reporting + * - Resource cleanup + * - Error handling + * + * The converter supports both file-based and content-based conversions, automatically + * managing temporary directories and cleanup on process termination. */ import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes'; @@ -11,6 +22,52 @@ import { PathUtils } from '../core/PathUtils'; import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder'; import { PandocExecutor } from './pandoc/PandocExecutor'; +/** + * Main converter class for Markdown → Typst → PDF conversion. + * + * This class orchestrates the PDF export process by delegating to specialized + * components (PandocCommandBuilder, PandocExecutor) while managing temporary + * resources and providing progress feedback. + * + * Key features: + * - File and content-based conversion support + * - Automatic temporary directory management + * - Process cleanup on termination (exit, SIGINT, SIGTERM, exceptions) + * - Progress callback support for UI updates + * - Configurable Pandoc and Typst settings + * + * Lifecycle: + * 1. Constructor initializes command builder and executor + * 2. Conversion methods create temp directories and build commands + * 3. Executor runs Pandoc with Typst engine + * 4. Cleanup automatically removes temporary files + * 5. dispose() for manual cleanup when done + * + * @example + * ```typescript + * const converter = new PandocTypstConverter( + * plugin, + * { template: 'modern', variables: { ... } }, + * { ppi: 144 } + * ); + * + * try { + * const result = await converter.convertToPDF( + * 'input.md', + * 'output.pdf', + * (message, progress) => console.log(`${progress}%: ${message}`) + * ); + * + * if (result.success) { + * console.log('PDF created:', result.outputPath); + * } else { + * console.error('Conversion failed:', result.error); + * } + * } finally { + * await converter.dispose(); + * } + * ``` + */ export class PandocTypstConverter { private tempDir: string | null = null; private cleanupHandlers: (() => void)[] = []; @@ -19,10 +76,34 @@ export class PandocTypstConverter { private pandocExecutor: PandocExecutor; /** - * Create a new PandocTypstConverter instance - * @param plugin The main plugin instance for accessing settings - * @param pandocOptions Configuration options for Pandoc - * @param typstSettings Settings specific to Typst engine + * Creates a new PandocTypstConverter instance with configuration. + * + * Initializes the converter with the plugin instance and configuration options + * for both Pandoc and Typst. Sets up cleanup handlers to ensure temporary + * files are removed on process termination. + * + * @param plugin - The main plugin instance for accessing app and settings + * @param pandocOptions - Configuration options for Pandoc conversion (template, variables, etc.) + * @param typstSettings - Settings specific to Typst rendering engine (ppi, font-paths, etc.) + * + * @example + * ```typescript + * const converter = new PandocTypstConverter( + * this.plugin, + * { + * template: 'modern', + * variables: { + * pageSize: 'a4', + * bodyFont: 'Georgia' + * }, + * metadata: { title: 'My Document' } + * }, + * { + * ppi: 144, + * fontPaths: ['/usr/share/fonts'] + * } + * ); + * ``` */ constructor( plugin: obsidianTypstPDFExport, @@ -37,15 +118,46 @@ export class PandocTypstConverter { } /** - * Convert a markdown file to PDF using Pandoc with Typst engine - * @param inputPath Path to the input markdown file - * @param outputPath Path where the PDF should be saved - * @param progressCallback Optional callback for progress updates - * @returns Promise resolving to conversion result + * Converts a Markdown file to PDF using the Pandoc → Typst → PDF pipeline. + * + * This is the primary conversion method that handles the complete export process: + * 1. Creates temporary directory for intermediate files + * 2. Builds Pandoc command with configured options + * 3. Executes Pandoc with Typst engine + * 4. Reports progress via optional callback + * 5. Returns result with success status and output path + * + * The method automatically manages temporary files and provides progress updates + * at key stages. If conversion fails, returns error information in the result + * object rather than throwing. + * + * @param inputPath - Absolute path to the input Markdown file + * @param outputPath - Absolute path where the PDF should be saved + * @param progressCallback - Optional callback for progress updates (message, percentage) + * @returns Promise resolving to conversion result with success flag and optional error + * + * @example + * ```typescript + * const result = await converter.convertToPDF( + * '/path/to/note.md', + * '/path/to/output.pdf', + * (message, progress) => { + * console.log(`${progress}%: ${message}`); + * // Update UI progress bar + * } + * ); + * + * if (result.success) { + * console.log('PDF created at:', result.outputPath); + * } else { + * console.error('Conversion failed:', result.error); + * console.log('Pandoc output:', result.stdout); + * } + * ``` */ async convertToPDF( - inputPath: string, - outputPath: string, + inputPath: string, + outputPath: string, progressCallback?: ProgressCallback ): Promise { try { @@ -89,7 +201,43 @@ export class PandocTypstConverter { } /** - * Convert markdown content to PDF + * Converts Markdown content (string) to PDF without requiring a file. + * + * This is a convenience method for converting Markdown content directly from + * memory without needing an existing file. It creates a temporary file, + * delegates to convertToPDF, then cleans up the temporary file. + * + * Useful for: + * - Converting dynamically generated content + * - Processing in-memory Markdown transformations + * - Testing conversion without file system operations + * + * Note: This method merges the provided options with existing pandocOptions. + * + * @param content - Markdown content to convert + * @param outputPath - Absolute path where the PDF should be saved + * @param options - Additional Pandoc options to merge with existing settings + * @param progressCallback - Optional callback for progress updates (message, percentage) + * @returns Promise resolving to conversion result with success flag and optional error + * + * @example + * ```typescript + * const markdown = ` + * # My Document + * This is **dynamically generated** content. + * `; + * + * const result = await converter.convertMarkdownToPDF( + * markdown, + * '/path/to/output.pdf', + * { variables: { title: 'Generated Doc' } }, + * (msg, pct) => updateProgress(pct) + * ); + * + * if (result.success) { + * console.log('Created PDF from content'); + * } + * ``` */ async convertMarkdownToPDF( content: string, @@ -131,7 +279,17 @@ export class PandocTypstConverter { } /** - * Set up cleanup handlers for temporary files + * Sets up automatic cleanup handlers for process termination events. + * + * Registers the cleanup method to run on various process termination events + * to ensure temporary files are removed even if the process exits unexpectedly. + * Handlers are registered for: + * - Normal exit + * - SIGINT (Ctrl+C) + * - SIGTERM (kill command) + * - Uncaught exceptions + * + * @private */ private setupCleanup(): void { const cleanup = () => { @@ -146,7 +304,16 @@ export class PandocTypstConverter { /** - * Clean up temporary files and directories + * Cleans up temporary files and directories. + * + * This method executes all registered cleanup handlers and removes the temporary + * directory created by the converter. Cleanup failures are logged but don't throw + * to avoid interfering with normal operation or other cleanup operations. + * + * Called automatically on process termination or manually via dispose(). + * + * @private + * @returns Promise that resolves when cleanup is complete */ private async cleanup(): Promise { try { @@ -171,7 +338,19 @@ export class PandocTypstConverter { } /** - * Ensure temporary directory exists + * Ensures a temporary directory exists for intermediate conversion files. + * + * Creates a temporary directory on first call and reuses it for subsequent calls. + * The directory is created inside the plugin folder if vaultBasePath is available, + * otherwise falls back to vault-level temp directories. + * + * The temporary directory is used for: + * - Temporary Markdown files + * - Intermediate Typst files (if debug mode enabled) + * - Processed resource files + * + * @private + * @returns Promise resolving to the temporary directory path */ private async ensureTempDirectory(): Promise { if (!this.tempDir) { @@ -194,7 +373,24 @@ export class PandocTypstConverter { /** - * Dispose of the converter and clean up resources + * Disposes of the converter and cleans up all resources. + * + * This method should be called when done with the converter to ensure temporary + * files are removed. While cleanup happens automatically on process termination, + * calling dispose explicitly allows for immediate cleanup and is recommended + * when the converter is no longer needed. + * + * @returns Promise that resolves when cleanup is complete + * + * @example + * ```typescript + * const converter = new PandocTypstConverter(plugin, options); + * try { + * await converter.convertToPDF(input, output); + * } finally { + * await converter.dispose(); // Cleanup even if conversion fails + * } + * ``` */ async dispose(): Promise { await this.cleanup(); diff --git a/src/converters/PdfToImageConverter.ts b/src/converters/PdfToImageConverter.ts index 0193724..88fa87a 100644 --- a/src/converters/PdfToImageConverter.ts +++ b/src/converters/PdfToImageConverter.ts @@ -1,6 +1,39 @@ /** - * PDF to Image Converter using pdf-to-img - * Converts PDF files to PNG images for preview in Typst exports + * PDF to Image conversion for embedded PDF files in Obsidian notes. + * + * This module provides a robust conversion system for transforming PDF files into + * images suitable for embedding in Typst-generated PDFs. Since Typst has limited + * native PDF embedding capabilities, this converter extracts the first page of + * embedded PDFs and converts them to high-quality PNG or JPEG images. + * + * Key features: + * - Singleton pattern for resource efficiency and state management + * - First-page-only conversion for preview purposes + * - Configurable image quality and dimensions + * - Multi-strategy PDF processing (pdf-to-img library with ImageMagick fallback) + * - Automatic format conversion and optimization + * - File discovery for handling various filename patterns + * - Comprehensive error handling and validation + * + * Conversion Pipeline: + * 1. PDF validation (file exists, valid format, readable) + * 2. Output directory preparation + * 3. CLI execution via pdf-to-img or ImageMagick + * 4. Generated file discovery (handles naming variations) + * 5. Image optimization (format conversion, dimension detection) + * 6. Result packaging with metadata + * + * The converter delegates to specialized utilities: + * - PdfProcessor: PDF validation and metadata extraction + * - PdfCliExecutor: Command-line tool execution + * - FileDiscovery: Generated file location + * - ImageOptimizer: Format conversion and dimension detection + * + * Architecture Notes: + * - Singleton pattern ensures consistent state across exports + * - Plugin reference enables vault file operations + * - Modular design allows easy extension for multi-page conversion + * - Error results preserve context for debugging */ import * as path from 'path'; @@ -11,6 +44,51 @@ import { FileDiscovery } from './pdf/FileDiscovery'; import type { obsidianTypstPDFExport } from '../../main'; import { PathUtils } from '../core/PathUtils'; +/** + * Configuration options for PDF to image conversion. + * + * These options control the quality, dimensions, and format of generated images. + * All options are optional with sensible defaults optimized for embedding in PDFs. + * + * @property scale - Rendering scale factor for image quality (default: 2.0) + * Higher values produce sharper images but larger file sizes. 2.0 is optimal + * for HiDPI displays and print-quality PDFs. Use 1.0 for web-optimized exports. + * @property maxWidth - Maximum output image width in pixels (default: 800) + * Images wider than this are scaled down proportionally. Prevents excessive + * file sizes while maintaining readability in typical PDF layouts. + * @property maxHeight - Maximum output image height in pixels (default: 600) + * Images taller than this are scaled down proportionally. Balances quality + * with file size for typical document heights. + * @property format - Output image format (default: 'png') + * - 'png': Lossless compression, best for diagrams and text + * - 'jpeg': Lossy compression, smaller files for photos + * @property quality - JPEG compression quality 1-100 (default: 90) + * Only applies when format is 'jpeg'. Higher values preserve more detail + * but increase file size. 90 provides excellent quality with good compression. + * + * @example + * ```typescript + * // High-quality conversion for print + * const printOptions: PdfConversionOptions = { + * scale: 3.0, + * maxWidth: 1200, + * maxHeight: 900, + * format: 'png' + * }; + * ``` + * + * @example + * ```typescript + * // Web-optimized conversion + * const webOptions: PdfConversionOptions = { + * scale: 1.0, + * maxWidth: 600, + * maxHeight: 450, + * format: 'jpeg', + * quality: 85 + * }; + * ``` + */ export interface PdfConversionOptions { /** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */ scale?: number; @@ -24,6 +102,58 @@ export interface PdfConversionOptions { quality?: number; } +/** + * Result of PDF to image conversion operation. + * + * This interface provides comprehensive information about the conversion outcome, + * including file paths, dimensions, and success status. The result always includes + * a success flag - when false, the error field provides diagnostic information. + * + * @property imagePath - Absolute path to the generated image file + * Empty string if conversion failed. Use this path to embed the image in Typst. + * @property originalDimensions - Original PDF page dimensions in pixels + * Width and height of the PDF page before conversion. Set to {0, 0} on failure. + * Note: Currently estimates based on converted image due to library limitations. + * @property imageDimensions - Generated image dimensions in pixels + * Actual width and height of the output image file. May differ from original + * due to scaling, format conversion, or optimization. Set to {0, 0} on failure. + * @property success - Conversion success flag + * True if image was generated successfully, false if any error occurred. + * Always check this before using imagePath or dimension data. + * @property error - Error message if conversion failed + * Present only when success is false. Contains diagnostic information about + * what went wrong (file not found, invalid PDF, conversion failure, etc.). + * + * @example + * ```typescript + * const result = await converter.convertFirstPageToImage(pdfPath, outputDir); + * + * if (result.success) { + * console.log('Image created:', result.imagePath); + * console.log('Dimensions:', result.imageDimensions); + * // Use result.imagePath in Typst template + * } else { + * console.error('Conversion failed:', result.error); + * // Fallback to placeholder or skip embed + * } + * ``` + * + * @example + * ```typescript + * // Handle dimension information + * const result = await converter.convertFirstPageToImage(pdfPath, outputDir); + * + * if (result.success) { + * const aspectRatio = result.imageDimensions.width / result.imageDimensions.height; + * console.log('Aspect ratio:', aspectRatio.toFixed(2)); + * + * // Adjust Typst layout based on dimensions + * if (aspectRatio > 1.5) { + * // Wide image - use landscape layout + * } + * } + * ``` + */ export interface PdfConversionResult { /** Path to the generated image file */ imagePath: string; @@ -43,15 +173,124 @@ export interface PdfConversionResult { error?: string; } +/** + * Singleton converter for transforming PDF files into embeddable images. + * + * This class provides the primary interface for PDF to image conversion in the + * export pipeline. It implements the singleton pattern to ensure consistent state + * and resource management across multiple conversion operations. + * + * Key Responsibilities: + * - First-page extraction from PDF files + * - High-quality image generation with configurable options + * - PDF validation and metadata extraction + * - Integration with Obsidian vault file system + * - Error handling and result reporting + * + * Architecture: + * The converter delegates to specialized utility classes: + * - **PdfProcessor**: PDF file validation and metadata + * - **PdfCliExecutor**: Command-line tool execution (pdf-to-img, ImageMagick) + * - **FileDiscovery**: Generated file location and verification + * - **ImageOptimizer**: Format conversion and dimension detection + * - **PathUtils**: Obsidian vault file operations + * + * Singleton Pattern: + * Use `getInstance()` to obtain the converter instance. The singleton ensures: + * - Single plugin reference across all conversions + * - Consistent configuration and state + * - Efficient resource usage + * - Simplified dependency injection + * + * Usage Flow: + * 1. Get instance with plugin reference: `PdfToImageConverter.getInstance(plugin)` + * 2. Convert PDF: `await converter.convertFirstPageToImage(path, outDir, options)` + * 3. Check result.success and use result.imagePath in Typst template + * 4. Handle errors via result.error message + * + * @example + * ```typescript + * // Initialize converter with plugin reference + * const converter = PdfToImageConverter.getInstance(this.plugin); + * + * // Convert PDF with default options + * const result = await converter.convertFirstPageToImage( + * '/vault/attachments/document.pdf', + * '/vault/.obsidian/plugins/typst-pdf-export/temp-images' + * ); + * + * if (result.success) { + * console.log('Converted to:', result.imagePath); + * // Embed result.imagePath in Typst template + * } else { + * console.error('Conversion failed:', result.error); + * } + * ``` + * + * @example + * ```typescript + * // High-quality conversion with custom options + * const converter = PdfToImageConverter.getInstance(this.plugin); + * + * const result = await converter.convertFirstPageToImage( + * pdfPath, + * outputDir, + * { + * scale: 3.0, // 3x rendering for print quality + * maxWidth: 1200, // Larger dimensions + * format: 'png' // Lossless format + * } + * ); + * ``` + */ export class PdfToImageConverter { private static instance: PdfToImageConverter; private plugin: obsidianTypstPDFExport | undefined; + /** + * Private constructor for singleton pattern. + * + * Use getInstance() to obtain the converter instance instead of constructing directly. + * + * @param plugin - Optional plugin reference for vault operations + * @private + */ private constructor(plugin?: obsidianTypstPDFExport) { this.plugin = plugin; } - + /** + * Gets or creates the singleton PdfToImageConverter instance. + * + * This method ensures only one converter instance exists throughout the application + * lifecycle. If a plugin reference is provided on subsequent calls, it updates the + * stored reference to ensure vault operations work correctly. + * + * Thread Safety: + * This implementation is safe for single-threaded JavaScript execution. + * The singleton is created on first access and reused thereafter. + * + * @param plugin - Optional plugin reference (updates stored reference if provided) + * @returns The singleton PdfToImageConverter instance + * + * @example + * ```typescript + * // First call creates instance + * const converter1 = PdfToImageConverter.getInstance(this.plugin); + * + * // Subsequent calls return same instance + * const converter2 = PdfToImageConverter.getInstance(); + * console.log(converter1 === converter2); // true + * ``` + * + * @example + * ```typescript + * // Update plugin reference after initialization + * const converter = PdfToImageConverter.getInstance(); // No plugin initially + * // ... later ... + * PdfToImageConverter.getInstance(this.plugin); // Updates plugin reference + * ``` + */ public static getInstance(plugin?: obsidianTypstPDFExport): PdfToImageConverter { if (!PdfToImageConverter.instance) { PdfToImageConverter.instance = new PdfToImageConverter(plugin); @@ -63,11 +302,93 @@ export class PdfToImageConverter { } /** - * Convert the first page of a PDF to an image + * Converts the first page of a PDF file to a high-quality image. + * + * This is the primary conversion method that orchestrates the complete PDF-to-image + * pipeline. It handles validation, conversion, optimization, and error reporting in + * a single operation suitable for embedding in Typst exports. + * + * Conversion Pipeline: + * 1. **Validation**: Verify PDF file exists and is valid + * 2. **Directory Setup**: Ensure output directory exists (via vault adapter) + * 3. **CLI Execution**: Run pdf-to-img or ImageMagick to convert first page + * 4. **File Discovery**: Locate generated image (handles various naming patterns) + * 5. **Optimization**: Convert format and detect dimensions + * 6. **Result Packaging**: Return success with image path and metadata + * + * Error Handling: + * Each stage reports specific errors via PdfConversionResult. Common failures: + * - File not found or inaccessible + * - Invalid or corrupted PDF format + * - CLI tool execution failure + * - Output file not found after conversion + * - Image optimization failure + * + * All errors are captured and returned in result.error, never thrown as exceptions. + * + * Performance: + * - First-page-only conversion is fast (~1-2 seconds typical) + * - Uses CLI tools for native-quality rendering + * - Temporary files cleaned up automatically by caller + * - Suitable for batch processing multiple PDFs + * + * @param pdfPath - Absolute path to PDF file to convert + * @param outputDir - Absolute path to output directory for generated image + * @param options - Optional conversion configuration (defaults to HiDPI quality) + * @returns Promise resolving to conversion result with success status and metadata + * + * @example + * ```typescript + * // Basic conversion with defaults + * const converter = PdfToImageConverter.getInstance(this.plugin); + * const result = await converter.convertFirstPageToImage( + * '/vault/attachments/report.pdf', + * '/vault/.obsidian/plugins/typst-pdf-export/temp-images' + * ); + * + * if (result.success) { + * console.log('Image:', result.imagePath); + * console.log('Size:', result.imageDimensions.width, 'x', result.imageDimensions.height); + * // Use result.imagePath in Typst: #image("path") + * } else { + * new Notice(`PDF conversion failed: ${result.error}`); + * } + * ``` + * + * @example + * ```typescript + * // High-quality conversion for print + * const result = await converter.convertFirstPageToImage( + * pdfPath, + * outputDir, + * { + * scale: 3.0, + * maxWidth: 1600, + * maxHeight: 1200, + * format: 'png' + * } + * ); + * ``` + * + * @example + * ```typescript + * // Batch convert multiple PDFs + * const converter = PdfToImageConverter.getInstance(this.plugin); + * const pdfPaths = ['/vault/doc1.pdf', '/vault/doc2.pdf', '/vault/doc3.pdf']; + * + * for (const pdfPath of pdfPaths) { + * const result = await converter.convertFirstPageToImage(pdfPath, outputDir); + * if (result.success) { + * console.log(`✓ ${path.basename(pdfPath)}`); + * } else { + * console.error(`✗ ${path.basename(pdfPath)}: ${result.error}`); + * } + * } + * ``` */ public async convertFirstPageToImage( - pdfPath: string, - outputDir: string, + pdfPath: string, + outputDir: string, options: PdfConversionOptions = {} ): Promise { try { @@ -180,14 +501,124 @@ export class PdfToImageConverter { } /** - * Check if a file is a valid PDF + * Validates whether a file is a readable PDF document. + * + * This utility method provides quick PDF validation before attempting conversion. + * It checks both file existence and PDF format validity by delegating to PdfProcessor. + * + * Validation includes: + * - File exists and is accessible + * - File has PDF magic bytes (header signature) + * - File is not corrupted or truncated + * + * Use this for pre-flight checks before expensive conversion operations or to + * filter PDF files from mixed file lists. + * + * @param filePath - Absolute path to file to validate + * @returns Promise resolving to true if file is valid PDF, false otherwise + * + * @example + * ```typescript + * const converter = PdfToImageConverter.getInstance(this.plugin); + * + * // Validate before conversion + * if (await converter.isValidPdf(pdfPath)) { + * const result = await converter.convertFirstPageToImage(pdfPath, outputDir); + * // Process result... + * } else { + * new Notice('Not a valid PDF file'); + * } + * ``` + * + * @example + * ```typescript + * // Filter PDF files from attachments + * const attachments = app.vault.getFiles(); + * const converter = PdfToImageConverter.getInstance(this.plugin); + * + * const validPdfs = []; + * for (const file of attachments) { + * if (file.extension === 'pdf' && await converter.isValidPdf(file.path)) { + * validPdfs.push(file); + * } + * } + * console.log(`Found ${validPdfs.length} valid PDFs`); + * ``` */ public async isValidPdf(filePath: string): Promise { return await PdfProcessor.isValidPdf(filePath); } /** - * Get PDF metadata (page count, dimensions, etc.) + * Retrieves metadata about a PDF file without converting it. + * + * This method extracts essential PDF information including page count and page + * dimensions. It's useful for: + * - Determining if multi-page conversion is needed + * - Checking PDF dimensions before conversion + * - Pre-flight validation with detailed error messages + * - UI display of PDF properties + * + * The method delegates to PdfProcessor for actual metadata extraction. On success, + * returns page count and first page dimensions. On failure, returns error details. + * + * Note: Dimensions are for the first page only. Multi-page PDFs may have varying + * page sizes, but this implementation focuses on first-page conversion. + * + * @param filePath - Absolute path to PDF file + * @returns Promise resolving to metadata object with page count, dimensions, and success status + * + * @example + * ```typescript + * const converter = PdfToImageConverter.getInstance(this.plugin); + * const info = await converter.getPdfInfo(pdfPath); + * + * if (info.success) { + * console.log(`Pages: ${info.pageCount}`); + * console.log(`Size: ${info.dimensions.width}x${info.dimensions.height}px`); + * + * if (info.pageCount > 1) { + * new Notice(`PDF has ${info.pageCount} pages - only first will be converted`); + * } + * } else { + * console.error('Failed to read PDF info:', info.error); + * } + * ``` + * + * @example + * ```typescript + * // Adjust conversion options based on PDF dimensions + * const info = await converter.getPdfInfo(pdfPath); + * + * if (info.success) { + * const isLandscape = info.dimensions.width > info.dimensions.height; + * + * const options: PdfConversionOptions = { + * maxWidth: isLandscape ? 1200 : 800, + * maxHeight: isLandscape ? 800 : 1200 + * }; + * + * const result = await converter.convertFirstPageToImage(pdfPath, outputDir, options); + * } + * ``` + * + * @example + * ```typescript + * // Check PDF before showing conversion dialog + * const info = await converter.getPdfInfo(pdfPath); + * + * if (!info.success) { + * new Notice(`Cannot process PDF: ${info.error}`); + * return; + * } + * + * // Show dialog with PDF details + * new PDFConversionModal( + * this.app, + * pdfPath, + * `${info.pageCount} pages, ${info.dimensions.width}x${info.dimensions.height}px` + * ).open(); + * ``` */ public async getPdfInfo(filePath: string): Promise<{ pageCount: number; diff --git a/src/converters/pandoc/PandocCommandBuilder.ts b/src/converters/pandoc/PandocCommandBuilder.ts index 33685ba..361017a 100644 --- a/src/converters/pandoc/PandocCommandBuilder.ts +++ b/src/converters/pandoc/PandocCommandBuilder.ts @@ -1,6 +1,50 @@ /** - * Pandoc Command Builder - * Handles construction of Pandoc command-line arguments for Typst PDF conversion + * Command-line argument builder for Pandoc-to-Typst PDF conversion. + * + * This module constructs complete Pandoc command-line arguments for converting + * preprocessed Markdown to Typst format, which is then compiled to PDF by the + * Typst engine. It orchestrates several key aspects of the conversion: + * - Input/output path specification + * - Typst PDF engine configuration + * - Template loading and variable passing + * - Resource path resolution for embedded media + * - Diagnostic and error reporting options + * + * Key Features: + * - Modular argument construction via specialized methods + * - Template system with universal wrapper for dynamic template selection + * - Comprehensive variable mapping from export config to Typst variables + * - Smart resource path resolution for Obsidian attachments + * - Enhanced diagnostics for debugging conversion failures + * - Safe path handling with automatic quoting via spawn + * + * Architecture: + * The builder delegates to specialized components: + * - **TypstVariableMapper**: Maps export config to Typst variables + * - **ResourcePathResolver**: Finds attachment directories in vault + * - **PathResolver**: Resolves executable paths with fallback logic + * - **PathUtils**: Obsidian vault file system operations + * + * Command Structure: + * ```bash + * pandoc input.md \ + * -o output.pdf \ + * --from markdown-smart \ + * --pdf-engine=typst \ + * --standalone \ + * --no-citeproc \ + * --embed-resources \ + * --resource-path /vault/attachments \ + * --template universal-wrapper.typ \ + * -V template_path=default.typ \ + * -V page_width=210mm \ + * ... (more variables) + * --pdf-engine-opt --diagnostic-format=short + * ``` + * + * The universal wrapper template receives the actual template path as a variable, + * allowing dynamic template selection without requiring separate wrapper files + * for each template. */ import * as path from 'path'; @@ -11,12 +55,58 @@ import { PathResolver } from '../../plugin/PathResolver'; import type { obsidianTypstPDFExport } from '../../../main'; import { PathUtils } from '../../core/PathUtils'; +/** + * Builder for Pandoc command-line arguments in the Markdown → Typst → PDF pipeline. + * + * This class encapsulates the complex logic for constructing Pandoc command arguments + * that correctly configure Typst PDF generation. It manages several interdependent + * concerns including template loading, variable mapping, resource path resolution, + * and diagnostic configuration. + * + * Design Philosophy: + * - Single responsibility: Only builds command arguments, doesn't execute + * - Modular construction: Each argument category handled by dedicated method + * - Dependency injection: Receives plugin reference for configuration access + * - Async-safe: Handles file system checks without blocking + * + * The builder pattern allows testing argument construction independently from + * command execution, and makes it easy to modify argument logic without touching + * the execution layer. + * + * @example + * ```typescript + * const builder = new PandocCommandBuilder(this.plugin); + * + * const args = await builder.buildPandocArgs( + * '/vault/note.md', + * '/vault/exports/note.pdf', + * { + * template: 'default', + * vaultBasePath: '/vault', + * pluginDir: '/vault/.obsidian/plugins/typst-pdf-export', + * typstPath: 'typst', + * exportConfig: { pageSize: 'a4', orientation: 'portrait' } + * } + * ); + * + * // Execute with spawn + * spawn('pandoc', args); + * ``` + */ export class PandocCommandBuilder { private plugin: obsidianTypstPDFExport; private variableMapper: TypstVariableMapper; private resourcePathResolver: ResourcePathResolver; private pathResolver: PathResolver; + /** + * Creates a new PandocCommandBuilder. + * + * Initializes all dependent components (variable mapper, resource path resolver, + * path resolver) that the builder needs to construct complete command arguments. + * + * @param plugin - Plugin instance for accessing configuration and vault operations + */ constructor(plugin: obsidianTypstPDFExport) { this.plugin = plugin; this.variableMapper = new TypstVariableMapper(plugin); @@ -25,7 +115,72 @@ export class PandocCommandBuilder { } /** - * Build pandoc command-line arguments + * Builds complete Pandoc command-line arguments for Typst PDF generation. + * + * This is the primary interface method that orchestrates all argument construction. + * It delegates to specialized private methods for each category of arguments, + * ensuring proper ordering and completeness. + * + * Argument Order (important for Pandoc): + * 1. Input file path + * 2. Output file specification (-o) + * 3. Input format (--from markdown-smart) + * 4. PDF engine configuration (--pdf-engine=typst) + * 5. Standalone mode (--standalone) + * 6. Citation processing (--no-citeproc) + * 7. Resource embedding (--embed-resources) + * 8. Resource paths (--resource-path, multiple) + * 9. Template configuration (--template, -V template_path) + * 10. Typst variables (-V key=value, multiple) + * 11. Engine options (--pdf-engine-opt, multiple) + * 12. Diagnostics (--pdf-engine-opt --diagnostic-format=short) + * + * Side Effects: + * - Changes process.cwd() if vaultBasePath is provided + * - Reads file system to verify template existence + * - May throw Error if universal wrapper template not found + * + * @param inputPath - Absolute path to preprocessed Markdown input file + * @param outputPath - Absolute path for generated PDF output file + * @param pandocOptions - Configuration for Pandoc execution and Typst variables + * @returns Promise resolving to array of command-line arguments for Pandoc + * + * @throws {Error} If universal wrapper template not found + * + * @example + * ```typescript + * // Basic usage + * const builder = new PandocCommandBuilder(this.plugin); + * const args = await builder.buildPandocArgs( + * '/vault/preprocessed.md', + * '/vault/output.pdf', + * { + * template: 'modern', + * vaultBasePath: '/vault', + * typstPath: '/usr/local/bin/typst', + * exportConfig: { + * pageSize: 'letter', + * margins: { top: '1in', bottom: '1in' } + * } + * } + * ); + * console.log('Pandoc args:', args.join(' ')); + * ``` + * + * @example + * ```typescript + * // With custom engine options + * const args = await builder.buildPandocArgs( + * inputPath, + * outputPath, + * { + * template: 'article', + * typstSettings: { + * engineOptions: ['--root', '/custom/root', '--font-path', '/fonts'] + * } + * } + * ); + * ``` */ async buildPandocArgs(inputPath: string, outputPath: string, pandocOptions: PandocOptions): Promise { const args: string[] = []; @@ -78,7 +233,20 @@ export class PandocCommandBuilder { } /** - * Add resource paths for attachment resolution + * Adds resource paths to command arguments for Obsidian attachment resolution. + * + * This method enables Pandoc to find embedded images, PDFs, and other attachments + * referenced in the markdown content. It uses ResourcePathResolver to discover all + * attachment directories in the vault and adds them via --resource-path flags. + * + * Multiple --resource-path arguments can be provided, and Pandoc searches them in + * order when resolving relative paths in the markdown. This allows attachments to + * be stored in various locations (root-level, nested folders, etc.) and still be + * found during conversion. + * + * @param args - Command arguments array to append to + * @param pandocOptions - Options including vaultBasePath for resource discovery + * @private */ private async addResourcePaths(args: string[], pandocOptions: PandocOptions): Promise { if (!pandocOptions.vaultBasePath) { @@ -96,7 +264,29 @@ export class PandocCommandBuilder { /** - * Add template configuration to pandoc arguments + * Adds template configuration using the universal wrapper pattern. + * + * This method implements the plugin's template system using a universal wrapper + * template that dynamically loads the actual template via a Typst import. This + * approach allows template selection at runtime without maintaining separate + * wrapper files for each template. + * + * Template Resolution: + * 1. Locate universal-wrapper.pandoc.typ in plugin templates directory + * 2. Verify wrapper exists (throws if missing) + * 3. Add wrapper as Pandoc --template + * 4. Add templates directory to resource paths (enables Typst imports) + * 5. Pass actual template path as template_path variable + * + * Path Handling: + * - Absolute template paths are made relative to vault root for Typst imports + * - Relative paths are passed through unchanged + * - spawn automatically handles path quoting for spaces + * + * @param args - Command arguments array to append to + * @param pandocOptions - Options including template path and plugin directory + * @throws {Error} If universal wrapper template not found + * @private */ private async addTemplateConfiguration(args: string[], pandocOptions: PandocOptions): Promise { // Use universal wrapper with --template and pass actual template as template_path variable @@ -130,19 +320,52 @@ export class PandocCommandBuilder { } /** - * Add all Typst variables using the variable mapper + * Adds all Typst template variables mapped from export configuration. + * + * This method delegates to TypstVariableMapper to transform the export configuration + * into Typst template variables. These variables control typography, layout, margins, + * and other formatting aspects of the final PDF. + * + * Variable Mapping: + * - ExportConfig fields → Typst variable names (e.g., pageSize → page_size) + * - Plugin settings provide fallback values for missing config fields + * - Values converted to Typst-compatible formats (e.g., "2.5cm" for margins) + * - Variables passed via -V key=value arguments to Pandoc + * + * Example Variables: + * - page_width, page_height: Page dimensions + * - margin_top, margin_bottom, margin_left, margin_right: Margins + * - body_font, heading_font, monospace_font: Typography + * - font_size: Base font size + * + * @param args - Command arguments array to append to + * @param pandocOptions - Options including exportConfig and plugin settings + * @private */ private addTypstVariables(args: string[], pandocOptions: PandocOptions): void { // Map all variables (ExportConfig + plugin settings fallbacks) using the variable mapper const typstVariables = this.variableMapper.mapAllVariablesToTypst(pandocOptions); - + // Convert to pandoc arguments and add to args const variableArgs = this.variableMapper.convertVariablesToPandocArgs(typstVariables); args.push(...variableArgs); } /** - * Add Typst engine options to pandoc arguments + * Adds custom Typst engine options for advanced configuration. + * + * This method passes additional command-line options directly to the Typst engine + * via Pandoc's --pdf-engine-opt flag. These options can override Typst's default + * behavior for specific use cases. + * + * Common Engine Options: + * - --root /path: Set Typst root directory for imports + * - --font-path /fonts: Add custom font directories + * - --input key=value: Pass additional variables to Typst + * + * @param args - Command arguments array to append to + * @param pandocOptions - Options including typstSettings.engineOptions + * @private */ private addTypstEngineOptions(args: string[], pandocOptions: PandocOptions): void { if (pandocOptions.typstSettings?.engineOptions) { @@ -153,7 +376,19 @@ export class PandocCommandBuilder { } /** - * Add enhanced Typst diagnostics for better error reporting + * Adds Typst diagnostic configuration for enhanced error reporting. + * + * This method enables short-format diagnostics in Typst, which provide cleaner + * and more readable error messages when compilation fails. The short format is + * easier to parse and present to users compared to the verbose default format. + * + * Diagnostic Format: + * - Short: Concise error messages with file:line:column locations + * - Default (verbose): Detailed multi-line error reports with context + * + * @param args - Command arguments array to append to + * @param pandocOptions - Pandoc options (currently unused but kept for consistency) + * @private */ private addTypstDiagnostics(args: string[], pandocOptions: PandocOptions): void { // Add Typst diagnostic options for better error reporting diff --git a/src/converters/pandoc/PandocExecutor.ts b/src/converters/pandoc/PandocExecutor.ts index cfdac7d..79e40d0 100644 --- a/src/converters/pandoc/PandocExecutor.ts +++ b/src/converters/pandoc/PandocExecutor.ts @@ -4,26 +4,148 @@ import { PathResolver } from '../../plugin/PathResolver'; import type { obsidianTypstPDFExport } from '../../../main'; /** - * Handles pandoc process execution, monitoring, and error parsing. - * Manages the spawning and lifecycle of pandoc processes for document conversion. + * Process executor for Pandoc command-line conversions with progress monitoring. + * + * This class manages the complete lifecycle of Pandoc subprocess execution including: + * - Process spawning with augmented PATH and working directory configuration + * - Real-time stdout/stderr streaming and parsing + * - Progress monitoring and user feedback via callbacks + * - Timeout enforcement to prevent hanging conversions + * - Error extraction and formatting for user-friendly messages + * - Graceful process termination and cleanup + * + * Key Features: + * - **Augmented PATH**: Ensures Pandoc and Typst are found in common locations + * - **Working Directory**: Sets vault root as CWD for proper attachment resolution + * - **Progress Callbacks**: Updates UI during conversion stages + * - **Timeout Protection**: Kills hung processes after configurable duration + * - **Error Parsing**: Extracts meaningful error messages from raw output + * - **Promise-based API**: Clean async interface for callers + * + * Process Lifecycle: + * 1. Resolve Pandoc executable path with PathResolver + * 2. Determine working directory (vault root preferred) + * 3. Augment PATH environment with common binary locations + * 4. Spawn Pandoc process with stdio piping + * 5. Set up timeout handler for hanging processes + * 6. Stream and parse stdout/stderr for progress + * 7. Handle process completion or error + * 8. Clean up timeout handler and resolve promise + * + * The executor is designed to work reliably across different environments (macOS, + * Linux, Windows) by handling path resolution and environment variables carefully. + * + * @example + * ```typescript + * const executor = new PandocExecutor(this.plugin); + * + * const result = await executor.executePandoc( + * ['input.md', '-o', 'output.pdf', '--pdf-engine=typst'], + * { + * pandocPath: 'pandoc', + * vaultBasePath: '/vault', + * timeout: 120000 + * }, + * (message, progress) => { + * console.log(`${progress}%: ${message}`); + * } + * ); + * + * if (result.success) { + * console.log('Conversion succeeded'); + * } else { + * console.error('Error:', result.error); + * } + * ``` */ export class PandocExecutor { private pathResolver: PathResolver; + /** + * Creates a new PandocExecutor. + * + * @param plugin - Plugin instance for accessing PathResolver configuration + */ constructor(plugin: obsidianTypstPDFExport) { this.pathResolver = new PathResolver(plugin); } /** - * Execute pandoc process with the given arguments - * @param args Command line arguments for pandoc - * @param pandocOptions Configuration options including paths and timeout - * @param progressCallback Optional callback for progress updates - * @returns Promise resolving to conversion result + * Executes Pandoc process with comprehensive monitoring and error handling. + * + * This is the primary execution method that spawns a Pandoc subprocess, monitors + * its progress, enforces timeouts, and returns a detailed result. The method is + * fully asynchronous and promise-based for clean integration with async workflows. + * + * Process Configuration: + * - **Executable Resolution**: Uses PathResolver to find Pandoc (handles custom paths) + * - **Working Directory**: Sets vault root for relative path resolution + * - **PATH Augmentation**: Adds common binary locations to ensure tool discovery + * - **Stdio Piping**: Captures stdout/stderr for progress parsing and error reporting + * + * Progress Monitoring: + * The progressCallback receives updates at various stages: + * - 45%: Reading input (parsing phase) + * - 60%: Processing document (conversion phase) + * - 75%: Generating output (template application) + * - 85%: Running Typst engine (PDF generation) + * - 90%: Complete + * + * Timeout Handling: + * - Default: 60 seconds (configurable via pandocOptions.timeout) + * - Process killed with SIGTERM on timeout + * - Returns error result with timeout message + * - Prevents hung processes from blocking export queue + * + * Error Handling: + * - Non-zero exit code → Parses stderr for meaningful error + * - Process spawn failure → Returns startup error + * - Timeout → Returns timeout error + * - All errors include diagnostic context for debugging + * + * @param args - Complete command-line arguments for Pandoc (from PandocCommandBuilder) + * @param pandocOptions - Configuration including paths, timeout, and working directory + * @param progressCallback - Optional callback for real-time progress updates + * @returns Promise resolving to ConversionResult with success status and output + * + * @example + * ```typescript + * // Basic execution + * const executor = new PandocExecutor(this.plugin); + * const result = await executor.executePandoc(args, options); + * + * if (!result.success) { + * new Notice(`Conversion failed: ${result.error}`); + * } + * ``` + * + * @example + * ```typescript + * // With progress callback for UI updates + * const result = await executor.executePandoc( + * args, + * options, + * (message, progress) => { + * progressModal.update(message, progress); + * } + * ); + * ``` + * + * @example + * ```typescript + * // With custom timeout for large documents + * const result = await executor.executePandoc( + * args, + * { + * ...options, + * timeout: 300000 // 5 minutes for large PDF + * } + * ); + * ``` */ async executePandoc( - args: string[], - pandocOptions: PandocOptions, + args: string[], + pandocOptions: PandocOptions, progressCallback?: ProgressCallback ): Promise { return new Promise((resolve) => { @@ -122,9 +244,59 @@ export class PandocExecutor { } /** - * Parse progress information from pandoc output and update progress callback - * @param output Raw output from pandoc stderr - * @param progressCallback Optional callback to update progress + * Parses Pandoc's stderr output to detect conversion progress and update the UI. + * + * This method implements heuristic progress detection by scanning stderr output for + * specific keywords that indicate which phase of the conversion pipeline is active. + * While Pandoc doesn't provide structured progress events, certain log patterns + * reliably appear during specific phases. + * + * Detection Heuristics: + * - **"parsing" or "reading"** → 45% (Input parsing phase) + * - Pandoc is reading and parsing the markdown input + * - AST construction is underway + * - **"writing" or "generating"** → 75% (Output generation phase) + * - Pandoc is generating Typst markup from the AST + * - Template application is occurring + * - **"typst"** → 85% (PDF generation phase) + * - Typst engine is compiling to PDF + * - Final rendering in progress + * + * Progress updates are only sent if a progressCallback was provided. Multiple + * matches to the same pattern won't duplicate callbacks - only one update per + * phase is typical. + * + * Enhancement Opportunities: + * - Parse Typst's own progress output for more granular PDF generation updates + * - Detect specific error keywords to provide early warning + * - Track file processing count for multi-file conversions + * + * @param output - Raw text from Pandoc's stderr stream + * @param progressCallback - Optional callback to invoke with progress updates + * @private + * + * @example + * ```typescript + * // Typical stderr patterns that trigger updates: + * parseProgressFromOutput('[INFO] Parsing markdown...', callback); + * // → Triggers: callback('Reading input...', 45) + * + * parseProgressFromOutput('[INFO] Writing typst output...', callback); + * // → Triggers: callback('Generating output...', 75) + * + * parseProgressFromOutput('Running typst compile...', callback); + * // → Triggers: callback('Running Typst engine...', 85) + * ``` + * + * @example + * ```typescript + * // Used in stderr stream handler: + * pandocProcess.stderr?.on('data', (data: Buffer) => { + * const output = data.toString(); + * stderr += output; + * this.parseProgressFromOutput(output, progressCallback); + * }); + * ``` */ private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void { // Basic progress parsing - could be enhanced based on pandoc output patterns @@ -138,10 +310,79 @@ export class PandocExecutor { } /** - * Extract meaningful error messages from pandoc output - * @param stderr Standard error output from pandoc - * @param stdout Standard output from pandoc - * @returns Formatted error message + * Extracts meaningful, user-friendly error messages from Pandoc's raw output. + * + * This method implements a multi-tier fallback strategy to find the most relevant + * error information from Pandoc's stderr and stdout streams. Pandoc and Typst can + * produce verbose diagnostic output, so this method filters to find the most + * actionable error message for users. + * + * Extraction Strategy (in priority order): + * 1. **Pattern Matching**: Scan all output for common error indicators + * - Case-insensitive "error:" matches most Pandoc/Typst errors + * - Case-sensitive "Error:" catches Python and other tool errors + * - "failed" indicates operation failures + * - "Fatal" indicates critical termination errors + * - "pandoc:" catches Pandoc-specific diagnostic messages + * + * 2. **First Stderr Line**: If no pattern matches, use first non-empty stderr line + * - Assumes most important error appears early in stderr + * - Filters out empty lines for cleaner messages + * + * 3. **Generic Fallback**: If no stderr content, return generic error + * - Indicates process failure with no diagnostic output + * - Should be rare in practice + * + * Error Pattern Examples: + * - `Error: Could not find template: custom.typ` (Pandoc template error) + * - `pandoc: Cannot find file input.md` (File not found) + * - `error: font not found: "NonexistentFont"` (Typst font error) + * - `Fatal error: out of memory` (Resource exhaustion) + * - `failed to compile: syntax error at line 42` (Typst compilation error) + * + * The extracted message is displayed directly to users in error notices, so it + * should be concise and actionable without requiring interpretation. + * + * @param stderr - Complete stderr output captured from Pandoc process + * @param stdout - Complete stdout output captured from Pandoc process + * @returns User-friendly error message suitable for display in Notice + * @private + * + * @example + * ```typescript + * // Template not found error + * const stderr = "Error: Could not find template: custom.typ\nUsage: pandoc..."; + * const error = this.extractErrorMessage(stderr, ''); + * // Returns: "Error: Could not find template: custom.typ" + * ``` + * + * @example + * ```typescript + * // Typst compilation error + * const stderr = "typst compile failed\nerror: undefined function `foo`\n at line 15"; + * const error = this.extractErrorMessage(stderr, ''); + * // Returns: "error: undefined function `foo`" + * ``` + * + * @example + * ```typescript + * // Generic failure with no specific error + * const stderr = ""; + * const stdout = "Some non-error output"; + * const error = this.extractErrorMessage(stderr, stdout); + * // Returns: "Unknown error occurred during conversion" + * ``` + * + * @example + * ```typescript + * // Used in process close handler: + * pandocProcess.on('close', (code: number | null) => { + * if (!success) { + * result.error = this.extractErrorMessage(stderr, stdout); + * new Notice(`Export failed: ${result.error}`); + * } + * }); + * ``` */ private extractErrorMessage(stderr: string, stdout: string): string { // Look for common error patterns @@ -154,7 +395,7 @@ export class PandocExecutor { ]; const allOutput = (stderr + '\n' + stdout).split('\n'); - + for (const line of allOutput) { for (const pattern of errorPatterns) { if (pattern.test(line)) { diff --git a/src/core/DependencyChecker.ts b/src/core/DependencyChecker.ts index 2279432..7f116fa 100644 --- a/src/core/DependencyChecker.ts +++ b/src/core/DependencyChecker.ts @@ -1,11 +1,29 @@ /** - * Dependency checking utilities for Obsidian Typst PDF Export plugin + * Dependency checking utilities for Obsidian Typst PDF Export plugin. + * + * This module provides comprehensive dependency checking for the three external + * tools required by the plugin: + * - Pandoc: Converts Markdown to Typst markup + * - Typst: Compiles Typst markup to PDF + * - ImageMagick: Handles PDF-to-image conversion for embedded PDFs (optional) + * + * The module offers both async and sync checking methods, automatic startup + * validation, and user-facing status display functionality. */ import { DEPENDENCY_CONSTANTS } from './constants'; import { ExportErrorHandler } from './ExportErrorHandler'; import { ExecutableChecker, DependencyInfo } from './ExecutableChecker'; +/** + * Complete result of a dependency check operation. + * + * @property pandoc - Detailed information about Pandoc installation + * @property typst - Detailed information about Typst installation + * @property imagemagick - Detailed information about ImageMagick installation + * @property allAvailable - True if all dependencies are available + * @property missingDependencies - Array of names of missing dependencies + */ export interface DependencyCheckResult { pandoc: DependencyInfo; typst: DependencyInfo; @@ -14,6 +32,46 @@ export interface DependencyCheckResult { missingDependencies: string[]; } +/** + * Utilities for checking external dependency availability and versions. + * + * This class provides static methods for validating that Pandoc, Typst, and + * ImageMagick are properly installed and accessible. It supports both async + * and sync operations, configurable executable paths, and user notifications. + * + * Key features: + * - Comprehensive async checking with version detection + * - Fast sync checking for startup validation + * - User-facing status display with formatted output + * - Silent background checking with error notifications + * - Support for custom executable paths and search directories + * + * @example + * ```typescript + * // Comprehensive check with version information + * const result = await DependencyChecker.checkAllDependencies( + * settings.pandocPath, + * settings.typstPath, + * settings.imagemagickPath, + * settings.additionalPaths + * ); + * + * if (!result.allAvailable) { + * console.error('Missing:', result.missingDependencies); + * } else { + * console.log(`Pandoc ${result.pandoc.version} found`); + * } + * + * // Quick startup check + * const missing = DependencyChecker.checkDependenciesSync( + * settings.pandocPath, + * settings.typstPath + * ); + * if (missing.length > 0) { + * console.error('Missing dependencies:', missing); + * } + * ``` + */ export class DependencyChecker { @@ -23,7 +81,51 @@ export class DependencyChecker { /** - * Comprehensive dependency check (async) - returns detailed information + * Performs comprehensive dependency checking with version detection (async). + * + * This method checks all three required external tools (Pandoc, Typst, and + * ImageMagick) in parallel for maximum efficiency. It resolves executable + * paths, verifies availability, and extracts version information using regex + * patterns. + * + * The method supports custom executable paths from user settings and falls + * back to searching system PATH if paths are not specified. Additional search + * directories can be provided to help locate tools in non-standard locations. + * + * @param pandocPath - Optional custom path to Pandoc executable + * @param typstPath - Optional custom path to Typst executable + * @param imagemagickPath - Optional custom path to ImageMagick convert executable + * @param additionalPaths - Additional directories to search for executables + * @returns Detailed dependency check result including version information + * + * @example + * ```typescript + * // Check with default paths (searches system PATH) + * const result = await DependencyChecker.checkAllDependencies(); + * if (result.allAvailable) { + * console.log('All dependencies found!'); + * console.log(`Pandoc: ${result.pandoc.version}`); + * console.log(`Typst: ${result.typst.version}`); + * } + * + * // Check with custom paths and additional search directories + * const result = await DependencyChecker.checkAllDependencies( + * '/usr/local/bin/pandoc', + * '/opt/typst/bin/typst', + * '/usr/bin/convert', + * ['/opt/local/bin', '/usr/local/opt/bin'] + * ); + * + * // Handle missing dependencies + * if (!result.allAvailable) { + * console.error('Missing:', result.missingDependencies.join(', ')); + * result.missingDependencies.forEach(name => { + * const dep = name === 'Pandoc' ? result.pandoc : + * name === 'Typst' ? result.typst : result.imagemagick; + * console.error(`${name} not found at: ${dep.executablePath}`); + * }); + * } + * ``` */ public static async checkAllDependencies( pandocPath?: string, @@ -58,7 +160,52 @@ export class DependencyChecker { } /** - * Quick dependency check (synchronous) - returns list of missing dependencies + * Performs fast synchronous dependency checking without version detection. + * + * This is a simplified version of checkAllDependencies that only checks if + * executables can be run successfully (exit code 0), without extracting version + * information. It's designed for scenarios where async operations are not + * possible (e.g., plugin initialization) or when only availability matters. + * + * The method checks all three tools sequentially and returns a list of missing + * dependency names. Empty array indicates all dependencies are available. + * + * @param pandocPath - Optional custom path to Pandoc executable + * @param typstPath - Optional custom path to Typst executable + * @param imagemagickPath - Optional custom path to ImageMagick convert executable + * @param additionalPaths - Additional directories to search for executables + * @returns Array of missing dependency names (empty if all available) + * + * @example + * ```typescript + * // Quick startup check in plugin onload() + * const missing = DependencyChecker.checkDependenciesSync( + * this.settings.pandocPath, + * this.settings.typstPath, + * this.settings.imagemagickPath + * ); + * + * if (missing.length > 0) { + * new Notice(`Missing dependencies: ${missing.join(', ')}`); + * return; + * } + * + * // Check with additional search paths + * const missing = DependencyChecker.checkDependenciesSync( + * undefined, // Use default Pandoc + * undefined, // Use default Typst + * undefined, // Use default ImageMagick + * ['/opt/local/bin', '~/.local/bin'] + * ); + * + * // React based on specific missing tools + * if (missing.includes('Pandoc')) { + * console.error('Pandoc is required for Markdown conversion'); + * } + * if (missing.includes('Typst')) { + * console.error('Typst is required for PDF generation'); + * } + * ``` */ public static checkDependenciesSync( pandocPath?: string, @@ -87,7 +234,47 @@ export class DependencyChecker { } /** - * Show dependency status modal + * Displays dependency status in a user-facing notice with version information. + * + * This method performs a comprehensive dependency check and displays the results + * in an Obsidian notice modal. The notice includes: + * - Status of each dependency (version or "Not found") + * - Overall availability message + * - Installation instructions if dependencies are missing + * + * The notice is displayed for 12 seconds to give users time to read the detailed + * information. This method is typically called from the plugin's settings or via + * a command palette action. + * + * @param pandocPath - Optional custom path to Pandoc executable + * @param typstPath - Optional custom path to Typst executable + * @param imagemagickPath - Optional custom path to ImageMagick convert executable + * @param additionalPaths - Additional directories to search for executables + * @returns Promise that resolves when the status has been displayed + * + * @example + * ```typescript + * // Display status from settings panel + * await DependencyChecker.showDependencyStatus( + * this.plugin.settings.pandocPath, + * this.plugin.settings.typstPath, + * this.plugin.settings.imagemagickPath + * ); + * + * // Display status via command palette + * this.addCommand({ + * id: 'check-dependencies', + * name: 'Check Dependencies', + * callback: async () => { + * await DependencyChecker.showDependencyStatus( + * this.settings.pandocPath, + * this.settings.typstPath, + * this.settings.imagemagickPath, + * this.settings.additionalPaths + * ); + * } + * }); + * ``` */ public static async showDependencyStatus( pandocPath?: string, @@ -117,7 +304,49 @@ ${dependencyResult.allAvailable } /** - * Check dependencies silently on startup and show notice if missing + * Performs silent dependency checking on plugin startup with error notifications. + * + * This method is designed for plugin initialization and performs a fast synchronous + * check of all dependencies. It only displays a notice if dependencies are missing, + * keeping the user experience clean when everything is working correctly. + * + * If dependencies are missing, a notice is shown for 8 seconds directing the user + * to run the full "Check Dependencies" command for detailed information. If an + * error occurs during checking, it's handled gracefully via ExportErrorHandler. + * + * This method should be called early in the plugin lifecycle (typically in onload) + * to ensure users are aware of missing dependencies before attempting exports. + * + * @param pandocPath - Optional custom path to Pandoc executable + * @param typstPath - Optional custom path to Typst executable + * @param imagemagickPath - Optional custom path to ImageMagick convert executable + * @param additionalPaths - Additional directories to search for executables + * @returns Promise that resolves when the check is complete + * + * @example + * ```typescript + * // Call during plugin initialization + * export default class MyPlugin extends Plugin { + * async onload() { + * await this.loadSettings(); + * + * // Silent startup check - only shows notice if problems exist + * await DependencyChecker.checkDependenciesAsync( + * this.settings.pandocPath, + * this.settings.typstPath, + * this.settings.imagemagickPath, + * this.settings.additionalPaths + * ); + * + * // Continue with plugin initialization + * this.registerCommands(); + * } + * } + * + * // User will see a notice only if dependencies are missing: + * // "Typst PDF Export: Missing dependencies: Pandoc, Typst. + * // Run 'Check Dependencies' command for details." + * ``` */ public static async checkDependenciesAsync( pandocPath?: string, diff --git a/src/core/ExecutableChecker.ts b/src/core/ExecutableChecker.ts index 4e5a77b..fd88fa3 100644 --- a/src/core/ExecutableChecker.ts +++ b/src/core/ExecutableChecker.ts @@ -1,10 +1,24 @@ /** - * Executable checking utilities for Obsidian Typst PDF Export plugin - * Handles path resolution, version detection, and availability checking for external executables + * Executable checking utilities for Obsidian Typst PDF Export plugin. + * + * This module provides comprehensive utilities for checking external executable + * availability and versions. It handles: + * - Path resolution with support for system PATH and additional paths + * - Version detection using configurable regex patterns + * - Both async and sync operations for different use cases + * - Cross-platform path handling (Unix and Windows) */ import { DEPENDENCY_CONSTANTS } from './constants'; +/** + * Information about a checked dependency executable. + * + * @property name - Human-readable name of the dependency (e.g., "Pandoc") + * @property version - Detected version string, or null if unavailable + * @property isAvailable - Whether the executable was found and executed successfully + * @property executablePath - The resolved path to the executable + */ export interface DependencyInfo { name: string; version: string | null; @@ -13,12 +27,55 @@ export interface DependencyInfo { } /** - * Utilities for checking executable availability and versions + * Utilities for checking executable availability and versions. + * + * This class provides static methods for: + * - Resolving executable paths from user input or system PATH + * - Augmenting PATH with common system directories + * - Checking if executables are available + * - Detecting executable versions using regex patterns + * + * All methods support additional search paths to extend the default system PATH, + * ensuring executables can be found in non-standard locations. + * + * @example + * ```typescript + * // Resolve path to pandoc executable + * const pandocPath = await ExecutableChecker.resolveExecutablePath( + * settings.pandocPath, + * 'pandoc', + * settings.additionalPaths + * ); + * + * // Check if pandoc is available and get version + * const info = await ExecutableChecker.checkDependency( + * 'Pandoc', + * pandocPath, + * '--version', + * /pandoc (\d+\.\d+(?:\.\d+)?)/ + * ); + * + * if (info.isAvailable) { + * console.log(`Pandoc ${info.version} found at ${info.executablePath}`); + * } + * ``` */ export class ExecutableChecker { /** - * Build an augmented PATH that includes common system paths and additional paths + * Builds an augmented PATH string that includes common system paths and additional paths. + * + * This method combines the current process PATH with: + * 1. Home-relative paths (e.g., ~/.local/bin, ~/.cargo/bin) + * 2. Common absolute paths (e.g., /usr/local/bin, /opt/homebrew/bin) + * 3. User-provided additional paths + * + * The resulting PATH helps find executables in non-standard locations that + * might not be in the user's shell PATH when running from Obsidian. + * + * @param additionalPaths - Optional array of additional paths to include + * @returns The augmented PATH string with all paths separated by colons + * @private */ private static getAugmentedPath(additionalPaths: string[] = []): string { const homeDir = process.env.HOME || process.env.USERPROFILE || ''; @@ -35,7 +92,15 @@ export class ExecutableChecker { } /** - * Build an augmented environment with extended PATH + * Builds an augmented environment object with extended PATH. + * + * Creates a new environment object that inherits all current process environment + * variables but with an augmented PATH that includes common system directories + * and any additional paths specified. + * + * @param additionalPaths - Optional array of additional paths to include in PATH + * @returns Environment object suitable for child_process spawn/exec + * @private */ private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv { return { @@ -45,7 +110,22 @@ export class ExecutableChecker { } /** - * Try to find an executable using which command + * Attempts to find an executable's full path using the `which` command. + * + * This method spawns a `which` subprocess with an augmented PATH to locate + * the executable. It's more reliable than simple PATH searches as it uses + * the system's own executable resolution logic. + * + * @param executableName - Name of the executable to find (e.g., 'pandoc') + * @param additionalPaths - Optional additional paths to search + * @returns The full path to the executable, or null if not found + * @private + * + * @example + * ```typescript + * const pandocPath = await findExecutableWithWhich('pandoc', ['/opt/local/bin']); + * // Returns: '/usr/local/bin/pandoc' or null + * ``` */ private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise { const { spawn } = require('child_process'); @@ -91,7 +171,35 @@ export class ExecutableChecker { } /** - * Resolve executable path - async version + * Resolves an executable path from user input or system PATH (async version). + * + * Resolution logic: + * 1. If userPath contains a '/', treat it as an absolute/relative path and use as-is + * 2. If userPath is just a name or empty, search for the executable using `which` + * 3. If `which` fails, fall back to the executable name (relies on runtime PATH) + * + * This method is useful for allowing users to specify either full paths or just + * executable names in plugin settings. + * + * @param userPath - User-provided path or executable name (can be undefined/empty) + * @param defaultName - Default executable name to use if userPath is empty + * @param additionalPaths - Additional directories to search for the executable + * @returns Resolved path to use for spawning the executable + * + * @example + * ```typescript + * // User provided full path + * const path1 = await resolveExecutablePath('/usr/local/bin/pandoc', 'pandoc'); + * // Returns: '/usr/local/bin/pandoc' + * + * // User provided just name + * const path2 = await resolveExecutablePath('pandoc', 'pandoc'); + * // Returns: '/usr/bin/pandoc' (found via which) + * + * // User provided nothing + * const path3 = await resolveExecutablePath('', 'typst', ['/opt/bin']); + * // Returns: '/opt/bin/typst' (found via which with additional path) + * ``` */ public static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise { // If user provided a full path (contains /), use it as-is @@ -113,7 +221,18 @@ export class ExecutableChecker { } /** - * Resolve executable path - sync version + * Resolves an executable path from user input or system PATH (synchronous version). + * + * This is the synchronous counterpart to `resolveExecutablePath`. Use this when + * async operations are not possible (e.g., in constructors or sync initialization). + * The resolution logic is identical to the async version. + * + * @param userPath - User-provided path or executable name (can be undefined/empty) + * @param defaultName - Default executable name to use if userPath is empty + * @param additionalPaths - Additional directories to search for the executable + * @returns Resolved path to use for spawning the executable + * + * @see {@link resolveExecutablePath} for detailed resolution logic and examples */ public static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string { // If user provided a full path (contains /), use it as-is @@ -147,7 +266,37 @@ export class ExecutableChecker { } /** - * Check if a dependency is available and get its version - async version + * Checks if a dependency executable is available and extracts its version (async version). + * + * This method: + * 1. Spawns the executable with the version command (e.g., '--version') + * 2. Captures stdout and parses version using the provided regex + * 3. Returns comprehensive dependency information + * + * Security: Uses spawn instead of exec to prevent command injection. Arguments + * are passed separately from the command. + * + * @param name - Human-readable name for the dependency (e.g., "Pandoc") + * @param executablePath - Path to the executable to check + * @param versionCommand - Command argument for version (e.g., '--version') + * @param versionRegex - Regex with capture group for version number + * @returns DependencyInfo object with availability and version information + * + * @example + * ```typescript + * const info = await ExecutableChecker.checkDependency( + * 'Pandoc', + * '/usr/bin/pandoc', + * '--version', + * /pandoc (\d+\.\d+(?:\.\d+)?)/ + * ); + * + * if (info.isAvailable) { + * console.log(`Found ${info.name} version ${info.version}`); + * } else { + * console.error(`${info.name} not available at ${info.executablePath}`); + * } + * ``` */ public static async checkDependency( name: string, @@ -209,7 +358,23 @@ export class ExecutableChecker { } /** - * Quick sync check if a dependency is available + * Performs a quick synchronous check if a dependency is available. + * + * This is a simplified version of `checkDependency` that only checks if the + * executable can be run successfully (exit code 0), without parsing version + * information. Useful for fast availability checks during initialization. + * + * @param executablePath - Path to the executable to check + * @param versionCommand - Command argument to test (e.g., '--version') + * @returns True if the executable runs successfully, false otherwise + * + * @example + * ```typescript + * const pandocAvailable = ExecutableChecker.checkDependencySync('/usr/bin/pandoc', '--version'); + * if (!pandocAvailable) { + * console.error('Pandoc not available'); + * } + * ``` */ public static checkDependencySync(executablePath: string, versionCommand: string): boolean { const { spawnSync } = require('child_process'); diff --git a/src/core/ExportErrorHandler.ts b/src/core/ExportErrorHandler.ts index 7e2357c..9ab40eb 100644 --- a/src/core/ExportErrorHandler.ts +++ b/src/core/ExportErrorHandler.ts @@ -1,16 +1,43 @@ /** - * Centralized error handling utilities for export operations + * Centralized error handling utilities for export operations. + * + * This module provides a unified interface for handling all types of errors that + * can occur during PDF export operations. It standardizes error logging, user + * notifications, and error message formatting across the plugin. + * + * Key features: + * - Consistent error messaging and logging + * - Batch export result tracking and reporting + * - User-facing notices with appropriate durations + * - Support for different log levels (error, warn, info) + * - Specialized handlers for different error types (dependency, processing, validation) */ import { Notice } from 'obsidian'; import { EXPORT_CONSTANTS } from './constants'; +/** + * Result summary for batch export operations. + * + * @property successful - Number of files exported successfully + * @property failed - Number of files that failed to export + * @property errors - Array of error messages for failed exports + */ export interface BatchExportResult { successful: number; failed: number; errors: string[]; } +/** + * Structured error information for export operations. + * + * @property fileName - Optional file name where the error occurred + * @property operation - Description of the operation that failed (e.g., "Pandoc conversion") + * @property error - The error object or message + * @property shouldShowNotice - Whether to display a user-facing notice (default: false) + * @property logLevel - Logging severity level (default: 'error') + */ export interface ExportError { fileName?: string; operation: string; @@ -19,9 +46,73 @@ export interface ExportError { logLevel?: 'error' | 'warn' | 'info'; } +/** + * Centralized error handler for all export-related errors. + * + * This class provides static utility methods for handling various error scenarios + * in the PDF export pipeline. It ensures consistent error reporting to both users + * (via Obsidian notices) and developers (via console logs). + * + * The handler supports: + * - Single and batch export error tracking + * - Context-specific error messages (dependencies, validation, processing) + * - Configurable notice durations based on error severity + * - Graceful error recovery with fallback content + * + * @example + * ```typescript + * // Handle single export error + * try { + * await exportFile(file); + * } catch (error) { + * ExportErrorHandler.handleSingleExportError(error); + * } + * + * // Track batch export results + * const batch = ExportErrorHandler.createBatchTracker(); + * for (const file of files) { + * try { + * await exportFile(file); + * batch.recordSuccess(); + * } catch (error) { + * batch.recordError(file.name, error); + * } + * } + * ExportErrorHandler.handleBatchResult(batch.getResult(), 'Folder export'); + * + * // Handle processing error with fallback + * try { + * return await processImage(path); + * } catch (error) { + * const { fallback } = ExportErrorHandler.handleProcessingError( + * 'Image', + * path, + * error, + * '![Image unavailable]' + * ); + * return fallback; + * } + * ``` + */ export class ExportErrorHandler { /** - * Handle batch export results with consistent messaging + * Displays batch export results with user-friendly summary messages. + * + * This method analyzes batch export results and shows appropriate notices + * based on the outcome. For fully successful exports, shows a success message. + * For partial or complete failures, shows a summary with counts and logs + * detailed errors to the console. + * + * @param result - The batch export result containing success/failure counts and errors + * @param operationDescription - Description of the operation (e.g., 'Export', 'Folder export') + * + * @example + * ```typescript + * const batch = { successful: 8, failed: 2, errors: ['file1: error', 'file2: error'] }; + * ExportErrorHandler.handleBatchResult(batch, 'Folder export'); + * // Shows: "Folder export complete: 8 successful, 2 failed" + * // Logs detailed errors to console + * ``` */ public static handleBatchResult( result: BatchExportResult, @@ -44,7 +135,36 @@ export class ExportErrorHandler { } /** - * Handle individual export errors consistently + * Handles individual export errors with configurable logging and notifications. + * + * This method provides flexible error handling that supports different log levels + * and optional user notices. It normalizes error messages, logs them at the + * appropriate level, and optionally displays a notice to the user. + * + * @param exportError - Structured error information including operation context + * @returns Formatted error message string suitable for collection or display + * + * @example + * ```typescript + * // Handle with notice + * const message = ExportErrorHandler.handleExportError({ + * fileName: 'document.md', + * operation: 'Pandoc conversion', + * error: new Error('Invalid syntax'), + * shouldShowNotice: true, + * logLevel: 'error' + * }); + * // Shows notice: "Pandoc conversion failed: Invalid syntax" + * // Returns: "document.md: Invalid syntax" + * + * // Handle silently (just logging) + * const message = ExportErrorHandler.handleExportError({ + * operation: 'Image processing', + * error: 'File not found', + * logLevel: 'warn' + * }); + * // Logs warning but no notice + * ``` */ public static handleExportError(exportError: ExportError): string { const { fileName, operation, error, shouldShowNotice = false, logLevel = 'error' } = exportError; @@ -74,7 +194,44 @@ export class ExportErrorHandler { } /** - * Handle processing errors for embeds and similar operations + * Handles processing errors with fallback content generation. + * + * This method is designed for operations that can gracefully degrade when errors + * occur, such as embed processing or image handling. It logs the error and returns + * both an error message and fallback content to use in place of the failed operation. + * + * The fallback content ensures exports can continue even when individual embeds or + * resources fail to process, providing a visible indication of the failure in the + * output document. + * + * @param operation - Description of the operation (e.g., 'Image', 'PDF embed') + * @param itemPath - Path to the item being processed + * @param error - The error that occurred + * @param fallbackContent - Optional custom fallback content (auto-generated if not provided) + * @returns Object with error message and fallback content to use + * + * @example + * ```typescript + * try { + * return await processWikilink(link); + * } catch (error) { + * const { fallback } = ExportErrorHandler.handleProcessingError( + * 'Wikilink', + * '[[MyNote]]', + * error, + * '[Link unavailable]' + * ); + * return fallback; // Use fallback in output + * } + * + * // Without custom fallback + * const { fallback } = ExportErrorHandler.handleProcessingError( + * 'Image', + * 'path/to/image.png', + * new Error('Not found') + * ); + * // fallback: "[⚠️ **Image processing error:** path/to/image.png]" + * ``` */ public static handleProcessingError( operation: string, @@ -96,7 +253,39 @@ export class ExportErrorHandler { } /** - * Create a batch export tracker for consistent error collection + * Creates a batch export tracker for systematic result collection. + * + * This method returns an object with methods to track successes and failures + * during batch export operations. It maintains counters and collects error + * messages, providing a clean API for recording results as exports progress. + * + * The tracker automatically logs individual errors to the console and formats + * error messages with file names for later reporting. Use getResult() to obtain + * the final BatchExportResult for display with handleBatchResult(). + * + * @returns Object with tracker state and methods for recording results + * + * @example + * ```typescript + * const batch = ExportErrorHandler.createBatchTracker(); + * + * for (const file of filesToExport) { + * try { + * await exportFile(file); + * batch.recordSuccess(); + * } catch (error) { + * batch.recordError(file.name, error); + * } + * } + * + * // Display final results + * const result = batch.getResult(); + * ExportErrorHandler.handleBatchResult(result, 'Folder export'); + * // result: { successful: 8, failed: 2, errors: ['file1.md: Error message', ...] } + * + * // Direct access to tracker state + * console.log(`Progress: ${batch.tracker.successful} / ${filesToExport.length}`); + * ``` */ public static createBatchTracker(): { tracker: BatchExportResult; @@ -128,7 +317,22 @@ export class ExportErrorHandler { } /** - * Handle single file export errors with proper notices + * Handles single file export errors with console logging and user notice. + * + * This is a convenience method for simple export error scenarios where the + * error should always be logged and shown to the user. Use this for single + * file exports or when you don't need the complexity of structured error handling. + * + * @param error - The error that occurred during export + * + * @example + * ```typescript + * try { + * await exportCurrentNote(); + * } catch (error) { + * ExportErrorHandler.handleSingleExportError(error); + * } + * ``` */ public static handleSingleExportError(error: Error | string): void { const errorMessage = error instanceof Error ? error.message : String(error); @@ -137,7 +341,24 @@ export class ExportErrorHandler { } /** - * Handle dependency or configuration errors + * Handles dependency checking or configuration errors with optional notices. + * + * This method is specifically for errors that occur during dependency validation + * or configuration loading. It supports silent error handling (logging only) or + * user-visible notices with extended duration for readability. + * + * @param dependency - Name of the dependency or configuration item + * @param error - The error that occurred + * @param showNotice - Whether to display a user-facing notice (default: true) + * + * @example + * ```typescript + * try { + * await checkPandocVersion(); + * } catch (error) { + * ExportErrorHandler.handleDependencyError('Pandoc', error); + * } + * ``` */ public static handleDependencyError( dependency: string, @@ -146,7 +367,7 @@ export class ExportErrorHandler { ): void { const errorMessage = error instanceof Error ? error.message : String(error); console.error(`Error checking ${dependency}:`, error); - + if (showNotice) { new Notice( `${dependency} error: ${errorMessage}`, @@ -156,28 +377,67 @@ export class ExportErrorHandler { } /** - * Show export progress notice + * Displays a progress or informational notice with configurable duration. + * + * @param message - The message to display + * @param timeout - Optional duration in milliseconds (0 = persist until dismissed) + * @returns The Notice object for potential manual dismissal + * + * @example + * ```typescript + * const notice = ExportErrorHandler.showProgressNotice('Exporting...', 0); + * await performExport(); + * notice.hide(); // Dismiss when done + * ``` */ public static showProgressNotice(message: string, timeout?: number): Notice { return new Notice(message, timeout || 0); } /** - * Show export cancellation notice + * Displays a cancellation notice when user aborts an export operation. + * + * @example + * ```typescript + * if (userCancelled) { + * ExportErrorHandler.showCancellationNotice(); + * } + * ``` */ public static showCancellationNotice(): void { new Notice('Export cancelled'); } /** - * Show settings validation error + * Displays a validation error for invalid settings or input. + * + * @param field - Name of the field that failed validation + * @param validationMessage - Explanation of why validation failed + * + * @example + * ```typescript + * if (pageSize < 0) { + * ExportErrorHandler.showValidationError('page size', 'must be positive'); + * } + * ``` */ public static showValidationError(field: string, validationMessage: string): void { new Notice(`Invalid ${field}: ${validationMessage}`); } /** - * Show template loading error + * Displays an error when template loading fails. + * + * @param error - The error that occurred during template loading + * + * @example + * ```typescript + * try { + * await loadTemplate(name); + * } catch (error) { + * ExportErrorHandler.showTemplateError(error); + * } + * ``` */ public static showTemplateError(error: Error | string): void { const errorMessage = error instanceof Error ? error.message : String(error); @@ -185,40 +445,83 @@ export class ExportErrorHandler { } /** - * Show font caching error + * Displays an error when font caching fails, with fallback notification. + * + * @param error - The error that occurred during font caching + * @param showFallback - Whether to show additional fallback notice (default: true) + * + * @example + * ```typescript + * try { + * await cacheSystemFonts(); + * } catch (error) { + * ExportErrorHandler.showFontError(error); + * } + * ``` */ public static showFontError(error: Error | string, showFallback: boolean = true): void { const errorMessage = error instanceof Error ? error.message : String(error); new Notice(`Font caching failed: ${errorMessage}. Using fallback fonts.`, 5000); - + if (showFallback) { new Notice('Font list may be incomplete. Check debug mode for details.', 3000); } } /** - * Show export success notice + * Displays a success notice when export completes successfully. + * + * @param outputPath - Path where the PDF was saved + * + * @example + * ```typescript + * ExportErrorHandler.showExportSuccess('/path/to/output.pdf'); + * ``` */ public static showExportSuccess(outputPath: string): void { new Notice(`PDF exported successfully to ${outputPath}`); } /** - * Show file not found warning + * Displays a warning when no active file is available for export. + * + * @param context - Description of the expected file type (e.g., 'Markdown') + * + * @example + * ```typescript + * if (!activeFile) { + * ExportErrorHandler.showFileNotFoundWarning('Markdown'); + * } + * ``` */ public static showFileNotFoundWarning(context: string): void { new Notice(`Please open a ${context} file to export`); } /** - * Show no files warning + * Displays a warning when no files are available for batch export. + * + * @param context - Description of the file type (default: 'files') + * + * @example + * ```typescript + * if (files.length === 0) { + * ExportErrorHandler.showNoFilesWarning('Markdown files'); + * } + * ``` */ public static showNoFilesWarning(context: string = 'files'): void { new Notice(`No ${context} to export`); } /** - * Show settings reset confirmation + * Displays a confirmation notice when settings are reset to defaults. + * + * @example + * ```typescript + * resetToDefaults(); + * ExportErrorHandler.showSettingsReset(); + * ``` */ public static showSettingsReset(): void { new Notice('Settings reset to defaults'); diff --git a/src/core/ModalSettingsHelper.ts b/src/core/ModalSettingsHelper.ts index 1f7498f..5a9b8eb 100644 --- a/src/core/ModalSettingsHelper.ts +++ b/src/core/ModalSettingsHelper.ts @@ -1,11 +1,30 @@ /** - * Helper utilities for preparing export modal settings + * Helper utilities for preparing export modal settings. + * + * This module provides utilities for transforming plugin settings and file context + * into the format expected by the export configuration modal. It handles both single + * and multi-file export scenarios, extracting defaults from plugin settings and + * building template variable objects. + * + * Key features: + * - Automatic template variable extraction from plugin settings + * - Multi-file export support with automatic title generation + * - Landscape mode width adjustment for single-page exports + * - Clean separation between single and multi-file modal preparation */ import { TFile } from 'obsidian'; import { obsidianTypstPDFExportSettings } from './settings'; import { ExportConfigModalSettings } from '../ui/modal/modalTypes'; +/** + * Input parameters for modal settings preparation. + * + * @property file - Primary file for the export + * @property additionalFiles - Additional files for multi-file export (optional) + * @property availableTemplates - List of available template names + * @property settings - Plugin settings to extract defaults from + */ export interface ModalSettingsInput { /** Primary file for the export */ file: TFile; @@ -17,9 +36,75 @@ export interface ModalSettingsInput { settings: obsidianTypstPDFExportSettings; } +/** + * Utility class for preparing export modal configuration from plugin settings. + * + * This class transforms plugin settings into the format required by the export + * configuration modal. It extracts defaults for all export options and builds + * template variable objects that can be customized in the modal before export. + * + * The helper handles special cases like: + * - Multi-file export title formatting ("5 files" instead of filename) + * - Landscape orientation width adjustments for single-page exports + * - Template variable extraction from typography and page setup settings + * + * @example + * ```typescript + * // Single file export + * const modalSettings = ModalSettingsHelper.prepareForSingleFile( + * file, + * ['default', 'modern', 'article'], + * this.plugin.settings + * ); + * const modal = new ExportConfigModal(this.app, modalSettings, async (config) => { + * await this.exportWithConfig(config); + * }); + * + * // Multi-file export + * const modalSettings = ModalSettingsHelper.prepareForMultiFile( + * selectedFiles, + * ['default', 'modern'], + * this.plugin.settings + * ); + * // Modal title will show "5 files" if 5 files selected + * ``` + */ export class ModalSettingsHelper { /** - * Prepare modal settings from plugin defaults and file context + * Prepares modal settings from plugin defaults and file context. + * + * This is the core method that transforms plugin settings and file information + * into the format expected by ExportConfigModal. It automatically detects multi-file + * scenarios, builds template variables from plugin settings, and extracts export + * defaults. + * + * For multi-file exports, the modal title is set to "{count} files" instead of + * the primary file name. Template variables include automatic width adjustment + * for landscape single-page exports. + * + * @param input - Configuration object containing file(s), templates, and settings + * @returns Partial modal settings ready for ExportConfigModal initialization + * + * @example + * ```typescript + * // Single file + * const settings = ModalSettingsHelper.prepareModalSettings({ + * file: activeFile, + * availableTemplates: ['default', 'modern'], + * settings: this.settings + * }); + * // settings.noteTitle = "My Note" + * + * // Multiple files + * const settings = ModalSettingsHelper.prepareModalSettings({ + * file: files[0], + * additionalFiles: files.slice(1), + * availableTemplates: ['default'], + * settings: this.settings + * }); + * // settings.noteTitle = "5 files" + * // settings.files = [file1, file2, file3, file4, file5] + * ``` */ public static prepareModalSettings(input: ModalSettingsInput): Partial { const { file, additionalFiles, availableTemplates, settings } = input; @@ -50,7 +135,33 @@ export class ModalSettingsHelper { } /** - * Build template variables object from plugin settings + * Builds template variables object from plugin settings. + * + * This method extracts typography and page setup settings and formats them + * as template variables suitable for Typst compilation. It handles special cases + * like automatic width adjustment for landscape single-page exports. + * + * Variables include: + * - Page setup: pageSize, orientation, flipped, margins (top/bottom/left/right) + * - Typography: bodyFont, headingFont, monospaceFont, bodyFontSize + * - Format-specific: width='auto' for landscape single-page mode + * + * @param settings - Plugin settings containing typography and page setup configuration + * @returns Object with template variables ready for Pandoc/Typst + * @private + * + * @example + * ```typescript + * const vars = ModalSettingsHelper.buildTemplateVariables(settings); + * // { + * // pageSize: 'a4', + * // orientation: 'landscape', + * // flipped: true, // auto-set for landscape + * // marginTop: '71', + * // bodyFont: 'Georgia', + * // width: 'auto' // for landscape single-page + * // } + * ``` */ private static buildTemplateVariables(settings: obsidianTypstPDFExportSettings): Record { const baseVariables = { @@ -80,11 +191,35 @@ export class ModalSettingsHelper { } /** - * Helper for single file export modal settings + * Convenience method for preparing modal settings for single file export. + * + * This is a simplified wrapper around prepareModalSettings for the common case + * of exporting a single file. It automatically sets up the modal with the file's + * basename as the title and extracts all defaults from plugin settings. + * + * @param file - The file to export + * @param availableTemplates - List of available template names + * @param settings - Plugin settings for default extraction + * @returns Partial modal settings for single file export + * + * @example + * ```typescript + * const activeFile = this.app.workspace.getActiveFile(); + * if (activeFile) { + * const modalSettings = ModalSettingsHelper.prepareForSingleFile( + * activeFile, + * this.templateManager.getAvailableTemplates(), + * this.settings + * ); + * new ExportConfigModal(this.app, modalSettings, async (config) => { + * await this.exportFile(activeFile, config); + * }).open(); + * } + * ``` */ public static prepareForSingleFile( - file: TFile, - availableTemplates: string[], + file: TFile, + availableTemplates: string[], settings: obsidianTypstPDFExportSettings ): Partial { return this.prepareModalSettings({ @@ -95,11 +230,42 @@ export class ModalSettingsHelper { } /** - * Helper for multi-file export modal settings + * Convenience method for preparing modal settings for multi-file export. + * + * This method handles batch export scenarios where multiple files should be + * exported together. It automatically splits the files array into primary and + * additional files, and sets the modal title to show the file count. + * + * The first file in the array becomes the primary file (used for initial path + * resolution), and the remaining files are treated as additional files for the + * batch export. + * + * @param files - Array of files to export (must contain at least one file) + * @param availableTemplates - List of available template names + * @param settings - Plugin settings for default extraction + * @returns Partial modal settings for multi-file export with "{count} files" title + * + * @example + * ```typescript + * // Export all files in a folder + * const folder = this.app.vault.getAbstractFileByPath('my-folder'); + * if (folder instanceof TFolder) { + * const files = folder.children.filter(f => f instanceof TFile) as TFile[]; + * const modalSettings = ModalSettingsHelper.prepareForMultiFile( + * files, + * this.templateManager.getAvailableTemplates(), + * this.settings + * ); + * // modalSettings.noteTitle = "15 files" (if 15 files) + * new ExportConfigModal(this.app, modalSettings, async (config) => { + * await this.exportFiles(files, config); + * }).open(); + * } + * ``` */ public static prepareForMultiFile( - files: TFile[], - availableTemplates: string[], + files: TFile[], + availableTemplates: string[], settings: obsidianTypstPDFExportSettings ): Partial { const [primaryFile, ...additionalFiles] = files; diff --git a/src/core/PathUtils.ts b/src/core/PathUtils.ts index 254f8cc..aea6a28 100644 --- a/src/core/PathUtils.ts +++ b/src/core/PathUtils.ts @@ -5,11 +5,50 @@ import { FileSystemAdapter, normalizePath, Notice } from 'obsidian'; import type { App, PluginManifest } from 'obsidian'; import * as path from 'path'; +/** + * Centralized path utilities for safe Obsidian API operations. + * + * This class provides a unified interface for path operations that work correctly + * with both vault-relative and absolute filesystem paths. It handles cross-platform + * path normalization and provides safe wrappers around Obsidian's vault adapter. + * + * Key features: + * - Automatic path normalization for cross-platform compatibility + * - Safe handling of absolute and relative paths + * - FileSystemAdapter validation for desktop-only operations + * - Error handling with user notifications + * + * @example + * ```typescript + * const pathUtils = new PathUtils(app); + * const vaultPath = pathUtils.getVaultPath(); + * const pluginDir = pathUtils.getPluginDir(manifest); + * const fullPath = pathUtils.joinPath(vaultPath, pluginDir, 'templates'); + * ``` + */ export class PathUtils { + /** + * Creates a new PathUtils instance. + * + * @param app - The Obsidian App instance used for vault operations + */ constructor(private app: App) {} /** - * Get vault base path safely with FileSystemAdapter check + * Gets the absolute filesystem path to the vault root directory. + * + * This method requires desktop Obsidian as it relies on FileSystemAdapter. + * If the adapter is not available (e.g., mobile), it will show a notice + * and throw an error. + * + * @returns The absolute path to the vault root directory + * @throws {Error} If FileSystemAdapter is not available (non-desktop environment) + * + * @example + * ```typescript + * const vaultPath = pathUtils.getVaultPath(); + * // Returns: '/Users/username/Documents/MyVault' + * ``` */ getVaultPath(): string { const adapter = this.app.vault.adapter; @@ -21,15 +60,44 @@ export class PathUtils { } /** - * Get plugin directory path + * Gets the vault-relative path to the plugin directory. + * + * Extracts the directory path from the plugin manifest and normalizes it + * for cross-platform compatibility. This is typically something like + * '.obsidian/plugins/plugin-name'. + * + * @param pluginManifest - The plugin's manifest containing directory information + * @returns The normalized vault-relative path to the plugin directory + * + * @example + * ```typescript + * const pluginDir = pathUtils.getPluginDir(this.manifest); + * // Returns: '.obsidian/plugins/typst-pdf-export' + * ``` */ getPluginDir(pluginManifest: PluginManifest): string { return normalizePath(pluginManifest.dir || ''); } /** - * Join path segments with normalizePath - * Handles absolute paths correctly by using the last absolute path found + * Joins multiple path segments into a single normalized path. + * + * This method filters out empty segments, joins them using Node's path.join, + * and normalizes the result for Obsidian compatibility. It correctly handles + * absolute paths by using Node's standard path joining behavior (which uses + * the rightmost absolute path if multiple absolute paths are provided). + * + * @param segments - Variable number of path segments to join + * @returns The joined and normalized path, or empty string if no segments + * + * @example + * ```typescript + * const fullPath = pathUtils.joinPath(vaultPath, '.obsidian', 'plugins', 'my-plugin'); + * // Returns: '/path/to/vault/.obsidian/plugins/my-plugin' + * + * const withEmpty = pathUtils.joinPath('folder', '', 'subfolder'); + * // Returns: 'folder/subfolder' (empty segments filtered) + * ``` */ joinPath(...segments: string[]): string { const filtered = segments.filter(s => s); @@ -41,7 +109,20 @@ export class PathUtils { } /** - * Ensure directory exists, create if necessary + * Ensures a directory exists, creating it if necessary. + * + * This method checks if the directory exists and creates it if it doesn't. + * The path is automatically normalized before operations. If creation fails, + * a notice is shown to the user and the error is re-thrown. + * + * @param path - The path to the directory (vault-relative or absolute) + * @throws {Error} If directory creation fails + * + * @example + * ```typescript + * await pathUtils.ensureDir('.obsidian/plugins/my-plugin/temp'); + * // Creates directory if it doesn't exist + * ``` */ async ensureDir(path: string): Promise { const normalizedPath = normalizePath(path); @@ -57,7 +138,23 @@ export class PathUtils { } /** - * Clean up directory contents (files only, like current TempDirectoryManager) + * Cleans up directory contents by removing all files (but not subdirectories). + * + * This method removes only the files directly within the directory, leaving + * any subdirectories intact. This matches the behavior of TempDirectoryManager + * for safe cleanup operations. If the directory doesn't exist or cleanup fails, + * the method returns false and logs a warning. + * + * @param path - The path to the directory to clean (vault-relative or absolute) + * @returns True if cleanup succeeded or directory doesn't exist, false on error + * + * @example + * ```typescript + * const success = await pathUtils.cleanupDir('temp-images'); + * if (success) { + * console.log('Temp directory cleaned'); + * } + * ``` */ async cleanupDir(path: string): Promise { const normalizedPath = normalizePath(path); @@ -78,8 +175,33 @@ export class PathUtils { } /** - * Check if file or directory exists - * Handles both vault-relative paths and absolute filesystem paths + * Checks if a file or directory exists at the given path. + * + * This method intelligently handles multiple path formats: + * 1. First attempts as vault-relative path + * 2. If that fails and path is within vault, converts absolute to relative + * 3. For paths outside vault, uses Node's fs module directly + * + * Supports: + * - Vault-relative paths: 'folder/file.md' + * - Absolute Unix paths: '/home/user/vault/file.md' + * - Windows drive letters: 'C:\\Users\\vault\\file.md' + * - Windows UNC paths: '\\\\server\\share\\file.md' + * + * @param path - The path to check (vault-relative or absolute) + * @returns True if the file or directory exists, false otherwise + * + * @example + * ```typescript + * // Check vault-relative path + * const exists = await pathUtils.fileExists('templates/default.typ'); + * + * // Check absolute path + * const exists = await pathUtils.fileExists('/usr/bin/pandoc'); + * + * // Check Windows path + * const exists = await pathUtils.fileExists('C:\\Program Files\\Pandoc\\pandoc.exe'); + * ``` */ async fileExists(path: string): Promise { try { diff --git a/src/core/SecurityUtils.ts b/src/core/SecurityUtils.ts index dfcfa18..848f2f4 100644 --- a/src/core/SecurityUtils.ts +++ b/src/core/SecurityUtils.ts @@ -1,14 +1,113 @@ /** - * Security utilities for path validation and sanitization + * Security utilities for path validation and command injection prevention. + * + * This module provides critical security validation for user-provided paths and + * executable configurations to prevent common security vulnerabilities including: + * - Directory traversal attacks (../ path manipulation) + * - Command injection via shell metacharacters + * - Null byte injection attacks + * - Windows reserved name exploitation + * - Path manipulation via special characters + * + * All validation methods in this module are designed to fail safely - when in doubt, + * they reject the input rather than risk a security vulnerability. This defensive + * approach ensures the plugin cannot be exploited to access files outside the vault + * or execute arbitrary commands. + * + * Key features: + * - Output path validation for PDF export destinations + * - Executable path validation for Pandoc/Typst/ImageMagick + * - Human-readable error messages for user feedback + * - Cross-platform security checks (Windows and Unix) + * - Zero-tolerance for suspicious patterns + * + * Security principles: + * - Whitelist approach where possible (allow known-safe patterns) + * - Multiple validation layers for defense in depth + * - Clear error messages without exposing implementation details + * - No automatic sanitization (reject rather than attempt to fix) */ import * as path from 'path'; +/** + * Security validation utilities for safe path and executable handling. + * + * This class provides static methods for validating user-provided paths and + * executable configurations before they are used in file operations or shell + * commands. All methods are designed with a security-first mindset: + * - Fail closed (reject when uncertain) + * - Multiple validation layers + * - No implicit trust of user input + * - Clear security error messages + * + * Use these methods to validate all user-configurable paths before: + * - Writing exported PDF files + * - Creating temporary directories + * - Executing external tools (Pandoc, Typst, ImageMagick) + * - Resolving output file paths + * + * @example + * ```typescript + * // Validate user-provided output folder + * const userFolder = settings.outputFolder; + * if (!SecurityUtils.validateOutputPath(userFolder)) { + * const error = SecurityUtils.getPathValidationError(userFolder); + * throw new Error(`Invalid output path: ${error}`); + * } + * + * // Safe to use the folder + * await exportToPDF(file, userFolder); + * ``` + * + * @example + * ```typescript + * // Validate executable path before spawning process + * const pandocPath = settings.pandocPath; + * if (!SecurityUtils.validateExecutablePath(pandocPath)) { + * const error = SecurityUtils.getExecutablePathValidationError(pandocPath); + * new Notice(`Invalid Pandoc path: ${error}`); + * return; + * } + * + * // Safe to spawn process with this path + * spawn(pandocPath, args); + * ``` + */ export class SecurityUtils { /** - * Validates that an output folder path is safe and doesn't contain traversal attempts - * @param outputFolder The folder path to validate - * @returns true if the path is safe, false otherwise + * Validates that an output folder path is safe for file operations. + * + * This method performs comprehensive security checks to prevent directory + * traversal attacks and path manipulation. It rejects: + * - Directory traversal attempts (..) + * - Absolute paths (must be relative to vault root) + * - Null bytes and control characters + * - Double slashes and other suspicious patterns + * - Invalid filename characters (<>:"|?*) + * - Windows reserved system names (CON, PRN, AUX, etc.) + * + * The validation is intentionally strict - when in doubt, reject the path + * rather than risk a security vulnerability. Use getPathValidationError() + * to provide specific feedback to the user about why their path was rejected. + * + * @param outputFolder - The relative folder path to validate + * @returns True if the path is safe for file operations, false otherwise + * + * @example + * ```typescript + * // Valid relative paths + * SecurityUtils.validateOutputPath('exports'); // true + * SecurityUtils.validateOutputPath('exports/pdfs'); // true + * SecurityUtils.validateOutputPath('my documents'); // true + * + * // Invalid paths (security risks) + * SecurityUtils.validateOutputPath('../../../etc'); // false - traversal + * SecurityUtils.validateOutputPath('/tmp/evil'); // false - absolute + * SecurityUtils.validateOutputPath('CON'); // false - reserved name + * SecurityUtils.validateOutputPath('test<>file'); // false - invalid chars + * SecurityUtils.validateOutputPath('path//with//double'); // false - suspicious + * ``` */ static validateOutputPath(outputFolder: string): boolean { if (!outputFolder || typeof outputFolder !== 'string') { @@ -38,9 +137,57 @@ export class SecurityUtils { } /** - * Validates that an executable path is safe for use in shell commands - * @param executablePath The executable path to validate - * @returns true if the path is safe, false otherwise + * Validates that an executable path is safe for use in shell commands. + * + * This method prevents command injection attacks by detecting shell + * metacharacters and command substitution patterns that could be used to + * execute arbitrary commands. It rejects paths containing: + * - Shell metacharacters (;&|`$(){}[]<>) + * - Null bytes and control characters + * - Newlines and carriage returns + * - Command separators (with or without whitespace) + * - Variable substitution patterns (${var}, $var) + * - Command substitution patterns (`cmd`, $(cmd)) + * + * Empty or whitespace-only paths are allowed (plugin will use system PATH). + * This enables users to simply specify executable names like 'pandoc' rather + * than full paths, relying on shell resolution. + * + * Use getExecutablePathValidationError() to provide specific feedback about + * why an executable path was rejected. + * + * @param executablePath - The executable path or name to validate + * @returns True if the path is safe for shell execution, false otherwise + * + * @example + * ```typescript + * // Valid executable paths + * SecurityUtils.validateExecutablePath(''); // true - use PATH + * SecurityUtils.validateExecutablePath('pandoc'); // true - simple name + * SecurityUtils.validateExecutablePath('/usr/bin/pandoc'); // true - full path + * SecurityUtils.validateExecutablePath('/opt/typst'); // true - full path + * SecurityUtils.validateExecutablePath('C:\\Program Files\\Pandoc\\pandoc.exe'); // true + * + * // Invalid paths (command injection risks) + * SecurityUtils.validateExecutablePath('pandoc; rm -rf /'); // false - separator + * SecurityUtils.validateExecutablePath('$(evil)'); // false - substitution + * SecurityUtils.validateExecutablePath('`malicious`'); // false - substitution + * SecurityUtils.validateExecutablePath('pandoc|cat /etc/passwd'); // false - pipe + * SecurityUtils.validateExecutablePath('${HOME}/bin/fake'); // false - variable + * ``` + * + * @example + * ```typescript + * // Use with spawn to prevent injection + * const userPath = settings.pandocPath; + * if (SecurityUtils.validateExecutablePath(userPath)) { + * // Safe to use with spawn (arguments passed separately) + * const process = spawn(userPath || 'pandoc', ['--version']); + * } else { + * const error = SecurityUtils.getExecutablePathValidationError(userPath); + * throw new Error(`Security violation: ${error}`); + * } + * ``` */ static validateExecutablePath(executablePath: string): boolean { // Allow empty paths (will use system PATH) @@ -66,9 +213,48 @@ export class SecurityUtils { } /** - * Gets a human-readable error message for invalid paths - * @param outputFolder The invalid path - * @returns Description of why the path is invalid + * Generates a human-readable error message explaining why a path is invalid. + * + * This method provides specific, actionable feedback to users when their + * output folder path fails validation. It identifies the exact security issue + * detected and explains it in user-friendly terms without exposing technical + * implementation details. + * + * The method checks for issues in priority order, returning the most critical + * security violation first. Use this alongside validateOutputPath() to provide + * clear feedback in error messages and UI validation. + * + * @param outputFolder - The path that failed validation + * @returns Descriptive error message explaining why the path is invalid + * + * @example + * ```typescript + * // Provide clear validation feedback in settings + * const userPath = folderInput.value; + * if (!SecurityUtils.validateOutputPath(userPath)) { + * const error = SecurityUtils.getPathValidationError(userPath); + * new Notice(`Invalid output folder: ${error}`); + * return; + * } + * // Continue with valid path... + * ``` + * + * @example + * ```typescript + * // Display specific error for different violations + * const testPaths = [ + * '../../../etc', // "Path traversal attempts (..) are not allowed" + * '/absolute/path', // "Absolute paths are not allowed..." + * 'CON', // "Reserved system names are not allowed..." + * 'invalid<>chars' // "Invalid characters found in path" + * ]; + * + * testPaths.forEach(path => { + * if (!SecurityUtils.validateOutputPath(path)) { + * console.error(`${path}: ${SecurityUtils.getPathValidationError(path)}`); + * } + * }); + * ``` */ static getPathValidationError(outputFolder: string): string { if (!outputFolder || typeof outputFolder !== 'string') { @@ -100,9 +286,52 @@ export class SecurityUtils { } /** - * Gets a human-readable error message for invalid executable paths - * @param executablePath The invalid executable path - * @returns Description of why the path is invalid + * Generates a human-readable error message for invalid executable paths. + * + * This method provides specific, security-focused feedback when an executable + * path fails validation. It identifies command injection attempts and explains + * them in terms users can understand without revealing exploit techniques. + * + * The error messages are designed to be clear about the security risk while + * remaining user-friendly. Use this alongside validateExecutablePath() to + * provide actionable feedback when users configure external tool paths. + * + * @param executablePath - The executable path that failed validation + * @returns Descriptive error message explaining the security issue + * + * @example + * ```typescript + * // Validate Pandoc path in settings with clear feedback + * const pandocPath = pandocInput.value; + * if (!SecurityUtils.validateExecutablePath(pandocPath)) { + * const error = SecurityUtils.getExecutablePathValidationError(pandocPath); + * new Notice(`Invalid Pandoc path: ${error}`, 8000); + * pandocInput.addClass('error'); + * return; + * } + * pandocInput.removeClass('error'); + * ``` + * + * @example + * ```typescript + * // Log security violations for monitoring + * function validateAndLogExecutable(name: string, path: string): boolean { + * if (!SecurityUtils.validateExecutablePath(path)) { + * const error = SecurityUtils.getExecutablePathValidationError(path); + * console.error(`Security: Rejected ${name} path: ${error}`); + * console.error(`Attempted path: ${path.substring(0, 50)}...`); + * return false; + * } + * return true; + * } + * + * // Validate all external tools + * const valid = [ + * validateAndLogExecutable('Pandoc', settings.pandocPath), + * validateAndLogExecutable('Typst', settings.typstPath), + * validateAndLogExecutable('ImageMagick', settings.imagemagickPath) + * ].every(v => v); + * ``` */ static getExecutablePathValidationError(executablePath: string): string { if (!executablePath || typeof executablePath !== 'string') { diff --git a/src/core/TempDirectoryManager.ts b/src/core/TempDirectoryManager.ts index 0279e6e..aacc57e 100644 --- a/src/core/TempDirectoryManager.ts +++ b/src/core/TempDirectoryManager.ts @@ -1,11 +1,38 @@ -// ABOUTME: Manages temporary directories for export operations -// ABOUTME: Uses normalizePath for cross-platform path operations +/** + * Temporary directory management for Obsidian Typst PDF Export plugin. + * + * This module provides centralized management of temporary directories used during + * the PDF export process. It handles creation, cleanup, and validation of temporary + * storage locations for intermediate files such as: + * - Converted images from embedded PDFs + * - Intermediate Pandoc processing files + * - Temporary Typst compilation artifacts + * + * Key features: + * - Cross-platform path handling using Obsidian's normalizePath + * - Automatic directory creation on first use + * - Safe cleanup that preserves directory structure + * - Plugin-scoped temporary directories within .obsidian folder + * - Validation utilities for path security + * + * The manager creates temporary directories at: + * `/.obsidian/plugins/typst-pdf-export/temp-images/` + * `/.obsidian/plugins/typst-pdf-export/temp-pandoc/` + */ import { PLUGIN_DIRS } from './constants'; import { normalizePath } from 'obsidian'; import type { App } from 'obsidian'; import * as path from 'path'; +/** + * Configuration options for TempDirectoryManager initialization. + * + * @property vaultPath - Absolute path to the vault root directory + * @property configDir - Configuration directory path (typically '.obsidian') + * @property pluginName - Optional custom plugin directory name (defaults to 'typst-pdf-export') + * @property app - Obsidian App instance for vault.adapter file operations + */ export interface TempDirectoryOptions { /** Base path for the vault */ vaultPath: string; @@ -17,12 +44,101 @@ export interface TempDirectoryOptions { app: App; } +/** + * Manager for plugin temporary directories used during PDF export operations. + * + * This class provides a centralized interface for managing temporary file storage + * during the Markdown → Typst → PDF conversion pipeline. It handles the full + * lifecycle of temporary directories: + * - Automatic directory creation on first use + * - Type-specific directory paths (images vs. pandoc processing) + * - Safe cleanup that removes files but preserves directory structure + * - Cross-platform path handling with proper normalization + * - Security validation to prevent directory traversal attacks + * + * The manager uses Obsidian's vault.adapter API for all file operations, ensuring + * compatibility with desktop-only features and proper permission handling. + * + * Temporary Directory Structure: + * ``` + * /.obsidian/plugins/typst-pdf-export/ + * ├── temp-images/ # Converted images from embedded PDFs + * └── temp-pandoc/ # Intermediate Pandoc/Typst processing files + * ``` + * + * Lifecycle: + * 1. Initialize manager with vault path and app instance + * 2. Call ensureTempDir() to create directories as needed + * 3. Use getTempDir() to resolve paths for file operations + * 4. Call cleanupTempDir() to remove temporary files (preserves directories) + * 5. Use isPluginTempDir() to validate paths before operations + * + * @example + * ```typescript + * // Initialize for a specific vault + * const manager = new TempDirectoryManager({ + * vaultPath: '/Users/name/vault', + * configDir: '.obsidian', + * app: this.app + * }); + * + * // Ensure temp directories exist before export + * const imagesDir = await manager.ensureTempDir('images'); + * const pandocDir = await manager.ensureTempDir('pandoc'); + * + * // Use directories for file operations + * await this.app.vault.adapter.write( + * `${imagesDir}/converted-pdf-page-1.png`, + * imageData + * ); + * + * // Clean up after export + * await manager.cleanupAllTempDirs(); + * ``` + * + * @example + * ```typescript + * // Factory method for quick initialization + * const manager = TempDirectoryManager.create( + * vaultPath, + * '.obsidian', + * 'typst-pdf-export', + * app + * ); + * + * // Validate paths before operations + * const userPath = '/some/user/provided/path'; + * if (manager.isPluginTempDir(userPath)) { + * // Safe to operate on this path + * await manager.cleanupTempDir('images'); + * } + * ``` + */ export class TempDirectoryManager { private readonly vaultPath: string; private readonly configDir: string; private readonly pluginName: string; private readonly app: App; + /** + * Creates a new TempDirectoryManager instance. + * + * Initializes the manager with vault configuration and Obsidian app instance. + * The manager will create temporary directories within the plugin folder using + * the provided paths. + * + * @param options - Configuration options for the temp directory manager + * + * @example + * ```typescript + * const manager = new TempDirectoryManager({ + * vaultPath: this.app.vault.adapter.getBasePath(), + * configDir: this.app.vault.configDir, + * pluginName: 'typst-pdf-export', + * app: this.app + * }); + * ``` + */ constructor(options: TempDirectoryOptions) { this.vaultPath = options.vaultPath; this.configDir = options.configDir; @@ -31,8 +147,22 @@ export class TempDirectoryManager { } /** - * Get the plugin directory path - * Handles absolute paths correctly on Windows + * Resolves the absolute path to the plugin directory. + * + * Constructs the full path to the plugin's directory within the vault's + * .obsidian/plugins folder. Uses Node.js path.join for proper cross-platform + * path handling (Windows drive letters, Unix-style paths) and Obsidian's + * normalizePath to ensure consistent forward slashes. + * + * @returns Normalized absolute path to plugin directory + * @private + * + * @example + * ```typescript + * // On Unix: '/Users/name/vault/.obsidian/plugins/typst-pdf-export' + * // On Windows: 'C:/Users/name/vault/.obsidian/plugins/typst-pdf-export' + * const pluginDir = this.getPluginDir(); + * ``` */ private getPluginDir(): string { // path.join automatically handles absolute paths correctly @@ -41,8 +171,34 @@ export class TempDirectoryManager { } /** - * Get the path for a specific temp directory - * Handles absolute paths correctly on Windows + * Resolves the path for a specific temporary directory type. + * + * Returns the absolute path to either the images or pandoc temporary directory + * without creating it. Use ensureTempDir() to also create the directory if it + * doesn't exist. + * + * Directory types: + * - 'images': For converted images from embedded PDF files + * - 'pandoc': For intermediate Pandoc/Typst processing files + * + * Paths use Obsidian's normalizePath to ensure consistent forward slashes + * across all platforms. + * + * @param type - Type of temporary directory ('images' or 'pandoc') + * @returns Normalized absolute path to the temporary directory + * + * @example + * ```typescript + * const imagesPath = manager.getTempDir('images'); + * // Returns: '/.obsidian/plugins/typst-pdf-export/temp-images' + * + * const pandocPath = manager.getTempDir('pandoc'); + * // Returns: '/.obsidian/plugins/typst-pdf-export/temp-pandoc' + * + * // Use with vault adapter for file operations + * const outputPath = `${imagesPath}/converted-page-1.png`; + * await this.app.vault.adapter.write(outputPath, imageData); + * ``` */ public getTempDir(type: 'images' | 'pandoc'): string { const dirName = type === 'images' ? PLUGIN_DIRS.TEMP_IMAGES : PLUGIN_DIRS.TEMP_PANDOC; @@ -55,7 +211,44 @@ export class TempDirectoryManager { } /** - * Ensure a temp directory exists, creating it if necessary + * Ensures a temporary directory exists, creating it if necessary. + * + * This method checks if the specified temporary directory exists and creates + * it if missing. It uses Obsidian's vault.adapter API for directory creation, + * ensuring proper permissions and cross-platform compatibility. + * + * This is the recommended method to use before writing temporary files, as it + * handles both path resolution and directory creation in a single call. + * + * @param type - Type of temporary directory ('images' or 'pandoc') + * @returns Promise resolving to the normalized absolute path of the directory + * + * @example + * ```typescript + * // Ensure images directory exists before conversion + * const imagesDir = await manager.ensureTempDir('images'); + * console.log('Images directory ready:', imagesDir); + * // Output: Images directory ready: /vault/.obsidian/plugins/typst-pdf-export/temp-images + * + * // Write converted image file + * await this.app.vault.adapter.write( + * `${imagesDir}/pdf-page-1.png`, + * imageBuffer + * ); + * ``` + * + * @example + * ```typescript + * // Ensure both directories exist before export + * const [imagesDir, pandocDir] = await Promise.all([ + * manager.ensureTempDir('images'), + * manager.ensureTempDir('pandoc') + * ]); + * + * // Use directories for export pipeline + * await convertPdfToImages(pdfPath, imagesDir); + * await runPandocConversion(inputPath, pandocDir); + * ``` */ public async ensureTempDir(type: 'images' | 'pandoc'): Promise { const tempDir = this.getTempDir(type); @@ -69,7 +262,42 @@ export class TempDirectoryManager { } /** - * Clean up a specific temp directory + * Cleans up temporary files from a specific directory. + * + * This method removes all files from the specified temporary directory while + * preserving the directory structure itself. It only removes files, not + * subdirectories, ensuring that the temporary directory remains ready for + * future use. + * + * Cleanup failures are logged to the console but don't throw errors, allowing + * the export process to continue even if cleanup encounters issues. This is + * important for user experience - a failed cleanup shouldn't prevent export + * completion. + * + * @param type - Type of temporary directory to clean ('images' or 'pandoc') + * @returns Promise resolving to true if cleanup succeeded, false if it failed + * + * @example + * ```typescript + * // Clean up after successful export + * const success = await manager.cleanupTempDir('images'); + * if (success) { + * console.log('Temporary images cleaned up'); + * } else { + * console.warn('Cleanup failed, but export completed'); + * } + * ``` + * + * @example + * ```typescript + * // Clean up in finally block to ensure cleanup even on errors + * try { + * await exportToPDF(file); + * } finally { + * await manager.cleanupTempDir('pandoc'); + * await manager.cleanupTempDir('images'); + * } + * ``` */ public async cleanupTempDir(type: 'images' | 'pandoc'): Promise { const tempDir = this.getTempDir(type); @@ -91,7 +319,34 @@ export class TempDirectoryManager { } /** - * Clean up all temp directories + * Cleans up all temporary directories in a single operation. + * + * This convenience method calls cleanupTempDir() for both the images and + * pandoc directories, running the cleanups in parallel for efficiency. It + * returns the success status for each directory independently, allowing + * partial cleanup if one directory fails. + * + * Use this method at the end of export operations to remove all temporary + * files created during the conversion process. + * + * @returns Promise resolving to object with cleanup success status for each directory type + * + * @example + * ```typescript + * // Clean up all temp directories after export + * const result = await manager.cleanupAllTempDirs(); + * console.log('Images cleanup:', result.images ? 'Success' : 'Failed'); + * console.log('Pandoc cleanup:', result.pandoc ? 'Success' : 'Failed'); + * ``` + * + * @example + * ```typescript + * // Use in plugin unload to ensure cleanup on disable + * async onunload() { + * await this.tempManager.cleanupAllTempDirs(); + * console.log('Temporary files cleaned up'); + * } + * ``` */ public async cleanupAllTempDirs(): Promise<{ images: boolean; pandoc: boolean }> { return { @@ -101,15 +356,88 @@ export class TempDirectoryManager { } /** - * Static helper to create manager from vault path and configDir + * Factory method for creating a TempDirectoryManager instance. + * + * This static convenience method provides a simpler way to instantiate the + * manager when you have individual parameters rather than an options object. + * It's particularly useful when parameters are obtained separately from + * different sources. + * + * @param vaultPath - Absolute path to the vault root directory + * @param configDir - Configuration directory path (typically '.obsidian') + * @param pluginName - Optional plugin directory name (defaults to 'typst-pdf-export') + * @param app - Obsidian App instance for vault.adapter operations + * @returns New TempDirectoryManager instance + * + * @example + * ```typescript + * // Create manager from separate parameters + * const pathUtils = new PathUtils(this.app); + * const vaultPath = pathUtils.getVaultPath(); + * const configDir = this.app.vault.configDir; + * + * const manager = TempDirectoryManager.create( + * vaultPath, + * configDir, + * 'typst-pdf-export', + * this.app + * ); + * ``` + * + * @example + * ```typescript + * // Quick initialization with default plugin name + * const manager = TempDirectoryManager.create( + * this.app.vault.adapter.getBasePath(), + * this.app.vault.configDir, + * undefined, // Use default plugin name + * this.app + * ); + * ``` */ public static create(vaultPath: string, configDir: string, pluginName: string | undefined, app: App): TempDirectoryManager { return new TempDirectoryManager({ vaultPath, configDir, pluginName, app }); } /** - * Check if a path is within the plugin's temp directories - * Handles absolute paths correctly on Windows + * Validates if a path is within the plugin's temporary directories. + * + * This security utility checks whether a given path is contained within either + * the temp-images or temp-pandoc directories. Use this method to validate paths + * before performing operations to prevent directory traversal attacks or + * accidental operations on user files. + * + * The method performs normalized path comparisons using Obsidian's normalizePath + * to ensure consistent behavior across Windows and Unix-like systems. + * + * @param dirPath - Path to validate (can be absolute or relative) + * @returns True if the path is within plugin temp directories, false otherwise + * + * @example + * ```typescript + * // Validate user-provided path before cleanup + * const userPath = '/vault/.obsidian/plugins/typst-pdf-export/temp-images/file.png'; + * if (manager.isPluginTempDir(userPath)) { + * await this.app.vault.adapter.remove(userPath); + * console.log('Safe to remove - within temp directory'); + * } else { + * console.error('Unsafe path - outside temp directories'); + * } + * ``` + * + * @example + * ```typescript + * // Use as guard before bulk operations + * async safeCleanup(filePaths: string[]) { + * for (const filePath of filePaths) { + * if (manager.isPluginTempDir(filePath)) { + * await this.app.vault.adapter.remove(filePath); + * } else { + * console.warn('Skipping non-temp file:', filePath); + * } + * } + * } + * ``` */ public isPluginTempDir(dirPath: string): boolean { const pluginDir = this.getPluginDir(); diff --git a/src/core/constants.ts b/src/core/constants.ts index 7073de4..9a02335 100644 --- a/src/core/constants.ts +++ b/src/core/constants.ts @@ -1,9 +1,53 @@ /** - * Constants used throughout the Obsidian Typst PDF Export plugin + * Global constants for Obsidian Typst PDF Export plugin. + * + * This module defines all constant values used throughout the plugin, including: + * - Fallback fonts for cross-platform compatibility + * - Plugin directory structure and file names + * - Export operation timeouts and durations + * - Dependency checking paths and executables + * + * All constants are defined using `as const` for maximum type safety, ensuring + * they cannot be modified at runtime and TypeScript can infer literal types. + * This prevents accidental mutations and catches typos at compile time. + * + * These constants are imported and used across: + * - Font management and caching + * - Temporary directory management + * - Export pipeline timeouts + * - Dependency resolution and validation + * - User notifications and feedback */ /** - * Fallback fonts used when Typst font detection fails + * Fallback fonts used when Typst cannot detect system fonts. + * + * This array provides a curated list of widely-available fonts that work across + * Windows, macOS, and Linux systems. When Typst's automatic font detection fails + * or specific fonts aren't found, the plugin will offer these fonts to users as + * safe alternatives. + * + * The list is organized by category: + * - Serif: Times New Roman, Georgia + * - Sans-serif: Arial, Helvetica, SF Pro Text + * - Monospace: Courier New, Monaco, SF Mono, Source Code Pro + * - Special: Concourse OT, UbuntuMono Nerd Font Mono + * + * These fonts are chosen for their: + * - Wide platform availability + * - Good readability in PDFs + * - Professional appearance + * - Comprehensive character coverage + * + * @example + * ```typescript + * // Use fallback fonts when system font detection fails + * let availableFonts = await detectSystemFonts(); + * if (availableFonts.length === 0) { + * availableFonts = [...FALLBACK_FONTS]; + * console.warn('Using fallback fonts - system font detection failed'); + * } + * ``` */ export const FALLBACK_FONTS = [ 'Times New Roman', @@ -20,7 +64,27 @@ export const FALLBACK_FONTS = [ ] as const; /** - * Plugin-specific directory names + * Plugin-specific directory and file names. + * + * Defines the structure of plugin-managed directories within the vault's + * .obsidian/plugins/typst-pdf-export folder. These directories are used for: + * - Temporary file storage during export operations + * - Font cache persistence for faster initialization + * + * Directory structure: + * ``` + * .obsidian/plugins/typst-pdf-export/ + * ├── temp-images/ # Converted images from embedded PDFs + * ├── temp-pandoc/ # Intermediate Pandoc/Typst processing files + * └── fonts-cache.json # Cached system font list + * ``` + * + * All paths are managed by TempDirectoryManager and automatically cleaned up + * to prevent disk space accumulation. + * + * @property TEMP_IMAGES - Directory for converted PDF images + * @property TEMP_PANDOC - Directory for Pandoc intermediate files + * @property FONTS_CACHE - JSON file storing cached font information */ export const PLUGIN_DIRS = { TEMP_IMAGES: 'temp-images', @@ -29,7 +93,31 @@ export const PLUGIN_DIRS = { } as const; /** - * Export-related constants + * Export operation timeouts and notification durations. + * + * Configures timing parameters for export operations and user feedback: + * - Process timeouts prevent hanging exports from blocking the UI + * - Notice durations ensure users have time to read important messages + * + * @property DEFAULT_TIMEOUT - Maximum time (ms) for export operations (2 minutes) + * @property NOTICE_DURATION - Standard durations for Obsidian notices + * @property NOTICE_DURATION.SHORT - Brief notices for status updates (5 seconds) + * @property NOTICE_DURATION.LONG - Extended notices for detailed info (12 seconds) + * + * @example + * ```typescript + * // Use timeout for export process + * const result = await Promise.race([ + * exportToPDF(file), + * new Promise((_, reject) => + * setTimeout(() => reject(new Error('Timeout')), + * EXPORT_CONSTANTS.DEFAULT_TIMEOUT) + * ) + * ]); + * + * // Show success notice with short duration + * new Notice('PDF exported successfully', EXPORT_CONSTANTS.NOTICE_DURATION.SHORT); + * ``` */ export const EXPORT_CONSTANTS = { DEFAULT_TIMEOUT: 120000, // 2 minutes @@ -40,24 +128,97 @@ export const EXPORT_CONSTANTS = { } as const; /** - * Dependency checking constants and utilities + * Dependency checking configuration and common paths. + * + * Defines default executable names and search paths for external tools required + * by the plugin (Pandoc, Typst, and ImageMagick). The plugin searches these + * paths in addition to the system PATH to handle various installation methods: + * - Package managers (brew, apt, snap, cargo) + * - User-local installations (~/.local/bin) + * - Language-specific package managers (cargo, npm, go) + * - System standard locations (/usr/bin, /usr/local/bin) + * + * These paths are always checked regardless of user settings, ensuring the plugin + * can find executables even when they're not in the user's shell PATH (common + * with GUI applications on macOS). + * + * @property DEFAULT_EXECUTABLES - Default command names for each dependency + * @property DEFAULT_EXECUTABLES.pandoc - Pandoc markdown converter (v2.0+) + * @property DEFAULT_EXECUTABLES.typst - Typst PDF compiler (v0.11+) + * @property DEFAULT_EXECUTABLES.imagemagick - ImageMagick convert utility (v7+) + * @property COMMON_PATHS - Standard installation locations to search + * @property COMMON_PATHS.HOME_RELATIVE - Paths relative to user home directory + * @property COMMON_PATHS.ABSOLUTE - System-wide absolute paths + * + * @example + * ```typescript + * // Build augmented PATH for dependency checking + * const homeDir = process.env.HOME || process.env.USERPROFILE; + * const homePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE + * .map(p => homeDir + p); + * const allPaths = [ + * ...process.env.PATH.split(':'), + * ...homePaths, + * ...DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE + * ]; + * + * // Search for pandoc in augmented PATH + * const pandocPath = findInPaths( + * DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, + * allPaths + * ); + * ``` + * + * @example + * ```typescript + * // Resolve executable with fallback to default name + * const executablePath = settings.pandocPath || + * DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc; + * + * // Check if executable exists in common paths + * const resolved = await resolveExecutable( + * executablePath, + * DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.concat( + * DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE + * ) + * ); + * ``` */ export const DEPENDENCY_CONSTANTS = { /** - * Default executable names for dependencies + * Default executable names for external dependencies. + * + * These are the command names used when users haven't configured custom paths. + * The plugin will search for these in the augmented PATH. + * + * @property pandoc - Pandoc executable (markdown → typst converter) + * @property typst - Typst executable (typst → PDF compiler) + * @property imagemagick - ImageMagick executable (PDF → image converter) */ DEFAULT_EXECUTABLES: { pandoc: 'pandoc', typst: 'typst', imagemagick: 'magick' }, - + /** - * Common paths to augment PATH with - these are always checked regardless of user settings + * Common installation paths to search for executables. + * + * These paths are checked in addition to the system PATH to handle tools + * installed via various methods. The plugin automatically augments PATH + * with these locations during dependency checking. */ COMMON_PATHS: { /** - * Paths relative to home directory (will have HOME prepended) + * Paths relative to the user's home directory. + * + * These paths will have HOME or USERPROFILE prepended before searching: + * - .local/bin: Local user installations (Linux standard) + * - .cargo/bin: Rust/Cargo package installations + * - go/bin: Go package installations + * - .npm-global/bin: Global npm package installations + * + * @example ['~/.local/bin', '~/.cargo/bin', '~/go/bin', '~/.npm-global/bin'] */ HOME_RELATIVE: [ '/.local/bin', @@ -66,7 +227,18 @@ export const DEPENDENCY_CONSTANTS = { '/.npm-global/bin' ], /** - * System-wide absolute paths (used as-is) + * System-wide absolute paths used as-is. + * + * Standard Unix/Linux system directories where executables are commonly + * installed by package managers: + * - /usr/local/bin: Homebrew (macOS), local installs + * - /opt/homebrew/bin: Homebrew on Apple Silicon + * - /usr/bin: System package manager installs + * - /bin: Essential system commands + * - /opt/local/bin: MacPorts installations + * - /snap/bin: Snap package installations (Linux) + * + * @example ['/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin', '/opt/local/bin', '/snap/bin'] */ ABSOLUTE: [ '/usr/local/bin', diff --git a/src/core/settings.ts b/src/core/settings.ts index ce6a73c..ba2a2ea 100644 --- a/src/core/settings.ts +++ b/src/core/settings.ts @@ -1,34 +1,162 @@ /** - * Core settings and configuration for Obsidian Typst PDF Export plugin + * Settings and configuration schema for Obsidian Typst PDF Export plugin. + * + * This module defines the complete configuration structure for the plugin, including: + * - External tool paths (Pandoc, Typst, ImageMagick) + * - Export defaults and presets + * - Typography and page layout settings + * - Behavior flags and preferences + * - Default values for fresh installations + * + * The settings are persisted to the vault's data.json file and can be modified + * through the plugin's settings tab. All settings have safe defaults that work + * out-of-the-box when external tools are available in PATH. + * + * Settings Organization: + * - Top-level: Core paths and output configuration + * - executablePaths: External tool configuration + * - exportDefaults: Default values for new exports + * - typography: Font configuration + * - pageSetup: Page layout and margins + * - behavior: Plugin behavior flags + * + * Type Safety: + * All settings use TypeScript for compile-time validation, preventing invalid + * configuration values and catching errors before runtime. */ +/** + * Export format options for PDF generation. + * + * Determines the pagination and layout style of the exported PDF: + * - Standard: Traditional multi-page format with page breaks + * - Single-page: Continuous single-page format without pagination + * + * The format affects Typst compilation parameters and influences layout decisions + * like automatic width adjustment for landscape orientation. + */ export enum ExportFormat { - /** Standard multi-page PDF format */ + /** Standard multi-page PDF format with automatic pagination */ Standard = 'standard', - /** Single-page continuous PDF format */ + /** Single-page continuous PDF format without page breaks */ SinglePage = 'single-page' } +/** + * Complete plugin settings interface. + * + * Defines all configurable options for the plugin, organized into logical groups. + * This interface serves as both the TypeScript type definition and the schema + * for the settings tab UI. + * + * Settings Lifecycle: + * 1. Plugin initializes with DEFAULT_SETTINGS + * 2. Persisted settings loaded from data.json (if exists) + * 3. User modifies via settings tab + * 4. Changes saved immediately to data.json + * 5. Export operations use current settings + * + * @example + * ```typescript + * // Load settings with defaults + * const settings: obsidianTypstPDFExportSettings = { + * ...DEFAULT_SETTINGS, + * ...await this.loadData() + * }; + * + * // Use settings in export + * const converter = new PandocTypstConverter( + * this.plugin, + * { template: settings.exportDefaults.template }, + * { ppi: 144 } + * ); + * ``` + */ export interface obsidianTypstPDFExportSettings { - /** Path to the Pandoc executable */ + /** + * Path to the Pandoc executable. + * + * Can be either: + * - Empty string: Use system PATH resolution + * - Executable name: e.g., 'pandoc' (searches augmented PATH) + * - Absolute path: e.g., '/usr/local/bin/pandoc' + * + * Pandoc 2.0+ required for Typst output support. + */ pandocPath: string; - /** Path to the Typst executable */ + + /** + * Path to the Typst executable. + * + * Can be either: + * - Empty string: Use system PATH resolution + * - Executable name: e.g., 'typst' (searches augmented PATH) + * - Absolute path: e.g., '/opt/typst/bin/typst' + * + * Typst 0.11+ recommended for best compatibility. + */ typstPath: string; - /** Default output folder for exported PDFs */ + + /** + * Default output folder for exported PDFs. + * + * Relative path from vault root. Will be created if it doesn't exist. + * Security: Must pass SecurityUtils.validateOutputPath() validation. + * + * @example 'exports' - PDF files saved to /exports/ + * @example 'pdfs/from-notes' - PDF files saved to /pdfs/from-notes/ + */ outputFolder: string; - - /** Executable paths configuration */ + + /** + * Executable paths configuration for optional dependencies. + * + * Controls where the plugin searches for external tools and how + * it augments the PATH environment variable. + */ executablePaths: { - /** Path to ImageMagick command (optional, uses PATH if not specified) */ + /** + * Path to ImageMagick command (optional). + * + * ImageMagick is optional but recommended for embedded PDF support. + * If not configured, embedded PDFs will be skipped during export. + * + * Can be: + * - Empty string: Use system PATH (default) + * - Executable name: e.g., 'magick' + * - Absolute path: e.g., '/usr/bin/magick' + */ imagemagickPath: string; - /** Additional paths to append to PATH environment variable */ + + /** + * Additional directories to search for executables. + * + * These paths are added to the PATH environment variable when + * searching for external tools. Useful for non-standard installations + * or when tools aren't in the user's shell PATH. + * + * @example ['/opt/homebrew/bin', '/usr/local/bin'] + */ additionalPaths: string[]; }; - - /** Custom environment variables for subprocess execution */ + + /** + * Custom environment variables for subprocess execution. + * + * Additional environment variables passed to Pandoc and Typst processes. + * Useful for configuring tool behavior or providing authentication. + * + * @example { 'TYPST_FONT_PATHS': '/custom/fonts:/system/fonts' } + * @example { 'PANDOC_USER_DATA_DIR': '/custom/pandoc/data' } + */ customEnvironmentVariables: { [key: string]: string }; - - /** Export defaults */ + + /** + * Default values for new export operations. + * + * These settings are used when opening the export modal. Users can override + * them on a per-export basis through the modal interface. + */ exportDefaults: { /** Default template to use for exports */ template: string; @@ -101,6 +229,55 @@ export interface obsidianTypstPDFExportSettings { }; } +/** + * Default settings for fresh plugin installations. + * + * These values are used when: + * - Plugin is first installed (no data.json exists) + * - Settings are reset to defaults + * - Individual settings are missing from persisted data + * + * The defaults are designed to: + * - Work out-of-the-box when external tools are in PATH + * - Produce professional-looking PDFs with minimal configuration + * - Use widely-available fonts as fallbacks + * - Enable helpful features (auto-open, folder structure preservation) + * + * Settings Strategy: + * - Empty paths for executables (rely on PATH resolution) + * - Common system paths in additionalPaths for macOS/Linux + * - Conservative concurrency (3) for stability + * - Professional typography (Concourse OT, SF Pro) + * - Standard A4 paper with reasonable margins + * + * @example + * ```typescript + * // Initialize plugin with defaults + * async onload() { + * await this.loadSettings(); // Merges with DEFAULT_SETTINGS + * this.registerSettingsTab(); + * } + * + * async loadSettings() { + * this.settings = Object.assign( + * {}, + * DEFAULT_SETTINGS, + * await this.loadData() + * ); + * } + * ``` + * + * @example + * ```typescript + * // Reset individual settings to defaults + * resetTypography() { + * this.settings.typography = { + * ...DEFAULT_SETTINGS.typography + * }; + * await this.saveSettings(); + * } + * ``` + */ export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = { pandocPath: '', typstPath: '',