ethanolivertroy_obsidian-ma.../main.js
Ethan Troy badef8ac29 Release v2.1.0: 11 new features + Python detection fix
New: drag-and-drop, URL/YouTube conversion, preview modal, post-conversion
hooks, custom filename templates, recursive folders, conversion history,
resolved path hint, troubleshooting UI, unit tests, BRAT beta channel.

Fixed: Python detection on macOS/Windows GUI apps, settings focus loss,
empty path crash, stale metadata detection.
2026-03-17 21:12:37 -04:00

22 lines
39 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
"use strict";var xt=Object.create;var B=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var Et=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var Dt=(c,n)=>{for(var t in n)B(c,t,{get:n[t],enumerable:!0})},at=(c,n,t,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Et(n))!Tt.call(c,s)&&s!==t&&B(c,s,{get:()=>n[s],enumerable:!(e=Pt(n,s))||e.enumerable});return c};var k=(c,n,t)=>(t=c!=null?xt(Ct(c)):{},at(n||!c||!c.__esModule?B(t,"default",{value:c,enumerable:!0}):t,c)),St=c=>at(B({},"__esModule",{value:!0}),c);var At={};Dt(At,{default:()=>Z});module.exports=St(At);var v=require("obsidian"),b=k(require("path")),R=k(require("fs"));var K={pythonPath:"python",enablePlugins:!1,pluginArgs:[],docintelEndpoint:"",outputPath:"",imageExtractionEnabled:!1,imageSubfolderTemplate:"{filename}-images",enableBatchProgress:!0,enableContextMenu:!0,enableRecursiveConversion:!1,outputFilenameTemplate:"{filename}",enableDragDrop:!0,enableAutoFrontmatter:!1,autoTags:"",conversionHistory:[]};var M=k(require("fs"));var Q=require("child_process"),lt=k(require("path"));function _(c,n,t,e){return new Promise((s,a)=>{let o=(0,Q.spawn)(c,[n,...t],{shell:!1,env:{...process.env,PYTHONUTF8:"1",...e},stdio:["ignore","pipe","pipe"]}),l="",r="";o.stdout.on("data",i=>{l+=i.toString()}),o.stderr.on("data",i=>{r+=i.toString()}),o.on("error",i=>{a(i)}),o.on("close",i=>{s({stdout:l.trim(),stderr:r.trim(),exitCode:i??1})})})}function L(c,n){return lt.join(n,"python",c)}async function tt(c,n){let t={pythonInstalled:!1,pythonVersion:null,markitdownInstalled:!1,markitdownVersion:null},e=[],s=c.trim();if(!s)return e.push({path:c||"(empty)",error:"Path is empty or whitespace-only"}),{status:t,resolvedPythonPath:c,triedPaths:e};let a=L("check_install.py",n),o=[s];if(s==="python"||s==="python3")if(process.platform==="win32"){s==="python"&&o.push("python3");let u=process.env.LOCALAPPDATA||"";if(u){for(let d of["313","312","311","310","39"])o.push(`${u}\\Programs\\Python\\Python${d}\\python.exe`);o.push(`${u}\\Microsoft\\WindowsApps\\python3.exe`)}}else{s==="python"?o.push("python3"):o.push("python"),o.push("/opt/homebrew/bin/python3"),o.push("/usr/local/bin/python3");for(let u of["3.13","3.12","3.11","3.10","3.9"])o.push(`/Library/Frameworks/Python.framework/Versions/${u}/bin/python3`);o.push("/usr/bin/python3")}let l=new Set,r=o.filter(p=>l.has(p)?!1:(l.add(p),!0)),i=null;for(let p of r)try{let u=await _(p,a,["--check","all"]);if(u.exitCode===0&&u.stdout){let d=JSON.parse(u.stdout),f={pythonInstalled:!0,pythonVersion:d.python_version??null,markitdownInstalled:!1,markitdownVersion:null};if(d.packages?.markitdown&&(f.markitdownInstalled=d.packages.markitdown.installed,f.markitdownVersion=d.packages.markitdown.version??null),f.markitdownInstalled)return e.push({path:p,error:""}),{status:f,resolvedPythonPath:p,triedPaths:e};e.push({path:p,error:"Python found but markitdown not installed"}),i||(i={status:f,resolvedPythonPath:p})}else{let d=u.stderr||`exit code ${u.exitCode}`;e.push({path:p,error:`Check script failed: ${d}`})}}catch(u){let d=u instanceof Error?u.message:String(u);e.push({path:p,error:d}),console.debug(`markitdown: ${p} failed:`,u);continue}return i?{...i,triedPaths:e}:{status:t,resolvedPythonPath:c,triedPaths:e}}async function ct(c,n,t,e){return c.trim()?new Promise((s,a)=>{let o=L("install_package.py",n),l=(0,Q.spawn)(c,[o,"--package",t],{shell:!1,env:{...process.env,PYTHONUTF8:"1"},stdio:["ignore","pipe","pipe"]}),r="";l.stdout.on("data",i=>{let p=i.toString().split(`
`);for(let u of p)u.trim()&&(r=u.trim(),e?.(u.trim()))}),l.stderr.on("data",i=>{let p=i.toString().split(`
`);for(let u of p)u.trim()&&e?.(u.trim())}),l.on("error",i=>{a(i)}),l.on("close",i=>{if(i===0)try{let p=JSON.parse(r);s(p.success===!0)}catch{s(!0)}else s(!1)})}):!1}var V=["pdf","docx","pptx","xlsx","xls","html","htm","txt","csv","json","xml","jpg","jpeg","png","gif","wav","mp3","zip","epub"],pt=V.map(c=>`.${c}`).join(","),ut=[{name:"PDF files",extensions:".pdf"},{name:"Word documents",extensions:".docx"},{name:"PowerPoint presentations",extensions:".pptx"},{name:"Excel spreadsheets",extensions:".xlsx,.xls"},{name:"Web pages",extensions:".html,.htm"},{name:"Text files",extensions:".txt"},{name:"Data files",extensions:".csv,.json,.xml"},{name:"Images",extensions:".jpg,.jpeg,.png,.gif"},{name:"Audio files",extensions:".wav,.mp3"},{name:"Archives & eBooks",extensions:".zip,.epub"}];function et(c){let n=c.toLowerCase().replace(/^\./,"");return V.includes(n)}var ht=k(require("path"));function dt(c){return/[:#\[\]{}&*!|>'"`,@%\\]/.test(c)||c.trim()!==c?`"${c.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:c}function Ft(c,n){let t={};if(n.enableAutoFrontmatter){let e=ht.basename(c),s=new Date,a=s.getFullYear(),o=String(s.getMonth()+1).padStart(2,"0"),l=String(s.getDate()).padStart(2,"0");t.source=e,t.converted=`${a}-${o}-${l}`,t.converter="markitdown"}if(n.autoTags.trim()){let e=n.autoTags.split(",").map(s=>s.trim()).filter(s=>s.length>0);e.length>0&&(t.tags=e)}return t}function gt(c){let n=[];for(let[t,e]of Object.entries(c))if(Array.isArray(e)){n.push(`${t}:`);for(let s of e)n.push(` - ${dt(s)}`)}else n.push(`${t}: ${dt(e)}`);return n.join(`
`)}function Mt(c){if(!c.startsWith("---"))return null;let n=c.indexOf(`
---`,3);if(n===-1)return null;let t=c.substring(4,n).trim(),e=n+4,s=c.substring(e);return{yaml:t,body:s}}function $t(c,n){let t=new Set;for(let a of c.split(`
`)){let o=a.match(/^(\w[\w-]*)\s*:/);o&&t.add(o[1])}let e={};for(let[a,o]of Object.entries(n))t.has(a)||(e[a]=o);if(Object.keys(e).length===0)return c;let s=gt(e);return c+`
`+s}function mt(c,n,t){let e=Ft(n,t);if(Object.keys(e).length===0)return c;let s=Mt(c);return s?`---
${$t(s.yaml,e)}
---${s.body}`:`---
${gt(e)}
---
${c}`}var $=class{constructor(n,t){this.pythonPath=n;this.pluginDir=t}getSupportedExtensions(){return V.map(n=>`.${n}`)}canConvert(n){let t=n.startsWith(".")?n.toLowerCase():`.${n.toLowerCase()}`;return this.getSupportedExtensions().includes(t)}async convertUrl(n,t,e){let s=Date.now(),a=L("markitdown_wrapper.py",this.pluginDir),o=["--url",n,"--output",t];e?.enablePlugins&&o.push("--enable-plugins"),e?.pluginArgs&&Object.keys(e.pluginArgs).length>0&&o.push("--plugin-args",JSON.stringify(e.pluginArgs)),e?.docintelEndpoint&&o.push("--docintel-endpoint",e.docintelEndpoint);try{let l=await _(this.pythonPath,a,o);if(l.exitCode!==0){let r="Unknown error";try{r=JSON.parse(l.stderr).error||"Unknown error"}catch{r=l.stderr||"Unknown error"}return r=r.replace(/(?:\/[\w.-]+)+\//g,"\u2026/"),{success:!1,error:`Conversion failed: ${r}`,processingTime:Date.now()-s}}return M.existsSync(t)?{success:!0,outputPath:t,processingTime:Date.now()-s}:{success:!1,error:"Output file was not created",processingTime:Date.now()-s}}catch(l){return{success:!1,error:`Conversion error: ${(l instanceof Error?l.message:String(l)).replace(/(?:\/[\w.-]+)+\//g,"\u2026/")}`,processingTime:Date.now()-s}}}async convert(n,t,e){let s=Date.now(),a=L("markitdown_wrapper.py",this.pluginDir),o=["--input",n,"--output",t];e?.enablePlugins&&o.push("--enable-plugins"),e?.pluginArgs&&Object.keys(e.pluginArgs).length>0&&o.push("--plugin-args",JSON.stringify(e.pluginArgs)),e?.docintelEndpoint&&o.push("--docintel-endpoint",e.docintelEndpoint),e?.extractImages&&e?.imageDir&&o.push("--extract-images","--image-dir",e.imageDir);try{let l=await _(this.pythonPath,a,o);if(l.exitCode!==0){let i="Unknown error";try{i=JSON.parse(l.stderr).error||"Unknown error"}catch{i=l.stderr||"Unknown error"}return i=i.replace(/(?:\/[\w.-]+)+\//g,"\u2026/"),{success:!1,error:`Conversion failed: ${i}`,processingTime:Date.now()-s}}if(!M.existsSync(t))return{success:!1,error:"Output file was not created",processingTime:Date.now()-s};if(e?.postProcess)try{let i=M.readFileSync(t,"utf-8"),p=mt(i,e.postProcess.inputPath,e.postProcess.settings);p!==i&&M.writeFileSync(t,p,"utf-8")}catch(i){console.warn("markitdown: post-conversion hook error:",i)}let r=0;try{r=JSON.parse(l.stdout).images_extracted??0}catch{}return{success:!0,outputPath:t,processingTime:Date.now()-s,imagesExtracted:r}}catch(l){return{success:!1,error:`Conversion error: ${(l instanceof Error?l.message:String(l)).replace(/(?:\/[\w.-]+)+\//g,"\u2026/")}`,processingTime:Date.now()-s}}}};var ft=require("obsidian"),g=k(require("path")),H=k(require("fs"));function x(c){return c.vault.adapter instanceof ft.FileSystemAdapter?c.vault.adapter.getBasePath():null}function E(c,n){let t;n?t=g.resolve(c,n):t=g.join(c,"markitdown-output");let e=g.resolve(c);return!t.startsWith(e+g.sep)&&t!==e&&(t=g.join(c,"markitdown-output")),H.existsSync(t)||H.mkdirSync(t,{recursive:!0}),t}function I(c,n){let t=g.basename(n,g.extname(n)),e=g.extname(n).replace(/^\./,""),s=new Date,a=i=>String(i).padStart(2,"0"),o=`${s.getFullYear()}-${a(s.getMonth()+1)}-${a(s.getDate())}`,l=`${o}_${a(s.getHours())}${a(s.getMinutes())}${a(s.getSeconds())}`,r=c.replace(/\{filename\}/g,t).replace(/\{ext\}/g,e).replace(/\{date\}/g,o).replace(/\{datetime\}/g,l);return r=r.replace(/[/\\:*?"<>|]/g,""),r.trim()||(r=t),r}function vt(c,n){let t=g.dirname(c),e=g.basename(c,".md"),a=n.replace(/[/\\]/g,"-").replace("{filename}",e);return g.join(t,a)}function nt(c,n){return g.relative(n,c).replace(/\\/g,"/")}var It=100;function st(c,n){return c.conversionHistory=[n,...c.conversionHistory].slice(0,It),c.conversionHistory}var h=require("obsidian");var j=class{constructor(n,t,e){this.containerEl=n;this.entries=t;this.onChange=e}render(){this.containerEl.empty();for(let t=0;t<this.entries.length;t++){let e=this.containerEl.createDiv("markitdown-plugin-arg-row"),s=e.createEl("input",{attr:{type:"text",placeholder:"Argument name"},cls:"markitdown-plugin-arg-key"});s.value=this.entries[t].key,s.addEventListener("input",()=>{this.entries[t].key=s.value,this.onChange(this.entries)});let a=e.createEl("input",{attr:{type:"text",placeholder:"Value"},cls:"markitdown-plugin-arg-value"});a.value=this.entries[t].value,a.addEventListener("input",()=>{this.entries[t].value=a.value,this.onChange(this.entries)}),e.createEl("button",{text:"\xD7",cls:"markitdown-plugin-arg-delete",attr:{"aria-label":"Remove argument"}}).addEventListener("click",()=>{this.entries.splice(t,1),this.onChange(this.entries),this.render()})}this.containerEl.createEl("button",{text:"+ Add argument",cls:"markitdown-plugin-arg-add"}).addEventListener("click",()=>{this.entries.push({key:"",value:""}),this.onChange(this.entries),this.render()})}};var U=class extends h.PluginSettingTab{constructor(t,e){super(t,e);this.pythonPathDebounceTimer=null;this.plugin=e}hide(){this.pythonPathDebounceTimer&&(clearTimeout(this.pythonPathDebounceTimer),this.pythonPathDebounceTimer=null,this.plugin.refreshDependencies().catch(console.error))}cancelPythonPathDebounce(){this.pythonPathDebounceTimer&&(clearTimeout(this.pythonPathDebounceTimer),this.pythonPathDebounceTimer=null)}display(){this.cancelPythonPathDebounce();let{containerEl:t}=this;t.empty(),new h.Setting(t).setName("Python").setHeading(),new h.Setting(t).setName("Python path").setDesc("Path to Python executable (e.g., python, python3, or a full path like C:\\Python311\\python.exe)").addText(r=>r.setPlaceholder("python").setValue(this.plugin.settings.pythonPath).onChange(async i=>{this.plugin.settings.pythonPath=i,await this.plugin.saveSettings(),this.pythonPathDebounceTimer&&clearTimeout(this.pythonPathDebounceTimer),this.pythonPathDebounceTimer=setTimeout(async()=>{this.pythonPathDebounceTimer=null,await this.plugin.refreshDependencies(),this.containerEl.isConnected&&this.display()},1500)}));let e=this.plugin.settings.pythonPath||"python",s=this.plugin.resolvedPythonPath;if(s&&s!==e&&t.createDiv("markitdown-resolved-path-hint").setText(`Resolved: ${s}`),new h.Setting(t).setName("Conversion").setHeading(),new h.Setting(t).setName("Output folder").setDesc('Folder for converted files (relative to vault root). Leave empty for "markitdown-output".').addText(r=>r.setPlaceholder("markitdown-output").setValue(this.plugin.settings.outputPath).onChange(async i=>{this.plugin.settings.outputPath=i,await this.plugin.saveSettings()})),new h.Setting(t).setName("Output filename template").setDesc("Template for converted filenames. Variables: {filename} (original name), {ext} (original extension), {date} (YYYY-MM-DD), {datetime} (YYYY-MM-DD_HHmmss). The .md extension is always appended automatically.").addText(r=>r.setPlaceholder("{filename}").setValue(this.plugin.settings.outputFilenameTemplate).onChange(async i=>{this.plugin.settings.outputFilenameTemplate=i||"{filename}",await this.plugin.saveSettings()})),new h.Setting(t).setName("Extract images").setDesc("Extract embedded images from PDFs and save as separate files").addToggle(r=>r.setValue(this.plugin.settings.imageExtractionEnabled).onChange(async i=>{this.plugin.settings.imageExtractionEnabled=i,await this.plugin.saveSettings(),this.display()})),this.plugin.settings.imageExtractionEnabled&&new h.Setting(t).setName("Image subfolder").setDesc("Subfolder name template for extracted images. Use {filename} as placeholder.").addText(r=>r.setPlaceholder("{filename}-images").setValue(this.plugin.settings.imageSubfolderTemplate).onChange(async i=>{this.plugin.settings.imageSubfolderTemplate=i||"{filename}-images",await this.plugin.saveSettings()})),new h.Setting(t).setName("Recursive folder conversion").setDesc("Include subfolders by default when converting a folder").addToggle(r=>r.setValue(this.plugin.settings.enableRecursiveConversion).onChange(async i=>{this.plugin.settings.enableRecursiveConversion=i,await this.plugin.saveSettings()})),new h.Setting(t).setName("Show batch progress").setDesc("Display a progress bar during batch folder conversions").addToggle(r=>r.setValue(this.plugin.settings.enableBatchProgress).onChange(async i=>{this.plugin.settings.enableBatchProgress=i,await this.plugin.saveSettings()})),new h.Setting(t).setName("Context menu").setDesc('Show "Convert to Markdown" in the file explorer right-click menu (requires restart)').addToggle(r=>r.setValue(this.plugin.settings.enableContextMenu).onChange(async i=>{this.plugin.settings.enableContextMenu=i,await this.plugin.saveSettings()})),new h.Setting(t).setName("Drag and drop").setDesc("Convert supported files automatically when dropped into the editor").addToggle(r=>r.setValue(this.plugin.settings.enableDragDrop).onChange(async i=>{this.plugin.settings.enableDragDrop=i,await this.plugin.saveSettings()})),new h.Setting(t).setName("Post-conversion").setHeading(),new h.Setting(t).setName("Auto frontmatter").setDesc("Automatically add YAML frontmatter with source filename, conversion date, and converter name").addToggle(r=>r.setValue(this.plugin.settings.enableAutoFrontmatter).onChange(async i=>{this.plugin.settings.enableAutoFrontmatter=i,await this.plugin.saveSettings()})),new h.Setting(t).setName("Auto tags").setDesc('Comma-separated tags to add to frontmatter (e.g., "converted, imported, pdf"). Requires auto frontmatter or adds a frontmatter block for tags alone.').addText(r=>r.setPlaceholder("converted, imported").setValue(this.plugin.settings.autoTags).onChange(async i=>{this.plugin.settings.autoTags=i,await this.plugin.saveSettings()})),new h.Setting(t).setName("Advanced").setHeading(),new h.Setting(t).setName("Enable Markitdown plugins").setDesc("Enable third-party Markitdown plugins (e.g., markitdown-pdf-separators)").addToggle(r=>r.setValue(this.plugin.settings.enablePlugins).onChange(async i=>{this.plugin.settings.enablePlugins=i,await this.plugin.saveSettings(),this.display()})),this.plugin.settings.enablePlugins){let r=new h.Setting(t).setName("Plugin arguments").setDesc("Key-value arguments passed to Markitdown plugins"),i=t.createDiv("markitdown-plugin-args-container");new j(i,this.plugin.settings.pluginArgs,async u=>{this.plugin.settings.pluginArgs=u,await this.plugin.saveSettings()}).render()}new h.Setting(t).setName("Azure Document Intelligence endpoint").setDesc("Optional: Azure endpoint URL for enhanced PDF conversion").addText(r=>r.setPlaceholder("https://your-resource.cognitiveservices.azure.com/").setValue(this.plugin.settings.docintelEndpoint).onChange(async i=>{this.plugin.settings.docintelEndpoint=i,await this.plugin.saveSettings()})),new h.Setting(t).setName("Status").setHeading();let a=t.createDiv("markitdown-status-container"),o=this.plugin.dependencyStatus;if(this.renderStatusItem(a,"Python",o.pythonInstalled,o.pythonVersion?`v${o.pythonVersion}`:void 0),this.renderStatusItem(a,"Markitdown",o.markitdownInstalled,o.markitdownVersion?`v${o.markitdownVersion}`:void 0),o.pythonInstalled&&a.createDiv("markitdown-resolved-path-hint").setText(`Using: ${this.plugin.resolvedPythonPath}`),o.pythonInstalled||this.renderPythonTroubleshooting(t),o.pythonInstalled&&!o.markitdownInstalled&&this.renderMarkitdownTroubleshooting(t),!o.markitdownInstalled&&o.pythonInstalled){let r=t.createEl("button",{text:"Install Markitdown",cls:"markitdown-install-button"});r.addEventListener("click",async()=>{r.disabled=!0,r.setText("Installing...");try{await this.plugin.installMarkitdown()?(new h.Notice("Markitdown installed successfully!"),await this.plugin.refreshDependencies(),this.display()):(new h.Notice("Failed to install Markitdown. Check the console for errors."),r.disabled=!1,r.setText("Try again"))}catch(i){let p=i instanceof Error?i.message:String(i);new h.Notice(`Error: ${p}`),r.disabled=!1,r.setText("Try again")}})}let l=t.createEl("button",{text:"Refresh status",cls:"markitdown-install-button"});l.addEventListener("click",async()=>{l.disabled=!0,l.setText("Checking..."),await this.plugin.refreshDependencies(),this.display()})}renderPythonTroubleshooting(t){let e=t.createEl("details",{cls:"markitdown-troubleshooting"});e.createEl("summary",{text:"Troubleshooting: Python not found"});let s=e.createDiv("markitdown-troubleshooting-content"),a=this.plugin.pythonDiscoveryLog;if(a.length>0){s.createEl("p",{text:"The following paths were checked:",cls:"markitdown-troubleshooting-label"});let i=s.createEl("ul",{cls:"markitdown-tried-paths"});for(let p of a){let u=i.createEl("li"),d=u.createEl("code",{text:p.path});p.error&&u.createSpan({text:` \u2014 ${p.error}`,cls:"markitdown-tried-path-error"})}}let o=s.createEl("p");o.createSpan({text:"Download Python from "}),o.createEl("a",{text:"python.org",href:"https://www.python.org/downloads/"});let r=process.platform==="win32"?"C:\\Python311\\python.exe":"/usr/local/bin/python3";s.createEl("p",{text:"Example path for your platform: ",cls:"markitdown-troubleshooting-label"}).createEl("code",{text:r})}renderMarkitdownTroubleshooting(t){let e=t.createEl("details",{cls:"markitdown-troubleshooting"});e.createEl("summary",{text:"Troubleshooting: markitdown not installed"});let s=e.createDiv("markitdown-troubleshooting-content");s.createEl("p",{text:"Python was found, but the markitdown package is not installed. Run this command to install it:"});let a=s.createDiv("markitdown-pip-command"),o=`${this.plugin.resolvedPythonPath} -m pip install "markitdown[all]"`;a.createEl("code",{text:o});let l=a.createEl("button",{text:"Copy",cls:"markitdown-copy-button"});l.addEventListener("click",()=>{navigator.clipboard.writeText(o).then(()=>{l.setText("Copied!"),setTimeout(()=>l.setText("Copy"),2e3)})}),s.createEl("p",{text:'Or use the "Install Markitdown" button below.',cls:"markitdown-troubleshooting-hint"})}renderStatusItem(t,e,s,a){let o=t.createDiv("markitdown-status-item"),l=o.createSpan("markitdown-status-icon");l.addClass(s?"success":"error"),l.setText(s?"\u2713":"\u2717");let r=`${e}: ${s?"Installed":"Not installed"}`;a&&(r+=` (${a})`),o.createSpan().setText(r)}};var P=require("obsidian"),rt=k(require("path")),N=k(require("fs"));var wt=require("obsidian"),it=500,A=class extends wt.Modal{constructor(n,t){super(n),this.content=t.content,this.outputPath=t.outputPath,this.processingTime=t.processingTime,this.onSave=t.onSave,this.onCancel=t.onCancel}onOpen(){let{contentEl:n}=this;n.addClass("markitdown-modal"),n.addClass("markitdown-preview-modal"),n.createEl("h2",{text:"Conversion preview"});let t=n.createDiv("markitdown-preview-meta");t.createEl("div",{text:`Output: ${this.outputPath}`,cls:"markitdown-preview-meta-item"}),t.createEl("div",{text:`Processing time: ${(this.processingTime/1e3).toFixed(1)}s`,cls:"markitdown-preview-meta-item"}),t.createEl("div",{text:`Content length: ${this.content.length.toLocaleString()} characters`,cls:"markitdown-preview-meta-item"});let e=this.content.split(`
`),s=e.length>it,a=s?e.slice(0,it).join(`
`):this.content;s&&n.createEl("div",{text:`Showing first ${it} of ${e.length} lines`,cls:"markitdown-preview-truncation-note"}),n.createDiv("markitdown-preview-content").createEl("pre",{text:a});let l=n.createDiv("markitdown-button-container"),r=l.createEl("button",{text:"Cancel"});r.addEventListener("click",async()=>{await this.onCancel(),this.close()});let i=l.createEl("button",{text:"Save",cls:"mod-cta"});i.addEventListener("click",async()=>{i.disabled=!0,i.setText("Saving..."),r.disabled=!0;try{await this.onSave()}finally{this.close()}})}onClose(){this.contentEl.empty()}};var W=class extends P.Modal{constructor(n,t){super(n),this.plugin=t}onOpen(){let{contentEl:n}=this;n.addClass("markitdown-modal"),n.createEl("h2",{text:"Convert file to Markdown"}),n.createEl("p",{text:"Select a file to convert:"});let e=n.createDiv("markitdown-file-input-container").createEl("input",{attr:{type:"file",accept:pt}}),a=n.createDiv("markitdown-button-container").createEl("button",{text:"Convert",cls:"mod-cta"});a.addEventListener("click",async()=>{if(!e.files||e.files.length===0){new P.Notice("Please select a file first");return}let o=e.files[0];a.disabled=!0,a.setText("Converting...");try{let l=x(this.app);if(!l){new P.Notice("Could not determine vault path. This plugin requires a local vault."),a.disabled=!1,a.setText("Convert");return}let r=E(l,this.plugin.settings.outputPath),i=I(this.plugin.settings.outputFilenameTemplate||"{filename}",o.name),p=rt.join(r,`${i}.md`),u=o.name.replace(/[^a-zA-Z0-9._-]/g,"_"),d=rt.join(r,`tmp_${Date.now()}_${u}`),f=await o.arrayBuffer();await N.promises.writeFile(d,Buffer.from(f));try{let w=await this.plugin.convertExternalFile(d,p);if(w.success){let y;try{y=await N.promises.readFile(p,"utf-8")}catch{new P.Notice("Conversion succeeded but could not read output file"),a.disabled=!1,a.setText("Convert");return}this.close(),new A(this.app,{content:y,outputPath:p,processingTime:w.processingTime??0,onSave:async()=>{let m=w.imagesExtracted?`Converted successfully (${w.imagesExtracted} images extracted)`:"Converted successfully";new P.Notice(m),await this.plugin.openConvertedFile(p,l)},onCancel:async()=>{await N.promises.unlink(p).catch(()=>{}),new P.Notice("Conversion discarded")}}).open()}else new P.Notice(`Conversion failed: ${w.error}`),a.disabled=!1,a.setText("Convert")}finally{await N.promises.unlink(d).catch(()=>{})}}catch(l){let r=l instanceof Error?l.message:String(l);new P.Notice(`Error: ${r}`),a.disabled=!1,a.setText("Convert")}})}onClose(){this.contentEl.empty()}};var C=require("obsidian"),S=k(require("path")),O=k(require("fs"));var yt=require("obsidian"),Y=class extends yt.Modal{constructor(n,t){super(n),this.totalFiles=t}onOpen(){let{contentEl:n}=this;n.addClass("markitdown-modal"),n.createEl("h2",{text:"Converting files"});let t=n.createDiv("markitdown-progress-bar");this.progressFill=t.createDiv("markitdown-progress-fill"),this.progressFill.style.width="0%",this.statusEl=n.createDiv("markitdown-progress-status"),this.statusEl.setText(`0 / ${this.totalFiles} files converted`),this.currentFileEl=n.createDiv("markitdown-progress-current"),this.currentFileEl.setText("Preparing...")}updateProgress(n,t,e,s){let a=this.totalFiles>0?Math.round(n/this.totalFiles*100):0;this.progressFill.style.width=`${a}%`,this.statusEl.setText(`${n} / ${this.totalFiles} files converted (${e} successful, ${s} failed)`),this.currentFileEl.setText(`Converting: ${t}`)}complete(n,t){this.progressFill.style.width="100%",this.statusEl.setText(`Conversion complete: ${n} successful, ${t} failed`),this.currentFileEl.setText("Done!"),setTimeout(()=>this.close(),2e3)}onClose(){this.contentEl.empty()}};var z=class extends C.Modal{constructor(n,t){super(n),this.plugin=t}onOpen(){let{contentEl:n}=this;n.addClass("markitdown-modal"),n.createEl("h2",{text:"Convert folder contents to Markdown"}),n.createEl("p",{text:"Select a folder to process:"});let e=n.createDiv("markitdown-file-input-container").createEl("input",{attr:{type:"file",webkitdirectory:"",directory:""}}),s=this.plugin.settings.enableRecursiveConversion,o=n.createDiv("markitdown-setting-row").createEl("label",{cls:"markitdown-checkbox-label"}),l=o.createEl("input",{attr:{type:"checkbox"}});l.checked=s,l.addEventListener("change",()=>{s=l.checked}),o.appendText(" Include subfolders (recursive)"),n.createEl("p",{text:"Select file types to convert:"});let r=n.createDiv("markitdown-checkbox-grid"),i=[];for(let d of ut){let f=r.createEl("label",{cls:"markitdown-checkbox-label"}),w=f.createEl("input",{attr:{type:"checkbox",value:d.extensions}});w.addEventListener("change",()=>{let y=d.extensions.split(",");if(w.checked)for(let m of y)i.includes(m)||i.push(m);else for(let m of y){let D=i.indexOf(m);D>-1&&i.splice(D,1)}}),f.appendText(d.name)}n.createDiv("markitdown-button-container").createEl("button",{text:"Convert",cls:"mod-cta"}).addEventListener("click",async()=>{if(!e.files||e.files.length===0){new C.Notice("Please select a folder first");return}if(i.length===0){new C.Notice("Please select at least one file type");return}let f=e.files[0].webkitRelativePath.split("/")[0],w=[];for(let y=0;y<e.files.length;y++){let m=e.files[y],D=S.extname(m.name).toLowerCase();if(!i.includes(D))continue;let ot=m.webkitRelativePath.split("/");if(!s&&ot.length>2)continue;let kt=ot.slice(1).join("/");w.push({file:m,absolutePath:null,name:m.name,relativePath:kt})}if(w.length===0){new C.Notice("No matching files found in the selected folder");return}this.close(),await this.runBatchConversion(w)})}async runBatchConversion(n){let t=x(this.app);if(!t){new C.Notice("Could not determine vault path. This plugin requires a local vault.");return}let e=E(t,this.plugin.settings.outputPath),s=null;this.plugin.settings.enableBatchProgress?(s=new Y(this.app,n.length),s.open()):new C.Notice(`Converting ${n.length} files...`);let a=0,o=0,l=[];for(let r=0;r<n.length;r++){let i=n[r];s?.updateProgress(r,i.name,a,o);let p=I(this.plugin.settings.outputFilenameTemplate||"{filename}",i.name),u=S.dirname(i.relativePath),d=u&&u!=="."?S.join(e,u):e;await O.promises.mkdir(d,{recursive:!0});let f=S.join(d,`${p}.md`),w=i.name.replace(/[^a-zA-Z0-9._-]/g,"_"),y=S.join(d,`tmp_${Date.now()}_${r}_${w}`);try{if(i.file){let D=await i.file.arrayBuffer();await O.promises.writeFile(y,Buffer.from(D))}else i.absolutePath&&await O.promises.copyFile(i.absolutePath,y);let m=await this.plugin.convertExternalFile(y,f);m.success?a++:(o++,l.push(`${i.relativePath}: ${m.error}`))}catch(m){o++;let D=m instanceof Error?m.message:String(m);l.push(`${i.relativePath}: ${D}`)}finally{await O.promises.unlink(y).catch(()=>{})}s?.updateProgress(r+1,i.name,a,o)}if(s)s.complete(a,o);else{let r=`Conversion complete: ${a} successful, ${o} failed`;l.length>0&&l.length<=3&&(r+=`
`+l.join(`
`)),new C.Notice(r)}}onClose(){this.contentEl.empty()}};var T=require("obsidian"),bt=k(require("path"));var J=class extends T.Modal{constructor(n,t){super(n),this.plugin=t}onOpen(){let{contentEl:n}=this;n.addClass("markitdown-modal"),n.createEl("h2",{text:"Convert URL to Markdown"}),n.createEl("p",{text:"Enter a URL to convert (e.g. YouTube):"});let e=n.createDiv("markitdown-url-input-container").createEl("input",{attr:{type:"url",placeholder:"https://www.youtube.com/watch?v=..."}});e.style.width="100%";let a=n.createDiv("markitdown-button-container").createEl("button",{text:"Convert",cls:"mod-cta"});a.addEventListener("click",async()=>{let o=e.value.trim();if(!o){new T.Notice("Please enter a URL");return}if(!o.startsWith("http://")&&!o.startsWith("https://")){new T.Notice("URL must start with http:// or https://");return}a.disabled=!0,a.setText("Converting...");try{let l=x(this.app);if(!l){new T.Notice("Could not determine vault path. This plugin requires a local vault."),a.disabled=!1,a.setText("Convert");return}let r=E(l,this.plugin.settings.outputPath),i=this.deriveFilename(o),p=bt.join(r,`${i}.md`),u=this.plugin.buildConversionOptions(p),d=await this.plugin.converter.convertUrl(o,p,u);d.success?(new T.Notice("URL converted successfully"),this.close(),await this.plugin.openConvertedFile(p,l)):(new T.Notice(`Conversion failed: ${d.error}`),a.disabled=!1,a.setText("Convert"))}catch(l){let r=l instanceof Error?l.message:String(l);new T.Notice(`Error: ${r}`),a.disabled=!1,a.setText("Convert")}})}deriveFilename(n){try{let t=new URL(n);if(t.hostname==="www.youtube.com"||t.hostname==="youtube.com"||t.hostname==="m.youtube.com"){let s=t.searchParams.get("v");if(s)return`youtube-${s}`}if(t.hostname==="youtu.be"){let s=t.pathname.slice(1);if(s)return`youtube-${s}`}return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"url-conversion"}catch{return`url-${Date.now()}`}}onClose(){this.contentEl.empty()}};var G=require("obsidian"),q=class extends G.Modal{constructor(n,t){super(n),this.plugin=t}onOpen(){let{contentEl:n}=this;n.addClass("markitdown-modal"),n.createEl("h2",{text:"Conversion history"});let t=this.plugin.settings.conversionHistory;if(t.length===0){n.createEl("p",{text:"No conversions have been recorded yet.",cls:"markitdown-history-empty"});return}let e=n.createDiv("markitdown-history-list");for(let o of t)this.renderEntry(e,o);n.createDiv("markitdown-button-container").createEl("button",{text:"Clear history",cls:"markitdown-history-clear-btn"}).addEventListener("click",async()=>{this.plugin.settings.conversionHistory=[],await this.plugin.saveSettings(),new G.Notice("Conversion history cleared"),this.close()})}renderEntry(n,t){let e=n.createDiv("markitdown-history-entry"),s=e.createDiv("markitdown-history-entry-header"),a=new Date(t.timestamp);s.createSpan({text:a.toLocaleString(),cls:"markitdown-history-timestamp"});let o=t.success?"markitdown-history-badge-success":"markitdown-history-badge-fail";s.createSpan({text:t.success?"Success":"Failed",cls:`markitdown-history-badge ${o}`});let l=t.inputFile.split("/").pop()?.split("\\").pop()??t.inputFile;e.createDiv({text:l,cls:"markitdown-history-filename"});let r=[];t.processingTimeMs!==void 0&&r.push(`${t.processingTimeMs}ms`),t.imagesExtracted!==void 0&&t.imagesExtracted>0&&r.push(`${t.imagesExtracted} image${t.imagesExtracted!==1?"s":""} extracted`),r.length>0&&e.createDiv({text:r.join(" \xB7 "),cls:"markitdown-history-details"}),!t.success&&t.error&&e.createDiv({text:t.error,cls:"markitdown-history-error"})}onClose(){this.contentEl.empty()}};var X=require("obsidian"),F=class extends X.Modal{constructor(n,t){super(n),this.plugin=t}onOpen(){let{contentEl:n}=this;if(n.addClass("markitdown-modal"),n.createEl("h2",{text:"Markitdown setup"}),!this.plugin.dependencyStatus.pythonInstalled){this.showPythonNotFound(n);return}if(this.plugin.dependencyStatus.markitdownInstalled){this.showAlreadyInstalled(n);return}this.showInstallPrompt(n)}showPythonNotFound(n){n.createEl("p",{text:"Python is not installed or not found at the configured path."});let t=n.createEl("div",{cls:"markitdown-setup-details"});t.createEl("p",{text:"To get started:"});let e=t.createEl("ol");e.createEl("li",{text:"Install Python 3.8+ from python.org"}),e.createEl("li",{text:"Set the correct Python path in plugin settings"}),e.createEl("li",{text:"Restart Obsidian or re-run this setup"}),n.createDiv("markitdown-button-container").createEl("button",{text:"Open settings"}).addEventListener("click",()=>{this.close(),this.app.setting?.open(),this.app.setting?.openTabById(this.plugin.manifest.id)})}showAlreadyInstalled(n){let t=this.plugin.dependencyStatus.markitdownVersion;n.createEl("p",{text:`Markitdown is installed${t?` (v${t})`:""}. You're ready to convert files.`}),n.createDiv("markitdown-button-container").createEl("button",{text:"Close"}).addEventListener("click",()=>this.close())}showInstallPrompt(n){n.createEl("p",{text:"Markitdown is not installed. Would you like to install it now?"}),n.createEl("p",{text:"This will install the markitdown Python package using pip.",cls:"setting-item-description"});let t=n.createDiv("markitdown-setup-log");t.style.display="none";let e=n.createDiv("markitdown-button-container"),s=e.createEl("button",{text:"Cancel"});s.addEventListener("click",()=>this.close());let a=e.createEl("button",{text:"Install Markitdown",cls:"mod-cta"});a.addEventListener("click",async()=>{a.disabled=!0,a.setText("Installing..."),s.disabled=!0,t.style.display="block",t.empty();try{await this.plugin.installMarkitdown(l=>{t.createEl("div",{text:l,cls:"markitdown-setup-log-line"}).scrollIntoView()})?(new X.Notice("Markitdown installed successfully!"),await this.plugin.refreshDependencies(),this.close()):(t.createEl("div",{text:"Installation failed. Check the log above for details.",cls:"markitdown-setup-log-error"}),a.disabled=!1,a.setText("Try again"),s.disabled=!1)}catch(o){let l=o instanceof Error?o.message:String(o);t.createEl("div",{text:`Error: ${l}`,cls:"markitdown-setup-log-error"}),a.disabled=!1,a.setText("Try again"),s.disabled=!1}})}onClose(){this.contentEl.empty()}};var Z=class extends v.Plugin{constructor(){super(...arguments);this.settings=K;this.dependencyStatus={pythonInstalled:!1,pythonVersion:null,markitdownInstalled:!1,markitdownVersion:null};this.converter=new $("python",".");this.pythonDiscoveryLog=[];this._resolvedPythonPath="python"}get resolvedPythonPath(){return this._resolvedPythonPath}async onload(){await this.loadSettings();let t=this.getPluginDir(),e=await tt(this.settings.pythonPath,t);this.dependencyStatus=e.status,this.pythonDiscoveryLog=e.triedPaths,this._resolvedPythonPath=e.resolvedPythonPath,this.converter=new $(this.resolvedPythonPath,t),this.addRibbonIcon("file-text","Convert to Markdown",()=>{this.openConvertModal()}),this.addCommand({id:"convert-file",name:"Convert file to Markdown",callback:()=>this.openConvertModal()}),this.addCommand({id:"convert-folder",name:"Convert folder to Markdown",callback:()=>this.openFolderModal()}),this.addCommand({id:"convert-url",name:"Convert URL to Markdown",callback:()=>this.openUrlModal()}),this.addCommand({id:"view-conversion-history",name:"View conversion history",callback:()=>new q(this.app,this).open()}),this.settings.enableContextMenu&&this.registerFileMenu(),this.settings.enableDragDrop&&this.registerDropHandler(),this.addSettingTab(new U(this.app,this))}onunload(){}openConvertModal(){if(!this.dependencyStatus.markitdownInstalled){new F(this.app,this).open();return}new W(this.app,this).open()}openFolderModal(){if(!this.dependencyStatus.markitdownInstalled){new F(this.app,this).open();return}new z(this.app,this).open()}openUrlModal(){if(!this.dependencyStatus.markitdownInstalled){new F(this.app,this).open();return}new J(this.app,this).open()}registerFileMenu(){this.registerEvent(this.app.workspace.on("file-menu",(t,e)=>{e instanceof v.TFile&&et(e.extension)&&t.addItem(s=>{s.setTitle("Convert to Markdown").setIcon("file-text").onClick(()=>this.convertVaultFile(e))})}))}registerDropHandler(){this.registerEvent(this.app.workspace.on("editor-drop",(t,e,s)=>{let a=t.dataTransfer?.files;if(!a||a.length===0)return;let o=[];for(let l=0;l<a.length;l++){let r=a[l],i=b.extname(r.name).toLowerCase().replace(/^\./,"");et(i)&&o.push(r)}if(o.length!==0){t.preventDefault();for(let l of o)this.handleDroppedFile(l,e).catch(r=>{let i=r instanceof Error?r.message:String(r);new v.Notice(`Drop conversion error: ${i}`)})}}))}async handleDroppedFile(t,e){let s=x(this.app);if(!s){new v.Notice("Could not determine vault path. This plugin requires a local vault.");return}if(!this.dependencyStatus.markitdownInstalled){new F(this.app,this).open();return}new v.Notice(`Converting dropped file: ${t.name}...`);let a=E(s,this.settings.outputPath),o=b.basename(t.name,b.extname(t.name)),l=b.join(a,`${o}.md`),r=t.name.replace(/[^a-zA-Z0-9._-]/g,"_"),i=b.join(a,`tmp_${Date.now()}_${r}`),p=await t.arrayBuffer();await R.promises.writeFile(i,Buffer.from(p));try{let u=await this.convertExternalFile(i,l);if(u.success){let f=`[[${nt(l,s).replace(/\.md$/,"")}]]`,w=e.getCursor();e.replaceRange(f,w);let y=u.imagesExtracted?`Converted ${t.name} (${u.imagesExtracted} images extracted)`:`Converted ${t.name} successfully`;new v.Notice(y)}else new v.Notice(`Conversion failed for ${t.name}: ${u.error}`)}finally{await R.promises.unlink(i).catch(()=>{})}}async convertVaultFile(t){let e=x(this.app);if(!e){new v.Notice("Could not determine vault path. This plugin requires a local vault.");return}if(!this.dependencyStatus.markitdownInstalled){new F(this.app,this).open();return}let s=b.join(e,t.path),a=E(e,this.settings.outputPath),o=I(this.settings.outputFilenameTemplate||"{filename}",s),l=b.join(a,`${o}.md`),r=this.buildConversionOptions(l,s);new v.Notice("Converting file...");let i=Date.now(),p=await this.converter.convert(s,l,r),u=Date.now()-i;if(st(this.settings,{inputFile:s,outputFile:l,timestamp:new Date().toISOString(),success:p.success,error:p.error,processingTimeMs:u,imagesExtracted:p.imagesExtracted}),await this.saveSettings(),p.success){let d;try{d=await R.promises.readFile(l,"utf-8")}catch{new v.Notice("Conversion succeeded but could not read output file");return}new A(this.app,{content:d,outputPath:l,processingTime:p.processingTime??0,onSave:async()=>{let f=p.imagesExtracted?`Converted successfully (${p.imagesExtracted} images extracted)`:"Converted successfully";new v.Notice(f),await this.openConvertedFile(l,e)},onCancel:async()=>{await R.promises.unlink(l).catch(()=>{}),new v.Notice("Conversion discarded")}}).open()}else new v.Notice(`Conversion failed: ${p.error}`)}async convertExternalFile(t,e){let s=this.buildConversionOptions(e,t),a=Date.now(),o=await this.converter.convert(t,e,s),l=Date.now()-a;return st(this.settings,{inputFile:t,outputFile:e,timestamp:new Date().toISOString(),success:o.success,error:o.error,processingTimeMs:l,imagesExtracted:o.imagesExtracted}),await this.saveSettings(),o}buildConversionOptions(t,e){let s={enablePlugins:this.settings.enablePlugins,docintelEndpoint:this.settings.docintelEndpoint||void 0};return this.settings.pluginArgs.length>0&&(s.pluginArgs=this.pluginArgsToRecord(this.settings.pluginArgs)),this.settings.imageExtractionEnabled&&(s.extractImages=!0,s.imageDir=vt(t,this.settings.imageSubfolderTemplate)),e&&(this.settings.enableAutoFrontmatter||this.settings.autoTags.trim())&&(s.postProcess={settings:this.settings,inputPath:e}),s}pluginArgsToRecord(t){let e=Object.create(null);for(let s of t)if(s.key.trim()&&!(s.key==="__proto__"||s.key==="constructor"||s.key==="prototype"))try{e[s.key]=JSON.parse(s.value)}catch{e[s.key]=s.value}return e}async openConvertedFile(t,e){let s=nt(t,e),a=this.app.vault.getAbstractFileByPath(s);a instanceof v.TFile&&await this.app.workspace.getLeaf().openFile(a)}getPluginDir(){let t=x(this.app);return t&&this.manifest.dir?b.join(t,this.manifest.dir):(console.warn("markitdown: Could not resolve vault base path. Plugin features may not work correctly."),b.resolve(this.manifest.dir??"."))}async installMarkitdown(t){let e=this.getPluginDir(),s=await ct(this._resolvedPythonPath,e,"markitdown[all]",t);return s&&(this.dependencyStatus.markitdownInstalled=!0),s}async refreshDependencies(){let t=this.getPluginDir(),e=await tt(this.settings.pythonPath,t);this.dependencyStatus=e.status,this.pythonDiscoveryLog=e.triedPaths,this._resolvedPythonPath=e.resolvedPythonPath,this.converter=new $(this.resolvedPythonPath,t)}async loadSettings(){this.settings=Object.assign({},K,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}};