/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var T=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var R=(m,t)=>{for(var e in t)T(m,e,{get:t[e],enumerable:!0})},k=(m,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of I(t))!N.call(m,r)&&r!==e&&T(m,r,{get:()=>t[r],enumerable:!(n=b(t,r))||n.enumerable});return m};var M=m=>k(T({},"__esModule",{value:!0}),m);var D={};R(D,{default:()=>x});module.exports=M(D);var c=require("obsidian");var a=require("obsidian");var C=["claude-opus-4-1-20250805","claude-opus-4-20250514","claude-sonnet-4-20250514","claude-3-7-sonnet-latest","claude-3-5-haiku-latest","claude-3-haiku-20240307"];var A={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."},g=class extends a.PluginSettingTab{constructor(e,n){super(e,n);this.plugin=n}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"Freewriting Prompts"}),e.createEl("h3",{text:"API Configuration"}),new a.Setting(e).setName("Anthropic API Key").setDesc("Your Anthropic API key for Claude. Get one at https://console.anthropic.com/").addText(n=>n.setPlaceholder("sk-ant-...").setValue(this.plugin.settings.apiKey).onChange(async r=>{this.plugin.settings.apiKey=r,await this.plugin.saveSettings(),this.plugin.promptGenerator.updateApiKey(r)})).then(n=>{var r;(r=n.controlEl.querySelector("input"))==null||r.setAttribute("type","password")}),new a.Setting(e).setName("Test API Key").setDesc("Test your API key to verify it works correctly").addButton(n=>n.setButtonText("Test Connection").onClick(async()=>{await this.testApiKey(n)})),new a.Setting(e).setName("Claude Model").setDesc("Which Claude model to use for generating prompts").addDropdown(n=>{C.forEach(r=>{n.addOption(r,r)}),n.setValue(this.plugin.settings.model).onChange(async r=>{this.plugin.settings.model=r,await this.plugin.saveSettings()})}),e.createEl("h3",{text:"Command Configuration"}),new a.Setting(e).setName("Timed Prompts Count").setDesc("Number of prompts to generate for timed notifications (1-50)").addText(n=>n.setPlaceholder("10").setValue(this.plugin.settings.timedCount.toString()).onChange(async r=>{let s=parseInt(r);!isNaN(s)&&s>=1&&s<=50&&(this.plugin.settings.timedCount=s,await this.plugin.saveSettings())})),new a.Setting(e).setName("Delay Between Prompts").setDesc("Seconds to wait between each timed prompt notification (1-300)").addText(n=>n.setPlaceholder("6").setValue(this.plugin.settings.delaySeconds.toString()).onChange(async r=>{let s=parseInt(r);!isNaN(s)&&s>=1&&s<=300&&(this.plugin.settings.delaySeconds=s,await this.plugin.saveSettings())})),new a.Setting(e).setName("Note Prompts Count").setDesc("Number of prompts to append to the current note (1-20)").addText(n=>n.setPlaceholder("3").setValue(this.plugin.settings.noteCount.toString()).onChange(async r=>{let s=parseInt(r);!isNaN(s)&&s>=1&&s<=20&&(this.plugin.settings.noteCount=s,await this.plugin.saveSettings())})),e.createEl("h3",{text:"Prompt Customization"}),new a.Setting(e).setName("System Prompt").setDesc("Instructions for the AI on how to generate prompts").addTextArea(n=>n.setPlaceholder("You are a creative writing assistant...").setValue(this.plugin.settings.systemPrompt).onChange(async r=>{this.plugin.settings.systemPrompt=r,await this.plugin.saveSettings()})).then(n=>{var r;(r=n.controlEl.querySelector("textarea"))==null||r.setAttribute("rows","3")}),new a.Setting(e).setName("Timed Prompts Example").setDesc("Example prompt to guide the style for timed notifications").addTextArea(n=>n.setPlaceholder("Write about a character who...").setValue(this.plugin.settings.timedExamplePrompt).onChange(async r=>{this.plugin.settings.timedExamplePrompt=r,await this.plugin.saveSettings()})).then(n=>{var r;(r=n.controlEl.querySelector("textarea"))==null||r.setAttribute("rows","2")}),new a.Setting(e).setName("Note Prompts Example").setDesc("Example prompt to guide the style for note prompts").addTextArea(n=>n.setPlaceholder("Describe a world where...").setValue(this.plugin.settings.freewritingExamplePrompt).onChange(async r=>{this.plugin.settings.freewritingExamplePrompt=r,await this.plugin.saveSettings()})).then(n=>{var r;(r=n.controlEl.querySelector("textarea"))==null||r.setAttribute("rows","2")}),e.createEl("h3",{text:"Actions"}),new a.Setting(e).setName("Clear Cache").setDesc("Clear the cached prompts to force regeneration").addButton(n=>n.setButtonText("Clear Cache").onClick(()=>{this.plugin.promptGenerator.clearCache();let r=new a.Notice("Cache cleared");setTimeout(()=>r.hide(),2e3)}))}async testApiKey(e){let n=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 o=s.details,i=o?` Details: \u2022 Model: ${o.model} \u2022 Response time: ${o.responseTime}ms \u2022 Input tokens: ${o.inputTokens||"N/A"} \u2022 Output tokens: ${o.outputTokens||"N/A"}`:"";new a.Notice(`\u2705 ${s.message}${i}`,8e3)}else{let o=s.details?` Troubleshooting: \u2022 Response time: ${s.details.responseTime}ms \u2022 Error type: ${s.error}`:"";new a.Notice(`\u274C ${s.message}${o}`,1e4)}}catch(r){console.error("Unexpected error during API test:",r),new a.Notice("\u274C Unexpected error during API test. Check console for details.",5e3)}finally{e.setButtonText(n),e.setDisabled(!1)}}};var u=require("obsidian");var P=require("obsidian"),w=class{constructor(t){this.baseUrl="https://api.anthropic.com/v1/messages";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=t}async generatePrompts(t,e,n,r,s){if(!this.apiKey)throw new Error("API key is required");try{let o=this.createUserMessage(t,r),i=n;s==="timed"&&(i+=this.TIMED_PROMPT_MODIFIER),i+=this.SYSTEM_PROMPT_SUFFIX;let p={model:e,max_tokens:1e3,messages:[{role:"user",content:o}],system:i},l=await this.makeRequest(p);return this.parsePromptsFromResponse(l)}catch(o){throw console.error("Error generating prompts:",o),o instanceof Error?(new P.Notice(`Failed to generate prompts: ${o.message}`),o):new Error("Unknown error occurred while generating prompts")}}createUserMessage(t,e){let n=`Generate exactly ${t} creative writing prompts. Return ONLY the numbered prompts with no additional text or commentary.`;return e.trim()?`${n} Example style: "${e}" Provide ${t} similar prompts in this exact format: 1. [prompt] 2. [prompt] (etc.)`:`${n} Provide ${t} diverse writing prompts in this exact format: 1. [prompt] 2. [prompt] (etc.)`}async makeRequest(t){try{let e=await(0,P.requestUrl)({url:this.baseUrl,method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify(t)});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(t){if(!t.content||t.content.length===0)throw new Error("No content received from API");let n=t.content[0].text.split(` `).map(s=>s.trim()).filter(s=>s.length>0),r=[];for(let s of n){let o=s.replace(/^\d+\.\s*/,"").trim();o.length>0&&r.push(o)}if(r.length===0)throw new Error("No valid prompts found in API response");return r}updateApiKey(t){this.apiKey=t}validateApiKey(){return!!(this.apiKey&&this.apiKey.trim().length>0)}async testApiKey(t){var n,r;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:t,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."},o=await this.makeRequest(s),i=Date.now()-e;return{success:!0,message:"API key is valid and working correctly",details:{model:o.model,responseTime:i,inputTokens:(n=o.usage)==null?void 0:n.input_tokens,outputTokens:(r=o.usage)==null?void 0:r.output_tokens}}}catch(s){let o=Date.now()-e;return this.parseTestError(s,o)}}parseTestError(t,e){let n={success:!1,details:{responseTime:e}};if(t instanceof Error){let r=t.message.toLowerCase();return r.includes("401")||r.includes("unauthorized")?{...n,message:"API key is invalid or unauthorized",error:"UNAUTHORIZED"}:r.includes("429")||r.includes("rate limit")?{...n,message:"Rate limit exceeded. Please try again later.",error:"RATE_LIMITED"}:r.includes("403")||r.includes("forbidden")?{...n,message:"API access forbidden. Check your account status and billing.",error:"FORBIDDEN"}:r.includes("400")||r.includes("bad request")?{...n,message:"Invalid request format. This may indicate a plugin bug.",error:"BAD_REQUEST"}:r.includes("500")||r.includes("internal server")?{...n,message:"Anthropic server error. Please try again later.",error:"SERVER_ERROR"}:r.includes("network")||r.includes("fetch")?{...n,message:"Network error. Check your internet connection.",error:"NETWORK_ERROR"}:{...n,message:`API test failed: ${t.message}`,error:"UNKNOWN_ERROR"}}return{...n,message:"Unknown error occurred during API test",error:"UNKNOWN_ERROR"}}};var y=class{constructor(t){this.cache=new Map;this.cacheExpiryMs=10*60*1e3;this.client=new w(t.apiKey)}get anthropicClient(){return this.client}async generateTimedPrompts(t){return this.generatePrompts(t.timedCount,t.model,t.systemPrompt,t.timedExamplePrompt,"timed")}async generateNotePrompts(t){return this.generatePrompts(t.noteCount,t.model,t.systemPrompt,t.freewritingExamplePrompt,"note")}updateApiKey(t){this.client.updateApiKey(t),this.clearCache()}clearCache(){this.cache.clear()}async generatePrompts(t,e,n,r,s){if(!this.client.validateApiKey())throw new u.Notice("Please configure your Anthropic API key in settings"),new Error("API key not configured");let o=this.createCacheKey(t,e,n,r,s),i=this.getCachedPrompts(o);if(i)return i.map(p=>p.text);try{new u.Notice("Generating prompts...");let p=await this.client.generatePrompts(t,e,n,r,s),l=p.map(E=>({text:E,timestamp:new Date}));return this.cache.set(o,l),new u.Notice(`Generated ${p.length} writing prompts`),p}catch(p){throw console.error("Error in PromptGeneratorService:",p),p instanceof Error?new u.Notice(`Error generating prompts: ${p.message}`):new u.Notice("Unknown error occurred while generating prompts"),p}}createCacheKey(t,e,n,r,s){let o={count:t,model:e,systemPrompt:n.trim(),examplePrompt:r.trim(),type:s};return JSON.stringify(o)}getCachedPrompts(t){let e=this.cache.get(t);if(!e)return null;let n=new Date().getTime(),r=e[0].timestamp.getTime();return n-r>this.cacheExpiryMs?(this.cache.delete(t),null):e}validateSettings(t){let e=[];return(!t.apiKey||t.apiKey.trim().length===0)&&e.push("API key is required"),(t.timedCount<1||t.timedCount>50)&&e.push("Timed count must be between 1 and 50"),(t.delaySeconds<1||t.delaySeconds>300)&&e.push("Delay seconds must be between 1 and 300"),(t.noteCount<1||t.noteCount>20)&&e.push("Note count must be between 1 and 20"),{isValid:e.length===0,errors:e}}};var f=require("obsidian"),v=class{constructor(t){this.promptGenerator=t;this.activeInterval=null;this.promptQueue=[];this.currentIndex=0}async execute(t){this.stop();try{let e=await this.promptGenerator.generateTimedPrompts(t);if(e.length===0){new f.Notice("No prompts were generated");return}this.promptQueue=e,this.currentIndex=0,this.showCurrentPrompt(t.delaySeconds),e.length>1&&this.startInterval(t.delaySeconds)}catch(e){console.error("Error executing timed prompts command:",e)}}stop(){this.activeInterval!==null&&(clearInterval(this.activeInterval),this.activeInterval=null),this.promptQueue=[],this.currentIndex=0}isRunning(){return this.activeInterval!==null}startInterval(t){this.activeInterval=window.setInterval(()=>{this.currentIndex++,this.currentIndex=this.promptQueue.length?[]:this.promptQueue.slice(this.currentIndex+1)}};var d=require("obsidian"),h=class{constructor(t){this.promptGenerator=t}async execute(t,e,n){if(!e||!n){new d.Notice("No active note found. Please open a note first.");return}try{let r=await this.promptGenerator.generateNotePrompts(t);if(r.length===0){new d.Notice("No prompts were generated");return}this.insertPromptsIntoNote(e,r),new d.Notice(`Added ${r.length} writing prompts to your note`)}catch(r){console.error("Error executing note prompts command:",r)}}insertPromptsIntoNote(t,e){let n=t.getCursor(),s=t.getLine(n.line).trim().length>0,o=this.formatPrompts(e),i="";s&&(i+=` `),i+=o;let p=t.lastLine();n.line{n+=`${s+1}. ${r} `}),n}static canExecute(t,e){return!!(t&&e&&e.file)}static getExecutionContext(t){let e=t.workspace.getActiveViewOfType(d.MarkdownView);return e?{editor:e.editor,view:e}:{editor:null,view:null}}};var x=class extends c.Plugin{async onload(){await this.loadSettings(),this.promptGenerator=new y(this.settings),this.timedCommand=new v(this.promptGenerator),this.noteCommand=new h(this.promptGenerator),this.registerCommands(),this.addSettingTab(new g(this.app,this))}onunload(){this.timedCommand&&this.timedCommand.stop(),this.promptGenerator&&this.promptGenerator.clearCache()}async loadSettings(){this.settings=Object.assign({},A,await this.loadData())}async saveSettings(){await this.saveData(this.settings),this.promptGenerator&&this.promptGenerator.updateApiKey(this.settings.apiKey)}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,n)=>{await this.executeNotePrompts(e,n)}}),this.addCommand({id:"stop-timed-prompts",name:"Stop Timed Prompts",callback:()=>{this.stopTimedPrompts()}})}async executeTimedPrompts(){if(this.timedCommand.isRunning()){new c.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 c.Notice(`Settings validation failed: ${e.errors.join(", ")}`);return}try{await this.timedCommand.execute(this.settings)}catch(n){console.error("Error executing timed prompts:",n)}}async executeNotePrompts(e,n){if(!h.canExecute(e,n)){new c.Notice("Please open a note and place your cursor where you want to insert prompts.");return}let r=this.promptGenerator.validateSettings(this.settings);if(!r.isValid){new c.Notice(`Settings validation failed: ${r.errors.join(", ")}`);return}try{await this.noteCommand.execute(this.settings,e,n)}catch(s){console.error("Error executing note prompts:",s)}}stopTimedPrompts(){this.timedCommand.isRunning()?(this.timedCommand.stop(),new c.Notice("Timed prompts stopped")):new c.Notice("No timed prompts are currently running")}getTimedStatus(){return this.timedCommand.getStatus()}};