`)&&(II++,lI===0&&(lI=$+1)),$--}var NI=f+II,Gl=y-lI;return U[y]={line:NI,lineStart:lI},{offset:y,line:NI+1,column:Gl+1}}function k(X){if(!i(X))throw new Error("not a parser: "+X)}function O(X,y){return typeof X=="string"?X.charAt(y):X[y]}function K(X){if(typeof X!="number")throw new Error("not a number: "+X)}function J(X){if(typeof X!="function")throw new Error("not a function: "+X)}function H(X){if(typeof X!="string")throw new Error("not a string: "+X)}var v=2,A=3,B=8,q=5*B,mI=4*B,nI=" ";function VI(X,y){return new Array(y+1).join(X)}function RI(X,y,U){var f=y-X.length;return f<=0?X:VI(U,f)+X}function uI(X,y,U,f){return{from:X-y>0?X-y:0,to:X+U>f?f:X+U}}function WI(X,y){var U,f,II,lI,$,NI=y.index,Gl=NI.offset,Hl=1;if(Gl===X.length)return"Got the end of the input";if(R(X)){var bl=Gl-Gl%B,be=Gl-bl,Dl=uI(bl,q,mI+B,X.length),Ml=a(function(Ol){return a(function(xb){return RI(xb.toString(16),2,"0")},Ol)},function(Ol,xb){var Ub=Ol.length,Jc=[],zb=0;if(Ub<=xb)return[Ol.slice()];for(var Bb=0;Bb<Ub;Bb++)Jc[zb]||Jc.push([]),Jc[zb].push(Ol[Bb]),(Bb+1)%xb==0&&zb++;return Jc}(X.slice(Dl.from,Dl.to).toJSON().data,B));lI=function(Ol){return Ol.from===0&&Ol.to===1?{from:Ol.from,to:Ol.to}:{from:Ol.from/B,to:Math.floor(Ol.to/B)}}(Dl),f=bl/B,U=3*be,be>=4&&(U+=1),Hl=2,II=a(function(Ol){return Ol.length<=4?Ol.join(" "):Ol.slice(0,4).join(" ")+" "+Ol.slice(4).join(" ")},Ml),($=(8*(lI.to>0?lI.to-1:lI.to)).toString(16).length)<2&&($=2)}else{var fl=X.split(/\r\n|[\n\r\u2028\u2029]/);U=NI.column-1,f=NI.line-1,lI=uI(f,v,A,fl.length),II=fl.slice(lI.from,lI.to),$=lI.to.toString().length}var Cl=f-lI.from;return R(X)&&($=(8*(lI.to>0?lI.to-1:lI.to)).toString(16).length)<2&&($=2),Z(function(Ol,xb,Ub){var Jc,zb=Ub===Cl,Bb=zb?"> ":nI;return Jc=R(X)?RI((8*(lI.from+Ub)).toString(16),$,"0"):RI((lI.from+Ub+1).toString(),$," "),[].concat(Ol,[Bb+Jc+" | "+xb],zb?[nI+VI(" ",$)+" | "+RI("",U," ")+VI("^",Hl)]:[])},[],II).join(`
`)}function LI(X,y){return[`
`,"-- PARSING FAILED "+VI("-",50),`
`,WI(X,y),`
`,(U=y.expected,U.length===1?`Expected:
`+U[0]:`Expectedoneofthefollowing:
`+U.join(", ")),`
`].join("");var U}function ll(X){return X.flags!==void 0?X.flags:[X.global?"g":"",X.ignoreCase?"i":"",X.multiline?"m":"",X.unicode?"u":"",X.sticky?"y":""].join("")}function ul(){for(var X=[].slice.call(arguments),y=X.length,U=0;U<y;U+=1)k(X[U]);return c(function(f,II){for(var lI,$=new Array(y),NI=0;NI<y;NI+=1){if(!(lI=w(X[NI]._(f,II),lI)).status)return lI;$[NI]=lI.value,II=lI.index}return w(h(II,$),lI)})}function vl(){var X=[].slice.call(arguments);if(X.length===0)throw new Error("seqMap needs at least one argument");var y=X.pop();return J(y),ul.apply(null,X).map(function(U){return y.apply(null,U)})}function hl(){var X=[].slice.call(arguments),y=X.length;if(y===0)return j("zero alternates");for(var U=0;U<y;U+=1)k(X[U]);return c(function(f,II){for(var lI,$=0;$<X.length;$+=1)if((lI=w(X[$]._(f,II),lI)).status)return lI;return lI})}function ge(X,y){return fG(X,y).or(NG([]))}function fG(X,y){return k(X),k(y),vl(X,y.then(X).many(),function(U,f){return[U].concat(f)})}function jG(X){H(X);var y="'"+X+"'";return c(function(U,f){var II=f+X.length,lI=U.slice(f,II);return lI===X?h(II,lI):F(f,y)})}function WG(X,y){(function(II){if(!(II instanceof RegExp))throw new Error("not a regexp: "+II);for(var lI=ll(II),$=0;$<lI.length;$++){var NI=lI.charAt($);if(NI!=="i"&&NI!=="m"&&NI!=="u"&&NI!=="s")throw new Error('unsupported regexp flag "'+NI+'": '+II)}})(X),arguments.length>=2?K(y):y=0;var U=function(II){return RegExp("^(?:"+II.source+")",ll(II))}(X),f=""+X;return c(function(II,lI){var $=U.exec(II.slice(lI));if($){if(0<=y&&y<=$.length){var NI=$[0],Gl=$[y];return h(lI+NI.length,Gl)}return F(lI,"valid match group (0 to "+$.length+") in "+f)}return F(lI,f)})}function NG(X){return c(function(y,U){return h(U,X)})}function j(X){return c(function(y,U){return F(U,X)})}function kI(X){if(i(X))return c(function(y,U){var f=X._(y,U);return f.index=U,f.value="",f});if(typeof X=="string")return kI(jG(X));if(X instanceof RegExp)return kI(WG(X));throw new Error("not a string, regexp, or parser: "+X)}function xI(X){return k(X),c(function(y,U){var f=X._(y,U),II=y.slice(U,f.index);return f.status?F(U,'not "'+II+'"'):h(U,null)})}function SI(X){return J(X),c(function(y,U){var f=O(y,U);return U<y.length&&X(f)?h(U+1,f):F(U,"a character/byte matching "+X)})}function te(X,y){arguments.length<2&&(y=X,X=void 0);var U=c(function(f,II){return U._=y()._,U._(f,II)});return X?U.desc(X):U}function YG(){return j("fantasy-land/empty")}b.parse=function(X){if(typeof X!="string"&&!R(X))throw new Error(".parse must be called with a string or Buffer as its argument");var y,U=this.skip(ce)._(X,0);return y=U.status?{status:!0,value:U.value}:{status:!1,index:T(X,U.furthest),expected:U.expected},delete E[X],y},b.tryParse=function(X){var y=this.parse(X);if(y.status)return y.value;var U=LI(X,y),f=new Error(U);throw f.type="ParsimmonError",f.result=y,f},b.assert=function(X,y){return this.chain(function(U){return X(U)?NG(U):j(y)})},b.or=function(X){return hl(this,X)},b.trim=function(X){return this.wrap(X,X)},b.wrap=function(X,y){return vl(X,this,y,function(U,f){return f})},b.thru=function(X){return X(this)},b.then=function(X){return k(X),ul(this,X).map(function(y){return y[1]})},b.many=function(){var X=this;return c(function(y,U){for(var f=[],II=void 0;;){if(!(II=w(X._(y,U),II)).status)return w(h(U,f),II);if(U===II.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");U=II.index,f.push(II.value)}})},b.tieWith=function(X){return H(X),this.map(function(y){if(function(II){if(!Q(II))throw new Error("not an array: "+II)}(y),y.length){H(y[0]);for(var U=y[0],f=1;f<y.length;f++)H(y[f]),U+=X+y[f];return U}return""})},b.tie=function(){return this.tieWith("")},b.times=function(X,y){var U=this;return arguments.length<2&&(y=X),K(X),K(y),c(function(f,II){for(var lI=[],$=void 0,NI=void 0,Gl=0;Gl<X;Gl+=1){if(NI=w($=U._(f,II),NI),!$.status)return NI;II=$.index,lI.push($.value)}for(;Gl<y&&(NI=w($=U._(f,II),NI),$.status);Gl+=1)II=$.index,lI.push($.value);return w(h(II,lI),NI)})},b.result=function(X){return thi
`),yc=jG(`\r
`),ye=hl(yc,MZ,Hc).desc("newline"),hW=hl(ye,ce);c.all=Ft,c.alt=hl,c.any=St,c.cr=Hc,c.createLanguage=function(X){var y={};for(var U in X)({}).hasOwnProperty.call(X,U)&&function(f){y[f]=te(function(){return X[f](y)})}(U);return y},c.crlf=yc,c.custom=function(X){return c(X(h,F))},c.digit=Tt,c.digits=vc,c.empty=YG,c.end=hW,c.eof=ce,c.fail=j,c.formatError=LI,c.index=SG,c.isParser=i,c.lazy=te,c.letter=qt,c.letters=ve,c.lf=MZ,c.lookahead=kI,c.makeFailure=F,c.makeSuccess=h,c.newline=ye,c.noneOf=function(X){return SI(function(y){return X.indexOf(y)<0}).desc("none of '"+X+"'")},c.notFollowedBy=xI,c.of=NG,c.oneOf=function(X){for(var y=X.split(""),U=0;U<y.length;U++)y[U]="'"+y[U]+"'";return SI(function(f){return X.indexOf(f)>=0}).desc(y)},c.optWhitespace=CW,c.Parser=c,c.range=function(X,y){return SI(function(U){return X<=U&&U<=y}).desc(X+"-"+y)},c.regex=WG,c.regexp=WG,c.sepBy=ge,c.sepBy1=fG,c.seq=ul,c.seqMap=vl,c.seqObj=function(){for(var X,y={},U=0,f=(X=arguments,Array.prototype.slice.call(X)),II=f.length,lI=0;lI<II;lI+=1){var $=f[lI];if(!i($)){if(Q($)&&$.length===2&&typeof $[0]=="string"&&i($[1])){var NI=$[0];if(Object.prototype.hasOwnProperty.call(y,NI))throw new Error("seqObj: duplicate key "+NI);y[NI]=!0,U++;continue}throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(U===0)throw new Error("seqObj expects at least one named parser, found zero");return c(function(Gl,Hl){for(var bl,be={},Dl=0;Dl<II;Dl+=1){var Ml,fl;if(Q(f[Dl])?(Ml=f[Dl][0],fl=f[Dl][1]):(Ml=null,fl=f[Dl]),!(bl=w(fl._(Gl,Hl),bl)).status)return bl;Ml&&(be[Ml]=bl.value),Hl=bl.index}return w(h(Hl,be),bl)})},c.string=jG,c.succeed=NG,c.takeWhile=function(X){return J(X),c(function(y,U){for(var f=U;f<y.length&&X(O(y,f));)f++;return h(f,y.slice(U,f))})},c.test=SI,c.whitespace=He,c["fantasy-land/empty"]=YG,c["fantasy-land/of"]=NG,c.Binary={bitSeq:N,bitSeqObj:function(X){W();var y={},U=0,f=a(function(lI){if(Q(lI)){var $=lI;if($.length!==2)throw new Error("["+$.join(", ")+"] should be length 2, got length "+$.length);if(H($[0]),K($[1]),Object.prototype.hasOwnProperty.call(y,$[0]))throw new Error("duplicate key in bitSeqObj: "+$[0]);return y[$[0]]=!0,U++,$}return K(lI),[null,lI]},X);if(U<1)throw new Error("bitSeqObj expects at least one named pair, got ["+X.join(", ")+"]");var II=a(function(lI){return lI[0]},f);return N(a(function(lI){return lI[1]},f)).map(function(lI){return Z(function($,NI){return NI[0]!==null&&($[NI[0]]=NI[1]),$},{},a(function($,NI){return[$,lI[NI]]},II))})},byte:function(X){if(W(),K(X),X>255)throw new Error("Value specified to byte constructor ("+X+"=0x"+X.toString(16)+") is larger in value than a single byte.");var y=(X>15?"0x":"0x0")+X.toString(16);return c(function(U,f){var II=O(U,f);return II===X?h(f+1,II):F(f,y)})},buffer:function(X){return Y("buffer",X).map(function(y){return Buffer.from(y)})},encodedString:function(X,y){return Y("string",y).map(function(U){return U.toString(X)})},uintBE:u,uint8BE:u(1),uint16BE:u(2),uint32BE:u(4),uintLE:V,uint8LE:V(1),uint16LE:V(2),uint32LE:V(4),intBE:C,int8BE:C(1),int16BE:C(2),int32BE:C(4),intLE:r,int8LE:r(1),int16LE:r(2),int32LE:r(4),floatBE:Y("floatBE",4).map(function(X){return X.readFloatBE(0)}),floatLE:Y("floatLE",4).map(function(X){return X.readFloatLE(0)}),doubleBE:Y("doubleBE",8).map(function(X){return X.readDoubleBE(0)}),doubleLE:Y("doubleLE",8).map(function(X){return X.readDoubleLE(0)})},l.exports=c}])})})(VY,VY.exports);var g=VY.exports,fh=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2
`)}function TZ(e){let I=Object.entries(e);if(I.length===0)return[];let G=["t","tm","yd"].map(b=>{let d=e[b];return d?[b,d]:null}).filter(b=>b!==null),t=new Set(G.map(([b])=>b)),c=I.filter(([b])=>!t.has(b)).sort((b,d)=>{let Z=b[0].length-d[0].length;return Z!==0?Z:b[0].localeCompare(d[0])});return[...G,...c]}function wW(e){return TZ(e).map(([I,l])=>`${I}=${l}`).join(", ")}var gW={choices:[],inputPrompt:"single-line",persistInputPromptDrafts:!0,useSelectionAsCaptureValue:!0,devMode:!1,templateFolderPath:"",announceUpdates:"major",version:"0.0.0",globalVariables:{},onePageInputEnabled:!1,disableOnlineFeatures:!0,enableRibbonIcon:!1,showCaptureNotification:!0,showInputCancellationNotification:!1,enableTemplatePropertyTypes:!1,dateAliases:jb,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:FW},migrations:{migrateToMacroIDFromEmbeddedMacro:!0,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1}};function el(e){let I=globalThis.structuredClone;if(typeof I=="function")try{return I(e)}catch{}return $t(e,new Map)}function $t(e,I){if(e===null||typeof e!="object")return e;if(I.has(e))return I.get(e);if(e instanceof Date){let t=new Date(e.getTime());return I.set(e,t),t}if(Array.isArray(e)){let t=[];I.set(e,t);for(let c of e)t.push($t(c,I));return t}if(e instanceof Map){let t=new Map;I.set(e,t);for(let[c,b]of e.entries())t.set($t(c,I),$t(b,I));return t}if(e instanceof Set){let t=new Set;I.set(e,t);for(let c of e.values())t.add($t(c,I));return t}if(e instanceof RegExp){let t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,I.set(e,t),t}if(e instanceof ArrayBuffer){let t=e.slice(0);return I.set(e,t),t}if(ArrayBuffer.isView(e)){if(e instanceof DataView){let d=new DataView($t(e.buffer,I),e.byteOffset,e.byteLength);return I.set(e,d),d}let t=e,c=$t(t.buffer,I),b=new t.constructor(c,t.byteOffset,t.length);return I.set(e,b),b}let l=Object.getPrototypeOf(e),G=Object.create(l);I.set(e,G);for(let[t,c]of Object.entries(e))Object.defineProperty(G,t,{value:$t(c,I),writable:!0,enumerable:!0,configurable:!0});return G}var P=(()=>{let e=Xp((t,c)=>({...el(gW)})),{getState:I,setState:l,subscribe:G}=e;return{getState:I,setState:l,subscribe:G}})();var EI=require("obsidian");var Kc="{{value}}",Ci="{{date}}",Rp="{{time}}",hi="{{name}}",Dw="{{value:<variable name>}}",Mw="{{value:<variable name>|<default value>}}",fw="{{value:<variable name>|default:<value>}}",jw="{{value:<variable name>|label:<helper text>}}",Sw="{{value:<items>|text:<display items>}}",Tw="{{value|case:kebab}}",qw="{{value:<variable name>|case:kebab}}",Pw="{{field:<field name>}}",Lp="{{mvalue}}",Fp="{{linkcurrent}}",wp="{{filenamecurrent}}",gp="{{title}}",vp="{{selected}}",Hp="{{clipboard}}",_w="{{random:<length>}}",$w="{{global_var:<name>}}";var yp=[Ci,"{{date:<dateformat>}}","{{vdate:<variable name>, <date format>}}","{{vdate:<variable name>, <date format>|<default value>}}",$w,Kc,hi,Tw,qw,Dw,Mw,fw,jw,Sw,Pw,_w];var pi=new RegExp(/^-?[0-9]*$/),Sb="top",qZ="bottom",PZ="cursor",vW=new RegExp(/{{DATE(\+-?[0-9]+)?}}/i),Tb=n
`+e,{line:b,ch:m.length}),t.setCursor({line:b+Z,ch:a})}}catch{x.logError(`unabletoinsert'${e}'onnewline${I}.`)}}function B2(e,I){z2(e,"above",I)}function D2(e,I){z2(e,"below",I)}function uy(e,I,l="replaceSelection",G={}){let{requireActiveView:t=!0}=G,c=e.workspace.getActiveViewOfType(xG.MarkdownView);if(!c){let m="Cannot append link because no active Markdown view is available.";if(t)throw new Error(m);x.logMessage(m);return}let b=c.editor,d=b.listSelections().map(m=>({anchor:{...m.anchor},head:{...m.head}}));if(l==="replaceSelection"){b.replaceSelection(I);return}let Z=({line:m,ch:n})=>b.posToOffset({line:m,ch:n}),a=d.sort((m,n)=>Z(n.head)-Z(m.head));for(let m of a){let n=Z(m.anchor)>Z(m.head)?m.anchor:m.head;switch(l){case"afterSelection":{b.replaceRange(I,n);break}case"endOfLine":{let W=b.getLine(n.line),N={line:n.line,ch:W.length};b.replaceRange(I,N);break}case"newLine":{let W=b.getLine(n.line),N={line:n.line,ch:W.length},s=W.length===0?"":`
`;b.replaceRange(s+I,N);break}}}}function Cy(e){let I=/^\s*!?\[[^\]]*\]\((.+)\)\s*$/,l=e.match(I);if(!l)return null;let G=l[1].trim();return G?(G.startsWith("<")&&G.endsWith(">")&&(G=G.slice(1,-1).trim()),G):null}function hy(e){let I=e.trim();if(I.startsWith("![[")&&I.includes("]]"))return e;let l=e.indexOf("[["),G=e.indexOf("]]",l+2);if(l!==-1&&G!==-1)return(l>0?e.charAt(l-1):"")==="!"?e:`${e.slice(0,l)}!${e.slice(l)}`;let t=Cy(e);return t?`![[${t}]]`:e.startsWith("!")?e:`!${e}`}function hN(e,I,l){if(!l?.enabled)return!1;let G=e.workspace.getActiveFile();if(!G&&l.requireActiveFile)throw new Error("Append link is enabled but there's no active file to insert into.");if(!e.workspace.getActiveViewOfType(xG.MarkdownView)){if(l.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}let c=G?.path??"",b=e.fileManager.generateMarkdownLink(I,c),Z=l.linkType==="embed"&&At(l.placement)?hy(b):b;return uy(e,Z,l.placement,{requireActiveView:!1}),!0}function py(e,I){return e.commands.findCommand(I)}function M2(e,I){py(e,I)&&(delete e.commands.commands[I],delete e.commands.editorCommands[I])}function nb(e){return e.vault.getAllLoadedFiles().filter(I=>I instanceof xG.TFolder).map(I=>I.path)}function Nn(e){let I=e.split("::").map(l=>l.trim()).filter(Boolean);return{basename:I[0],memberAccess:I.slice(1)}}async function Wb(e,I,l={}){let{location:G="tab",direction:t="vertical",mode:c,focus:b=!0,eState:d}=l,Z=typeof I=="string"?e.vault.getAbstractFileByPath(I):I;if(!Z)throw new Error(`Filenotfound:${String(I)}`);let a;switch(G){case"reuse":a=e.workspace.getLeaf(!1);break;case"tab":a=e.workspace.getLeaf("tab");break;case"split":a=e.workspace.getLeaf("split",t);break;case"window":a=e.workspace.getLeaf("window");break;case"left-sidebar":a=e.workspace.getLeftLeaf(!0);break;case"right-sidebar":a=e.workspace.getRightLeaf(!0);break;default:a=e.workspace.getLeaf("tab")}if(!a)throw new Error("Could not obtain a workspace leaf.");if(await a.openFile(Z),c&&c!=="default"&&!(typeof c=="object"&&c.mode==="default")){let m=a.getViewState(),n={...m.state??{}};c==="preview"||typeof c=="object"&&c.mode==="preview"?(n.mode="preview",delete n.source):c==="source"?(n.mode="source",n.source=!0):c==="live"||c==="live-preview"?(n.mode="source",n.source=!1):typeof c=="object"&&c.mode==="source"&&(n.mode="source",n.source=c.source),await a.setViewState({...m,state:{...n,...d}})}return b&&e.workspace.setActiveLeaf(a,{focus:!0}),a}function O2(e){return(0,xG.normalizePath)(e).replace(/\/{2,}/g,"/").replace(/^\/+/,"")}function Vy(e,I){return O2(e)===O2(I)}function Yn(e,I,l=!0){let G;return e.workspace.iterateRootLeaves(t=>{let c=t.view;if(c instanceof xG.FileView&&c.file&&(c.file===I||Vy(I.path,c.file.path))){G=t;return}}),G!==void 0?(l&&e.workspace.setActiveLeaf(G,{focus:!0}),G):null}async function kt(e,I){let l=I.vault.getAbstractFileByPath(e.path);if(!l){x.logError(`failedtoloadfile${e.path}.`);return}if(l instanceof xG.TFile){let G=n=>window.require&&window.require(n),t={},c={exports:t},b=await I.vault.read(l);window.eval(`(function(require,module,exports){${b}
`).filter(Boolean).reduce((G,t)=>{let[c,b,...d]=t.split(" "),Z=Number.parseInt(b,10);return d.forEach((a,m)=>G[a]=Z+m),G},{});for(let[G,t]of Object.entries(l)){let c=qr.default.toByteArray(G);this.rankMap.set(c.join(","),t),this.textMap.set(t,c)}this.specialTokens={...e.special_tokens,...I},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((G,[t,c])=>(G[c]=this.textEncoder.encode(t),G),{})}encode(e,I=[],l="all"){let G=new RegExp(this.patStr,"ug"),t=ch.specialTokenRegex(Object.keys(this.specialTokens)),c=[],b=new Set(I==="all"?Object.keys(this.specialTokens):I),d=new Set(l==="all"?Object.keys(this.specialTokens).filter(a=>!b.has(a)):l);if(d.size>0){let a=ch.specialTokenRegex([...d]),m=e.match(a);if(m!=null)throw new Error(`Thetextcontainsaspecialtokenthatisnotallowed:${m[0]}`)}let Z=0;for(;;){let a=null,m=Z;for(;t.lastIndex=m,a=t.exec(e),!(a==null||b.has(a[0]));)m=a.index+1;let n=a?.index??e.length;for(let N of e.substring(Z,n).matchAll(G)){let Y=this.textEncoder.encode(N[0]),s=this.rankMap.get(Y.join(","));if(s!=null){c.push(s);continue}c.push(...Y5(Y,this.rankMap))}if(a==null)break;let W=this.specialTokens[a[0]];c.push(W),Z=a.index+a[0].length}return c}decode(e){let I=[],l=0;for(let c=0;c<e.length;++c){let b=e[c],d=this.textMap.get(b)??this.inverseSpecialTokens[b];d!=null&&(I.push(d),l+=d.length)}let G=new Uint8Array(l),t=0;for(let c of I)G.set(c,t),t+=c.length;return this.textDecoder.decode(G)}},lY=ch;W5(lY,"specialTokenRegex",e=>new RegExp(e.map(I=>s5(I)).join("|"),"g"));function bh(e){switch(e){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":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":retur
${I}`:""}`;functiontY(e){if(e){letI=newtX.Notice(eX("starting",""),1e6);return{setMessage:(l,G)=>{I.setMessage(eX(l,G))},hide:()=>I.hide()}}return{setMessage:()=>{},hide:()=>{}}}varcX={cl100k_base:Pr,o200k_base:_r},bX=newMap;functiono5(e){letI=eincX?e:"cl100k_base",l=bX.get(I);if(l)returnl;letG=newlY(cX[I]);returnbX.set(I,G),G}var$G=(e,I)=>{letl="cl100k_base";try{l=bh(I.name)}catch{l="cl100k_base"}return(l==="p50k_base"||l==="p50k_edit"||l==="r50k_base"||l==="gpt2")&&(l="cl100k_base"),o5(l).encode(e).length},dX=25,he=[];functionah(e){return{...e,modelOptions:{...e.modelOptions},usage:e.usage?{...e.usage}:void0}}functionGX(e){letI=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,l=Date.now();returnhe.push({...e,modelOptions:{...e.modelOptions??{}},id:I,createdAt:l,status:"pending"}),mX(),I}functiondh(e,I){letl=he.find(G=>G.id===e);l&&(l.status=I.status,l.durationMs=I.durationMs,l.usage=I.usage,l.errorMessage=I.errorMessage,mX())}functionaX(e=10){Number.isFinite(e)||(e=10);letI=Math.floor(e);returnI<=0?[]:he.slice(-I).map(ah).reverse()}functionmX(){if(he.length<=dX)return;lete=he.length-dX;for(;e>0;){letI=he.findIndex(l=>l.status!=="pending");if(I===-1)break;he.splice(I,1),e-=1}}functionnX(e){letI=he.find(l=>l.id===e);returnI?ah(I):null}functionWX(){lete=he[he.length-1];returne?ah(e):null}functionNX(){he.splice(0,he.length)}asyncfunctionr5(e,I,l){if(typeofe!="function")thrownewTypeError("Callback must be a function.");if(!(IinstanceofPromise))thrownewTypeError("Promise must be an instance of Promise.");if(typeofl!="number"||l<=0)thrownewTypeError("Interval must be a positive number.");letG=!1;for(I.finally(()=>{G=!0});!G;)e(),awaitsleep(l)}asyncfunctionX5(e,I,l){letG;if(I.enable)G=l.find(d=>d.path.endsWith(I.name));else{letd=l.map(Z=>Z.basename);G=awaitCG.Suggest(e,d,l)}_G(G,"Prompt template does not exist");lett=G.path,c=e.vault.getAbstractFileByPath(t);_G(cinstanceofZX.TFile,`${t} is not a file`);letb=awaite.vault.cachedRead(c);return[G.basename,b]}asyncfunctionYX(e,I,l){if(P.getState().disableOnlineFeatures)thrownewError("Blocking request to OpenAI: Online features are disabled in settings.");letG=tY(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:b,promptTemplate:d,systemPrompt:Z,promptTemplateFolder:a}=I,m=mc(e,a),[n,W]=awaitX5(e,d,m);G.setMessage("waiting","QuickAdd is formatting the prompt template.");letN=awaitl(W),Y=["prompting",`Using prompt template "${n}".`];G.setMessage(Y[0],Y[1]);letu=eY(e,t,c,Z,I.modelOptions)(N),C=(awaitmh(u,100,Q=>{G.setMessage(Y[0],`${Y[1]} (${(Q/1e3).toFixed(2)}s)`)},Q=>{G.setMessage("finished",`Took ${(Q/1e3).toFixed(2)}s.`)})).content,r=("> "+C).replace(/\n/g,`
>`),i={[b]:C,[`${b}-quoted`]:r};return setTimeout(()=>G.hide(),5e3),i}catch(t){throw G.setMessage("dead",t.message),setTimeout(()=>G.hide(),5e3),pl(t)?new jI("Input cancelled by user"):t}}async function mh(e,I,l,G){let t=Date.now();return await r5(()=>l(Date.now()-t),e,I),G(Date.now()-t),await e}async function sX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=tY(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:b,systemPrompt:d,prompt:Z,modelOptions:a}=I;G.setMessage("waiting","QuickAdd is formatting the prompt template.");let m=await l(Z),n=["prompting","Using custom prompt."];G.setMessage(n[0],n[1]);let N=eY(e,t,c,d,a)(m),s=(await mh(N,100,C=>{G.setMessage(n[0],`${n[1]}(${(C/1e3).toFixed(2)}s)`)},C=>{G.setMessage("finished",`Took${(C/1e3).toFixed(2)}s.`)})).content,u=("> "+s).replace(/\n/g,`
>`),V={[b]:s,[`${b}-quoted`]:u};return setTimeout(()=>G.hide(),5e3),V}catch(t){throw G.setMessage("dead",t.message),setTimeout(()=>G.hide(),5e3),t}}var Zh=class{constructor(I,l){this.maxRequests=I;this.intervalMs=l;this.queue=[];this.pendingPromises=[]}add(I){return new Promise((l,G)=>{this.queue.push(async()=>{try{l(await I())}catch(t){G(t)}}),this.schedule()})}schedule(){if(this.queue.length===0||this.pendingPromises.length>=this.maxRequests)return;let I=this.queue.shift();if(!I)return;let l=I();this.pendingPromises.push(l),l.finally(()=>{this.pendingPromises=this.pendingPromises.filter(G=>G!==l),this.schedule()}),setTimeout(()=>this.schedule(),this.intervalMs)}};async function iX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=tY(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:b,systemPrompt:d,promptTemplate:Z,text:a,modelOptions:m}=I;G.setMessage("chunking","Creating prompt chunks with text and prompt template");let n=I.chunkSeparator||/\n/g,W=a.split(n),N=$G(d,c),Y=await l(Z,{chunk:" "}),s=$G(Y,c),u=lX(c.name)/2-N,V=I.shouldMerge??!0,C=[],r=u-s;if(V){let O=[],K="",J=0;for(let H of W){let v=$G(H,c)+1;if(v>r)throw new Error(`Thechunk"${H.slice(0,25)}..."istoolargetofitinasingleprompt.`);J+v<r?(K+=H,J+=v):(O.push(K),K=H,J=v)}K!==""&&O.push(K);for(let H of O){let v=await l(Z,{chunk:H});C.push(v)}}else for(let O of W){let K=$G(O,c);if(K>u)throw new Error(`Chunksize(${K})islargerthanthemaximumchunksize(${u}).Pleasecheckyourchunkseparator.`);let J=await l(Z,{chunk:O});C.push(J)}let i=eY(e,t,c,d,m),Q=["prompting",`${C.length}promptsbeingsent.`];G.setMessage(Q[0],Q[1]);let R=new Zh(5,1e3*30),h=Promise.all(C.map(O=>R.add(()=>i(O)))),E=(await mh(h,100,O=>{G.setMessage(Q[0],`${Q[1]}(${(O/1e3).toFixed(2)}s)`)},O=>{G.setMessage("finished",`Took${(O/1e3).toFixed(2)}s.`)})).map(O=>O.content).join(I.resultJoiner),T=("> "+E).replace(/\n/g,`
>`),k={[b]:E,[`${b}-quoted`]:T};return setTimeout(()=>G.hide(),5e3),k}catch(t){throw G.setMessage("dead",t.message),setTimeout(()=>G.hide(),5e3),t}}var Q5="quickadd-ai";function R5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function L5(e){let I=e.name?.trim()||"provider";return`${Q5}-${R5(I)}`}async function Bt(e,I){let l=I.apiKeyRef?.trim();if(l&&e?.secretStorage?.getSecret)try{let G=await Promise.resolve(e.secretStorage.getSecret(l));if(G)return G}catch(G){x.logWarning(`FailedtoreadSecretStorageentry"${l}":${G.message??G}`)}return I.apiKey??""}async function uX(e,I,l){let G=l?.trim();if(!G||!e?.secretStorage?.getSecret||!e.secretStorage?.setSecret)return null;let t=L5(I),c=t,b=1;for(;;){let d=null;try{d=await Promise.resolve(e.secretStorage.getSecret(c))}catch(Z){x.logWarning(`FailedtoreadSecretStorageentry"${c}":${Z.message??Z}`)}if(!d)break;if(d===G)return c;b+=1,c=`${t}-${b}`}try{return await Promise.resolve(e.secretStorage.setSecret(c,G)),c}catch(d){return x.logWarning(`FailedtowriteSecretStorageentry"${c}":${d.message??d}`),null}}var Dd=require("obsidian"),Fn=class e extends Dd.Modal{constructor(l,G,t=[]){super(l);this.items=G;this.selectedItems=t;this._selectedItems=[...t],this.promise=new Promise((c,b)=>{this.resolvePromise=c,this.rejectPromise=b}),this.display(),this.open()}static Open(l,G,t){return new e(l,G,t).promise}display(){this.contentEl.empty(),this.containerEl.addClass("quickAddModal","checkboxPrompt"),this.addCheckboxRows(),this.addSubmitButton()}onClose(){super.onClose(),this.resolved||this.rejectPromise("no input given.")}addCheckboxRows(){let l=this.contentEl.createDiv("checkboxRowContainer");this.items.forEach(G=>this.addCheckboxRow(G,l))}addCheckboxRow(l,G){let t=G.createDiv("checkboxRow");t.createEl("span",{text:l}),new Dd.ToggleComponent(t).setTooltip(`Toggle${l}`).setValue(this._selectedItems.contains(l)).onChange(b=>{if(b)this._selectedItems.push(l);else{let d=this._selectedItems.findIndex(Z=>l===Z);this._selectedItems.splice(d,1)}})}addSubmitButton(){let l=this.contentEl.createDiv("submitButtonContainer");new Dd.ButtonComponent(l).setButtonText("Submit").setCta().onClick(t=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};var cY=require("obsidian"),wn=class e extends cY.Modal{constructor(l,G,t){super(l);this.header=G;this.text=t;this.waitForClose=new Promise(c=>{this.resolvePromise=c}),this.open(),this.display()}static Show(l,G,t){return new e(l,G,t).waitForClose}display(){this.contentEl.empty(),this.titleEl.textContent=this.header,String.isString(this.text)?this.contentEl.createEl("p",{text:this.text}):Array.isArray(this.text)&&this.text.forEach(t=>this.contentEl.createEl("p",{text:t}));let l=this.contentEl.createDiv(),G=new cY.ButtonComponent(l).setButtonText("OK").onClick(()=>this.close());Object.assign(l.style,{display:"flex",justifyContent:"flex-end"}),G.buttonEl.focus()}onClose(){super.onClose(),this.resolvePromise()}};var Md=require("obsidian");var sc=class e extends Md.Modal{constructor(l,G,t,c,b,d){super(l);this.header=G;this.linkSourcePath=b;this.didSubmit=!1;this.submitClickCallback=l=>this.submit();this.cancelClickCallback=l=>this.cancel();this.submitEnterCallback=l=>{(l.ctrlKey||l.metaKey)&&l.key==="Enter"&&(l.preventDefault(),this.submit())};this.placeholder=t??"",this.description=d?.trim()||void 0,this.draftHandler=new Ud({kind:"multi",header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath}),this.input=this.draftHandler.hydrate(c??""),this.waitForClose=new Promise((Z,a)=>{this.resolvePromise=Z,this.rejectPromise=a}),this.display(),this.open(),this.fileSuggester=new Od(l,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new Kd(l,this.inputComponent.inputEl)}static Prompt(l,G,t,c,b){return new e(l,G,t,c,void 0,b).waitForClose}static PromptWithContext(l,G,t,c,b,d){return new e(l,G,t,c,b,d).waitForClose}display(){if(this.containerEl.addClass("quickAddModal","qaWideInputPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.he
`,shouldMerge:d?.shouldMerge??!0},(C,r)=>{let i={...Z,...r};return n(C,i,!1)});return V?(d?.shouldAssignVariables&&Object.entries(V).forEach(([C,r])=>{G.variables.set(C,r)}),V):(cl(new Error("AI Assistant returned null"),"Chunked AI Prompt error"),{})},getModels:()=>Wt(),getMaxTokens:t=>{let c=xe(t);if(!c)throw new Error(`Model${t}notfound.`);return c.maxTokens},countTokens(t,c){return $G(t,c)},getRequestLogs(t=10){return aX(t)},getRequestLogById(t){return nX(t)},getLastRequestLog(){return WX()},clearRequestLogs(){NX()}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async t=>await navigator.clipboard.writeText(t),getSelection:()=>{let t=I.workspace.getActiveViewOfType(Sh.MarkdownView);return t?t.editor.getSelection()??"":""},getSelectedText:()=>{let t=I.workspace.getActiveViewOfType(Sh.MarkdownView);if(!t){cl(new Error("No active view"),"Could not get selected text");return}if(!t.editor.somethingSelected()){cl(new Error("No text selected"),"Could not get selected text");return}return t.editor.getSelection()}},date:{now:(t,c)=>Et({format:t,offset:c}),tomorrow:t=>Et({format:t,offset:1}),yesterday:t=>Et({format:t,offset:-1})},fieldSuggestions:{getFieldValues:async(t,c)=>{let b=c?.includeInlineCodeBlocks?.map(m=>m.trim().toLowerCase()).filter(m=>m.length>0),d={folder:c?.folder,tags:c?.tags,inline:c?.includeInline??!1,inlineCodeBlocks:b},Z=I.vault.getMarkdownFiles();Z=HY.filterFiles(Z,d,m=>I.metadataCache.getFileCache(m));let a=new Set;for(let m of Z){let W=I.metadataCache.getFileCache(m)?.frontmatter?.[t];if(W!=null){if(Array.isArray(W))W.forEach(N=>{let Y=N.toString().trim();Y&&a.add(Y)});else if(typeof W!="object"){let N=W.toString().trim();N&&a.add(N)}}if(d.inline){let N=await I.vault.read(m);tZ.getFieldValues(N,t,{includeCodeBlocks:b}).forEach(s=>a.add(s))}}return Array.from(a).sort()},clearCache:t=>{it.getInstance().clear(t)}}}}static async inputPrompt(I,l,G,t){try{return await ol.Prompt(I,l,G,t)}catch(c){Vc(c);return}}static async datePrompt(I,l,G){try{let t=await rb.Prompt(I,l,G?.placeholder,G?.defaultValue,G?.dateFormat);if(t&&t.startsWith("@date:")){let c=t.slice(6);return(G?.dateFormat?Yc(c,G.dateFormat):null)??c}return t}catch(t){Vc(t);return}}static async wideInputPrompt(I,l,G,t){try{return await sc.Prompt(I,l,G,t)}catch(c){Vc(c);return}}static async yesNoPrompt(I,l,G){try{return await pe.Prompt(I,l,G)}catch(t){Vc(t);return}}static async infoDialog(I,l,G){try{return await wn.Show(I,l,G)}catch(t){Vc(t);return}}static async suggester(I,l,G,t,c=!1,b){try{let d;return typeof l=="function"?d=G.map(l):d=l,d=d.map(Z=>FG(Z)),c?await aG.Suggest(I,d,G,{...t?{placeholder:t}:{},...b?.renderItem?{renderItem:b.renderItem}:{}}):await CG.Suggest(I,d,G,t,b?.renderItem)}catch(d){Vc(d);return}}static async checkboxPrompt(I,l,G){try{return await Fn.Open(I,l,G)}catch(t){Vc(t);return}}};function Vc(e){if(e instanceof jI)throw e;if(pl(e))throw new jI("Input cancelled by user")}var dZ=class extends vd{};var mG=[];for(let e=0;e<256;++e)mG.push((e+256).toString(16).slice(1));function $Q(e,I=0){return(mG[e[I+0]]+mG[e[I+1]]+mG[e[I+2]]+mG[e[I+3]]+"-"+mG[e[I+4]]+mG[e[I+5]]+"-"+mG[e[I+6]]+mG[e[I+7]]+"-"+mG[e[I+8]]+mG[e[I+9]]+"-"+mG[e[I+10]]+mG[e[I+11]]+mG[e[I+12]]+mG[e[I+13]]+mG[e[I+14]]+mG[e[I+15]]).toLowerCase()}var Th,kA=new Uint8Array(16);function qh(){if(!Th){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Th=crypto.getRandomValues.bind(crypto)}return Th(kA)}var OA=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ph={randomUUID:OA};function KA(e,I,l){if(Ph.randomUUID&&!I&&!e)return Ph.randomUUID();e=e||{};let G=e.random??e.rng?.()??qh();if(G.length<16)throw new Error("Random bytes length must be >= 16");if(G[6]=G[6]&15|64,G[8]=G[8]&63|128,I){if(l=l||0,l<0||l+16>I.length)throw new RangeError(`UUIDbyterange${l}:${l+15}isoutofbufferbounds`);for(let t=0;t<16;++t)I[l+t]=G[t];return I}return $Q(G)}var hG=KA;var GG=class{constructor(I,l){this.name=I,this.type=
`)}var NR=require("obsidian");function CZ(e,I){if(I.options)for(let l in I.options){let G=e[l]===void 0,t="defaultValue"in I.options[l]&&I.options[l].defaultValue!==void 0;G&&t&&(e[l]=I.options[l].defaultValue)}}var xA=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],eR=new Set(["true","1","yes","on"]),tR=new Set(["false","0","no","off"]);function oc(e){return xA.includes(e)}function cR(e){switch(e){case"lessThan":case"lessThanOrEqual":case"greaterThan":case"greaterThanOrEqual":return"number";case"equals":case"notEquals":return"string";case"contains":case"notContains":return"string";case"isTruthy":case"isFalsy":default:return"boolean"}}function bR(e){if(!oc(e.operator)||e.expectedValue===void 0||e.expectedValue===null)return;let I=e.expectedValue.trim();switch(e.valueType){case"number":{let l=Number(I);return Number.isNaN(l)?NaN:l}case"boolean":{let l=I.toLowerCase();return eR.has(l)?!0:tR.has(l)?!1:!!I}case"string":default:return I}}function $h(e,I){switch(I){case"number":return typeof e=="number"?e:typeof e=="boolean"?e?1:0:Number(e);case"boolean":if(typeof e=="boolean")return e;if(typeof e=="string"){let l=e.trim().toLowerCase();if(eR.has(l))return!0;if(tR.has(l))return!1}return!!e;case"string":default:return e==null?"":String(e)}}function UA(e){if(!oc(e.operator))return"";let I=e.expectedValue??"";return I.length===0?"(empty)":e.valueType==="string"?`"${I}"`:I}function zA(e){let I=e.variableName?`$${e.variableName}`:"(missing variable)",l=DA(e.operator),G=oc(e.operator)?`${UA(e)}`:"";return`${I}${l}${G}`.trim()}function BA(e){let I=e.exportName?`::${e.exportName}`:"";return`script${e.scriptPath}${I}`}function hZ(e){return e.mode==="variable"?zA(e):BA(e)}function DA(e){switch(e){case"equals":return"equals";case"notEquals":return"does not equal";case"lessThan":return"is less than";case"lessThanOrEqual":return"is less than or equal to";case"greaterThan":return"is greater than";case"greaterThanOrEqual":return"is greater than or equal to";case"contains":return"contains";case"notContains":return"does not contain";case"isTruthy":return"is truthy";case"isFalsy":return"is falsy";default:return e}}async function ZR(e,I){return e.mode==="script"?await I.evaluateScriptCondition(e):MA(e,I.variables)}function MA(e,I){let l=e.variableName?.trim();if(!l)return x.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(l in I))return x.logWarning(`Conditionalcommandskipped:Variable'${l}'isnotdefined.`),!1;let G=I[l];switch(e.operator){case"isTruthy":return!!G;case"isFalsy":return!G}if(oc(e.operator)){let t=bR(e);return t===void 0?(x.logWarning(`Conditionalcommand:Operator'${e.operator}'requiresacomparisonvalue.`),!1):e.operator==="contains"?dR(G,t,e):e.operator==="notContains"?!dR(G,t,e):fA(G,t,e)}return!1}function dR(e,I,l){return e==null?!1:typeof I=="string"&&I.length===0?(x.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1):Array.isArray(e)?e.map(G=>$h(G,l.valueType)).some(G=>G===I):typeof e=="string"?e.includes(String(I)):typeof e=="number"&&typeof I=="number"?e===I:String(e).includes(String(I))}function fA(e,I,l){let G=$h(e,l.valueType);switch(l.operator){case"equals":return G===I;case"notEquals":return G!==I;case"lessThan":return yY(G,I,(t,c)=>t<c);case"lessThanOrEqual":return yY(G,I,(t,c)=>t<=c);case"greaterThan":return yY(G,I,(t,c)=>t>c);case"greaterThanOrEqual":return yY(G,I,(t,c)=>t>=c);default:return!1}}function yY(e,I,l){let G=Number(e),t=Number(I);return Number.isNaN(G)||Number.isNaN(t)?(x.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):l(G,t)}var aR=require("obsidian");function rc(e,{logPrefix:I,noticePrefix:l=I,defaultReason:G}){if(!(e instanceof jI))return!1;let t=typeof e.message=="string"&&e.message.trim().length>0?e.message:G;return x.logMessage(`${I}:${t}`),(!(typeof e.message=="string"&&e.message.toLowerCase().includes("cancelled by user"))||P.getState().showInputCancellationNotification)&&new aR.Notice(`${l}:${t}`
`).map(r=>r.trim()).filter(r=>r.length>0),u=this.truncatePickerText(s[0]??"(empty text card)",90),V=[`${s.length}line${s.length===1?"":"s"}`];m&&V.push(m);let C=V.join(" \xB7 ");return{id:Z.id,type:a,title:u,subtitle:C,searchText:`${Z.id}${u}${C}`.toLowerCase(),capturable:!0,capturableReason:""}}if(a==="file"){let Y=this.getCanvasNodeFilePath(Z.file),s=JG.test(Y),u=s?"":"Canvas file cards must link to markdown files (.md).",V=this.truncatePickerText(Y.split("/").pop()??Y,90),C=[this.truncatePickerText(Y,120)];m&&C.push(m),s||C.push("Not capturable in this version");let r=C.join(" \xB7 ");return{id:Z.id,type:a,title:V,subtitle:r,searchText:`${Z.id}${V}${r}`.toLowerCase(),capturable:s,capturableReason:u}}let W=`Unsupportednode(${typeofZ.type=="string"&&Z.type.length>0?Z.type:"unknown"})`,N=m||"Type is not currently capturable";return{id:Z.id,type:a,title:W,subtitle:N,searchText:`${Z.id}${W}${N}`.toLowerCase(),capturable:!1,capturableReason:"This Canvas node type is not capturable."}}),d={text:0,file:1,other:2};return b.sort((Z,a)=>{let m=d[Z.type]-d[a.type];return m!==0?m:Z.title.localeCompare(a.title)})}catch{return[]}}getCanvasNodeFilePath(l){return typeof l=="string"?l:l&&typeof l=="object"&&"path"in l&&typeof l.path=="string"?l.path:"(missing file path)"}describeCanvasNodeCoordinates(l){return typeof l.x!="number"||typeof l.y!="number"||typeof l.width!="number"||typeof l.height!="number"?"":`${Math.round(l.x)},${Math.round(l.y)}\xB7${Math.round(l.width)}x${Math.round(l.height)}`}truncatePickerText(l,G){return l.length<=G?l:l.slice(0,G-1)+"\u2026"}addTaskSetting(){new EI.Setting(this.contentEl).setName("Task").setDesc("Formats the value as a task.").addToggle(G=>{G.setValue(this.choice.task),G.onChange(t=>this.choice.task=t)})}addAppendLinkSetting(){let l=ac(this.choice.appendLink),G=l.linkType??"link",t=l.enabled?l.requireActiveFile?"required":"optional":"disabled";new EI.Setting(this.contentEl).setName("Link to captured file").setDesc("Choose how QuickAdd should insert a link to the captured file in the current note.").addDropdown(b=>{b.addOption("required","Enabled (requires active file)"),b.addOption("optional","Enabled (skip if no active file)"),b.addOption("disabled","Disabled"),b.setValue(t),b.onChange(d=>{switch(d){case"disabled":this.choice.appendLink=!1;break;case"required":this.choice.appendLink={enabled:!0,placement:l.placement,requireActiveFile:!0,linkType:G};break;case"optional":this.choice.appendLink={enabled:!0,placement:l.placement,requireActiveFile:!1,linkType:G};break}this.reload()})}),t!=="disabled"&&(new EI.Setting(this.contentEl).setName("Link placement").setDesc("Where to place the link when appending").addDropdown(d=>{d.addOption("replaceSelection","Replace selection"),d.addOption("afterSelection","After selection"),d.addOption("endOfLine","End of line"),d.addOption("newLine","New line"),d.setValue(l.placement),d.onChange(Z=>{let a=this.choice.appendLink,m=typeof a=="boolean"?l.requireActiveFile:a.requireActiveFile,n=typeof a=="boolean"?G:a.linkType??G,W=At(Z)?n:"link";this.choice.appendLink={enabled:!0,placement:Z,requireActiveFile:m,linkType:W},this.reload()})}),At(l.placement)&&new EI.Setting(this.contentEl).setName("Link type").setDesc("Choose whether to insert a regular link or an embed when replacing the selection.").addDropdown(Z=>{Z.addOption("link","Link"),Z.addOption("embed","Embed"),Z.setValue(G),Z.onChange(a=>{let m=this.choice.appendLink,n=typeof m=="boolean"?l.requireActiveFile:m.requireActiveFile,W=typeof m=="boolean"?l.placement:m.placement;this.choice.appendLink={enabled:!0,placement:W,requireActiveFile:n,linkType:a}})}))}addWritePositionSetting(){let l=new EI.Setting(this.contentEl),G=!!this.choice?.captureToActiveFile;this.choice.activeFileWritePosition||(this.choice.activeFileWritePosition="cursor"),l.setName("Write position").setDesc(G?"Where to place the capture in the current file.":"Where to place the capture in the target file.").addDropdown(t=>{let c=this.choice.insertAfter?.enabled?"after":this.choice.newLineCapture?.enabled?this.choice.newLineCapture.direc
Inordertobeiterable,non-arrayobjectsmusthavea[Symbol.iterator]()method.`)}function NE(){throw new TypeError(`Invalidattempttodestructurenon-iterableinstance.
Inordertobeiterable,non-arrayobjectsmusthavea[Symbol.iterator]()method.`)}function $n(e,I){var l=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!l){if(Array.isArray(e)||(l=W0(e))||I&&e&&typeof e.length=="number"){l&&(e=l);var G=0,t=function(){};return{s:t,n:function(){return G>=e.length?{done:!0}:{done:!1,value:e[G++]}},e:function(Z){throw Z},f:t}}throw new TypeError(`Invalidattempttoiteratenon-iterableinstance.
${l?"Deleting this choice will delete all ("+e.choices.length+") choices inside it!":""}
${G?"Deleting this choice will delete its macro commands!":""}
`)}async function NL(e,I,l){if(e.type==="Multi")try{return await new ps(I,e).waitForClose}catch{return}let G=qk(e,I,l);if(!G)throw new Error("Invalid choice type");return await G.waitForClose}function YL(e){return{...e,command:!e.command}}var os=class{constructor(I){this.plugin=I}enableCommand(I){this.plugin.addCommandForChoice(I)}disableCommand(I){this.plugin.removeCommandForChoice(I)}updateCommand(I,l){this.plugin.removeCommandForChoice(I),this.plugin.addCommandForChoice(l)}};function sL(e,I,l){if(!I||!l)return e;let G=L0(e,I),t=L0(e,l);if(!G||!t||t.type!=="Multi"||G.type==="Multi"&&(G.id===t.id||Pk(G).has(t.id)))return e;let{updated:c,removed:b}=iL(e,I);return b?uL(c,l,b)??e:e}function L0(e,I){for(let l of e){if(l.id===I)return l;if(l.type==="Multi"){let G=L0(l.choices,I);if(G)return G}}}function Pk(e){let I=new Set,l=G=>{I.add(G.id),G.type==="Multi"&&G.choices.forEach(l)};return(e.choices??[]).forEach(l),I}function iL(e,I){let l;return{updated:e.map(t=>{if(t.id===I){l=t;return}if(t.type!=="Multi")return t;let c=iL(t.choices,I);return c.removed&&(l=c.removed),c.removed?{...t,choices:c.updated}:t}).filter(Boolean),removed:l}}function uL(e,I,l){let G=!1,t=e.map(c=>{if(c.id===I&&c.type==="Multi"){G=!0;let d=c;return{...d,choices:[...d.choices,l]}}if(c.type!=="Multi")return c;let b=uL(c.choices,I,l);return b?(G=!0,{...c,choices:b}):c});return G?t:void 0}var Qt=require("obsidian");var Rl=require("obsidian");var CL=require("obsidian");var rs=null,_k=24*60*60*1e3;async function hL(){if(rs&&Date.now()-rs.fetchedAt<_k)return rs.data;if(P.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let I=await(await(0,CL.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;return rs={data:I,fetchedAt:Date.now()},I}function g0(e){let I=e.toLowerCase();return I.includes("openai.com")?"openai":I.includes("openrouter.ai")?"openrouter":I.includes("generativelanguage.googleapis.com")?"google":I.includes("anthropic.com")||I.includes("anthropic")?"anthropic":I.includes("groq.com")?"groq":I.includes("together.ai")?"togetherai":I.includes("huggingface.co")||I.includes("huggingface")?"huggingface":I.includes("github")&&I.includes("models")?"github-models":I.includes("bedrock")||I.includes("aws")?"amazon-bedrock":I.includes("modelscope")?"modelscope":I.includes("dashscope")?"alibaba":I.includes("fireworks.ai")?"fireworks-ai":I.includes("vercel")?"vercel":I.includes("inference.net")?"inference":I.includes("z.ai")||I.includes("zhipu")?"zhipuai":I.includes("deepseek.com")?"deepseek":I.includes("cerebras")?"cerebras":I.includes("venice.ai")?"venice":I.includes("upstage.ai")?"upstage":I.includes("llama.com")||I.includes("api.llama.com")?"llama":I.includes("morphllm")?"morph":I.includes("inceptionlabs.ai")?"inception":I.includes("deepinfra")?"deepinfra":I.includes("gateway.opencode.ai")?"opencode":I.includes("router.huggingface.co")?"huggingface":I.includes("inference.wandb.ai")?"wandb":I.includes("api.githubcopilot.com")?"github-copilot":I.includes("api.openai.com")?"openai":null}function pL(e){return e.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}function v0(e,I){let l=new Set(e.map(t=>t.name)),G=I.filter(t=>!l.has(t.name));return e.concat(G)}var rL=require("obsidian");var $k=128e3;async function Xs(e,I){let l=e.modelSource??"providerApi";if(l==="modelsDev")return VL(e);if(l==="providerApi")return oL(e,I);try{return await oL(e,I)}catch(G){if(!g0(e.endpoint))throw G;return VL(e,G)}}async function VL(e,I){try{let l=await hL(),G=g0(e.endpoint);if(!G||!(G in l))throw new Error(`models.devdoesnotlistaproviderthatmatches${e.endpoint}.`);let t=Object.values(l[G].models);return pL(t)}catch(l){throw I?new Error(`ProviderAPIfailed(${I.message}).Fallbacktomodels.devalsofailed:${l.message}`):l}}async function oL(e,I){let{disableOnlineFeatures:l}=P.getState();if(l)throw new Error("Online features are disabled \u2014 enable them to browse provider models.");if(!e.endpoint)throw new Error("Provider is missing an endpoi
yd=yesterday`).setValue(ui(P.getState().dateAliases)).onChange(b=>{P.setState({dateAliases:Qp(b)})}),c.inputEl.style.width="100%",c.inputEl.style.minHeight="6rem",c.inputEl.style.flex="1 1 280px",c.inputEl.style.maxWidth="100%",c.inputEl.style.boxSizing="border-box"}),G.addButton(c=>{c.setButtonText("Reset to defaults").onClick(()=>{P.setState({dateAliases:jb}),t&&t.setValue(ui(jb))}),c.buttonEl.style.alignSelf="flex-start",c.buttonEl.style.whiteSpace="nowrap"})})}addDisableOnlineFeaturesSetting(l){l.addSetting(G=>{G.setName("Disable AI & Online features").setDesc("This prevents the plugin from making requests to external providers like OpenAI. You can still use User Scripts to execute arbitrary code, including contacting external providers. However, this setting disables plugin features like the AI Assistant from doing so. You need to disable this setting to use the AI Assistant.").addToggle(t=>t.setValue(P.getState().disableOnlineFeatures).onChange(c=>{P.setState({disableOnlineFeatures:c}),this.display()}))})}addEnableRibbonIconSetting(l){l.addSetting(G=>{G.setName("Show icon in sidebar").setDesc("Add QuickAdd icon to the sidebar ribbon. Requires a reload.").addToggle(t=>{t.setValue(P.getState().enableRibbonIcon).onChange(c=>{P.setState({enableRibbonIcon:c}),this.display()})})})}};var KZ=class{formatOutputString(I){return`QuickAdd:(${I.level})${I.message}`}getQuickAddError(I,l,G,t){return{message:I,level:l,time:Date.now(),stack:G,originalError:t}}};var mW=class extends KZ{constructor(){super(...arguments);this.ErrorLog=[]}logError(l,G,t){let c=this.getQuickAddError(l,"ERROR",G,t);this.addMessageToErrorLog(c);let b=t||new Error(l);console.error(this.formatOutputString(c),b)}logWarning(l,G,t){let c=this.getQuickAddError(l,"WARNING",G,t);this.addMessageToErrorLog(c);let b=t||new Error(l);console.warn(this.formatOutputString(c),b)}logMessage(l,G,t){let c=this.getQuickAddError(l,"LOG",G,t);this.addMessageToErrorLog(c),t?console.log(this.formatOutputString(c),t):console.log(this.formatOutputString(c))}addMessageToErrorLog(l){this.ErrorLog.push(l),this.ErrorLog.length>sC&&(this.ErrorLog=this.ErrorLog.slice(-sC))}clearErrorLog(){this.ErrorLog=[]}};var j0=require("obsidian");var zs=class extends KZ{constructor(l){super();this.plugin=l}logError(l,G,t){let c=this.getQuickAddError(l,"ERROR",G,t);new j0.Notice(this.formatOutputString(c),15e3)}logWarning(l,G,t){let c=this.getQuickAddError(l,"WARNING",G,t);new j0.Notice(this.formatOutputString(c))}logMessage(l,G,t){}};var Bs=class{constructor(I,l,G,t){this.app=I;this.plugin=l;this.choices=G;this.choiceExecutor=t}async run(){let I=je(this.choices).filter(l=>l.type==="Macro"&&l.runOnStartup);for(let l of I)await new ut(this.app,this.plugin,l,this.choiceExecutor,new Map).run()}};var S0=require("obsidian"),AF=require("obsidian");var Ds=class extends oZ{constructor(I,l,G,t){super(I,l,t),this.choiceExecutor=t,this.choice=G}async run(){try{_G(this.choice.templatePath,()=>`Invalidtemplatepathfor${this.choice.name}.${this.choice.templatePath.length===0?"Template path is empty.":`Template path is not valid: ${this.choice.templatePath}`}`);let I=ac(this.choice.appendLink);this.setLinkToCurrentFileBehavior(I.enabled&&!I.requireActiveFile?"optional":"required");let l="";if(this.choice.folder.enabled)l=await this.getFolderPath();else{let n=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");l=n===this.app.vault.getRoot()?"":n.path}let G=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:Kc,t=await this.formatter.formatFileName(G,this.choice.name),{fileName:c,strippedPrefix:b}=this.stripDuplicateFolderPrefix(t,l),d=this.shouldTreatFormattedNameAsVaultRelativePath(t,b),Z=this.normalizeTemplateFilePath(d?"":l,c,this.choice.templatePath);this.choice.fileExistsMode===Uc&&(Z=await this.incrementFileName(Z));let a,m=!1;if(await this.app.vault.adapter.exists(Z)){let n=this.findExistingFile(Z);if(!(n instanceof S0.TFile)||n.extension!=="md"&&n.extension!=="canvas"&&n.extension!=="base"){x.logError(`'${Z}'alreadyexistsbutcouldnotberesolveda
`)?Math.max(G,b-1):b}async insertAfterHandler(l){let G=await this.formatLocationString(this.choice.insertAfter.after);if(this.choice.insertAfter?.inline)return await this.insertAfterInlineHandler(l,G);let t=_h(this.fileContent),c=this.findInsertAfterIndex(t,G);if(c===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(l);throw new zI(`Insert-aftertargetnotfound:'${G}'.`)}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let d=Ts(t,c,!!this.choice.insertAfter.considerSubsections);c=this.findInsertAfterPositionAtSectionEnd(t,d??t.length-1,this.fileContent,l)}else{let d=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";c=this.findInsertAfterPositionWithBlankLines(t,c,this.fileContent,d)}return this.insertTextAfterPositionInBody(l,this.fileContent,c)}hasInlineTargetLinebreak(l){return l.includes(`
`,l);return G===-1?this.fileContent.length:G>0&&this.fileContent[G-1]==="\r"?G-1:G}async insertAfterInlineHandler(l,G){if(this.hasInlineTargetLinebreak(G))return cl(new Error("Inline insert after target must be a single line."),"Insert After Inline Error"),this.fileContent;let t=this.fileContent.indexOf(G);if(t===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInlineInsertAfterIfNotFound(l,G);throw new zI(`Inlineinsert-aftertargetnotfound:'${G}'.`)}let c=t+G.length;if(this.choice.insertAfter?.replaceExisting){let b=this.getInlineEndOfLine(c);return this.fileContent.slice(0,c)+l+this.fileContent.slice(b)}return this.fileContent.slice(0,c)+l+this.fileContent.slice(c)}async createInsertAfterIfNotFound(l){let t=`${this.replaceLinebreakInString(awaitthis.formatLocationString(this.choice.insertAfter.after))}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===PZ)try{let c=this.app.workspace.getActiveViewOfType(lp.MarkdownView);if(!c)throw new Error("No active view.");let d=c.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let a=_h(this.fileContent),m=Ts(a,d,!!this.choice.insertAfter.considerSubsections);d=this.findInsertAfterPositionAtSectionEnd(a,m??a.length-1,this.fileContent,t)}return this.insertTextAfterPositionInBody(t,this.fileContent,d)}catch{throw new zI(`Unabletoinsertline'${this.choice.insertAfter.after}'atcursorposition.`)}throw new zI(`UnknowncreateIfNotFoundLocation:${this.choice.insertAfter?.createIfNotFoundLocation}`)}async createInlineInsertAfterIfNotFound(l,G){let t=`${G}${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Sb){let c=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(t,this.fileContent,c)}if(this.choice.insertAfter?.createIfNotFoundLocation===qZ)return`${this.fileContent}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===PZ)try{let c=this.app.workspace.getActiveViewOfType(lp.MarkdownView);if(!c)throw new Error("No active view.");let d=c.editor.getCursor().line;return this.insertTextAfterPositionInBody(t,this.fileContent,d)}catch{throw new zI(`Unabletoinsertline'${this.choice.insertAfter.after}'atcursorposition.`)}throw new zI(`UnknowncreateIfNotFoundLocation:${this.choice.insertAfter?.createIfNotFoundLocation}`)}getFrontmatterEndPosition(l,G){let t=this.app.metadataCache.getFileCache(l);if(t?.frontmatterPosition)return t.frontmatterPosition.end.line;if(G){let c=this.inferFrontmatterEndLineFromContent(G);if(c!==null)return c}return x.logMessage("could not get frontmatter. Maybe there isn't any."),-1}inferFrontmatterEndLineFromContent(l){let G=oN(l);if(!G)return null;let t=l.slice(0,G[1]),c=t.split(/\r?\n/);return c.length===0?null:t.endsWith(`
${l}${d}`}};function UF(e){return e.captureToActiveFile&&!e.insertAfter.enabled&&e.newLineCapture?.enabled?e.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":e.captureToActiveFile&&!e.insertAfter.enabled?e.activeFileWritePosition==="top"?"activeFileTop":e.activeFileWritePosition==="bottom"||e.prepend?"append":"currentLine":e.insertAfter.enabled?"insertAfter":e.prepend?"prepend":"append"}function Gp(e){return e?.type==="text"?"text":e?.type==="file"||e?.file?"file":typeof e?.text=="string"?"text":"unsupported"}function L3(e,I){let l=I.id;if(!l)return null;let G=e.getData?.();return G?.nodes?.length?G.nodes.find(t=>t.id===l)??null:null}function zF(e,I){if(e==="text"){if(I==="currentLine")return"Canvas capture does not support 'At cursor' for text cards. Use top, bottom, or insert-after placement.";if(I==="newLineAbove"||I==="newLineBelow")return"Canvas capture does not support 'New line above/below cursor' for text cards. Use top, bottom, or insert-after placement."}return e==="file"&&(I==="currentLine"||I==="newLineAbove"||I==="newLineBelow")?"Canvas file cards do not support cursor-based capture modes. Use top, bottom, or insert-after modes.":null}function F3(e){let I=e.file;return I?typeof I=="string"?I:typeof I=="object"&&"path"in I&&typeof I.path=="string"?I.path:null:null}function ep(e){return!!e&&"path"in e&&"extension"in e}function w3(e){let l=(e.workspace.activeLeaf??e.workspace.getMostRecentLeaf?.()??null)?.view;return!l||l.getViewType?.()!=="canvas"?null:l}function g3(e,I){let l=I.file??e.workspace.getActiveFile?.();if(!l)throw new zI("Cannot capture to Canvas because no active Canvas file is available.");return l}function v3(e){let I=e.selection?Array.from(e.selection):[];if(I.length!==1)throw new zI("Canvas capture requires exactly one selected node.");return I[0]}function BF(e){let I=F3(e);if(!I)throw new zI("Selected Canvas file card does not have a valid linked file path.");if(!JG.test(I))throw new zI("Canvas file card targets markdown files only in this version.");return I}function H3(e,I){let l=BF(I),G=e.vault.getAbstractFileByPath(l);if(!ep(G))throw new zI(`SelectedCanvasfilecardtargetnotfound:${l}`);return G}function y3(e,I){let l=BF(I),G=e.vault.getAbstractFileByPath(l);if(!G)return{targetPath:l};if(!ep(G))throw new zI(`SelectedCanvasfilecardtargetnotfound:${l}`);return{targetPath:l,targetFile:G}}function J3(e,I){let l;try{l=JSON.parse(e)}catch{throw new zI(`CanvasfileisnotvalidJSON:${I}`)}if(!l||typeof l!="object")throw new zI(`Canvasfilehasinvalidstructure:${I}`);let G=l;if(!Array.isArray(G.nodes))throw new zI(`Canvasfilehasnonodesarray:${I}`);return l}function DF(e,I){let l=e,G=w3(l);if(!G)return null;let t=G.canvas;if(!t)throw new zI("Canvas capture is unavailable in this Obsidian version.");let c=g3(l,G),b=v3(t),d=L3(t,b),Z=Gp(b);if(Z==="unsupported"&&d&&(Z=Gp(d)),Z==="unsupported")throw new zI("Canvas capture currently supports only text and file cards.");let a=zF(Z,I);if(a)throw new zI(a);if(Z==="text")return{kind:"text",source:"active",canvas:t,canvasFile:c,node:b,nodeData:d};let m=b.file||!d?.file?b:{...b,file:d.file};return{kind:"file",source:"active",canvasFile:c,node:m,targetFile:H3(l,m)}}async function MF(e,I,l,G){let t=l.trim();if(!t)throw new zI("Canvas node id is required for Canvas node capture.");let c=e.vault.getAbstractFileByPath(I);if(!ep(c))throw new zI(`Canvastargetnotfound:${I}`);if(!AG.test(c.path))throw new zI("Canvas node capture requires the target path to be a .canvas file.");let b=await e.vault.read(c),d=J3(b,c.path),Z=d.nodes.findIndex(s=>s.id===t);if(Z===-1)throw new zI(`Canvasnodeid'${t}'wasnotfoundin${c.path}.`);let a=d.nodes[Z],m=Gp(a);if(m==="unsupported")throw new zI("Canvas capture currently supports only text and file cards.");let n=zF(m,G);if(n)throw new zI(n);if(m==="text")return{kind:"text",source:"configured",canvasFile:c,rawCanvas:b,canvasData:d,nodeData:a,nodeIndex:Z};let W=e,{targetPath:N,targetFile:Y}=y3(W,a);return{kind:"file",source:"configured",canvasFile:c,nodeData:a,targetPath:N,targetFile:Y}
`),l}async getFormattedPathToCaptureTo(l){let G=this.choiceExecutor?.variables?.get(Ia);if(!l&&G&&typeof G=="string"&&G.length>0)return this.normalizeCaptureFilePath(G);if(l){let d=this.app.workspace.getActiveFile();return _G(d,"Cannot capture to active file - no active file."),d.path}let t=this.choice.captureTo,c=await this.formatter.formatFileName(t,this.choice.name),b=this.resolveCaptureTarget(c);switch(b.kind){case"vault":return this.selectFileInFolder("",!0);case"tag":return this.selectFileWithTag(b.tag);case"folder":return this.selectFileInFolder(b.folder,!1);case"file":return this.normalizeCaptureFilePath(b.path)}}resolveCaptureTarget(l){let G=this.stripLeadingSlash(l.trim());if(G==="")return{kind:"vault"};if(G.startsWith("#"))return{kind:"tag",tag:G.replace(/\.md$/,"")};if(Gt.test(G))throw new zI(`Captureto'.base'filesisnotsupported(${G}).UseaTemplatechoiceinstead.`);let t=G.endsWith("/"),c=G.replace(/\/+$/,"");if(t)return{kind:"folder",folder:c};if(JG.test(G)||AG.test(G))return{kind:"file",path:G};let b=this.normalizeMarkdownFilePath("",c),Z=!!this.app.vault.getAbstractFileByPath(b);return pN(this.app,c)&&!Z?{kind:"folder",folder:c}:{kind:"file",path:G}}async selectFileInFolder(l,G){let t=l.endsWith("/")||G?l:`${l}/`,c=mc(this.app,t);_G(c.length>0,`Folder${t}isempty.`);let b=c.map(a=>a.path),d;try{d=await aG.Suggest(this.app,b.map(a=>a.replace(t,"")),b)}catch(a){throw pl(a)?new jI("Input cancelled by user"):a}_G(!!d&&d.length>0,"No file selected for capture.");let Z=d.startsWith(`${t}`)?d:`${t}/${d}`;return await this.formatFilePath(Z)}async selectFileWithTag(l){let G=l.startsWith("#")?l:`#${l}`,t=VN(this.app,G);_G(t.length>0,`Nofileswithtag${l}.`);let c=t.map(d=>d.path),b;try{b=await aG.Suggest(this.app,c,c)}catch(d){throw pl(d)?new jI("Input cancelled by user"):d}return _G(!!b&&b.length>0,"No file selected for capture."),await this.formatFilePath(b)}async onFileExists(l,G){let t=this.getFileByPath(l);if(!t)throw new Error("File not found");this.formatter.setTitle(t.basename),this.formatter.setDestinationFile(t);let c=await this.formatter.formatContentOnly(G);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let b=await this.app.vault.read(t),d=await this.formatter.formatContentWithFile(c,this.choice,b,t);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let Z=await this.app.vault.read(t),a=d;if(Z!==b){let m=OF(Z,b,d);_G(!m.isSuccess,()=>`Thefile${l}hasbeenmodifiedsincethelastread.
QuickAddwillnowreverttobackup.`),e.settings=G}}e.saveSettings()}var dw=e9;var BZ=require("obsidian");async function t9(e,I,l){let G=await fetch(`https://api.github.com/repos/${e}/${I}/releases`),t=await G.json();if(!G.ok&&"message"in t||!Array.isArray(t))throw new Error(`Failed to fetch releases: ${t.message??"Unknown error"}`);let c=t.findIndex(b=>b.tag_name===l);if(c===-1)throw new Error(`Could not find release with tag ${l}`);return t.slice(0,c).filter(b=>!b.draft&&!b.prerelease)}function c9(e,I=1){let l=e.split(`
`,G="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.",t='<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>',c=I.createDiv("quickadd-update-modal"),b=this.releases.map(m=>m.body).join(`
${c9(b)}`;BZ.MarkdownRenderer.renderMarkdown(a,c,this.app.vault.getRoot().path,new BZ.Component)}};var Bl=require("obsidian");var di=class extends Bl.Modal{constructor(l,G){super(l);this.showAdvancedSettings=!1;this.settings=G,this.waitForClose=new Promise((t,c)=>{this.rejectPromise=c,this.resolvePromise=t}),this.open(),this.display()}get systemPromptTokenLength(){let l=xe(this.settings.model);return l?$G(this.settings.systemPrompt,l):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();let l=this.contentEl.createEl("h2",{text:`${this.settings.name}Settings`});l.style.textAlign="center",l.style.cursor="pointer",l.style.userSelect="none",l.addEventListener("click",async()=>{try{let G=await ol.Prompt(this.app,"New name",this.settings.name,this.settings.name);G&&G!==this.settings.name&&(this.settings.name=G,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(l){new Bl.Setting(l).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(G=>{let t=Wt();for(let c of t)G.addOption(c,c);G.addOption("Ask me","Ask me"),G.setValue(this.settings.model),G.onChange(c=>{this.settings.model=c,this.reload()})})}addOutputVariableNameSetting(l){new Bl.Setting(l).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(G=>{G.setValue(this.settings.outputVariableName).onChange(t=>{this.settings.outputVariableName=t})})}addSystemPromptSetting(l){new Bl.Setting(l).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let G=this.contentEl.createEl("div"),t=G.createEl("span");t.style.color="var(--text-muted-color)";let c=G.createEl("div",{text:"Exact for OpenAI models; estimates for others."});c.style.color="var(--text-muted-color)",c.style.fontSize="var(--font-ui-smaller)",G.appendChild(t),G.appendChild(c);let b=new Bl.TextAreaComponent(l);b.setValue(this.settings.systemPrompt).onChange(async m=>{this.settings.systemPrompt=m,Z.innerText=await d.format(m),a()}),new tG(this.app,b.inputEl,$I.instance);let d=new wG(this.app,$I.instance);b.inputEl.style.width="100%",b.inputEl.style.height="100px",b.inputEl.style.minHeight="100px",b.inputEl.style.marginBottom="1em";let Z=this.contentEl.createEl("span"),a=(0,Bl.debounce)(()=>{t.innerText=`Tokencount:${this.systemPromptTokenLength}`},50);a(),(async()=>Z.innerText=await d.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(l){new Bl.Setting(l).setName("Show advanced settings").setDesc("Show advanced settings such as temperature, top p, and frequency penalty.").addToggle(G=>{G.setValue(this.showAdvancedSettings),G.onChange(t=>{this.showAdvancedSettings=t,this.reload()})})}addTemperatureSetting(l){new Bl.Setting(l).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(G=>{G.setLimits(0,1,.1),G.setDynamicTooltip(),G.setValue(this.settings.modelParameters.temperature??1),G.onChange(t=>{this.settings.modelParameters.temperature=t})})}addTopPSetting(l){new Bl.Setting(l).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(G=>{G.setLimits(0,1,