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