You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
3.4 MiB

2 years ago
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
2 months ago
var eV=Object.create;var Ic=Object.defineProperty;var tV=Object.getOwnPropertyDescriptor;var wV=Object.getOwnPropertyNames;var uV=Object.getPrototypeOf,yV=Object.prototype.hasOwnProperty;var oV=(c,G,I)=>G in c?Ic(c,G,{enumerable:!0,configurable:!0,writable:!0,value:I}):c[G]=I;var AV=(c,G)=>()=>(G||c((G={exports:{}}).exports,G),G.exports),zV=(c,G)=>{for(var I in G)Ic(c,I,{get:G[I],enumerable:!0})},AW=(c,G,I,l)=>{if(G&&typeof G=="object"||typeof G=="function")for(let b of wV(G))!yV.call(c,b)&&b!==I&&Ic(c,b,{get:()=>G[b],enumerable:!(l=tV(G,b))||l.enumerable});return c};var zW=(c,G,I)=>(I=c!=null?eV(uV(c)):{},AW(G||!c||!c.__esModule?Ic(I,"default",{value:c,enumerable:!0}):I,c)),gV=c=>AW(Ic({},"__esModule",{value:!0}),c);var G2=(c,G,I)=>(oV(c,typeof G!="symbol"?G+"":G,I),I);var v0=AV(T1=>{"use strict";T1.byteLength=nN;T1.toByteArray=EN;T1.fromByteArray=vN;var Ul=[],pl=[],pN=typeof Uint8Array<"u"?Uint8Array:Array,PZ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(K2=0,Q0=PZ.length;K2<Q0;++K2)Ul[K2]=PZ[K2],pl[PZ.charCodeAt(K2)]=K2;var K2,Q0;pl["-".charCodeAt(0)]=62;pl["_".charCodeAt(0)]=63;function J0(c){var G=c.length;if(G%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var I=c.indexOf("=");I===-1&&(I=G);var l=I===G?0:4-I%4;return[I,l]}function nN(c){var G=J0(c),I=G[0],l=G[1];return(I+l)*3/4-l}function sN(c,G,I){return(G+I)*3/4-I}function EN(c){var G,I=J0(c),l=I[0],b=I[1],Z=new pN(sN(c,l,b)),W=0,d=b>0?l-4:l,V;for(V=0;V<d;V+=4)G=pl[c.charCodeAt(V)]<<18|pl[c.charCodeAt(V+1)]<<12|pl[c.charCodeAt(V+2)]<<6|pl[c.charCodeAt(V+3)],Z[W++]=G>>16&255,Z[W++]=G>>8&255,Z[W++]=G&255;return b===2&&(G=pl[c.charCodeAt(V)]<<2|pl[c.charCodeAt(V+1)]>>4,Z[W++]=G&255),b===1&&(G=pl[c.charCodeAt(V)]<<10|pl[c.charCodeAt(V+1)]<<4|pl[c.charCodeAt(V+2)]>>2,Z[W++]=G>>8&255,Z[W++]=G&255),Z}function QN(c){return Ul[c>>18&63]+Ul[c>>12&63]+Ul[c>>6&63]+Ul[c&63]}function JN(c,G,I){for(var l,b=[],Z=G;Z<I;Z+=3)l=(c[Z]<<16&16711680)+(c[Z+1]<<8&65280)+(c[Z+2]&255),b.push(QN(l));return b.join("")}function vN(c){for(var G,I=c.length,l=I%3,b=[],Z=16383,W=0,d=I-l;W<d;W+=Z)b.push(JN(c,W,W+Z>d?d:W+Z));return l===1?(G=c[I-1],b.push(Ul[G>>2]+Ul[G<<4&63]+"==")):l===2&&(G=(c[I-2]<<8)+c[I-1],b.push(Ul[G>>10]+Ul[G>>4&63]+Ul[G<<2&63]+"=")),b.join("")}});var x5={};zV(x5,{default:()=>GI});module.exports=gV(x5);var pV=require("obsidian");var Al=require("obsidian");function DI(){}function El(c,G){for(let I in G)c[I]=G[I];return c}function zb(c){return c()}function gW(){return Object.create(null)}function WI(c){c.forEach(zb)}function VI(c){return typeof c=="function"}function _(c,G){return c!=c?G==G:c!==G||c&&typeof c=="object"||typeof c=="function"}function iW(c){return Object.keys(c).length===0}function Uc(c,G,I,l){if(c){let b=rW(c,G,I,l);return c[0](b)}}function rW(c,G,I,l){return c[1]&&l?El(I.ctx.slice(),c[1](l(G))):I.ctx}function Mc(c,G,I,l){if(c[2]&&l){let b=c[2](l(I));if(G.dirty===void 0)return b;if(typeof b=="object"){let Z=[],W=Math.max(G.dirty.length,b.length);for(let d=0;d<W;d+=1)Z[d]=G.dirty[d]|b[d];return Z}return G.dirty|b}return G.dirty}function Bc(c,G,I,l,b,Z){if(b){let W=rW(G,I,l,Z);c.p(W,b)}}function Lc(c){if(c.ctx.length>32){let G=[],I=c.ctx.length/32;for(let l=0;l<I;l++)G[l]=-1;return G}return-1}function jc(c){let G={};for(let I in c)I[0]!=="$"&&(G[I]=c[I]);return G}function ZG(c,G){let I={};G=new Set(G);for(let l in c)!G.has(l)&&l[0]!=="$"&&(I[l]=c[l]);return I}function fc(c){return c&&VI(c.destroy)?c.destroy:DI}var kW=typeof window<"u"?window:typeof globalThis<"u"?globalThis:global,Gc=class{constructor(G){this.options=G,this._listeners="WeakMap"in kW?new WeakMap:void 0}observe(G,I){return this._listeners.set(G,I),this._getObserver().observe(G,this.options),()=>{this._listeners.delete(G),this._observer.unobserve(G)}}_getObserver(){var G;return(G=this._observer)!==null&&G!==void 0?G:this._observer=new ResizeObserver(I=>{var l;for(let b of I)Gc.entries.set(b.target,b),(l=this._listeners.get(b.target))===null||l===void 0||l(b)})}};Gc.entries="WeakMap"in kW?new WeakMap:void 0;var xW=!1;function iV(){xW=!0}function rV(){x
<span class="suggestion-main-text">${I}</span>
2 years ago
<span class="suggestion-sub-text">Unknown</span>
2 months ago
`;else switch(b.type){case 0:l.innerHTML=`
<span class="suggestion-main-text">${b?.file?.basename}</span>
<span class="suggestion-sub-text">${b?.file?.path}</span>
`;break;case 1:l.innerHTML=`
<span class="suggestion-main-text">${I}</span>
<span class="suggestion-sub-text">${b?.file?.path}</span>
`;break;case 2:l.innerHTML=`
<span class="suggestion-main-text">${I}</span>
<span class="suggestion-sub-text">Unresolved link</span>
1 week ago
`;break;default:break}l.classList.add("qaFileSuggestionItem")}selectSuggestion(I){if(this.inputEl.selectionStart===null)return;let l=this.inputEl.selectionStart,b=this.lastInput.length,Z=this.inputEl.value,W=0,d=this.fileMap.get(I);d!==void 0&&d.file!==void 0?d.type===0?W=this.makeLinkObsidianMethod(d.file,Z,l,b):d.type===1&&(W=this.makeLinkObsidianMethod(d.file,Z,l,b,I)):W=this.makeLinkManually(Z,I.replace(/.md$/,""),l,b),this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(W,W)}makeLinkObsidianMethod(I,l,b,Z,W){let d=this.app.vault.getAbstractFileByPath(I.path),V=this.app.fileManager.generateMarkdownLink(d,"","",W??"");return this.inputEl.value=this.getNewInputValueForFileLink(l,V,b,Z),b-Z+V.length+2}makeLinkManually(I,l,b,Z){return this.inputEl.value=this.getNewInputValueForFileName(I,l,b,Z),b-Z+l.length+2}getNewInputValueForFileLink(I,l,b,Z){return`${I.substr(0,b-Z-2)}${l}${I.substr(b)}`}getNewInputValueForFileName(I,l,b,Z){return`${I.substr(0,b-Z)}${l}]]${I.substr(b)}`}getUnresolvedLinkNames(I){let l=I.metadataCache.unresolvedLinks,b=new Set;for(let Z in l)for(let W in l[Z])b.add(W);return Array.from(b)}};var tG=class extends qI{constructor(I,l){super(I,l);this.app=I;this.inputEl=l;this.lastInput="";this.tags=Object.keys(I.metadataCache.getTags())}getSuggestions(I){if(this.inputEl.selectionStart===null)return[];let l=this.inputEl.selectionStart,b=I.substr(0,l),Z=Ud.exec(b);if(!Z)return[];let W=Z[1];this.lastInput=W;let d=this.tags.filter(m=>m.toLowerCase().contains(W.toLowerCase()));return new Zl(d,{findAllMatches:!0,threshold:.8}).search(this.lastInput).map(m=>m.item)}renderSuggestion(I,l){l.setText(I)}selectSuggestion(I){if(!this.inputEl.selectionStart)return;let l=this.inputEl.selectionStart,b=this.lastInput.length,Z=this.inputEl.value,W=0;this.inputEl.value=this.getNewInputValueForTag(Z,I,l,b),W=l-b+I.length-1,this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(W,W)}getNewInputValueForTag(I,l,b,Z){return`${I.substr(0,b-Z-1)}${l}${I.substr(b)}`}};var dI=class extends wG.Modal{constructor(I,l,b,Z){super(I);this.header=l;this.didSubmit=!1;this.submitClickCallback=I=>this.submit();this.cancelClickCallback=I=>this.cancel();this.submitEnterCallback=I=>{!I.isComposing&&I.key==="Enter"&&(I.preventDefault(),this.submit())};this.placeholder=b??"",this.input=Z??"",this.waitForClose=new Promise((W,d)=>{this.resolvePromise=W,this.rejectPromise=d}),this.display(),this.open(),this.fileSuggester=new eG(I,this.inputComponent.inputEl),this.tagSuggester=new tG(I,this.inputComponent.inputEl)}static Prompt(I,l,b,Z){return new dI(I,l,b,Z).waitForClose}display(){this.containerEl.addClass("quickAddModal","qaInputPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.header;let I=this.contentEl.createDiv();this.inputComponent=this.createInputField(I,this.placeholder,this.input),this.createButtonBar(I)}createInputField(I,l,b){let Z=new wG.TextComponent(I);return Z.inputEl.style.width="100%",Z.setPlaceholder(l??"").setValue(b??"").onChange(W=>this.input=W).inputEl.addEventListener("keydown",this.submitEnterCallback),Z}createButton(I,l,b){let Z=new wG.ButtonComponent(I);return Z.setButtonText(l).onClick(b),Z}createButtonBar(I){let l=I.createDiv();this.createButton(l,"Ok",this.submitClickCallback).setCta().buttonEl.style.marginRight="0",this.createButton(l,"Cancel",this.cancelClickCallback),l.style.display="flex",l.style.flexDirection="row-reverse",l.style.justifyContent="flex-start",l.style.marginTop="1rem",l.style.gap="0.5rem"}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}resolveInput(){this.didSubmit?this.resolvePromise(this.input):this.rejectPromise("No input given.")}removeInputListener(){this.inputComponent.inputEl.removeEventListener("keydown",this.submitEnterCallback)}onOpen(){super.onOpen(),this.inputComponent.inputEl.focus(),this.inputComponent.inputEl.select()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListener()}};var uG=class{register(G){return uG.loggers.push(G),this}logError(G){uG.loggers.forEach(I=>I.logError(G))}logWarning(
2 months ago
})`)(l,Z,b);let V=b.default||Z.exports;if(!V)return;let a=V,{memberAccess:m}=uc(c.name);if(m&&m.length>0){let N;for(;N=m.shift();)a=a[N]}return a}}function Y0(c,G){let I=structuredClone(c);for(let l of G)delete I[l];return I}function H0(c){let G=Z=>Z.type==="Template",I=Z=>Z.type==="Macro",l=Z=>Z.type==="Capture",b=Z=>Z.type==="Multi";return G(c)||I(c)||l(c)||b(c)}function R0(c){let G=app.vault.getAbstractFileByPath(c);return!!G&&G instanceof C2.TFolder}function AG(c){return app.vault.getMarkdownFiles().filter(G=>G.path.startsWith(c))}function RN(c){let G=c.frontmatter;if(!G)return[];let I=Object.entries(G);if(!I.length)return[];let l=I.filter(([Z,W])=>{let d=Z.toLowerCase();return d==="tags"||d==="tag"});return l?l.flatMap(([Z,W])=>{if(typeof W=="string")return W.split(/,|\s+/).map(d=>d.trim());if(Array.isArray(W))return W}).filter(Z=>!!Z):[]}function XN(c){let G=app.metadataCache.getFileCache(c);if(!G)return[];let I=[];return G.frontmatter&&I.push(...RN(G)),G.tags&&Array.isArray(G.tags)&&I.push(...G.tags.map(l=>l.tag.replace(/^\#/,""))),I}function X0(c){let G=c.replace(/^\#/,"");return app.vault.getMarkdownFiles().filter(I=>XN(I).includes(G))}var F2=class{constructor(){this.variables=new Map}replacer(G,I,l){return G.replace(I,function(){return l})}replaceDateInString(G){let I=G;for(;p1.test(I);){let l=p1.exec(I),b;if(l&&l[1]){let Z=l[1].replace("+","").trim();wZ.test(Z)&&(b=parseInt(Z))}I=this.replacer(I,p1,ql({offset:b}))}for(;n1.test(I);){let l=n1.exec(I);if(!l)throw new Error("unable to parse date");let b=l[1],Z;if(l[2]){let W=l[2].replace("+","").trim();wZ.test(W)&&(Z=parseInt(W))}I=this.replacer(I,n1,ql({format:b,offset:Z}))}return I}replaceTimeInString(G){let I=G;for(;s1.test(I);){if(!s1.exec(I))throw new Error("unable to parse time");I=this.replacer(I,s1,ql({format:"HH:mm"}))}for(;E1.test(I);){let l=E1.exec(I);if(!l)throw new Error("unable to parse time");let b=l[1];I=this.replacer(I,E1,ql({format:b}))}return I}async replaceValueInString(G){let I=G;for(;uZ.test(I);)this.value||(this.value=await this.promptForValue()),I=this.replacer(I,uZ,this.value);return I}async replaceSelectedInString(G){let I=G,l=await this.getSelectedText();for(;oZ.test(I);)I=this.replacer(I,oZ,l);return I}async replaceLinkToCurrentFileInString(G){let I=this.getCurrentFileLink(),l=G;if(!I&&e1.test(l))throw new Error("unable to get current file path");if(!I)return l;for(;e1.test(l);)l=this.replacer(l,e1,I);return l}async replaceVariableInString(G){let I=G;for(;Q1.test(I);){let l=Q1.exec(I);if(!l)throw new Error("unable to parse variable");let b=l[1];if(b){if(!this.getVariableValue(b)){let Z=b.split(",");Z.length===1?this.variables.set(b,await this.promptForVariable(b)):this.variables.set(b,await this.suggestForValue(Z))}I=this.replacer(I,Q1,this.getVariableValue(b))}else break}return I}async replaceFieldVarInString(G){let I=G;for(;J1.test(I);){let l=J1.exec(I);if(!l)throw new Error("unable to parse variable");let b=l[1];if(b)this.getVariableValue(b)||this.variables.set(b,await this.suggestForField(b)),I=this.replacer(I,J1,this.getVariableValue(b));else break}return I}async replaceMathValueInString(G){let I=G;for(;yZ.test(I);){let l=await this.promptForMathValue();I=this.replacer(I,yZ,l)}return I}async replaceMacrosInString(G){let I=G;for(;w1.test(I);){let l=w1.exec(I);if(!l||!l[1])continue;let b=l[1],Z=await this.getMacroValue(b);I=this.replacer(I,w1,Z?Z.toString():"")}return I}async replaceDateVariableInString(G){let I=G;for(;v1.test(I);){let l=v1.exec(I);if(!l||!l[1]||!l[2])continue;let b=l[1],Z=l[2];if(b&&Z){if(!this.variables.get(b)){this.variables.set(b,await this.promptForVariable(b));let W=this.getNaturalLanguageDates();if(!W||!W.parseDate||typeof W.parseDate!="function")continue;let d=W.parseDate(this.variables.get(b));if(d)this.variables.set(b,d.moment.format(Z));else throw new Error(`unable to parse date variable ${this.variables.get(b)}`)}I=this.replacer(I,v1,this.variables.get(b))}else break}return I}async replaceTemplateInString(G){let I=G;for(;u1.test(I);){let l=u1.exec(I);if(!l||!l[1])continue;let b=l[1],Z=await this.getTempl
1 week ago
`),l=y1.exec(I);let b=/\\\\n/;for(;b.test(I);)I=this.replacer(I,b,"\\n");return I}};var zG=class extends F2{constructor(I){super();this.app=I}async format(I){let l=I;return l=await this.replaceMacrosInString(l),l=this.replaceDateInString(l),l=this.replaceTimeInString(l),l=await this.replaceValueInString(l),l=await this.replaceDateVariableInString(l),l=await this.replaceVariableInString(l),l=await this.replaceFieldVarInString(l),`File Name: ${l}`}promptForValue(I){return"FileName"}getVariableValue(I){return I}getCurrentFileLink(){return this.app.workspace.getActiveFile()?.path??""}getNaturalLanguageDates(){return oG(this.app)}suggestForValue(I){return"_suggest_"}promptForMathValue(){return Promise.resolve("_math_")}getMacroValue(I){return`_macro: ${I}`}async promptForVariable(I){return`_${I}_`}async getTemplateContent(I){return`/${I}/`}async getSelectedText(){return"_selected_"}suggestForField(I){return`_field: ${I}_`}};var CI=class extends qI{constructor(I,l,b,Z=!1){super(I,l);this.app=I;this.inputEl=l;this.plugin=b;this.suggestForFileNames=Z;this.lastInput="";this.macroNames=this.plugin.settings.macros.map(W=>W.name),this.templatePaths=this.plugin.getTemplateFiles().map(W=>W.path)}getSuggestions(I){if(this.inputEl.selectionStart===null)return[];let l=this.inputEl.selectionStart,b=15,Z=I.substr(l-b,b),W=[];return this.processToken(Z,(d,V,a)=>{this.lastInput=d[0],this.lastInputType=V,W.push(a),this.lastInputType===8&&W.push(...this.templatePaths.map(m=>`{{TEMPLATE:${m}}}`)),this.lastInputType===7&&W.push(...this.macroNames.map(m=>`{{MACRO:${m}}}`))}),W}selectSuggestion(I){if(this.inputEl.selectionStart===null)return;let l=this.inputEl.selectionStart,b=this.lastInput.length,Z=this.inputEl.value,W=0,d=(V,a=0)=>`${Z.substr(0,l-b+a)}${V}${Z.substr(l)}`;this.processToken(I,(V,a,m)=>{I.contains(m)&&(this.inputEl.value=d(I),this.lastInputType=a,W=l-b+I.length,(this.lastInputType===2||this.lastInputType===5||this.lastInputType===1)&&(W-=2))}),this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(W,W)}renderSuggestion(I,l){I&&l.setText(I)}processToken(I,l){let b=Bd.exec(I);b&&l(b,1,"{{DATE:}}");let Z=Md.exec(I);Z&&l(Z,0,eZ);let W=Od.exec(I);W&&l(W,10,Ad);let d=Ld.exec(I);d&&l(d,4,tZ);let V=jd.exec(I);V&&l(V,3,L2);let a=Kd.exec(I);a&&l(a,9,zd);let m=Pd.exec(I);m&&l(m,11,id);let N=fd.exec(I);N&&l(N,5,"{{VALUE:}}");let F=Td.exec(I);if(F&&l(F,2,"{{VDATE:}}"),!this.suggestForFileNames){let h=Cd.exec(I);h&&l(h,6,gd);let H=Sd.exec(I);H&&l(H,8,"{{TEMPLATE:");let X=Dd.exec(I);X&&l(X,7,"{{MACRO:")}}};var B1=class extends qI{constructor(I,l,b,Z){super(I,l);this.app=I;this.inputEl=l;this.suggestItems=b;this.currentItems=Z}updateCurrentItems(I){this.currentItems=I}getSuggestions(I){return this.suggestItems.filter(l=>l.contains(I))}selectSuggestion(I){this.inputEl.value=I,this.inputEl.trigger("input"),this.close()}renderSuggestion(I,l){I&&l.setText(I)}};var gG=class extends N2{constructor(I,l,b){super(I);this.plugin=b;this.choice=l,this.display()}display(){this.containerEl.addClass("templateChoiceBuilder"),this.addCenteredChoiceNameHeader(this.choice),this.addTemplatePathSetting(),this.addFileNameFormatSetting(),this.addFolderSetting(),this.addAppendLinkSetting(),this.addFileAlreadyExistsSetting(),this.addOpenFileSetting(),this.choice.openFile&&this.addOpenFileInNewTabSetting()}addTemplatePathSetting(){new oI.Setting(this.contentEl).setName("Template Path").setDesc("Path to the Template.").addSearch(I=>{let l=this.plugin.getTemplateFiles().map(b=>b.path);I.setValue(this.choice.templatePath),I.setPlaceholder("Template path"),new MI(this.app,I.inputEl,l,50),I.onChange(b=>{this.choice.templatePath=b})})}addFileNameFormatSetting(){let I;new oI.Setting(this.contentEl).setName("File Name Format").setDesc("Set the file name format.").addToggle(d=>{d.setValue(this.choice.fileNameFormat.enabled).onChange(V=>{this.choice.fileNameFormat.enabled=V,I.setDisabled(!V)})});let b=this.contentEl.createEl("span"),Z=new zG(this.app);(async()=>b.textContent=await Z.format(this.choice.fileNameFormat.format))();let W=new oI.TextComponent(this.con
2 months ago
`).filter(Boolean).reduce((l,b)=>{let[Z,W,...d]=b.split(" "),V=Number.parseInt(W,10);return d.forEach((a,m)=>l[a]=V+m),l},{});for(let[l,b]of Object.entries(I)){let Z=e0.default.toByteArray(l);this.rankMap.set(Z.join(","),b),this.textMap.set(b,Z)}this.specialTokens={...c.special_tokens,...G},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((l,[b,Z])=>(l[Z]=this.textEncoder.encode(b),l),{})}encode(c,G=[],I="all"){let l=new RegExp(this.patStr,"ug"),b=OZ.specialTokenRegex(Object.keys(this.specialTokens)),Z=[],W=new Set(G==="all"?Object.keys(this.specialTokens):G),d=new Set(I==="all"?Object.keys(this.specialTokens).filter(a=>!W.has(a)):I);if(d.size>0){let a=OZ.specialTokenRegex([...d]),m=c.match(a);if(m!=null)throw new Error(`The text contains a special token that is not allowed: ${m[0]}`)}let V=0;for(;;){let a=null,m=V;for(;b.lastIndex=m,a=b.exec(c),!(a==null||W.has(a[0]));)m=a.index+1;let N=a?.index??c.length;for(let h of c.substring(V,N).matchAll(l)){let H=this.textEncoder.encode(h[0]),X=this.rankMap.get(H.join(","));if(X!=null){Z.push(X);continue}Z.push(...yN(H,this.rankMap))}if(a==null)break;let F=this.specialTokens[a[0]];Z.push(F),V=a.index+a[0].length}return Z}decode(c){let G=[],I=0;for(let Z=0;Z<c.length;++Z){let W=c[Z],d=this.textMap.get(W)??this.inverseSpecialTokens[W];d!=null&&(G.push(d),I+=d.length)}let l=new Uint8Array(I),b=0;for(let Z of G)l.set(Z,b),b+=Z.length;return this.textDecoder.decode(l)}},h2=OZ;wN(h2,"specialTokenRegex",c=>new RegExp(c.map(G=>oN(G)).join("|"),"g"));function qZ(c){switch(c){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":return"cl100k_base";default:throw new Error("Unknown model")}}var AN={explicit_n_vocab:50257,pat_str:"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+",special_tokens:{"<|endoftext|>":50256},bpe_ranks:"! 0 IQ== Ig== Iw== JA== JQ== Jg== Jw== KA== KQ== Kg== Kw== LA== LQ== Lg== Lw== MA== MQ== Mg== Mw== NA== NQ== Ng== Nw== OA== OQ== Og== Ow== PA== PQ== Pg== Pw== QA== QQ== Qg== Qw== RA== RQ== Rg== Rw== SA== SQ== Sg== Sw== TA== TQ== Tg== Tw== UA== UQ== Ug== Uw== VA== VQ== Vg== Vw== WA== WQ== Wg== Ww== XA== XQ== Xg== Xw== YA== YQ== Yg== Yw== ZA== ZQ== Zg== Zw== aA== aQ== ag== aw== bA== bQ== bg== bw== cA== cQ== cg== cw== dA== dQ== dg== dw== eA== eQ== eg== ew== fA== fQ== fg== oQ== og== ow== pA== pQ== pg== pw== qA== qQ== qg== qw== rA== rg== rw== sA== sQ== sg== sw== tA== tQ== tg== tw== uA== uQ== ug== uw== vA== vQ== vg== vw== wA== wQ== wg== ww== xA== xQ== xg== xw== yA== yQ== yg== yw== zA== zQ== zg== zw== 0A== 0Q== 0g== 0w== 1A== 1Q== 1g== 1w== 2A== 2Q== 2g== 2w== 3A== 3Q== 3g== 3w== 4A== 4Q== 4g== 4w== 5A== 5Q== 5g== 5w== 6A== 6Q== 6g== 6w== 7A== 7Q== 7g== 7w== 8A== 8Q== 8g== 8w== 9A== 9Q== 9g== 9w== +A== +Q== +g== +w== /A== /Q== /g== /w== AA== AQ== Ag==
! 50257 ICA= ICAg ICAgIA== ICAgICA= ICAgICAg ICAgICAgIA== ICAgICAgICA= ICAgICAgICAg ICAgICAgICAgIA== ICAgICAgICAgICA= ICAgICAgICAgICAg ICAgICAgICAgICAgIA== ICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgIA==`},gN={pat_str:"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+",special_tokens:{"<|endoftext|>":50256,"<|fim_prefix|>":50281,"<|fim_middle|>":50282,"<|fim_suffix|>":50283},bpe_ranks:`! 0 IQ== Ig== Iw== JA== JQ== Jg== Jw== KA== KQ== Kg== Kw== LA== LQ== Lg== Lw== MA== MQ== Mg== Mw== NA== NQ== Ng== Nw== OA== OQ== Og== Ow== PA== PQ== Pg== Pw== QA== QQ== Qg== Qw== RA== RQ== Rg== Rw== SA== SQ== Sg== Sw== TA== TQ== Tg== Tw== UA== UQ== Ug== Uw== VA== VQ== Vg== Vw== WA== WQ== Wg== Ww== XA== XQ== Xg== Xw== YA== YQ== Yg== Yw== ZA== ZQ== Zg== Zw== aA== aQ== ag== aw== bA== bQ== bg== bw== cA== cQ== cg== cw== dA== dQ== dg== dw== eA== eQ== eg== ew== fA== fQ== fg== oQ== og== ow== pA== pQ== pg== pw== qA== qQ== qg== qw== rA== rg== rw== sA== sQ== sg== sw== tA== tQ== tg== tw== uA== uQ== ug== uw== vA== vQ== vg== vw== wA== wQ== wg== ww== xA== xQ== xg== xw== yA== yQ== yg== yw== zA== zQ== zg== zw== 0A== 0Q== 0g== 0w== 1A== 1Q== 1g== 1w== 2A== 2Q== 2g== 2w== 3A== 3Q== 3g== 3w== 4A== 4Q== 4g== 4w== 5A== 5Q== 5g== 5w== 6A== 6Q== 6g== 6w== 7A== 7Q== 7g== 7w== 8A== 8Q== 8g== 8w== 9A== 9Q== 9g== 9w== +A== +Q== +g== +w== /A== /Q== /g== /w== AA== AQ== Ag== Aw== BA== BQ== Bg== Bw== CA== CQ== Cg== Cw== DA== DQ== Dg== Dw== EA== EQ== Eg== Ew== FA== FQ== Fg== Fw== GA== GQ== Gg== Gw== HA== HQ== Hg== Hw== IA== fw== gA== gQ== gg== gw== hA== hQ== hg== hw== iA== iQ== ig== iw== jA== jQ== jg== jw== kA== kQ== kg== kw== lA== lQ== lg== lw== mA== mQ== mg== mw== nA== nQ== ng== nw== oA== rQ== IHQ= IGE= aGU= aW4= cmU= b24= IHRoZQ== ZXI= IHM= YXQ= IHc= IG8= ZW4= IGM= aXQ= aXM= YW4= b3I= ZXM= IGI= ZWQ= IGY= aW5n IHA= b3U= IGFu YWw= YXI= IHRv IG0= IG9m IGlu IGQ= IGg= IGFuZA== aWM= YXM= bGU= IHRo aW9u b20= bGw= ZW50 IG4= IGw= c3Q= IHJl dmU= IGU= cm8= bHk= IGJl IGc= IFQ= Y3Q= IFM= aWQ= b3Q= IEk= dXQ= ZXQ= IEE= IGlz IG9u aW0= YW0= b3c= YXk= YWQ= c2U= IHRoYXQ= IEM= aWc= IGZvcg== YWM= IHk= dmVy dXI= IHU= bGQ= IHN0 IE0= J3M= IGhl IGl0 YXRpb24= aXRo aXI= Y2U= IHlvdQ== aWw= IEI= IHdo b2w= IFA= IHdpdGg= IDE= dGVy Y2g= IGFz IHdl ICg= bmQ= aWxs IEQ= aWY= IDI= YWc= ZXJz a2U= ICI= IEg= ZW0= IGNvbg== IFc= IFI= aGVy IHdhcw== IHI= b2Q= IEY= dWw= YXRl IGF0 cmk= cHA= b3Jl IFRoZQ== IHNl dXM= IHBybw== IGhh dW0= IGFyZQ== IGRl YWlu YW5k IG9y aWdo ZXN0 aXN0 YWI= cm9t IE4= dGg= IGNvbQ== IEc= dW4= b3A= MDA= IEw= IG5vdA== ZXNz IGV4 IHY= cmVz IEU= ZXc= aXR5 YW50 IGJ5 ZWw= b3M= b3J0 b2M= cXU= IGZyb20= IGhhdmU= IHN1 aXZl b3VsZA== IHNo IHRoaXM= bnQ= cmE= cGU= aWdodA== YXJ0 bWVudA== IGFs dXN0 ZW5k LS0= YWxs IE8= YWNr IGNo IGxl aWVz cmVk YXJk 4oA= b3V0 IEo= IGFi ZWFy aXY= YWxseQ== b3Vy b3N0 Z2g= cHQ= IHBs YXN0 IGNhbg== YWs= b21l dWQ= VGhl IGhpcw== IGRv IGdv IGhhcw== Z2U= J3Q= IFU= cm91 IHNh IGo= IGJ1dA== IHdvcg== IGFsbA== ZWN0 IGs= YW1l IHdpbGw= b2s= IHdoZQ== IHRoZXk= aWRl MDE= ZmY= aWNo cGw= dGhlcg== IHRy Li4= IGludA== aWU= dXJl YWdl IG5l aWFs YXA= aW5l aWNl IG1l IG91dA== YW5z b25l b25n aW9ucw== IHdobw== IEs= IHVw IHRoZWly IGFk IDM= IHVz YXRlZA== b3Vz IG1vcmU= dWU= b2c= IFN0 aW5k aWtl IHNv aW1l cGVy LiI= YmVy aXo= YWN0 IG9uZQ== IHNhaWQ= IC0= YXJl IHlvdXI= Y2M= IFRo IGNs ZXA= YWtl YWJsZQ== aXA= IGNvbnQ= IHdoaWNo aWE= IGlt IGFib3V0 IHdlcmU= dmVyeQ== dWI= IGhhZA== IGVu IGNvbXA= LCI= IElu IHVu IGFn aXJl YWNl YXU= YXJ5 IHdvdWxk YXNz cnk= IOKA Y2w= b29r ZXJl c28= IFY= aWdu aWI= IG9mZg== IHRl dmVu IFk= aWxl b3Nl aXRl b3Jt IDIwMQ== IHJlcw== IG1hbg== IHBlcg== IG90aGVy b3Jk dWx0 IGJlZW4= IGxpa2U= YXNl YW5jZQ== a3M= YXlz b3du ZW5jZQ== IGRpcw== Y3Rpb24= IGFueQ== IGFwcA== IHNw aW50 cmVzcw== YXRpb25z YWls IDQ= aWNhbA== IHRoZW0= IGhlcg== b3VudA== IENo IGFy IGlm IHRoZXJl IHBl IHllYXI= YXY= IG15 IHNv
! 50257 ICA= ICAg ICAgIA== ICAgICA= ICAgICAg ICAgICAgIA== ICAgICAgICA= ICAgICAgICAg ICAgICAgICAgIA== ICAgICAgICAgICA= ICAgICAgICAgICAg ICAgICAgICAgICAgIA== ICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgIA==`},iN={explicit_n_vocab:50257,pat_str:"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+",special_tokens:{"<|endoftext|>":50256},bpe_ranks:"! 0 IQ== Ig== Iw== JA== JQ== Jg== Jw== KA== KQ== Kg== Kw== LA== LQ== Lg== Lw== MA== MQ== Mg== Mw== NA== NQ== Ng== Nw== OA== OQ== Og== Ow== PA== PQ== Pg== Pw== QA== QQ== Qg== Qw== RA== RQ== Rg== Rw== SA== SQ== Sg== Sw== TA== TQ== Tg== Tw== UA== UQ== Ug== Uw== VA== VQ== Vg== Vw== WA== WQ== Wg== Ww== XA== XQ== Xg== Xw== YA== YQ== Yg== Yw== ZA== ZQ== Zg== Zw== aA== aQ== ag== aw== bA== bQ== bg== bw== cA== cQ== cg== cw== dA== dQ== dg== dw== eA== eQ== eg== ew== fA== fQ== fg== oQ== og== ow== pA== pQ== pg== pw== qA== qQ== qg== qw== rA== rg== rw== sA== sQ== sg== sw== tA== tQ== tg== tw== uA== uQ== ug== uw== vA== vQ== vg== vw== wA== wQ== wg== ww== xA== xQ== xg== xw== yA== yQ== yg== yw== zA== zQ== zg== zw== 0A== 0Q== 0g== 0w== 1A== 1Q== 1g== 1w== 2A== 2Q== 2g== 2w== 3A== 3Q== 3g== 3w== 4A== 4Q== 4g== 4w== 5A== 5Q== 5g== 5w== 6A== 6Q== 6g== 6w== 7A== 7Q== 7g== 7w== 8A== 8Q== 8g== 8w== 9A== 9Q== 9g== 9w== +A== +Q== +g== +w== /A== /Q== /g== /w== AA== AQ== Ag== Aw== BA== BQ== Bg== Bw== CA== CQ== Cg== Cw== DA== DQ== Dg== Dw== EA== EQ== Eg== Ew== FA== FQ== Fg== Fw== GA== GQ== Gg== Gw== HA== HQ== Hg== Hw== IA== fw== gA== gQ== gg== gw== hA== hQ== hg== hw== iA== iQ== ig== iw== jA== jQ== jg== jw== kA== kQ== kg== kw== lA== lQ== lg== lw== mA== mQ== mg== mw== nA== nQ== ng== nw== oA== rQ== IHQ= IGE= aGU= aW4= cmU= b24= IHRoZQ== ZXI= IHM= YXQ= IHc= IG8= ZW4= IGM= aXQ= aXM= YW4= b3I= ZXM= IGI= ZWQ= IGY= aW5n IHA= b3U= IGFu YWw= YXI= IHRv IG0= IG9m IGlu IGQ= IGg= IGFuZA== aWM= YXM= bGU= IHRo aW9u b20= bGw= ZW50 IG4= IGw= c3Q= IHJl dmU= IGU= cm8= bHk= IGJl IGc= IFQ= Y3Q= IFM= aWQ= b3Q= IEk= dXQ= ZXQ= IEE= IGlz IG9u aW0= YW0= b3c= YXk= YWQ= c2U= IHRoYXQ= IEM= aWc= IGZvcg== YWM= IHk= dmVy dXI= IHU= bGQ= IHN0 IE0= J3M= IGhl IGl0 YXRpb24= aXRo aXI= Y2U= IHlvdQ== aWw= IEI= IHdo b2w= IFA= IHdpdGg= IDE= dGVy Y2g= IGFz IHdl ICg= bmQ= aWxs IEQ= aWY= IDI= YWc= ZXJz a2U= ICI= IEg= ZW0= IGNvbg== IFc= IFI= aGVy IHdhcw== IHI= b2Q= IEY= dWw= YXRl IGF0 cmk= cHA= b3Jl IFRoZQ== IHNl dXM= IHBybw== IGhh dW0= IGFyZQ== IGRl YWlu YW5k IG9y aWdo ZXN0 aXN0 YWI= cm9t IE4= dGg= IGNvbQ== IEc= dW4= b3A= MDA= IEw= IG5vdA== ZXNz IGV4 IHY= cmVz IEU= ZXc= aXR5 YW50 IGJ5 ZWw= b3M= b3J0 b2M= cXU= IGZyb20= IGhhdmU= IHN1 aXZl b3VsZA== IHNo IHRoaXM= bnQ= cmE= cGU= aWdodA== YXJ0 bWVudA== IGFs dXN0 ZW5k LS0= YWxs IE8= YWNr IGNo IGxl aWVz cmVk YXJk 4oA= b3V0 IEo= IGFi ZWFy aXY= YWxseQ== b3Vy b3N0 Z2g= cHQ= IHBs YXN0 IGNhbg== YWs= b21l dWQ= VGhl IGhpcw== IGRv IGdv IGhhcw== Z2U= J3Q= IFU= cm91 IHNh IGo= IGJ1dA== IHdvcg== IGFsbA== ZWN0 IGs= YW1l IHdpbGw= b2s= IHdoZQ== IHRoZXk= aWRl MDE= ZmY= aWNo cGw= dGhlcg== IHRy Li4= IGludA== aWU= dXJl YWdl IG5l aWFs YXA= aW5l aWNl IG1l IG91dA== YW5z b25l b25n aW9ucw== IHdobw== IEs= IHVw IHRoZWly IGFk IDM= IHVz YXRlZA== b3Vz IG1vcmU= dWU= b2c= IFN0 aW5k aWtl IHNv aW1l cGVy LiI= YmVy aXo= YWN0 IG9uZQ== IHNhaWQ= IC0= YXJl IHlvdXI= Y2M= IFRo IGNs ZXA= YWtl YWJsZQ== aXA= IGNvbnQ= IHdoaWNo aWE= IGlt IGFib3V0 IHdlcmU= dmVyeQ== dWI= IGhhZA== IGVu IGNvbXA= LCI= IElu IHVu IGFn aXJl YWNl YXU= YXJ5 IHdvdWxk YXNz cnk= IOKA Y2w= b29r ZXJl c28= IFY= aWdu aWI= IG9mZg== IHRl dmVu IFk= aWxl b3Nl aXRl b3Jt IDIwMQ== IHJlcw== IG1hbg== IHBlcg== IG90aGVy b3Jk dWx0 IGJlZW4= IGxpa2U= YXNl YW5jZQ== a3M= YXlz b3du ZW5jZQ== IGRpcw== Y3Rpb24= IGFueQ== IGFwcA== IHNw aW50 cmVzcw== YXRpb25z YWls IDQ= aWNhbA== IHRoZW0= IGhlcg== b3VudA== IENo IGFy IGlm IHRoZXJl IHBl IHllYXI= YXY= IG15 IHNvbWU= IHdoZW4= b3VnaA== YWNo IHRoYW4= cnU= b25k
${G}`:""}`;function S1(c){if(c){let G=new o0.Notice(y0("starting",""),1e6);return{setMessage:(I,l)=>{G.setMessage(y0(I,l))},hide:()=>G.hide()}}return{setMessage:(G,I)=>{u.logMessage(`(${G}) ${I}`)},hide:()=>{}}}var dl=(c,G)=>{let I=G.name==="gpt-3.5-turbo-16k"?"gpt-3.5-turbo":G.name;I=I==="gpt-4-1106-preview"?"gpt-4":I,I=I==="gpt-3.5-turbo-1106"?"gpt-3.5-turbo":I;try{return t0(I).encode(c).length}catch{return _Z("cl100k_base").encode(c).length}};async function BN(c,G,I){if(typeof c!="function")throw new TypeError("Callback must be a function.");if(!(G instanceof Promise))throw new TypeError("Promise must be an instance of Promise.");if(typeof I!="number"||I<=0)throw new TypeError("Interval must be a positive number.");let l=!1;for(G.finally(()=>{l=!0});!l;)c(),await sleep(I)}async function LN(c,G){let I;if(c.enable)I=G.find(W=>W.path.endsWith(c.name));else{let W=G.map(d=>d.basename);I=await AI.Suggest(app,W,G)}Wl(I,"Prompt template does not exist");let l=I.path,b=app.vault.getAbstractFileByPath(l);Wl(b instanceof A0.TFile,`${l} is not a file`);let Z=await app.vault.cachedRead(b);return[I.basename,Z]}async function z0(c,G){if(i.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let I=S1(c.showAssistantMessages);try{let{apiKey:l,model:b,outputVariableName:Z,promptTemplate:W,systemPrompt:d,promptTemplateFolder:V}=c,a=AG(V),[m,N]=await LN(W,a);I.setMessage("waiting","QuickAdd is formatting the prompt template.");let F=await G(N),h=["prompting",`Using prompt template "${m}".`];I.setMessage(h[0],h[1]);let X=C1(l,b,d,c.modelOptions)(F),R=(await lW(X,100,Y=>{I.setMessage(h[0],`${h[1]} (${(Y/1e3).toFixed(2)}s)`)},Y=>{I.setMessage("finished",`Took ${(Y/1e3).toFixed(2)}s.`)})).content,J=("> "+R).replace(/\n/g,`
> `),t={[Z]:R,[`${Z}-quoted`]:J};return setTimeout(()=>I.hide(),5e3),t}catch(l){I.setMessage("dead",l.message),setTimeout(()=>I.hide(),5e3)}}async function lW(c,G,I,l){let b=Date.now();return await BN(()=>I(Date.now()-b),c,G),l(Date.now()-b),await c}async function g0(c,G){if(i.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let I=S1(c.showAssistantMessages);try{let{apiKey:l,model:b,outputVariableName:Z,systemPrompt:W,prompt:d,modelOptions:V}=c;I.setMessage("waiting","QuickAdd is formatting the prompt template.");let a=await G(d),m=["prompting","Using custom prompt."];I.setMessage(m[0],m[1]);let F=C1(l,b,W,V)(a),H=(await lW(F,100,R=>{I.setMessage(m[0],`${m[1]} (${(R/1e3).toFixed(2)}s)`)},R=>{I.setMessage("finished",`Took ${(R/1e3).toFixed(2)}s.`)})).content,X=("> "+H).replace(/\n/g,`
> `),n={[Z]:H,[`${Z}-quoted`]:X};return setTimeout(()=>I.hide(),5e3),n}catch(l){I.setMessage("dead",l.message),setTimeout(()=>I.hide(),5e3)}}var IW=class{constructor(G,I){this.maxRequests=G;this.intervalMs=I;this.queue=[];this.pendingPromises=[]}add(G){return new Promise((I,l)=>{this.queue.push(async()=>{try{I(await G())}catch(b){l(b)}}),this.schedule()})}schedule(){if(this.queue.length===0||this.pendingPromises.length>=this.maxRequests)return;let G=this.queue.shift();if(!G)return;let I=G();this.pendingPromises.push(I),I.finally(()=>{this.pendingPromises=this.pendingPromises.filter(l=>l!==I),this.schedule()}),setTimeout(()=>this.schedule(),this.intervalMs)}};async function i0(c,G){if(i.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let I=S1(c.showAssistantMessages);try{let{apiKey:l,model:b,outputVariableName:Z,systemPrompt:W,promptTemplate:d,text:V,modelOptions:a}=c;I.setMessage("chunking","Creating prompt chunks with text and prompt template");let m=c.chunkSeparator||/\n/g,N=V.split(m),F=dl(W,b),h=await G(d,{chunk:" "}),H=dl(h,b),X=u0(b.name)/2-F,n=c.shouldMerge??!0,R=[],J=X-H;if(n){let Q=[],II="",cI=0;for(let hI of N){let ZI=dl(hI,b)+1;if(ZI>J)throw new Error(`The chunk "${hI.slice(0,25)}..." is too large to fit in a single prompt.`);cI+ZI<J?(II+=hI,cI+=ZI):(Q.push(II),II=hI,cI=ZI)}II!==""&&Q.push(II);for(let hI of Q){let ZI=await G(d,{chunk:hI});R.push(ZI)}}else for(let Q of N){let II=dl(Q,b);if(II>X)throw new Error(`Chunk size (${II}) is larger than the maximum chunk size (${X}). Please check your chunk separator.`);let cI=await G(d,{chunk:Q});R.push(cI)}let t=C1(l,b,W,a),Y=["prompting",`${R.length} prompts being sent.`];I.setMessage(Y[0],Y[1]);let p=new IW(5,1e3*30),E=Promise.all(R.map(Q=>p.add(()=>t(Q)))),v=(await lW(E,100,Q=>{I.setMessage(Y[0],`${Y[1]} (${(Q/1e3).toFixed(2)}s)`)},Q=>{I.setMessage("finished",`Took ${(Q/1e3).toFixed(2)}s.`)})).map(Q=>Q.content).join(c.resultJoiner),x=("> "+v).replace(/\n/g,`
> `),P={[Z]:v,[`${Z}-quoted`]:x};return setTimeout(()=>I.hide(),5e3),P}catch(l){I.setMessage("dead",l.message),setTimeout(()=>I.hide(),5e3)}}var xG=class{static GetApi(G,I,l){return{inputPrompt:(b,Z,W)=>this.inputPrompt(G,b,Z,W),wideInputPrompt:(b,Z,W)=>this.wideInputPrompt(G,b,Z,W),yesNoPrompt:(b,Z)=>this.yesNoPrompt(G,b,Z),infoDialog:(b,Z)=>this.infoDialog(G,b,Z),suggester:(b,Z)=>this.suggester(G,b,Z),checkboxPrompt:(b,Z)=>this.checkboxPrompt(G,b,Z),executeChoice:async(b,Z)=>{let W=I.getChoiceByName(b);W||u.logError(`choice named '${b}' not found`),Z&&Object.keys(Z).forEach(d=>{l.variables.set(d,Z[d])}),await l.execute(W),l.variables.clear()},format:async(b,Z,W=!0)=>{Z&&Object.keys(Z).forEach(V=>{l.variables.set(V,Z[V])});let d=await new Bl(G,I,l).formatFileContent(b);return W&&l.variables.clear(),d},ai:{prompt:async(b,Z,W)=>{let d=i.getState(),V=d.ai;if(d.disableOnlineFeatures)throw new Error("Rejecting request to `prompt` via API AI module. Online features are disabled in settings.");let a=this.GetApi(G,I,l).format,m;if(typeof Z=="string"){let h=yl(Z);if(!h)throw new Error(`Model '${Z}' not found.`);m=h}else m=Z;let N=P2(m.name);if(!N)throw new Error(`Model '${m.name}' not found in any provider`);let F=await g0({model:m,prompt:b,apiKey:N.apiKey,modelOptions:W?.modelOptions??{},outputVariableName:W?.variableName??"output",showAssistantMessages:W?.showAssistantMessages??!0,systemPrompt:W?.systemPrompt??V.defaultSystemPrompt},(h,H)=>a(h,H,!1));return F?(W?.shouldAssignVariables&&Object.assign(l.variables,F),F):(u.logError("AI Assistant returned null"),{})},chunkedPrompt:async(b,Z,W,d,V)=>{let a=i.getState(),m=a.ai;if(a.disableOnlineFeatures)throw new Error("Rejecting request to `prompt` via API AI module. Online features are disabled in settings.");let N=this.GetApi(G,I,l).format,F;if(typeof W=="string"){let X=yl(W);if(!X)throw new Error(`Model ${W} not found.`);F=X}else F=W;let h=P2(F.name);if(!h)throw new Error(`Model '${F.name}' not found in any provider`);let H=await i0({model:F,text:b,promptTemplate:Z,chunkSeparator:d?.chunkSeparator??/\n/,apiKey:h.apiKey,modelOptions:d?.modelOptions??{},outputVariableName:d?.variableName??"output",showAssistantMessages:d?.showAssistantMessages??!0,systemPrompt:d?.systemPrompt??m.defaultSystemPrompt,resultJoiner:d?.chunkJoiner??`
`,shouldMerge:d?.shouldMerge??!0},(X,n)=>{let R={...V,...n};return N(X,R,!1)});return H?(d?.shouldAssignVariables&&Object.assign(l.variables,H),H):(u.logError("AI Assistant returned null"),{})},getModels:()=>Ml(),getMaxTokens:b=>{let Z=yl(b);if(!Z)throw new Error(`Model ${b} not found.`);return Z.maxTokens},countTokens(b,Z){return dl(b,Z)}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async b=>await navigator.clipboard.writeText(b),getSelectedText:()=>{let b=G.workspace.getActiveViewOfType(r0.MarkdownView);if(!b){u.logError("no active view - could not get selected text.");return}if(!b.editor.somethingSelected()){u.logError("no text selected.");return}return b.editor.getSelection()}},date:{now:(b,Z)=>ql({format:b,offset:Z}),tomorrow:b=>ql({format:b,offset:1}),yesterday:b=>ql({format:b,offset:-1})}}}static async inputPrompt(G,I,l,b){try{return await dI.Prompt(G,I,l,b)}catch{return}}static async wideInputPrompt(G,I,l,b){try{return await _l.Prompt(G,I,l,b)}catch{return}}static async yesNoPrompt(G,I,l){try{return await OI.Prompt(G,I,l)}catch{return}}static async infoDialog(G,I,l){try{return await S2.Show(G,I,l)}catch{return}}static async suggester(G,I,l){try{let b;return typeof I=="function"?b=l.map(I):b=I,await AI.Suggest(G,b,l)}catch{return}}static async checkboxPrompt(G,I,l){try{return await D2.Open(G,I,l)}catch{return}}};var UG=class extends iG{};var jI=class{constructor(G,I){this.name=G,this.type=I,this.id=Sl()}};var k0=require("obsidian");var zI=class extends jI{constructor(I){super(I,"EditorCommand");this.editorCommandType=I}static getSelectedText(I){return this.getActiveMarkdownView(I).editor.getSelection()}static getActiveMarkdownView(I){let l=I.workspace.getActiveViewOfType(k0.MarkdownView);if(!l)throw u.logError("no active markdown view."),new Error("no active markdown view.");return l}};var MG=class extends zI{constructor(){super("Cut")}static async run(G){let I=zI.getSelectedText(G),l=zI.getActiveMarkdownView(G);if(!I){u.logError("nothing selected.");return}await navigator.clipboard.writeText(I),l.editor.replaceSelection("")}};var LG=class extends zI{constructor(){super("Copy")}static async run(G){let I=zI.getSelectedText(G);await navigator.clipboard.writeText(I)}};var jG=class extends zI{constructor(){super("Paste")}static async run(G){let I=await navigator.clipboard.readText(),l=zI.getActiveMarkdownView(G);if(!l){u.logError("no active markdown view.");return}l.editor.replaceSelection(I)}};var fG=class extends zI{constructor(){super("Select active line")}static run(G){let I=zI.getActiveMarkdownView(G),{line:l}=I.editor.getCursor(),Z=I.editor.getLine(l).length;I.editor.setSelection({line:l,ch:0},{line:l,ch:Z})}};var TG=class extends zI{constructor(){super("Select link on active line")}static run(G){let I=zI.getActiveMarkdownView(G),{line:l}=I.editor.getCursor(),b=I.editor.getLine(l),Z=qd.exec(b);if(!Z){u.logError(`no internal link found on line ${l}.`);return}let W=Z.index,d=Z[0].length+W;I.editor.setSelection({line:l,ch:W},{line:l,ch:d})}};function x0(c){return new Promise(G=>setTimeout(G,c))}function GW(c){return c.split(`
`)}function U0(c){return c.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}var Ll=class extends UG{constructor(I,l,b,Z,W,d){super(I);this.choice=b,this.plugin=l,this.macros=Z,this.choiceExecutor=W,this.params={app:this.app,quickAddApi:xG.GetApi(I,l,W),variables:{},obsidian:jN},d?.forEach((V,a)=>{this.params.variables[a]=V})}async run(){let I=this.choice.macroId??this.choice?.macro?.id,l=this.macros.find(b=>b.id===I);if(!l||!l?.commands){u.logError(`No commands in the selected macro. Did you select a macro for '${this.choice.name}'?`);return}await this.executeCommands(l.commands)}async executeCommands(I){for(let l of I)l?.type==="Obsidian"&&this.executeObsidianCommand(l),l?.type==="UserScript"&&await this.executeUserScript(l),l?.type==="Choice"&&await this.executeChoice(l),l?.type==="Wait"&&await x0(l.time),l?.type==="NestedChoice"&&await this.executeNestedChoice(l),l?.type==="EditorCommand"&&await this.executeEditorCommand(l),l?.type==="AIAssistant"&&await this.executeAIAssistant(l),Object.keys(this.params.variables).forEach(b=>{this.choiceExecutor.variables.set(b,this.params.variables[b])})}async executeUserScript(I){let l=await M1(I,this.app);if(!l){u.logError(`failed to load user script ${I.path}.`);return}l.settings&&(this.userScriptCommand=I);try{await this.userScriptDelegator(l)}catch(b){u.logError(`failed to run user script ${I.name}. Error:
${b.message}`)}this.userScriptCommand&&(this.userScriptCommand=null)}async runScriptWithSettings(I,l){if(typeof I!="function"&&I.entry&&typeof I.entry=="function")return await this.onExportIsFunction(I.entry,l.settings);if(typeof I=="function")return await this.onExportIsFunction(I,l.settings)}async userScriptDelegator(I){switch(typeof I){case"function":this.userScriptCommand?await this.runScriptWithSettings(I,this.userScriptCommand):await this.onExportIsFunction(I);break;case"object":await this.onExportIsObject(I);break;case"bigint":case"boolean":case"number":case"string":this.output=I.toString();break;default:u.logError(`user script in macro for '${this.choice.name}' is invalid`)}}async onExportIsFunction(I,l){this.output=await I(this.params,l||{})}async onExportIsObject(I){if(Object.keys(I).length===0)throw new Error(`user script in macro for '${this.choice.name}' is an empty object`);if(this.userScriptCommand&&I.entry!==null){await this.runScriptWithSettings(I,this.userScriptCommand);return}try{let l=Object.keys(I),b=await AI.Suggest(this.app,l,l);await this.userScriptDelegator(I[b])}catch(l){u.logMessage(l)}}executeObsidianCommand(I){this.app.commands.executeCommandById(I.commandId)}async executeChoice(I){let l=this.plugin.getChoiceById(I.choiceId);if(!l){u.logError("choice could not be found.");return}await this.choiceExecutor.execute(l)}async executeNestedChoice(I){let l=I.choice;if(!l){u.logError(`choice in ${I.name} is invalid`);return}await this.choiceExecutor.execute(l)}async executeEditorCommand(I){switch(I.editorCommandType){case"Cut":await MG.run(this.app);break;case"Copy":await LG.run(this.app);break;case"Paste":await jG.run(this.app);break;case"Select active line":fG.run(this.app);break;case"Select link on active line":TG.run(this.app);break}}async executeAIAssistant(I){if(i.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let l=i.getState().ai,b=Ml(),Z=I.model==="Ask me"?await AI.Suggest(app,b,b):I.model,W=yl(Z);if(!W)throw new Error(`Model ${Z} not found with any provider.`);let d=new Bl(app,GI.instance,this.choiceExecutor),V=P2(W.name);if(!V)throw new Error(`Model ${W.name} not found in the AI providers settings.`);let a=await z0({apiKey:V.apiKey,model:W,outputVariableName:I.outputVariableName,promptTemplate:I.promptTemplate,promptTemplateFolder:l.promptTemplatesFolderPath,systemPrompt:I.systemPrompt,showAssistantMessages:l.showAssistant,modelOptions:I.modelParameters},async m=>d.formatFileContent(m));for(let m in a)this.choiceExecutor.variables.set(m,a[m])}};var D1=class extends Ll{constructor(I,l,b,Z,W){super(I,l,null,b,Z,W)}async runAndGetOutput(I){let{basename:l,memberAccess:b}=uc(I),Z=this.macros.find(W=>W.name===l);if(!Z)throw u.logError(`macro '${I}' does not exist.`),new Error(`macro '${I}' does not exist.`);return b&&b.length>0&&(this.memberAccess=b),await this.executeCommands(Z.commands),this.output}async onExportIsObject(I){if(!this.memberAccess)return await super.onExportIsObject(I);let l=I;this.memberAccess.forEach(b=>{l=l[b]}),await this.userScriptDelegator(l)}};var j0=require("obsidian");var K1=class extends Ll{constructor(G,I,l,b){super(G,I,null,null,l,b)}async runAndGetOutput(G){let I=Object.getPrototypeOf(async function(){}).constructor;return await new I(G).bind(this.params,this).call()}};var _I=require("obsidian");var S="\u261A",fN=["\\!","\\,","\\:","\\>","\\;","\\#","\\$","\\%","\\&","\\","_","{ }","|",`^{${S}}${S}`,`[${S}]${S}`,"\\above","\\abovewithdelims","\\acute","\\aleph","\\alpha","\\amalg","\\And","\\angle","\\approx","\\approxeq","\\arccos","\\arcsin","\\arctan","\\arg","\\array","\\arrowvert","\\Arrowvert","\\ast","\\asymp","\\atop","\\atopwithdelims","\\backepsilon","\\backprime","\\backsim","\\backsimeq","\\backslash","\\bar","\\barwedge","\\Bbb","\\Bbbk","\\because","\\begin","\\beta","\\beth","\\between","\\bf","\\Bigg","\\bigg","\\Big","\\big","\\Biggl","\\Biggm","\\Biggr","\\biggl","\\biggm","\\biggr","\\Bigl","\\Bigm","\\Bigl","\\bigl","\\bigm","\\bigr","\\bigcap","\\bigcirc","\\bigcup","\\b
${S}
\\end{${c}}${S}`}var M0=[...fN,...TN.map(CN)];var B0=require("obsidian");var SN=new RegExp(/\\([a-z{}A-Z0-9]*)$/),P1=class extends qI{constructor(I){super(GI.instance.app,I);this.inputEl=I;this.lastInput="";this.symbols=Object.assign([],M0),this.elementsRendered=this.symbols.reduce((l,b)=>{try{l[b.toString()]=(0,B0.renderMath)(b,!0)}catch{}return l},{})}getSuggestions(I){if(this.inputEl.selectionStart===null)return[];let l=this.inputEl.selectionStart,b=I.substr(0,l),Z=b.lastIndexOf("\\"),W=b.substr(Z),d=SN.exec(W),V=[];return d&&(this.lastInput=d[1],V=this.symbols.filter(N=>N.toLowerCase().contains(this.lastInput))),new Zl(V,{findAllMatches:!0,threshold:.8}).search(this.lastInput).map(N=>N.item)}renderSuggestion(I,l){I&&(l.setText(I),l.append(this.elementsRendered[I]))}selectSuggestion(I){if(this.inputEl.selectionStart===null)return;let l=this.inputEl.selectionStart,b=this.lastInput.length,Z=this.inputEl.value,W=0,d=I.replace(/\\\\/g,"\\");if(this.inputEl.value=`${Z.substr(0,l-b-1)}${d}${Z.substr(l)}`,W=l-b+I.length-1,this.inputEl.trigger("input"),this.close(),I.contains(S)){let V=this.inputEl.value.indexOf(S);this.inputEl.value=this.inputEl.value.replace(S,""),this.inputEl.setSelectionRange(V,V)}else this.inputEl.setSelectionRange(W,W)}};var CG=class extends _I.Modal{constructor(){super(GI.instance.app);this.didSubmit=!1;this.keybindListener=I=>{I.ctrlKey&&I.key==="Enter"&&this.submit(),I.key==="Tab"&&(I.preventDefault(),this.cursorToGoTo())};this.submitClickCallback=I=>this.submit();this.cancelClickCallback=I=>this.cancel();this.open(),this.display(),this.waitForClose=new Promise((I,l)=>{this.resolvePromise=I,this.rejectPromise=l}),new P1(this.inputEl),this.inputEl.focus(),this.inputEl.select()}static Prompt(){return new CG().waitForClose}display(){this.containerEl.addClass("quickAddModal","qaMathModal"),this.contentEl.empty();let I=this.contentEl.createDiv();I.className="math math-block is-loaded";let l=new _I.TextAreaComponent(this.contentEl);l.inputEl.style.width="100%",l.inputEl.style.height="10rem",this.inputEl=l.inputEl,l.onChange((0,_I.debounce)(async b=>await this.mathjaxLoop(I,b),50)),l.inputEl.addEventListener("keydown",this.keybindListener),this.createButtonBar(this.contentEl.createDiv())}async onOpen(){super.onOpen(),await(0,_I.loadMathJax)()}async mathjaxLoop(I,l){let b=(0,_I.renderMath)(l,!0);await(0,_I.finishRenderMath)(),I.empty(),I.append(b)}cursorToGoTo(){if(this.inputEl.value.contains(S)){let I=this.inputEl.value.indexOf(S);this.inputEl.value=this.inputEl.value.replace(S,""),this.inputEl.setSelectionRange(I,I)}}createButton(I,l,b){let Z=new _I.ButtonComponent(I);return Z.setButtonText(l).onClick(b),Z}createButtonBar(I){let l=I.createDiv();this.createButton(l,"Ok",this.submitClickCallback).setCta().buttonEl.style.marginRight="0",this.createButton(l,"Cancel",this.cancelClickCallback),l.style.display="flex",l.style.flexDirection="row-reverse",l.style.justifyContent="flex-start",l.style.marginTop="1rem"}removeInputListeners(){this.inputEl.removeEventListener("keydown",this.keybindListener)}resolveInput(){let I=this.inputEl.value.replace("\\n","\\\\n").replace(new RegExp(S,"g"),"");this.didSubmit?this.resolvePromise(I):this.rejectPromise("No input given.")}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListeners()}};var SG=class{factory(){return GI.instance.settings.inputPrompt==="multi-line"?_l:dI}};var L0=require("obsidian"),jl=class extends L0.FuzzySuggestModal{constructor(I,l,b,Z={}){super(I);this.displayItems=l;this.items=b;this.promise=new Promise((W,d)=>{this.resolvePromise=W,this.rejectPromise=d}),this.inputEl.addEventListener("keydown",W=>{if(W.code!=="Tab"||!("chooser"in this))return;let{values:d,selectedItem:V}=this.chooser,{value:a}=this.inputEl;this.inputEl.value=d[V].item??a}),Z.placeholder&&this.setPlaceholder(Z.placeholder),Z.limit&&(this.limit=Z.limit),Z.emptyStateText&&(this.emptyStateText=Z.emptyStateText),this.open()}static Suggest(I,l,b,Z={}){return new jl(I,l,b,Z).promise}getItemText(I){return I===this.inpu
${b.message}`),null}}async overwriteFileWithTemplate(I,l){try{let b=await this.getTemplateContent(l),Z=await this.formatter.formatFileContent(b);return await this.app.vault.modify(I,Z),await yG(this.app,I,!0),I}catch(b){return u.logError(b),null}}async appendToFileWithTemplate(I,l,b){try{let Z=await this.getTemplateContent(l),W=await this.formatter.formatFileContent(Z),d=await this.app.vault.cachedRead(I),V=b==="top"?`${W}
${d}`:`${d}
${W}`;return await this.app.vault.modify(I,V),await yG(this.app,I,!0),I}catch(Z){return u.logError(Z),null}}async getTemplateContent(I){let l=I;t1.test(I)||(l+=".md");let b=this.app.vault.getAbstractFileByPath(l);if(!(b instanceof f0.TFile))throw new Error(`Template file not found at path "${l}".`);return await this.app.vault.cachedRead(b)}};var Y2=class extends DG{constructor(I,l,b,Z){super(I,l,Z);this.templatePath=b}async run(){let I=await this.getTemplateContent(this.templatePath);return I||u.logError(`Template ${this.templatePath} not found.`),I=await this.formatter.formatFileContent(I),I}};var Vl=class extends F2{constructor(I,l){super();this.app=I;this.plugin=l}async format(I){let l=I;return l=this.replaceDateInString(l),l=this.replaceTimeInString(l),l=await this.replaceValueInString(l),l=await this.replaceDateVariableInString(l),l=await this.replaceVariableInString(l),l=await this.replaceLinkToCurrentFileInString(l),l=await this.replaceMacrosInString(l),l=await this.replaceTemplateInString(l),l=await this.replaceFieldVarInString(l),l=this.replaceLinebreakInString(l),l}promptForValue(I){return"_value_"}getVariableValue(I){return I}getCurrentFileLink(){return this.app.workspace.getActiveFile()?.path??"_noPageOpen_"}getNaturalLanguageDates(){return oG(this.app)}suggestForValue(I){return"_suggest_"}getMacroValue(I){return`_macro: ${I}_`}promptForMathValue(){return Promise.resolve("_math_")}promptForVariable(I){return Promise.resolve(`${I}_`)}async getTemplateContent(I){try{return await new Y2(this.app,this.plugin,I,void 0).run()}catch{return`Template (not found): ${I}`}}async getSelectedText(){return"_selected_"}async suggestForField(I){return Promise.resolve(`_field: ${I}_`)}};var KG=class extends N2{constructor(I,l,b){super(I);this.plugin=b;this.choice=l,this.display()}display(){this.containerEl.addClass("captureChoiceBuilder"),this.contentEl.empty(),this.addCenteredChoiceNameHeader(this.choice),this.addCapturedToSetting(),this.choice?.captureToActiveFile||(this.addCreateIfNotExistsSetting(),this.choice?.createFileIfItDoesntExist?.enabled&&this.addCreateWithTemplateSetting()),this.addTaskSetting(),this.addPrependSetting(),this.addAppendLinkSetting(),this.addInsertAfterSetting(),this.choice.captureToActiveFile||(this.addOpenFileSetting(),this.choice.openFile&&this.addOpenFileInNewTabSetting()),this.addFormatSetting()}addCapturedToSetting(){let I;new aI.Setting(this.contentEl).setName("Capture To").setDesc("File to capture to. Supports some format syntax.");let l=this.contentEl.createDiv("captureToContainer"),b=l.createDiv("captureToActiveFileContainer"),Z=b.createEl("span");Z.textContent="Capture to active file";let W=new aI.ToggleComponent(b);if(W.setValue(this.choice?.captureToActiveFile),W.onChange(d=>{this.choice.captureToActiveFile=d,this.reload()}),!this.choice?.captureToActiveFile){let d=l.createDiv("captureToFileContainer"),V=d.createEl("span"),a=new zG(this.app);(async()=>V.textContent=await a.format(this.choice.captureTo))();let m=new aI.TextComponent(d);m.setPlaceholder("File name format"),I=m,m.inputEl.style.width="100%",m.inputEl.style.marginBottom="8px",m.setValue(this.choice.captureTo).setDisabled(this.choice?.captureToActiveFile).onChange(async F=>{this.choice.captureTo=F,V.textContent=await a.format(F)});let N=[...this.app.vault.getMarkdownFiles().map(F=>F.path),...rd];new MI(this.app,I.inputEl,N,50)}}addPrependSetting(){new aI.Setting(this.contentEl).setName("Write to bottom of file").setDesc(`Put value at the bottom of the file - otherwise at the ${this.choice?.captureToActiveFile?"active cursor location":"top"}.`).addToggle(l=>{l.setValue(this.choice.prepend),l.onChange(b=>{this.choice.prepend=b,this.choice.prepend&&this.choice.insertAfter.enabled&&(this.choice.insertAfter.enabled=!1,this.reload())})})}addTaskSetting(){new aI.Setting(this.contentEl).setName("Task").setDesc("Formats the value as a task.").addToggle(l=>{l.setValue(this.choice.task),l.onChange(b=>this.choice.task=b)})}addAppendLinkSetting(){new aI.Setting(this.contentEl).setName("Append link").setDesc("Add a link on your current cur
${s?"Deleting this choice will delete all ("+p.choices.length+") choices inside it!":""}
${E?"Deleting this choice will delete the macro associated with it!":""}
1 week ago
`)&&(E&&(I(9,b=b.filter(v=>v.id!==p.macroId)),W(b)),I(0,l=l.filter(v=>$0(p.id,v))),V.removeCommandForChoice(p),Z(l))}async function N(Y){let{choice:p}=Y.detail,E;if(p.type==="Multi"){E=p;let s=await dI.Prompt(d,`Rename ${p.name}`,"",p.name);if(!s)return;E.name=s}else{let s=X(p);if(!s)throw new Error("Invalid choice type");E=await s.waitForClose}E&&(I(0,l=l.map(s=>aW(s,E))),V.removeCommandForChoice(p),V.addCommandForChoice(E),Z(l))}async function F(Y){let{choice:p}=Y.detail,E={...p,command:!p.command};E.command?V.addCommandForChoice(E):V.removeCommandForChoice(E),I(0,l=l.map(s=>aW(s,E))),Z(l)}async function h(Y){let{choice:p}=Y.detail,E=H(p);I(0,l=[...l,E]),Z(l)}function H(Y){if(!H0(Y))throw new Error("Invalid choice type");let p;switch(Y.type){case"Template":p=new o2(`${Y.name} (copy)`);break;case"Capture":p=new A2(`${Y.name} (copy)`);break;case"Macro":p=new Hc(`${Y.name} (copy)`);break;case"Multi":p=new z2(`${Y.name} (copy)`);break}return Y.type!=="Multi"?Object.assign(p,Y0(Y,["id","name"])):p.choices=Y.choices.map(E=>H(E)),p}function X(Y){switch(Y.type){case"Template":return new gG(d,Y,V);case"Capture":return new KG(d,Y,V);case"Macro":return new bb(d,Y,b,i.getState().choices);case"Multi":default:break}}async function n(){let Y=await new Zb(d,V,b,l).waitForClose;Y&&(W(Y),I(9,b=Y))}async function R(){let Y=await new db(i.getState().ai).waitForClose;Y&&i.setState(p=>({...p,ai:Y}))}function J(Y){l=Y,I(0,l)}let t=Y=>Z(Y.detail.choices);return c.$$set=Y=>{"choices"in Y&&I(0,l=Y.choices),"macros"in Y&&I(9,b=Y.macros),"saveChoices"in Y&&I(1,Z=Y.saveChoices),"saveMacros"in Y&&I(10,W=Y.saveMacros),"app"in Y&&I(11,d=Y.app),"plugin"in Y&&I(12,V=Y.plugin)},[l,Z,a,m,N,F,h,n,R,b,W,d,V,J,t]}var NW=class extends O{constructor(G){super(),$(this,G,X5,R5,_,{choices:0,macros:9,saveChoices:1,saveMacros:10,app:11,plugin:12},Y5)}},IV=NW;var p5={name:"OpenAI",endpoint:"https://api.openai.com/v1",apiKey:"",models:[{name:"text-davinci-003",maxTokens:4096},{name:"gpt-3.5-turbo",maxTokens:4096},{name:"gpt-3.5-turbo-16k",maxTokens:16384},{name:"gpt-3.5-turbo-1106",maxTokens:16385},{name:"gpt-4",maxTokens:8192},{name:"gpt-4-32k",maxTokens:32768},{name:"gpt-4-1106-preview",maxTokens:128e3},{name:"gpt-4-turbo",maxTokens:128e3},{name:"gpt-4o",maxTokens:128e3},{name:"gpt-4o-mini",maxTokens:128e3}]},Vb=[p5];var f1={choices:[],macros:[],inputPrompt:"single-line",devMode:!1,templateFolderPath:"",announceUpdates:!0,version:"0.0.0",disableOnlineFeatures:!0,enableRibbonIcon:!1,ai:{defaultModel:"Ask me",defaultSystemPrompt:'As an AI assistant within Obsidian, your primary goal is to help users manage their ideas and knowledge more effectively. Format your responses using Markdown syntax. Please use the [[Obsidian]] link format. You can write aliases for the links by writing [[Obsidian|the alias after the pipe symbol]]. To use mathematical notation, use LaTeX syntax. LaTeX syntax for larger equations should be on separate lines, surrounded with double dollar signs ($$). You can also inline math expressions by wrapping it in $ symbols. For example, use $$w_{ij}^{ ext{new}}:=w_{ij}^{ ext{current}}+etacdotdelta_jcdot x_{ij}$$ on a separate line, but you can write "($eta$ = learning rate, $delta_j$ = error term, $x_{ij}$ = input)" inline.',promptTemplatesFolderPath:"",showAssistant:!0,providers:Vb},migrations:{migrateToMacroIDFromEmbeddedMacro:!1,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1}},mb=class extends Al.PluginSettingTab{constructor(I,l){super(I,l);this.plugin=l}display(){let{containerEl:I}=this;I.empty(),I.createEl("h2",{text:"QuickAdd Settings"}),this.addChoicesSetting(),this.addUseMultiLineInputPromptSetting(),this.addTemplateFolderPathSetting(),this.addAnnounceUpdatesSetting(),this.addDisableOnlineFeaturesSetting(),this.addEnableRibbonIconSetting()}addAnnounceUpdatesSetting(){let I=new Al.Setting(this.containerEl);I.setName("Announce Updates"),I.setDesc("Display release notes when a new version i
2 months ago
`:""}${l}`}if(this.choice.insertAfter.enabled)return await this.insertAfterHandler(l);let Z=this.file?this.getFrontmatterEndPosition(this.file):null;return Z?this.insertTextAfterPositionInBody(l,this.fileContent,Z):`${l}${this.fileContent}`}async formatContentOnly(I){let l=await super.formatFileContent(I);return l=this.replaceLinebreakInString(l),l.trim()===""?this.fileContent:l}async insertAfterHandler(I){let l=await this.format(this.choice.insertAfter.after),b=new RegExp(`\\s*${U0(l.replace("\\n",""))}\\s*`),Z=GW(this.fileContent),W=Z.findIndex(V=>b.test(V));if(W===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(I);u.logError("unable to find insert after line in file.")}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");W=Yb(Z,W,!!this.choice.insertAfter.considerSubsections)??Z.length-1}return this.insertTextAfterPositionInBody(I,this.fileContent,W)}async createInsertAfterIfNotFound(I){let b=`${this.replaceLinebreakInString(await this.format(this.choice.insertAfter.after))}
${I}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Jc){let Z=this.file?this.getFrontmatterEndPosition(this.file):-1;return this.insertTextAfterPositionInBody(b,this.fileContent,Z)}if(this.choice.insertAfter?.createIfNotFoundLocation===R1)return`${this.fileContent}
${b}`;if(this.choice.insertAfter?.createIfNotFoundLocation===X1)try{let Z=this.app.workspace.getActiveViewOfType(bV.MarkdownView);if(!Z)throw new Error("No active view.");let d=Z.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let a=GW(this.fileContent);d=Yb(a,d,!!this.choice.insertAfter.considerSubsections)??a.length-1}return this.insertTextAfterPositionInBody(b,this.fileContent,d)}catch(Z){u.logError(`unable to insert line '${this.choice.insertAfter.after}' on your cursor.
1 week ago
${Z}`)}}getFrontmatterEndPosition(I){let l=this.app.metadataCache.getFileCache(I);return!l||!l.frontmatter?(u.logMessage("could not get frontmatter. Maybe there isn't any."),-1):l.frontmatterPosition?l.frontmatterPosition.end.line:-1}insertTextAfterPositionInBody(I,l,b){if(b===-1){let V=!this.choice.task;return`${I}${V?`
2 months ago
`:""}${l}`}let Z=l.split(`
`),W=Z.slice(0,b+1).join(`
`),d=Z.slice(b+1).join(`
`);return`${W}
${I}${d}`}};var Rb=class{isResolved(){return!this.hasConflicts}isConflicted(){return this.hasConflicts}},H2=class extends Rb{constructor(G,I,l){super(),this.left=G,this.base=I,this.right=l,this.hasConflicts=!0}static create(G){return new H2(G.left,G.base,G.right)}apply(G){return H2.create({left:G(this.left),base:G(this.base),right:G(this.right)})}},$I=class extends Rb{constructor(G){super(),this.hasConflicts=!1,this.result=G}combine(G){this.result=this.result.concat(G.result)}apply(G){return new $I(G(this.result))}};var sl=class{constructor(G,I){this.left=G,this.right=I}static executeDiff(G,I){if(!G.push)throw new Error("Argument is not an array");let l=sl.diff(G,I);return new YW(G,I,l).convertToTypedOutput()}static diff(G,I){return new sl(G,I).performDiff()}performDiff(){let G=this.identifyUniquePositions();G.sort((Z,W)=>W[0]-Z[0]);let[I,l]=this.findNextChange(),b=new Xb(I,l,[]);return G.forEach(Z=>{b=this.getDifferences(b,Z)}),b.changeRanges}getDifferences(G,I){let[l,b]=[G.leftChangePos,G.rightChangePos],[Z,W]=I;if(Z<l||W<b)return G;{let[d,V,a,m]=this.findPrevChange(l,b,Z-1,W-1),[N,F]=this.findNextChange(Z+1,W+1),h=this.appendChangeRange(G.changeRanges,d,V,a,m);return new Xb(N,F,h)}}findNextChange(G=0,I=0){let l=this.left.slice(G)||[],b=this.right.slice(I)||[],Z=this.mismatchOffset(l,b);return[G+Z,I+Z]}findPrevChange(G,I,l,b){if(G>l||I>b)return[G,l,I,b];{let Z=this.left.slice(G,l+1).reverse()||[],W=this.right.slice(I,b+1).reverse()||[],d=this.mismatchOffset(Z,W);return[G,l-d,I,b-d]}}mismatchOffset(G,I){let l=Math.max(G.length,I.length);for(let b=0;b<l;b++)if(G[b]!==I[b])return b;return Math.min(G.length,I.length)}identifyUniquePositions(){let G=this.findUnique(this.left),I=this.findUnique(this.right),l=new Set(...G.keys()),b=new Set(...I.keys()),W=[...new Set([...l].filter(d=>b.has(d)))].map(d=>[G.get(d),I.get(d)]);return W.unshift([this.left.length,this.right.length]),W}findUnique(G){let I=new Map;G.forEach((b,Z)=>{I.set(b,new hW(Z,!I.has(b)))});let l=new Map;for(let[b,Z]of I.entries())Z.unique&&l.set(b,Z.pos);return l}appendChangeRange(G,I,l,b,Z){return I<=l&&b<=Z?G.push(new rc(Tl.change,I+1,l+1,b+1,Z+1)):I<=l?G.push(new rc(Tl.remove,I+1,l+1,b+1,b)):b<=Z&&G.push(new rc(Tl.add,I+1,I,b+1,Z+1)),G}},hW=class{constructor(G,I){this.pos=G,this.unique=I}},qG=class{constructor(G,I){this.text=G,this.low=I}},YW=class{constructor(G,I,l){this.oldTextArray=G,this.newTextArray=I,this.chunks=l,this.oldText=[],this.newText=[]}convertToTypedOutput(){let G=new HW(0,0);return this.chunks.forEach(I=>{let[l,b]=this.setTextNodeIndexes(I,G.oldIndex,G.newIndex),[Z,W]=this.appendChanges(I,G.oldIndex+l,G.newIndex+b);G.oldIndex=Z,G.newIndex=W}),this.setTheRemainingTextNodeIndexes(G.oldIndex,G.newIndex),{oldText:this.oldText,newText:this.newText}}setTextNodeIndexes(G,I,l){let b=0;for(;I+b<G.leftLo-1;)this.oldText.push(new qG(this.oldTextArray[I+b],l+b)),b+=1;let Z=0;for(;l+Z<G.rightLo-1;)this.newText.push(new qG(this.newTextArray[l+Z],I+Z)),Z+=1;return[b,Z]}appendChanges(G,I,l){for(;I<=G.leftHi-1;)this.oldText.push(this.oldTextArray[I]),I+=1;for(;l<=G.rightHi-1;)this.newText.push(this.newTextArray[l]),l+=1;return[I,l]}setTheRemainingTextNodeIndexes(G,I){let l=0;for(;G+l<this.oldTextArray.length;)this.oldText.push(new qG(this.oldTextArray[G+l],I+l)),l+=1;for(;I+l<this.newTextArray.length;)this.newText.push(new qG(this.newTextArray[I+l],G+l)),l+=1}},HW=class{constructor(G,I){this.oldIndex=G,this.newIndex=I}},Tl;(function(c){c.change="change",c.add="add",c.remove="remove"})(Tl||(Tl={}));var rc=class{constructor(G,I,l,b,Z){this.action=G,this.leftLo=I,this.leftHi=l,this.rightLo=b,this.rightHi=Z}},Xb=class{constructor(G,I,l){this.leftChangePos=G,this.rightChangePos=I,this.changeRanges=l}};var _G=class{constructor(G,I,l,b,Z){this.code=G,this.baseLo=I,this.baseHi=l,this.sideLo=b,this.sideHi=Z}static fromChangeRange(G){return new _G(G.action,G.leftLo,G.leftHi,G.rightLo,G.rightHi)}},R2=class{constructor(G,I,l){this.left=G,this.base=I,this.right=l}static executeDiff(G,I,l){return new R2(G,I,l).getDifferences()}getDifferences(){let G=sl.diff(this.base,this
`)}}).join(`
`)}}var WV=c=>c.join(""),e5=c=>c.split(/\b/),t5=ZV("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",WV),w5={splitFunction:e5,joinFunction:WV,conflictFunction:t5};function pW(c,G,I,l={}){l=Object.assign({},w5,l);let[b,Z,W]=[c,G,I].map(a=>l.splitFunction.call(l,a)),d=O2.merge(b,Z,W);return _2.collateMerge(d,l.joinFunction,l.conflictFunction)}var dV=pW;var nb=class extends UG{constructor(I,l,b,Z){super(I);this.choiceExecutor=Z;this.choice=b,this.plugin=l,this.formatter=new Hb(I,l,Z)}async run(){try{let I=await this.getFormattedPathToCaptureTo(this.choice.captureToActiveFile),l=this.getCaptureContent(),b;if(await this.fileExists(I))b=this.onFileExists.bind(this);else if(this.choice?.createFileIfItDoesntExist?.enabled)b=this.onCreateFileIfItDoesntExist.bind(this);else{u.logWarning(`The file ${I} does not exist and "Create file if it doesn't exist" is disabled.`);return}let{file:Z,newFileContent:W,captureContent:d}=await b(I,l);if(this.choice.captureToActiveFile&&!this.choice.prepend&&!this.choice.insertAfter.enabled){let V=await x1(app,d,Z);tc(V,this.app)}else await this.app.vault.modify(Z,W);if(this.choice.appendLink){let V=this.app.fileManager.generateMarkdownLink(Z,"");tc(V,this.app)}this.choice?.openFile&&await U1(this.app,Z,{openInNewTab:this.choice.openFileInNewTab.enabled,direction:this.choice.openFileInNewTab.direction,focus:this.choice.openFileInNewTab.focus,mode:this.choice.openFileInMode})}catch(I){u.logError(I)}}getCaptureContent(){let I;return this.choice.format.enabled?I=this.choice.format.format:I=L2,this.choice.task&&(I=`- [ ] ${I}
`),I}async getFormattedPathToCaptureTo(I){if(I){let a=this.app.workspace.getActiveFile();return Wl(a,"Cannot capture to active file - no active file."),a.path}let l=this.choice.captureTo,b=await this.formatFilePath(l),Z=b.replace(/^\/$|\/\.md$|^\.md$/,""),W=Z==="",d=W||R0(Z),V=b.startsWith("#");if(d)return this.selectFileInFolder(Z,W);if(V){let a=b.replace(/\.md$/,"");return this.selectFileWithTag(a)}return b}async selectFileInFolder(I,l){let b=I.endsWith("/")||l?I:`${I}/`,Z=AG(b);Wl(Z.length>0,`Folder ${b} is empty.`);let W=Z.map(a=>a.path),d=await jl.Suggest(app,W.map(a=>a.replace(b,"")),W);Wl(!!d&&d.length>0,"No file selected for capture.");let V=d.startsWith(`${b}`)?d:`${b}/${d}`;return await this.formatFilePath(V)}async selectFileWithTag(I){let l=I.startsWith("#")?I:`#${I}`,b=X0(l);Wl(b.length>0,`No files with tag ${I}.`);let Z=b.map(d=>d.path),W=await jl.Suggest(app,Z,Z);return Wl(!!W&&W.length>0,"No file selected for capture."),await this.formatFilePath(W)}async onFileExists(I,l){let b=this.getFileByPath(I);if(!b)throw new Error("File not found");let Z=await this.formatter.formatContentOnly(l),W=await this.app.vault.read(b),d=await this.formatter.formatContentWithFile(Z,this.choice,W,b),V=await this.app.vault.read(b),a=d;if(V!==W){let m=dV(V,W,d);Wl(!m.isSuccess,()=>`The file ${I} has been modified since the last read.
QuickAdd could not merge the versions two without conflicts, and will not modify the file.
1 week ago
This is in order to prevent data loss.`),a=m.joinedResults()}return{file:b,newFileContent:a,captureContent:Z}}async onCreateFileIfItDoesntExist(I,l){let b="";this.choice.createFileIfItDoesntExist.createWithTemplate&&(b=await new Y2(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor).run());let Z=await this.createFileWithInput(I,b);await yG(this.app,Z);let W=await this.app.vault.cachedRead(Z),d=await this.formatter.formatContentWithFile(l,this.choice,W,Z);return{file:Z,newFileContent:d,captureContent:l}}async formatFilePath(I){let l=await this.formatter.formatFileName(I,this.choice.name);return this.normalizeMarkdownFilePath("",l)}};var sb=require("obsidian");var zl=class extends sb.FuzzySuggestModal{constructor(I,l,b){super(I.app);this.plugin=I;this.choices=l;this.choiceExecutor=new X2(this.app,this.plugin);b&&(this.choiceExecutor=b)}static Open(I,l,b){new zl(I,l,b).open()}renderSuggestion(I,l){l.empty(),sb.MarkdownRenderer.renderMarkdown(I.item.name,l,"",this.plugin),l.classList.add("quickadd-choice-suggestion")}getItemText(I){return I.name}getItems(){return this.choices}async onChooseItem(I,l){I.type==="Multi"?this.onChooseMultiType(I):await this.choiceExecutor.execute(I)}onChooseMultiType(I){let l=[...I.choices];I.name!="\u2190 Back"&&l.push(new z2("\u2190 Back").addChoices(this.choices)),zl.Open(this.plugin,l)}};var X2=class{constructor(G,I){this.app=G;this.plugin=I;this.variables=new Map}async execute(G){switch(G.type){case"Template":{let I=G;await this.onChooseTemplateType(I);break}case"Capture":{let I=G;await this.onChooseCaptureType(I);break}case"Macro":{let I=G;await this.onChooseMacroType(I);break}case"Multi":{let I=G;this.onChooseMultiType(I);break}default:break}}async onChooseTemplateType(G){await new hb(this.app,this.plugin,G,this).run()}async onChooseCaptureType(G){await new nb(this.app,this.plugin,G,this).run()}async onChooseMacroType(G){let I=new Ll(this.app,this.plugin,G,this.plugin.settings.macros,this,this.variables);await I.run(),Object.entries(I.params.variables).forEach(([l,b])=>{this.variables.set(l,b)})}onChooseMultiType(G){zl.Open(this.plugin,G.choices,this)}};var VV={description:"Migrate to macro ID from embedded macro in macro choices.",migrate:async c=>{function G(I){if(I.type==="Multi"){let b=I,Z=b.choices.map(G);return b={...b,choices:Z},b}if(I.type!=="Macro")return I;let l=I;return l.macro&&(l.macroId=l.macro.id,delete l.macro),l}c.settings.choices=c.settings.choices.map(G),await c.saveSettings()}};var mV={description:"Use QuickAdd template folder instead of Obsidian templates plugin folder / Templater templates folder.",migrate:async c=>{try{let G=app.plugins.plugins.templater,I=app.internalPlugins.plugins.templates;if(!G&&!I){u.logMessage("No template plugin found. Skipping migration.");return}if(I){let l=I.instance.options;l.folder&&(c.settings.templateFolderPath=l.folder,u.logMessage("Migrated template folder path to Obsidian Templates' setting."))}if(G){let l=G.settings;l.template_folder&&(c.settings.templateFolderPath=l.template_folder,u.logMessage("Migrated template folder path to Templaters setting."))}}catch(G){throw u.logError("Failed to migrate template folder path."),G}}};function Eb(c){return c===null||typeof c!="object"||!("type"in c)||!("choices"in c)?!1:c.type==="Multi"&&c.choices!==void 0}function Qb(c){return c===null||typeof c!="object"||!("choice"in c)?!1:c.choice!==void 0}function nW(c){return typeof c!="object"||c===null?!1:"incrementFileName"in c}function aV(c){for(let G of c)Eb(G)&&(G.choices=aV(G.choices)),nW(G)&&(G.setFileExistsBehavior=!0,G.fileExistsMode="Increment the file name",delete G.incrementFileName);return c}function u5(c){for(let G of c)if(Array.isArray(G.commands))for(let I of G.commands)Qb(I)&&nW(I.choice)&&(I.choice.setFileExistsBehavior=!0,I.choice.fileExistsMode="Increment the file name",delete I.choice.incrementFileName);return c}var y5={description:"'Increment file name' setting moved to 'Set default behavior if file already exists' setting",migrate:async c=>{let G=structuredClone(c.settings.choices),I=aV(G),l
2 years ago
2 months ago
${b}
2 years ago
2 months ago
QuickAdd will now revert to backup.`),c.settings=l}}c.saveSettings()}var RV=i5;var XV=require("obsidian"),vb=require("obsidian");async function r5(c,G,I){let l=await fetch(`https://api.github.com/repos/${c}/${G}/releases`),b=await l.json();if(!l.ok&&"message"in b||!Array.isArray(b))throw new Error(`Failed to fetch releases: ${b.message??"Unknown error"}`);let Z=b.findIndex(W=>W.tag_name===I);if(Z===-1)throw new Error(`Could not find release with tag ${I}`);return b.slice(0,Z).filter(W=>!W.draft&&!W.prerelease)}function k5(c,G=1){let I=c.split(`
`);for(let l=0;l<I.length;l++)I[l].startsWith("#")&&(I[l]="#".repeat(G)+I[l]);return I.join(`
`)}var Jb=class extends vb.Modal{constructor(I){super(app);this.previousVersion=I,this.releaseNotesPromise=r5("chhoumann","quickadd",I),this.releaseNotesPromise.then(l=>{if(this.releases=l,this.releases.length===0){this.close();return}this.display()}).catch(l=>{u.logError(`Failed to fetch release notes: ${l}`)})}onOpen(){let{contentEl:I}=this;I.empty(),I.createEl("h1",{text:"Fetching release notes..."})}onClose(){let{contentEl:I}=this;I.empty()}display(){let{contentEl:I}=this;I.empty(),I.classList.add("quickadd-update-modal-container");let l=`### New in QuickAdd v${this.releases[0].tag_name}
`,b="Thank you for using QuickAdd! If you like the plugin, please consider supporting me by buying me a coffee. With your sponsorship, I'll be able to contribute more to my existing projects, start new ones, and be more responsive to issues & feature requests.",Z='<div class="quickadd-bmac-container"><a href="https://www.buymeacoffee.com/chhoumann" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 144px !important;" ></a></div>',W=I.createDiv("quickadd-update-modal"),d=this.releases.map(N=>N.body).join(`
2 years ago
---
2 months ago
`),V=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,m=`${l}
${b}
${Z}
I'd love to get your feedback on QuickAdd! Please fill out this <a href="https://forms.gle/WRq1ewcKK8qmkqps6">feedback form</a> to let me know what you think.
2 years ago
2 months ago
${V}
1 year ago
2 months ago
---
2 years ago
1 week ago
${k5(d)}`;vb.MarkdownRenderer.renderMarkdown(m,W,app.vault.getRoot().path,new XV.Component)}};var eI=require("obsidian");var eb=class extends eI.Modal{constructor(I){super(app);this.showAdvancedSettings=!1;this.settings=I,this.waitForClose=new Promise((l,b)=>{this.rejectPromise=b,this.resolvePromise=l}),this.open(),this.display()}get systemPromptTokenLength(){let I=yl(this.settings.model);return I?dl(this.settings.systemPrompt,I):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();let I=this.contentEl.createEl("h2",{text:`${this.settings.name} Settings`});I.style.textAlign="center",I.style.cursor="pointer",I.style.userSelect="none",I.addEventListener("click",async()=>{try{let l=await dI.Prompt(app,"New name",this.settings.name,this.settings.name);l&&l!==this.settings.name&&(this.settings.name=l,this.reload())}catch{}}),this.addResultJoinerSetting(this.contentEl),this.addChunkSeparatorSetting(this.contentEl),this.addMaxTokensSetting(this.contentEl),this.addMergeChunksSetting(this.contentEl),this.addModelSetting(this.contentEl),this.addOutputVariableNameSetting(this.contentEl),this.addShowAdvancedSettingsToggle(this.contentEl),this.showAdvancedSettings&&(this.settings.modelParameters||(this.settings.modelParameters={}),this.addTemperatureSetting(this.contentEl),this.addTopPSetting(this.contentEl),this.addFrequencyPenaltySetting(this.contentEl),this.addPresencePenaltySetting(this.contentEl)),this.addSystemPromptSetting(this.contentEl)}reload(){this.contentEl.empty(),this.display()}addModelSetting(I){new eI.Setting(I).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(l=>{let b=Ml();for(let Z of b)l.addOption(Z,Z);l.addOption("Ask me","Ask me"),l.setValue(this.settings.model),l.onChange(Z=>{this.settings.model=Z,this.reload()})})}addOutputVariableNameSetting(I){new eI.Setting(I).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(l=>{l.setValue(this.settings.outputVariableName).onChange(b=>{this.settings.outputVariableName=b})})}addSystemPromptSetting(I){new eI.Setting(I).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let l=this.contentEl.createEl("div"),b=l.createEl("span");b.style.color="var(--text-muted-color)",l.appendChild(b);let Z=new eI.TextAreaComponent(I);Z.setValue(this.settings.systemPrompt).onChange(async a=>{this.settings.systemPrompt=a,d.innerText=await W.format(a),V()}),new CI(this.app,Z.inputEl,GI.instance);let W=new Vl(this.app,GI.instance);Z.inputEl.style.width="100%",Z.inputEl.style.height="100px",Z.inputEl.style.minHeight="100px",Z.inputEl.style.marginBottom="1em";let d=this.contentEl.createEl("span"),V=(0,eI.debounce)(()=>{b.innerText=`Token count: ${this.systemPromptTokenLength}`},50);V(),(async()=>d.innerText=await W.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(I){new eI.Setting(I).setName("Show advanced settings").setDesc("Show advanced settings such as temperature, top p, and frequency penalty.").addToggle(l=>{l.setValue(this.showAdvancedSettings),l.onChange(b=>{this.showAdvancedSettings=b,this.reload()})})}addTemperatureSetting(I){new eI.Setting(I).setName("Temperature").setDesc("Sampling temperature. Higher values like 0.8 makes the output more random, whereas lower values like 0.2 will make it more focused and deterministic. The default is 1.").addSlider(l=>{l.setLimits(0,1,.1),l.setDynamicTooltip(),l.setValue(this.settings.modelParameters.temperature??1),l.onChange(b=>{this.settings.modelParameters.temperature=b})})}addTopPSetting(I){new eI.Setting(I).setName("Top P").setDesc("Nucleus sampling - consider this an alternative to temperature. The model considers the results of the tokens with top_p probability mass. 0.1 means only tokens compromising the top 10% probability mass are considered. The default is 1.").addSlider(l=>{l.setLimits(0,1,.1),l.setDynamicTooltip(),l.setValue(this.settings.modelParameters.top_p??1),l.onChange(b=>{this.settings.modelParameters.top_p=b})})}addFrequencyPenaltySetting(I){new eI.Setting(I).setName
/* nosourcemap */