/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var k=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var V=(m,r)=>{for(var e in r)k(m,e,{get:r[e],enumerable:!0})},q=(m,r,e,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of $(r))!G.call(m,t)&&t!==e&&k(m,t,{get:()=>r[t],enumerable:!(i=O(r,t))||i.enumerable});return m};var U=m=>q(k({},"__esModule",{value:!0}),m);var L={};V(L,{default:()=>D});module.exports=U(L);var f=require("obsidian");var o=require("obsidian"),x={apiKey:"",model:"claude-3-5-haiku-latest",timedCount:10,delaySeconds:6,noteCount:3,systemPrompt:"You are a creative writing assistant. Generate engaging, thought-provoking writing prompts that inspire creativity and help writers overcome blocks. Focus on variety, originality, and emotional depth.",timedExamplePrompt:"The interesting thing about a rose is\u2026",freewritingExamplePrompt:"Describe a world where colors have been outlawed and only exist in secret underground galleries."},b=class extends o.PluginSettingTab{constructor(e,i){super(e,i);this.modelDropdown=null;this.availableModels=[];this.apiKeyDebounceTimer=null;this.settingsSaveTimer=null;this.API_KEY_DEBOUNCE_MS=500;this.SETTINGS_SAVE_DEBOUNCE_MS=500;this.plugin=i}hide(){this.apiKeyDebounceTimer!==null&&(window.clearTimeout(this.apiKeyDebounceTimer),this.apiKeyDebounceTimer=null),this.settingsSaveTimer!==null&&(window.clearTimeout(this.settingsSaveTimer),this.settingsSaveTimer=null)}debounceSaveSettings(){this.settingsSaveTimer!==null&&window.clearTimeout(this.settingsSaveTimer),this.settingsSaveTimer=window.setTimeout(()=>{this.plugin.saveSettings(),this.settingsSaveTimer=null},this.SETTINGS_SAVE_DEBOUNCE_MS)}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"Freewriting Prompts"}),e.createEl("h3",{text:"API Configuration"}),new o.Setting(e).setName("Anthropic API Key").setDesc("Your Anthropic API key for Claude. Get one at https://console.anthropic.com/").addText(i=>i.setPlaceholder("sk-ant-...").setValue(this.plugin.settings.apiKey).onChange(t=>{this.plugin.settings.apiKey=t,this.apiKeyDebounceTimer!==null&&(window.clearTimeout(this.apiKeyDebounceTimer),this.apiKeyDebounceTimer=null),this.apiKeyDebounceTimer=window.setTimeout(()=>{(async()=>(await this.plugin.saveSettings(),t.trim().length>0&&await this.refreshModels(),this.apiKeyDebounceTimer=null))()},this.API_KEY_DEBOUNCE_MS)})).then(i=>{var t;(t=i.controlEl.querySelector("input"))==null||t.setAttribute("type","password")}),new o.Setting(e).setName("Test API Key").setDesc("Test your API key to verify it works correctly").addButton(i=>i.setButtonText("Test Connection").onClick(()=>{this.testApiKey(i)})),new o.Setting(e).setName("Claude Model").setDesc("Which Claude model to use for generating prompts").addDropdown(i=>{this.modelDropdown=i,this.populateModelDropdown(i),this.availableModels.length>0&&i.setValue(this.plugin.settings.model),i.onChange(t=>{this.plugin.settings.model=t,this.debounceSaveSettings()})}),this.loadModelsAsync(),e.createEl("h3",{text:"Command Configuration"}),new o.Setting(e).setName("Timed Prompts Count").setDesc("Number of prompts to generate for timed notifications (1-50)").addText(i=>i.setPlaceholder("10").setValue(this.plugin.settings.timedCount.toString()).onChange(async t=>{let s=parseInt(t);!isNaN(s)&&s>=1&&s<=50&&(this.plugin.settings.timedCount=s,await this.plugin.saveSettings())})).then(i=>{let t=i.controlEl.querySelector("input");t&&(t.setAttribute("type","number"),t.setAttribute("min","1"),t.setAttribute("max","50"),t.setAttribute("step","1"))}),new o.Setting(e).setName("Delay Between Prompts").setDesc("Seconds to wait between each timed prompt notification (1-300)").addText(i=>i.setPlaceholder("6").setValue(this.plugin.settings.delaySeconds.toString()).onChange(async t=>{let s=parseInt(t);!isNaN(s)&&s>=1&&s<=300&&(this.plugin.settings.delaySeconds=s,await this.plugin.saveSettings())})).then(i=>{let t=i.controlEl.querySelector("input");t&&(t.setAttribute("type","number"),t.setAttribute("min","1"),t.setAttribute("max","300"),t.setAttribute("step","1"))}),new o.Setting(e).setName("Note Prompts Count").setDesc("Number of prompts to append to the current note (1-20)").addText(i=>i.setPlaceholder("3").setValue(this.plugin.settings.noteCount.toString()).onChange(async t=>{let s=parseInt(t);!isNaN(s)&&s>=1&&s<=20&&(this.plugin.settings.noteCount=s,await this.plugin.saveSettings())})).then(i=>{let t=i.controlEl.querySelector("input");t&&(t.setAttribute("type","number"),t.setAttribute("min","1"),t.setAttribute("max","20"),t.setAttribute("step","1"))}),e.createEl("h3",{text:"Prompt Customization"}),new o.Setting(e).setName("System Prompt").setDesc("Instructions for the AI on how to generate prompts").addTextArea(i=>i.setPlaceholder("You are a creative writing assistant...").setValue(this.plugin.settings.systemPrompt).onChange(t=>{this.plugin.settings.systemPrompt=t,this.debounceSaveSettings()})).then(i=>{var t;(t=i.controlEl.querySelector("textarea"))==null||t.setAttribute("rows","3")}),new o.Setting(e).setName("Timed Prompts Example").setDesc("Example prompt to guide the style for timed notifications").addTextArea(i=>i.setPlaceholder("Write about a character who...").setValue(this.plugin.settings.timedExamplePrompt).onChange(t=>{this.plugin.settings.timedExamplePrompt=t,this.debounceSaveSettings()})).then(i=>{var t;(t=i.controlEl.querySelector("textarea"))==null||t.setAttribute("rows","2")}),new o.Setting(e).setName("Note Prompts Example").setDesc("Example prompt to guide the style for note prompts").addTextArea(i=>i.setPlaceholder("Describe a world where...").setValue(this.plugin.settings.freewritingExamplePrompt).onChange(t=>{this.plugin.settings.freewritingExamplePrompt=t,this.debounceSaveSettings()})).then(i=>{var t;(t=i.controlEl.querySelector("textarea"))==null||t.setAttribute("rows","2")}),e.createEl("h3",{text:"Actions"}),new o.Setting(e).setName("Clear Cache").setDesc("Clear the cached prompts to force regeneration").addButton(i=>i.setButtonText("Clear Cache").onClick(()=>{this.plugin.promptGenerator.clearCache();let t=new o.Notice("Cache cleared");setTimeout(()=>t.hide(),2e3)})),new o.Setting(e).setName("Clear Model List Cache").setDesc("Clear cached Claude model list to force a fresh fetch from the API").addButton(i=>i.setButtonText("Clear Models Cache").onClick(()=>{this.plugin.modelService.clearCache();let t=new o.Notice("Model list cache cleared");setTimeout(()=>t.hide(),2e3),this.plugin.saveSettings()}))}async loadModels(){try{this.availableModels=await this.plugin.modelService.getAvailableModels()}catch(e){console.error("Error loading models:",e)}}async loadModelsAsync(){if(await this.loadModels(),this.modelDropdown){this.populateModelDropdown(this.modelDropdown);let e=this.plugin.settings.model;if(this.availableModels.some(t=>t.id===e))this.modelDropdown.setValue(e);else{let t=this.availableModels[0];t?this.plugin.settings.model!==t.id&&(this.modelDropdown.setValue(t.id),this.plugin.settings.model=t.id,await this.plugin.saveSettings(),new o.Notice(`Your selected model is no longer available. Defaulting to ${t.displayName} (${t.id})`)):(this.modelDropdown.setDisabled(!0),this.modelDropdown.selectEl.empty(),this.modelDropdown.addOption("","No models available"))}}}populateModelDropdown(e){if(this.availableModels.length===0){e.addOption("","Loading models..."),e.setDisabled(!0);return}e.selectEl.empty(),this.availableModels.forEach(i=>{e.addOption(i.id,i.displayName)}),e.setDisabled(!1)}async refreshModels(){try{if(this.modelDropdown&&(this.modelDropdown.setDisabled(!0),this.modelDropdown.selectEl.empty(),this.modelDropdown.addOption("","Refreshing models...")),this.availableModels=await this.plugin.modelService.refreshModels(),this.modelDropdown){this.populateModelDropdown(this.modelDropdown);let e=this.plugin.settings.model;if(this.availableModels.some(t=>t.id===e))this.modelDropdown.setValue(e);else{let t=this.availableModels[0];t&&this.plugin.settings.model!==t.id&&(this.modelDropdown.setValue(t.id),this.plugin.settings.model=t.id,new o.Notice(`Your selected model is no longer available. Defaulting to ${t.displayName} (${t.id})`),await this.plugin.saveSettings())}}}catch(e){console.error("Error refreshing models:",e)}}async testApiKey(e){let i=e.buttonEl.textContent||"Test Connection";e.setButtonText("Testing..."),e.setDisabled(!0);try{let s=await this.plugin.promptGenerator.anthropicClient.testApiKey(this.plugin.settings.model);if(s.success){let n=s.details,l=n?` Details: \u2022 Model: ${n.model} \u2022 Response time: ${n.responseTime}ms \u2022 Input tokens: ${n.inputTokens||"N/A"} \u2022 Output tokens: ${n.outputTokens||"N/A"}`:"";new o.Notice(`\u2705 ${s.message}${l}`,8e3)}else{let n=s.details?` Troubleshooting: \u2022 Response time: ${s.details.responseTime}ms \u2022 Error type: ${s.error}`:"";new o.Notice(`\u274C ${s.message}${n}`,1e4)}}catch(t){console.error("Unexpected error during API test:",t),new o.Notice("\u274C Unexpected error during API test. Check console for details.",5e3)}finally{e.setButtonText(i),e.setDisabled(!1)}}};var P=require("obsidian");var R=require("obsidian"),A=class{constructor(r){this.API_BASE="https://api.anthropic.com/v1";this.API_VERSION="2023-06-01";this.messagesUrl=`${this.API_BASE}/messages`;this.modelsUrl=`${this.API_BASE}/models`;this.SYSTEM_PROMPT_SUFFIX=` IMPORTANT OUTPUT REQUIREMENTS: - Return ONLY the numbered writing prompts, nothing else - Do not include any explanations, questions, or additional commentary - Do not ask if the user wants more prompts or different styles - Format: numbered list with one prompt per line (1. [prompt], 2. [prompt], etc.)`;this.TIMED_PROMPT_MODIFIER=` FOR TIMED PROMPTS - MAKE THEM EXTREMELY SHORT AND DIRECT: - Each prompt should be answerable in 1-5 words or a single sentence - Focus on immediate, concrete observations or quick thoughts - Avoid complex scenarios or deep philosophical questions - Examples: "What color is closest to you?", "Your favorite word today:", "First sound you hear:", "Describe your mood in one word", "Name something soft" - Keep prompts simple, immediate, and concrete`;this.apiKey=r}async generatePrompts(r,e,i,t,s){if(!this.apiKey)throw new Error("API key is required");try{let n=this.createUserMessage(r,t),l=i;s==="timed"&&(l+=this.TIMED_PROMPT_MODIFIER),l+=this.SYSTEM_PROMPT_SUFFIX;let a={model:e,max_tokens:s==="timed"?256:1e3,messages:[{role:"user",content:n}],system:l},p=await this.makeRequest(a);return this.parsePromptsFromResponse(p)}catch(n){throw console.error("Error generating prompts:",n),n instanceof Error?n:new Error("Unknown error occurred while generating prompts")}}async fetchModels(){if(!this.apiKey)throw new Error("API key is required");try{let r=[],e=new Set,i=!0,t,s="",n="",l=0,c=1e3;for(;i;){if(l++,l>c)throw new Error(`Pagination exceeded maximum iterations (${c}). Possible API issue.`);let d=new URLSearchParams;d.set("limit","1000"),t&&d.set("after_id",t);let w=`${this.modelsUrl}?${d.toString()}`,g=await(0,R.requestUrl)({url:w,method:"GET",headers:{"x-api-key":this.apiKey,"anthropic-version":this.API_VERSION}});if(g.status<200||g.status>=300)throw new Error(`Models API request failed: ${g.status} ${g.text}`);let u=g.json;if(!u||typeof u!="object"||!("data"in u)||!Array.isArray(u.data))throw new Error("Invalid models API response structure");if(!u.data.every(y=>y&&typeof y=="object"&&"id"in y&&typeof y.id=="string"))throw new Error("Invalid model structure in API response");let E=u;for(let y of E.data)e.has(y.id)||(e.add(y.id),r.push(y));s||(s=E.first_id);let K=t;if(n=E.last_id,i=E.has_more,!n||n===K){console.warn("Pagination cursor did not advance. Stopping pagination.");break}i&&(t=n)}let a=r.slice().sort((d,w)=>{var g,u;return((g=d.display_name)!=null?g:d.id).localeCompare((u=w.display_name)!=null?u:w.id)}),p=a.length>0?a[0].id:s,h=a.length>0?a[a.length-1].id:n;return{data:a,first_id:p,has_more:!1,last_id:h}}catch(r){throw r instanceof Error?r:new Error(`Network request failed: ${String(r)}`)}}createUserMessage(r,e){let i=`Generate exactly ${r} creative writing prompts. Return ONLY the numbered prompts with no additional text or commentary.`;return e.trim()?`${i} Example style: "${e}" Provide ${r} similar prompts in this exact format: 1. [prompt] 2. [prompt] (etc.)`:`${i} Provide ${r} diverse writing prompts in this exact format: 1. [prompt] 2. [prompt] (etc.)`}async makeRequest(r){try{let e=await(0,R.requestUrl)({url:this.messagesUrl,method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.API_VERSION},body:JSON.stringify(r)});if(e.status<200||e.status>=300)throw new Error(`API request failed: ${e.status} ${e.text}`);return e.json}catch(e){throw e instanceof Error?e:new Error(`Network request failed: ${String(e)}`)}}parsePromptsFromResponse(r){if(!r.content||r.content.length===0)throw new Error("No content received from API");let i=r.content.filter(s=>s&&s.type==="text"&&typeof s.text=="string").map(s=>s.text).join(` `).split(` `).map(s=>s.trim()).filter(s=>s.length>0),t=[];for(let s of i){let n=s.replace(/^\s*(?:\d+[.)]|[-*•])\s*/,"").trim();n.length>0&&t.push(n)}if(t.length===0)throw new Error("No valid prompts found in API response");return t}updateApiKey(r){this.apiKey=r}validateApiKey(){return!!(this.apiKey&&this.apiKey.trim().length>0)}async testApiKey(r){var i,t;if(!this.validateApiKey())return{success:!1,message:"API key is empty or invalid format",error:"INVALID_KEY_FORMAT"};let e=Date.now();try{let s={model:r,max_tokens:10,messages:[{role:"user",content:'Please respond with just the word "ping"'}],system:"You are a test assistant. Respond only with the exact word requested."},n=await this.makeRequest(s),l=Date.now()-e,p=(n.content||[]).filter(h=>h&&h.type==="text"&&typeof h.text=="string").map(h=>h.text).join(" ").trim().toLowerCase().replace(/^[^a-z]+|[^a-z]+$/g,"").replace(/\s+/g,"")==="ping";return{success:p,message:p?"API key is valid and working correctly":"API responded but returned unexpected content",details:{model:n.model,responseTime:l,inputTokens:(i=n.usage)==null?void 0:i.input_tokens,outputTokens:(t=n.usage)==null?void 0:t.output_tokens}}}catch(s){let n=Date.now()-e;return this.parseTestError(s,n)}}parseTestError(r,e){let i={success:!1,details:{responseTime:e}};if(r instanceof Error){let t=r.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?{...i,message:"API key is invalid or unauthorized",error:"UNAUTHORIZED"}:t.includes("429")||t.includes("rate limit")?{...i,message:"Rate limit exceeded. Please try again later.",error:"RATE_LIMITED"}:t.includes("403")||t.includes("forbidden")?{...i,message:"API access forbidden. Check your account status and billing.",error:"FORBIDDEN"}:t.includes("400")||t.includes("bad request")?{...i,message:"Invalid request format. This may indicate a plugin bug.",error:"BAD_REQUEST"}:t.includes("500")||t.includes("internal server")?{...i,message:"Anthropic server error. Please try again later.",error:"SERVER_ERROR"}:t.includes("network")||t.includes("fetch")?{...i,message:"Network error. Check your internet connection.",error:"NETWORK_ERROR"}:{...i,message:`API test failed: ${r.message}`,error:"UNKNOWN_ERROR"}}return{...i,message:"Unknown error occurred during API test",error:"UNKNOWN_ERROR"}}};var T=class{constructor(r){this.cache=new Map;this.inFlight=new Map;this.cacheExpiryMs=10*60*1e3;this.client=new A(r.apiKey)}get anthropicClient(){return this.client}async generateTimedPrompts(r){return this.generatePrompts(r.timedCount,r.model,r.systemPrompt,r.timedExamplePrompt,"timed")}async generateNotePrompts(r){return this.generatePrompts(r.noteCount,r.model,r.systemPrompt,r.freewritingExamplePrompt,"note")}updateApiKey(r){this.client.updateApiKey(r),this.clearCache()}clearCache(){this.cache.clear()}async generatePrompts(r,e,i,t,s){if(!this.client.validateApiKey())throw new P.Notice("Please configure your Anthropic API key in settings"),new Error("API key not configured");let n=this.createCacheKey(r,e,i,t,s),l=this.getCachedPrompts(n);if(l)return l.map(a=>a.text);let c=this.inFlight.get(n);if(c)return c;try{new P.Notice("Generating prompts...");let a=this.client.generatePrompts(r,e,i,t,s);this.inFlight.set(n,a);let p=await a;p.length>r&&(p=p.slice(0,r));let h=p.map(d=>({text:d,timestamp:new Date}));return this.cache.set(n,h),new P.Notice(`Generated ${p.length} writing prompts`),p}catch(a){throw console.error("Error in PromptGeneratorService:",a),a instanceof Error?new P.Notice(`Error generating prompts: ${a.message}`):new P.Notice("Unknown error occurred while generating prompts"),a}finally{this.inFlight.delete(n)}}createCacheKey(r,e,i,t,s){let n={count:r,model:e,systemPrompt:i.trim(),examplePrompt:t.trim(),type:s};return JSON.stringify(n)}getCachedPrompts(r){let e=this.cache.get(r);if(!e)return null;if(e.length===0)return this.cache.delete(r),null;let i=new Date().getTime(),t=e[0].timestamp.getTime();return i-t>this.cacheExpiryMs?(this.cache.delete(r),null):e}validateSettings(r){let e=[];return(!r.apiKey||r.apiKey.trim().length===0)&&e.push("API key is required"),(!r.model||r.model.trim().length===0)&&e.push("Claude model is required"),(r.timedCount<1||r.timedCount>50)&&e.push("Timed count must be between 1 and 50"),(r.delaySeconds<1||r.delaySeconds>300)&&e.push("Delay seconds must be between 1 and 300"),(r.noteCount<1||r.noteCount>20)&&e.push("Note count must be between 1 and 20"),{isValid:e.length===0,errors:e}}};var F=require("obsidian");var _=["claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001","claude-opus-4-1-20250805","claude-sonnet-4-20250514","claude-3-7-sonnet-latest","claude-opus-4-20250514","claude-3-5-haiku-latest","claude-3-haiku-20240307"];var M=class{constructor(r){this.modelCache=null;this.CACHE_TTL_MS=24*60*60*1e3;this.hasShownFallbackNotice=!1;this.inFlight=null;this.anthropicClient=r}async getAvailableModels(){return this.isCacheValid()&&this.modelCache?this.formatModels(this.modelCache.models):this.anthropicClient.validateApiKey()?this.fetchWithDeduplication("Could not fetch latest models from API. Using default model list."):this.getFallbackModels()}async refreshModels(){return this.anthropicClient.validateApiKey()?this.fetchWithDeduplication("Fetching current models failed. Using hardcoded fallback list."):this.getFallbackModels()}loadCache(r){this.modelCache=r}getCache(){return this.modelCache}clearCache(){this.modelCache=null,this.hasShownFallbackNotice=!1}async fetchWithDeduplication(r){var e;this.inFlight||(this.inFlight=(async()=>{let i=await this.anthropicClient.fetchModels();return this.updateCache(i.data),this.hasShownFallbackNotice=!1,this.formatModels(i.data)})().finally(()=>{this.inFlight=null}));try{return await this.inFlight}catch(i){return console.error("Failed to fetch models from API:",i),this.hasShownFallbackNotice||(new F.Notice(r),this.hasShownFallbackNotice=!0),(e=this.getStaleCacheModels())!=null?e:this.getFallbackModels()}}isCacheValid(){return this.modelCache?Date.now()-this.modelCache.fetchedAt({id:e.id,displayName:e.display_name||e.id})).sort((e,i)=>e.displayName.localeCompare(i.displayName))}getFallbackModels(){return _.map(r=>({id:r,displayName:r})).sort((r,e)=>r.displayName.localeCompare(e.displayName))}};var S=require("obsidian"),I=class{constructor(r){this.promptGenerator=r;this.activeInterval=null;this.promptQueue=[];this.currentIndex=0;this.inProgress=!1}async execute(r){if(this.inProgress){new S.Notice("Timed prompts are already being generated. Please wait.");return}this.inProgress=!0,this.stop();try{let e=await this.promptGenerator.generateTimedPrompts(r);if(e.length===0){new S.Notice("No prompts were generated");return}this.promptQueue=e,this.currentIndex=0,this.showCurrentPrompt(r.delaySeconds),e.length>1&&this.startInterval(r.delaySeconds)}catch(e){console.error("Error executing timed prompts command:",e)}finally{this.inProgress=!1}}stop(){this.activeInterval!==null&&(clearInterval(this.activeInterval),this.activeInterval=null),this.promptQueue=[],this.currentIndex=0}isRunning(){return this.activeInterval!==null}startInterval(r){this.activeInterval=window.setInterval(()=>{this.currentIndex++,this.currentIndex=1e3?s-500:Math.max(300,Math.min(900,s-100)),c=new S.Notice(`Writing Prompt ${i}/${t}: ${e}`,n).noticeEl;c&&c.addClass("freewriting-prompt-notice")}}getStatus(){let r=this.promptQueue.length,e=r===0?0:Math.min(this.currentIndex+1,r);return{isRunning:this.isRunning(),currentPrompt:e,totalPrompts:r}}getRemainingPrompts(){return this.currentIndex>=this.promptQueue.length?[]:this.promptQueue.slice(this.currentIndex+1)}};var C=require("obsidian"),v=class{constructor(r){this.promptGenerator=r}async execute(r,e,i){if(!v.canExecute(e,i)){new C.Notice("No active note found. Please open a note first.");return}try{let t=await this.promptGenerator.generateNotePrompts(r);if(t.length===0){new C.Notice("No prompts were generated");return}this.insertPromptsIntoNote(e,t),new C.Notice(`Added ${t.length} writing prompts to your note`)}catch(t){console.error("Error executing note prompts command:",t)}}insertPromptsIntoNote(r,e){var N;let i=r.getCursor("from"),t=r.getCursor("to");(i.line!==t.line||i.ch!==t.ch)&&r.setCursor(i);let n=r.getCursor(),l=(N=r.getLine(n.line))!=null?N:"",c=n.ch>0&&l.slice(0,n.ch).trim().length>0,a=n.ch0,p=this.formatPrompts(e),h=r.lastLine(),d="";c&&(d+=` `),d+=p,(a||n.line{let n=String(t).replace(/\s+/g," ").trim();i+=`${s+1}. ${n} `}),i}static canExecute(r,e){return!!(r&&e&&e.file)}static getExecutionContext(r){let e=r.workspace.getActiveViewOfType(C.MarkdownView);return e?{editor:e.editor,view:e}:{editor:null,view:null}}};var D=class extends f.Plugin{async onload(){let e;try{let i=await this.loadData();if(i){let{modelCache:t,...s}=i;e=t,this.settings=Object.assign({},x,s)}else this.settings={...x},e=void 0}catch(i){console.error("Failed to load settings; using defaults.",i),this.settings={...x},e=void 0}this.lastApiKey=this.settings.apiKey,this.promptGenerator=new T(this.settings),this.modelService=new M(this.promptGenerator.anthropicClient),this.timedCommand=new I(this.promptGenerator),this.noteCommand=new v(this.promptGenerator),e&&this.modelService.loadCache(e),this.registerCommands(),this.addSettingTab(new b(this.app,this))}onunload(){this.timedCommand&&this.timedCommand.stop(),this.promptGenerator&&this.promptGenerator.clearCache()}async saveSettings(){var i,t;let e={...this.settings,modelCache:((i=this.modelService)==null?void 0:i.getCache())||void 0};await this.saveData(e),this.promptGenerator&&this.lastApiKey!==this.settings.apiKey&&(this.promptGenerator.updateApiKey(this.settings.apiKey),this.lastApiKey=this.settings.apiKey,(t=this.modelService)==null||t.clearCache())}registerCommands(){this.addCommand({id:"timed-prompts",name:"Show Timed Prompts",callback:async()=>{await this.executeTimedPrompts()}}),this.addCommand({id:"note-prompts",name:"Add Note Prompts",editorCallback:async(e,i)=>{await this.executeNotePrompts(e,i)}}),this.addCommand({id:"stop-timed-prompts",name:"Stop Timed Prompts",callback:()=>{this.stopTimedPrompts()}})}async executeTimedPrompts(){if(this.timedCommand.isRunning()){new f.Notice('Timed prompts are already running. Use "Stop Timed Prompts" to stop them first.');return}let e=this.promptGenerator.validateSettings(this.settings);if(!e.isValid){new f.Notice(`Settings validation failed: ${e.errors.join(", ")}`);return}try{await this.timedCommand.execute(this.settings)}catch(i){console.error("Error executing timed prompts:",i)}}async executeNotePrompts(e,i){if(!v.canExecute(e,i)){new f.Notice("Please open a note and place your cursor where you want to insert prompts.");return}let t=this.promptGenerator.validateSettings(this.settings);if(!t.isValid){new f.Notice(`Settings validation failed: ${t.errors.join(", ")}`);return}try{await this.noteCommand.execute(this.settings,e,i)}catch(s){console.error("Error executing note prompts:",s)}}stopTimedPrompts(){this.timedCommand.isRunning()?(this.timedCommand.stop(),new f.Notice("Timed prompts stopped")):new f.Notice("No timed prompts are currently running")}getTimedStatus(){return this.timedCommand.getStatus()}};