Files
StudyDiary/.obsidian/plugins/quickadd/main.js
T

106 lines
4.1 MiB
JavaScript
Raw Normal View History

2026-07-23 20:36:13 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var Fw=Object.create;var _a=Object.defineProperty;var gw=Object.getOwnPropertyDescriptor;var ww=Object.getOwnPropertyNames;var vw=Object.getPrototypeOf,Hw=Object.prototype.hasOwnProperty;var yw=(e,I,l)=>I in e?_a(e,I,{enumerable:!0,configurable:!0,writable:!0,value:l}):e[I]=l;var $p=(e,I)=>()=>(I||e((I={exports:{}}).exports,I),I.exports),uG=(e,I)=>{for(var l in I)_a(e,l,{get:I[l],enumerable:!0})},Io=(e,I,l,G)=>{if(I&&typeof I=="object"||typeof I=="function")for(let t of ww(I))!Hw.call(e,t)&&t!==l&&_a(e,t,{get:()=>I[t],enumerable:!(G=gw(I,t))||G.enumerable});return e};var Bi=(e,I,l)=>(l=e!=null?Fw(vw(e)):{},Io(I||!e||!e.__esModule?_a(l,"default",{value:e,enumerable:!0}):l,e)),Jw=e=>Io(_a({},"__esModule",{value:!0}),e);var $=(e,I,l)=>yw(e,typeof I!="symbol"?I+"":I,l);var JX=$p(ws=>{"use strict";ws.byteLength=FA;ws.toByteArray=wA;ws.fromByteArray=yA;var it=[],oe=[],LA=typeof Uint8Array<"u"?Uint8Array:Array,Mh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(wd=0,HX=Mh.length;wd<HX;++wd)it[wd]=Mh[wd],oe[Mh.charCodeAt(wd)]=wd;var wd,HX;oe[45]=62;oe[95]=63;function yX(e){var I=e.length;if(I%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var l=e.indexOf("=");l===-1&&(l=I);var G=l===I?0:4-l%4;return[l,G]}function FA(e){var I=yX(e),l=I[0],G=I[1];return(l+G)*3/4-G}function gA(e,I,l){return(I+l)*3/4-l}function wA(e){var I,l=yX(e),G=l[0],t=l[1],c=new LA(gA(e,G,t)),d=0,b=t>0?G-4:G,a;for(a=0;a<b;a+=4)I=oe[e.charCodeAt(a)]<<18|oe[e.charCodeAt(a+1)]<<12|oe[e.charCodeAt(a+2)]<<6|oe[e.charCodeAt(a+3)],c[d++]=I>>16&255,c[d++]=I>>8&255,c[d++]=I&255;return t===2&&(I=oe[e.charCodeAt(a)]<<2|oe[e.charCodeAt(a+1)]>>4,c[d++]=I&255),t===1&&(I=oe[e.charCodeAt(a)]<<10|oe[e.charCodeAt(a+1)]<<4|oe[e.charCodeAt(a+2)]>>2,c[d++]=I>>8&255,c[d++]=I&255),c}function vA(e){return it[e>>18&63]+it[e>>12&63]+it[e>>6&63]+it[e&63]}function HA(e,I,l){for(var G,t=[],c=I;c<l;c+=3)G=(e[c]<<16&16711680)+(e[c+1]<<8&65280)+(e[c+2]&255),t.push(vA(G));return t.join("")}function yA(e){for(var I,l=e.length,G=l%3,t=[],c=16383,d=0,b=l-G;d<b;d+=c)t.push(HA(e,d,d+c>b?b:d+c));return G===1?(I=e[l-1],t.push(it[I>>2]+it[I<<4&63]+"==")):G===2&&(I=(e[l-2]<<8)+e[l-1],t.push(it[I>>10]+it[I>>4&63]+it[I<<2&63]+"=")),t.join("")}});var AR=$p(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});require("obsidian");var qt=class extends Error{},b0=class extends qt{constructor(I){super(`Invalid DateTime: ${I.toMessage()}`)}},a0=class extends qt{constructor(I){super(`Invalid Interval: ${I.toMessage()}`)}},n0=class extends qt{constructor(I){super(`Invalid Duration: ${I.toMessage()}`)}},Jd=class extends qt{},Ds=class extends qt{constructor(I){super(`Invalid unit ${I}`)}},BG=class extends qt{},Ct=class extends qt{constructor(){super("Zone is an abstract class")}},aI="numeric",Se="short",ee="long",fs={year:aI,month:aI,day:aI},AQ={year:aI,month:Se,day:aI},IE={year:aI,month:Se,day:aI,weekday:Se},EQ={year:aI,month:ee,day:aI},kQ={year:aI,month:ee,day:aI,weekday:ee},OQ={hour:aI,minute:aI},KQ={hour:aI,minute:aI,second:aI},xQ={hour:aI,minute:aI,second:aI,timeZoneName:Se},UQ={hour:aI,minute:aI,second:aI,timeZoneName:ee},zQ={hour:aI,minute:aI,hourCycle:"h23"},BQ={hour:aI,minute:aI,second:aI,hourCycle:"h23"},DQ={hour:aI,minute:aI,second:aI,hourCycle:"h23",timeZoneName:Se},fQ={hour:aI,minute:aI,second:aI,hourCycle:"h23",timeZoneName:ee},MQ={year:aI,month:aI,day:aI,hour:aI,minute:aI},jQ={year:aI,month:aI,day:aI,hour:aI,minute:aI,second:aI},SQ={year:aI,month:Se,day:aI,hour:aI,minute:aI},TQ={year:aI,month:Se,day:aI,hour:aI,minute:aI,second:aI},lE={year:aI,month:Se,day:aI,weekday:Se,hour:aI,minute:aI},qQ={year:aI,month:ee,day:aI,hour:aI,minute:aI,timeZoneName:Se},PQ={year:aI,month:ee,day:aI,hour:aI,minute:aI,second:aI,timeZoneName:Se},_Q={year:aI,month:ee,day:aI,weekday:ee,hour:aI,minute:aI,timeZoneName:ee},$Q={year:aI,month:ee,day:aI,weekday:ee,hour:aI,minute:aI,second:aI,timeZoneName:ee},kd=class{get type(){throw new Ct}get name(){throw new Ct}get ianaName(){return this.name}get isUniversal(){throw new Ct}offsetName(I,l){throw new Ct}formatOffset(I,l){
`||r.charAt(II)==="\r"&&r.charAt(II+1)!==`
`)&&(lI++,GI===0&&(GI=II+1)),II--}var mI=M+lI,el=v-GI;return O[v]={line:mI,lineStart:GI},{offset:v,line:mI+1,column:el+1}}function x(r){if(!C(r))throw new Error("not a parser: "+r)}function B(r,v){return typeof r=="string"?r.charAt(v):r[v]}function f(r){if(typeof r!="number")throw new Error("not a number: "+r)}function z(r){if(typeof r!="function")throw new Error("not a function: "+r)}function y(r){if(typeof r!="string")throw new Error("not a string: "+r)}var H=2,J=3,_=8,bI=5*_,rI=4*_,QI=" ";function BI(r,v){return new Array(v+1).join(r)}function yI(r,v,O){var M=v-r.length;return M<=0?r:BI(O,M)+r}function hI(r,v,O,M){return{from:r-v>0?r-v:0,to:r+O>M?M:r+O}}function YI(r,v){var O,M,lI,GI,II,mI=v.index,el=mI.offset,Hl=1;if(el===r.length)return"Got the end of the input";if(g(r)){var nl=el-el%_,be=el-nl,Dl=hI(nl,bI,rI+_,r.length),fl=n(function(Kl){return n(function(jd){return yI(jd.toString(16),2,"0")},Kl)},(function(Kl,jd){var Sd=Kl.length,zc=[],Td=0;if(Sd<=jd)return[Kl.slice()];for(var qd=0;qd<Sd;qd++)zc[Td]||zc.push([]),zc[Td].push(Kl[qd]),(qd+1)%jd==0&&Td++;return zc})(r.slice(Dl.from,Dl.to).toJSON().data,_));GI=(function(Kl){return Kl.from===0&&Kl.to===1?{from:Kl.from,to:Kl.to}:{from:Kl.from/_,to:Math.floor(Kl.to/_)}})(Dl),M=nl/_,O=3*be,be>=4&&(O+=1),Hl=2,lI=n(function(Kl){return Kl.length<=4?Kl.join(" "):Kl.slice(0,4).join(" ")+" "+Kl.slice(4).join(" ")},fl),(II=(8*(GI.to>0?GI.to-1:GI.to)).toString(16).length)<2&&(II=2)}else{var Ml=r.split(/\r\n|[\n\r\u2028\u2029]/);O=mI.column-1,M=mI.line-1,GI=hI(M,H,J,Ml.length),lI=Ml.slice(GI.from,GI.to),II=GI.to.toString().length}var Cl=M-GI.from;return g(r)&&(II=(8*(GI.to>0?GI.to-1:GI.to)).toString(16).length)<2&&(II=2),a(function(Kl,jd,Sd){var zc,Td=Sd===Cl,qd=Td?"> ":QI;return zc=g(r)?yI((8*(GI.from+Sd)).toString(16),II,"0"):yI((GI.from+Sd+1).toString(),II," "),[].concat(Kl,[qd+zc+" | "+jd],Td?[QI+BI(" ",II)+" | "+yI("",O," ")+BI("^",Hl)]:[])},[],lI).join(`
`)}function DI(r,v){return[`
`,"-- PARSING FAILED "+BI("-",50),`
`,YI(r,v),`
`,(O=v.expected,O.length===1?`Expected:
`+O[0]:`Expected one of the following:
`+O.join(", ")),`
`].join("");var O}function gG(r){return r.flags!==void 0?r.flags:[r.global?"g":"",r.ignoreCase?"i":"",r.multiline?"m":"",r.unicode?"u":"",r.sticky?"y":""].join("")}function kG(){for(var r=[].slice.call(arguments),v=r.length,O=0;O<v;O+=1)x(r[O]);return c(function(M,lI){for(var GI,II=new Array(v),mI=0;mI<v;mI+=1){if(!(GI=R(r[mI]._(M,lI),GI)).status)return GI;II[mI]=GI.value,lI=GI.index}return R(X(lI,II),GI)})}function OG(){var r=[].slice.call(arguments);if(r.length===0)throw new Error("seqMap needs at least one argument");var v=r.pop();return z(v),kG.apply(null,r).map(function(O){return v.apply(null,O)})}function nG(){var r=[].slice.call(arguments),v=r.length;if(v===0)return T("zero alternates");for(var O=0;O<v;O+=1)x(r[O]);return c(function(M,lI){for(var GI,II=0;II<r.length;II+=1)if((GI=R(r[II]._(M,lI),GI)).status)return GI;return GI})}function ye(r,v){return jG(r,v).or(YG([]))}function jG(r,v){return x(r),x(v),OG(r,v.then(r).many(),function(O,M){return[O].concat(M)})}function SG(r){y(r);var v="'"+r+"'";return c(function(O,M){var lI=M+r.length,GI=O.slice(M,lI);return GI===r?X(lI,GI):w(M,v)})}function sG(r,v){(function(lI){if(!(lI instanceof RegExp))throw new Error("not a regexp: "+lI);for(var GI=gG(lI),II=0;II<GI.length;II++){var mI=GI.charAt(II);if(mI!=="i"&&mI!=="m"&&mI!=="u"&&mI!=="s")throw new Error('unsupported regexp flag "'+mI+'": '+lI)}})(r),arguments.length>=2?f(v):v=0;var O=(function(lI){return RegExp("^(?:"+lI.source+")",gG(lI))})(r),M=""+r;return c(function(lI,GI){var II=O.exec(lI.slice(GI));if(II){if(0<=v&&v<=II.length){var mI=II[0],el=II[v];return X(GI+mI.length,el)}return w(GI,"valid match group (0 to "+II.length+") in "+M)}return w(GI,M)})}function YG(r){return c(function(v,O){return X(O,r)})}function T(r){return c(function(v,O){return w(O,r)})}function KI(r){if(C(r))return c(function(v,O){var M=r._(v,O);return M.index=O,M.value="",M});if(typeof r=="string")return KI(SG(r));if(r instanceof RegExp)return KI(sG(r));throw new Error("not a string, regexp, or parser: "+r)}function fI(r){return x(r),c(function(v,O){var M=r._(v,O),lI=v.slice(O,M.index);return M.status?w(O,'not "'+lI+'"'):X(O,null)})}function qI(r){return z(r),c(function(v,O){var M=B(v,O);return O<v.length&&r(M)?X(O+1,M):w(O,"a character/byte matching "+r)})}function ce(r,v){arguments.length<2&&(v=r,r=void 0);var O=c(function(M,lI){return O._=v()._,O._(M,lI)});return r?O.desc(r):O}function iG(){return T("fantasy-land/empty")}d.parse=function(r){if(typeof r!="string"&&!g(r))throw new Error(".parse must be called with a string or Buffer as its argument");var v,O=this.skip(de)._(r,0);return v=O.status?{status:!0,value:O.value}:{status:!1,index:j(r,O.furthest),expected:O.expected},delete A[r],v},d.tryParse=function(r){var v=this.parse(r);if(v.status)return v.value;var O=DI(r,v),M=new Error(O);throw M.type="ParsimmonError",M.result=v,M},d.assert=function(r,v){return this.chain(function(O){return r(O)?YG(O):T(v)})},d.or=function(r){return nG(this,r)},d.trim=function(r){return this.wrap(r,r)},d.wrap=function(r,v){return OG(r,this,v,function(O,M){return M})},d.thru=function(r){return r(this)},d.then=function(r){return x(r),kG(this,r).map(function(v){return v[1]})},d.many=function(){var r=this;return c(function(v,O){for(var M=[],lI=void 0;;){if(!(lI=R(r._(v,O),lI)).status)return R(X(O,M),lI);if(O===lI.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");O=lI.index,M.push(lI.value)}})},d.tieWith=function(r){return y(r),this.map(function(v){if((function(lI){if(!Q(lI))throw new Error("not an array: "+lI)})(v),v.length){y(v[0]);for(var O=v[0],M=1;M<v.length;M++)y(v[M]),O+=r+v[M];return O}return""})},d.tie=function(){return this.tieWith("")},d.times=function(r,v){var O=this;return arguments.length<2&&(v=r),f(r),f(v),c(function(M,lI){for(var GI=[],II=void 0,mI=void 0,el=0;el<r;el+=1){if(mI=R(II=O._(M,lI),mI),!II.status)return mI;lI=II.index,GI.push(II.value)}for(;el<v&&(mI=R(II=O._(M,lI),mI),II.status);el+=1)lI=II.index,GI.push(II.value);return R(X(lI,GI),mI)})},d
`),Uc=SG(`\r
`),Ee=nG(Uc,Pa,xc).desc("newline"),qW=nG(Ee,de);c.all=yt,c.alt=nG,c.any=Ic,c.cr=xc,c.createLanguage=function(r){var v={};for(var O in r)({}).hasOwnProperty.call(r,O)&&(function(M){v[M]=ce(function(){return r[M](v)})})(O);return v},c.crlf=Uc,c.custom=function(r){return c(r(X,w))},c.digit=lc,c.digits=Kc,c.empty=iG,c.end=qW,c.eof=de,c.fail=T,c.formatError=DI,c.index=TG,c.isParser=C,c.lazy=ce,c.letter=Gc,c.letters=Je,c.lf=Pa,c.lookahead=KI,c.makeFailure=w,c.makeSuccess=X,c.newline=Ee,c.noneOf=function(r){return qI(function(v){return r.indexOf(v)<0}).desc("none of '"+r+"'")},c.notFollowedBy=fI,c.of=YG,c.oneOf=function(r){for(var v=r.split(""),O=0;O<v.length;O++)v[O]="'"+v[O]+"'";return qI(function(M){return r.indexOf(M)>=0}).desc(v)},c.optWhitespace=TW,c.Parser=c,c.range=function(r,v){return qI(function(O){return r<=O&&O<=v}).desc(r+"-"+v)},c.regex=sG,c.regexp=sG,c.sepBy=ye,c.sepBy1=jG,c.seq=kG,c.seqMap=OG,c.seqObj=function(){for(var r,v={},O=0,M=(r=arguments,Array.prototype.slice.call(r)),lI=M.length,GI=0;GI<lI;GI+=1){var II=M[GI];if(!C(II)){if(Q(II)&&II.length===2&&typeof II[0]=="string"&&C(II[1])){var mI=II[0];if(Object.prototype.hasOwnProperty.call(v,mI))throw new Error("seqObj: duplicate key "+mI);v[mI]=!0,O++;continue}throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(O===0)throw new Error("seqObj expects at least one named parser, found zero");return c(function(el,Hl){for(var nl,be={},Dl=0;Dl<lI;Dl+=1){var fl,Ml;if(Q(M[Dl])?(fl=M[Dl][0],Ml=M[Dl][1]):(fl=null,Ml=M[Dl]),!(nl=R(Ml._(el,Hl),nl)).status)return nl;fl&&(be[fl]=nl.value),Hl=nl.index}return R(X(Hl,be),nl)})},c.string=SG,c.succeed=YG,c.takeWhile=function(r){return z(r),c(function(v,O){for(var M=O;M<v.length&&r(B(v,M));)M++;return X(M,v.slice(O,M))})},c.test=qI,c.whitespace=Ae,c["fantasy-land/empty"]=iG,c["fantasy-land/of"]=YG,c.Binary={bitSeq:N,bitSeqObj:function(r){W();var v={},O=0,M=n(function(GI){if(Q(GI)){var II=GI;if(II.length!==2)throw new Error("["+II.join(", ")+"] should be length 2, got length "+II.length);if(y(II[0]),f(II[1]),Object.prototype.hasOwnProperty.call(v,II[0]))throw new Error("duplicate key in bitSeqObj: "+II[0]);return v[II[0]]=!0,O++,II}return f(GI),[null,GI]},r);if(O<1)throw new Error("bitSeqObj expects at least one named pair, got ["+r.join(", ")+"]");var lI=n(function(GI){return GI[0]},M);return N(n(function(GI){return GI[1]},M)).map(function(GI){return a(function(II,mI){return mI[0]!==null&&(II[mI[0]]=mI[1]),II},{},n(function(II,mI){return[II,GI[mI]]},lI))})},byte:function(r){if(W(),f(r),r>255)throw new Error("Value specified to byte constructor ("+r+"=0x"+r.toString(16)+") is larger in value than a single byte.");var v=(r>15?"0x":"0x0")+r.toString(16);return c(function(O,M){var lI=B(O,M);return lI===r?X(M+1,lI):w(M,v)})},buffer:function(r){return s("buffer",r).map(function(v){return Buffer.from(v)})},encodedString:function(r,v){return s("string",v).map(function(O){return O.toString(r)})},uintBE:Y,uint8BE:Y(1),uint16BE:Y(2),uint32BE:Y(4),uintLE:p,uint8LE:p(1),uint16LE:p(2),uint32LE:p(4),intBE:u,int8BE:u(1),int16BE:u(2),int32BE:u(4),intLE:o,int8LE:o(1),int16LE:o(2),int32LE:o(4),floatBE:s("floatBE",4).map(function(r){return r.readFloatBE(0)}),floatLE:s("floatLE",4).map(function(r){return r.readFloatLE(0)}),doubleBE:s("doubleBE",8).map(function(r){return r.readDoubleBE(0)}),doubleLE:s("doubleLE",8).map(function(r){return r.readDoubleLE(0)})},l.exports=c}])})})(Ps,Ps.exports);var F=Ps.exports,J0=()=>/[#*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\u29
`)[0];let G=l.substring(2).trim();return F.makeSuccess(I+l.length,G)}),namedField:e=>F.alt(e.explicitNamedField,_k(je.field).map(([I,l])=>$s.named($k(l),I))),sortField:e=>F.seqMap(je.field.skip(F.optWhitespace),F.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1),(I,l)=>{let G=l.length==0?"ascending":l[0].toLowerCase();return G=="desc"&&(G="descending"),G=="asc"&&(G="ascending"),{field:I,direction:G}}),headerClause:e=>e.queryType.chain(I=>{switch(I){case"table":return JQ(()=>({type:I,fields:[],showId:!0}),F.seqMap(F.regexp(/WITHOUT\s+ID/i).skip(F.optWhitespace).atMost(1),F.sepBy(e.namedField,F.string(",").trim(F.optWhitespace)),(l,G)=>({type:I,fields:G,showId:l.length==0})));case"list":return JQ(()=>({type:I,format:void 0,showId:!0}),F.seqMap(F.regexp(/WITHOUT\s+ID/i).skip(F.optWhitespace).atMost(1),je.field.atMost(1),(l,G)=>({type:I,format:G.length==1?G[0]:void 0,showId:l.length==0})));case"task":return F.succeed({type:I});case"calendar":return F.whitespace.then(F.seqMap(e.namedField,l=>({type:I,showId:!0,field:l})));default:return F.fail(`Unrecognized query type '${I}'`)}}).desc("TABLE or LIST or TASK or CALENDAR"),fromClause:e=>F.seqMap(F.regexp(/FROM/i),F.whitespace,je.source,(I,l,G)=>G),whereClause:e=>F.seqMap(F.regexp(/WHERE/i),F.whitespace,je.field,(I,l,G)=>({type:"where",clause:G})).desc("WHERE <expression>"),sortByClause:e=>F.seqMap(F.regexp(/SORT/i),F.whitespace,e.sortField.sepBy1(F.string(",").trim(F.optWhitespace)),(I,l,G)=>({type:"sort",fields:G})).desc("SORT field [ASC/DESC]"),limitClause:e=>F.seqMap(F.regexp(/LIMIT/i),F.whitespace,je.field,(I,l,G)=>({type:"limit",amount:G})).desc("LIMIT <value>"),flattenClause:e=>F.seqMap(F.regexp(/FLATTEN/i).skip(F.whitespace),e.namedField,(I,l)=>({type:"flatten",field:l})).desc("FLATTEN <value> [AS <name>]"),groupByClause:e=>F.seqMap(F.regexp(/GROUP BY/i).skip(F.whitespace),e.namedField,(I,l)=>({type:"group",field:l})).desc("GROUP BY <value> [AS <name>]"),clause:e=>F.alt(e.fromClause,e.whereClause,e.sortByClause,e.limitClause,e.groupByClause,e.flattenClause),query:e=>F.seqMap(e.headerClause.trim(d0),e.fromClause.trim(d0).atMost(1),e.clause.trim(d0).many(),(I,l,G)=>({header:I,source:l.length==0?ht.folder(""):l[0],operations:G,settings:y0}))}),d0=F.alt(F.whitespace,JR.comment).many().map(e=>e.join("")),IO=e=>e?e.plugins.plugins.dataview?.api:window.DataviewAPI,lO=e=>e.plugins.enabledPlugins.has("dataview");pt.DATE_SHORTHANDS=Q0;pt.DURATION_TYPES=X0;pt.EXPRESSION=je;pt.KEYWORDS=R0;pt.QUERY_LANGUAGE=JR;pt.getAPI=IO;pt.isPluginEnabled=lO;pt.parseField=Pk});var lU={};uG(lU,{default:()=>Il});module.exports=Jw(lU);var Lw=require("obsidian");var ge=require("obsidian");function $I(){}function Di(e){return e()}function PW(){return Object.create(null)}function pI(e){e.forEach(Di)}function EI(e){return typeof e=="function"}function xI(e,I){return e!=e?I==I:e!==I||e&&typeof e=="object"||typeof e=="function"}function lo(e){return Object.keys(e).length===0}function fi(e){return e??""}function Bc(e){return e&&EI(e.destroy)?e.destroy:$I}var $a=typeof window<"u"?window:typeof globalThis<"u"?globalThis:global;var _W=class e{constructor(I){$(this,"_listeners","WeakMap"in $a?new WeakMap:void 0);$(this,"_observer");$(this,"options");this.options=I}observe(I,l){return this._listeners.set(I,l),this._getObserver().observe(I,this.options),()=>{this._listeners.delete(I),this._observer.unobserve(I)}}_getObserver(){return this._observer??(this._observer=new ResizeObserver(I=>{for(let l of I)e.entries.set(l.target,l),this._listeners.get(l.target)?.(l)}))}};_W.entries="WeakMap"in $a?new WeakMap:void 0;var Go=!1;function eo(){Go=!0}function to(){Go=!1}function h(e,I){e.appendChild(I)}function Zl(e,I,l){let G=co(e);if(!G.getElementById(I)){let t=L("style");t.id=I,t.textContent=l,kw(G,t)}}function co(e){if(!e)return document;let I=e.getRootNode?e.getRootNode():e.ownerDocument;return I&&I.host?I:e.ownerDocument}function kw(e,I){return h(e.head||e,I),I.sheet}function cI(e,I,l){e.insertBefore(I,l||null)}function eI(e){e.parentNode&&e.parentNode.removeChild(e)}function Jt(e,I){for(let l=0;l<e.length;l+=1)e[l
`)}function ln(e){let I=Object.entries(e);if(I.length===0)return[];let G=["t","tm","yd"].map(d=>{let b=e[d];return b?[d,b]:null}).filter(d=>d!==null),t=new Set(G.map(([d])=>d)),c=I.filter(([d])=>!t.has(d)).sort((d,b)=>{let a=d[0].length-b[0].length;return a!==0?a:d[0].localeCompare(b[0])});return[...G,...c]}function cN(e){return ln(e).map(([I,l])=>`${I}=${l}`).join(", ")}var dN={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:Ib,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}^{\\text{new}}:=w_{ij}^{\\text{current}}+\\eta\\cdot\\delta_j\\cdot 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:tN},migrations:{migrateToMacroIDFromEmbeddedMacro:!0,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,consolidateFileExistsBehavior:!1,repairTemplateFileExistsBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1}};function jI(e){let l=(typeof window<"u"?window:globalThis).structuredClone;if(typeof l=="function")try{return l(e)}catch{}return cc(e,new Map)}function cc(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(cc(c,I));return t}if(e instanceof Map){let t=new Map;I.set(e,t);for(let[c,d]of e.entries())t.set(cc(c,I),cc(d,I));return t}if(e instanceof Set){let t=new Set;I.set(e,t);for(let c of e.values())t.add(cc(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 b=new DataView(cc(e.buffer,I),e.byteOffset,e.byteLength);return I.set(e,b),b}let t=e,c=cc(t.buffer,I),d=new t.constructor(c,t.byteOffset,t.length);return I.set(e,d),d}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:cc(c,I),writable:!0,enumerable:!0,configurable:!0});return G}var S=(()=>{let e=so((t,c)=>({...jI(dN)})),{getState:I,setState:l,subscribe:G}=e;return{getState:I,replaceState:t=>l(t,!0),setState:l,subscribe:G}})();var LI=require("obsidian");var jc="{{value}}",$i="{{date}}",io="{{time}}",Iu="{{name}}",$w="{{value:<variable name>}}",Iv="{{value:<variable name>|<default value>}}",lv="{{value:<variable name>|default:<value>}}",Gv="{{value:<variable name>|label:<helper text>}}",ev="{{value:<items>|text:<display items>}}",tv="{{value|case:kebab}}",cv="{{value:<variable name>|case:kebab}}",dv="{{field:<field name>}}",uo="{{mvalue}}",Co="{{linkcurrent}}",ho="{{filenamecurrent}}",po="{{title}}",oo="{{selected}}",Vo="{{clipboard}}",bv="{{random:<length>}}",av="{{global_var:<name>}}";var ro=[$i,"{{date:<dateformat>}}","{{vdate:<variable name>, <date format>}}","{{vdate:<variable name>, <date format>|<default value>}}",av,jc,Iu,t
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
reference: ${JSON.stringify(this.reference)}]`}date(){let I=this.dateWithoutTimezoneAdjustment(),l=this.reference.getSystemTimezoneAdjustmentMinute(I,this.get("timezoneOffset"));return new Date(I.getTime()+l*6e4)}addTag(I){return this._tags.add(I),this}addTags(I){for(let l of I)this._tags.add(l);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let I=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return I.setFullYear(this.get("year")),I}},kI=class e{constructor(I,l,G,t,c){$(this,"refDate");$(this,"index");$(this,"text");$(this,"reference");$(this,"start");$(this,"end");this.reference=I,this.refDate=I.instant,this.index=l,this.text=G,this.start=t||new D(I),this.end=c}clone(){let I=new e(this.reference,this.index,this.text);return I.start=this.start?this.start.clone():null,I.end=this.end?this.end.clone():null,I}date(){return this.start.date()}addTag(I){return this.start.addTag(I),this.end&&this.end.addTag(I),this}addTags(I){return this.start.addTags(I),this.end&&this.end.addTags(I),this}tags(){let I=new Set(this.start.tags());if(this.end)for(let l of this.end.tags())I.add(l);return I}toString(){let I=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(I)} ...}]`}};function yl(e,I,l="\\s{0,5},?\\s{0,5}"){let G=I.replace(/\((?!\?)/g,"(?:");return`${e}${G}(?:${l}${G}){0,10}`}function mv(e){let I;return e instanceof Array?I=[...e]:e instanceof Map?I=Array.from(e.keys()):I=Object.keys(e),I}function P(e){return`(?:${mv(e).sort((l,G)=>G.length-l.length).join("|").replace(/\./g,"\\.")})`}function Tl(e){return e<100&&(e>50?e=e+1900:e=e+2e3),e}function JI(e,I,l){let G=new Date(e);G.setMonth(l-1),G.setDate(I);let t=Gl(G,{year:1}),c=Gl(G,{year:-1});return Math.abs(t.getTime()-e.getTime())<Math.abs(G.getTime()-e.getTime())?G=t:Math.abs(c.getTime()-e.getTime())<Math.abs(G.getTime()-e.getTime())&&(G=c),G.getFullYear()}var sN={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},au={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},ne={...au,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},du={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},bu={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},So={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"day",days:"day",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},an={s:"second",sec:"second",second:"second",seconds:"second",m:"minute",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",hour:"hour",hours:"hour",d:"day",day:"day",days:"day",w:"week",week:"week",weeks:"week",mo:"month",mon:"month",mos:"month",month:"month",months:"month",qtr:"quarter",quarter:"quarter",quarters:"quarter",y:"year",yr:"year",year:"year",years:"year",...So},To=`(?:${P(du)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;function Wv(e){let I=e.toLowerCase()
`),a=b.length,n=b[a-1]?.length??0;if(I==="above")t.replaceRange(e+`
`,{line:d,ch:0}),t.setCursor({line:d+a-1,ch:n});else{let Z=t.getLine(d);t.replaceRange(`
`+e,{line:d,ch:Z.length}),t.setCursor({line:d+a,ch:n})}}catch{k.logError(`unable to insert '${e}' on new line ${I}.`)}}function Vr(e,I){or(e,"above",I)}function rr(e,I){or(e,"below",I)}function v5(e,I,l="replaceSelection",G={}){let{requireActiveView:t=!0}=G,c=e.workspace.getActiveViewOfType(wG.MarkdownView);if(!c){let Z="Cannot append link because no active Markdown view is available.";if(t)throw new Error(Z);k.logMessage(Z);return}let d=c.editor,b=d.listSelections().map(Z=>({anchor:{...Z.anchor},head:{...Z.head}}));if(l==="replaceSelection"){d.replaceSelection(I);return}let a=({line:Z,ch:m})=>d.posToOffset({line:Z,ch:m}),n=b.sort((Z,m)=>a(m.head)-a(Z.head));for(let Z of n){let m=a(Z.anchor)>a(Z.head)?Z.anchor:Z.head;switch(l){case"afterSelection":{d.replaceRange(I,m);break}case"endOfLine":{let W=d.getLine(m.line),N={line:m.line,ch:W.length};d.replaceRange(I,N);break}case"newLine":{let W=d.getLine(m.line),N={line:m.line,ch:W.length},i=W.length===0?"":`
`;d.replaceRange(i+I,N);break}}}}function H5(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 y5(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=H5(e);return t?`![[${t}]]`:e.startsWith("!")?e:`!${e}`}function SN(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(wG.MarkdownView)){if(l.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}let c=G?.path??"",d=e.fileManager.generateMarkdownLink(I,c),a=l.linkType==="embed"&&xt(l.placement)?y5(d):d;return v5(e,a,l.placement,{requireActiveView:!1}),!0}function J5(e,I){return e.commands.findCommand(I)}function Xr(e,I){J5(e,I)&&(delete e.commands.commands[I],delete e.commands.editorCommands[I])}function ud(e){return e.vault.getAllLoadedFiles().filter(I=>I instanceof wG.TFolder).map(I=>I.path)}function Bm(e){let I=e.split("::").map(l=>l.trim()).filter(Boolean);return{basename:I[0],memberAccess:I.slice(1)}}function Qr(e){if(!e)return!1;let I=e,l=I.getViewState?.();return!!I.pinned||!!l?.pinned||!!l?.state?.pinned}function dh(e){let I=e.workspace;return(I.rootSplit?I.getMostRecentLeaf?.(I.rootSplit):null)??I.getMostRecentLeaf?.()??I.activeLeaf??null}function A5(e){let I=[];return e.workspace.iterateRootLeaves(l=>{I.includes(l)||I.push(l)}),I}function ir(e){return e.parent?.id??e.parent??null}function E5(e,I){let l=ir(I),G=e.filter(d=>d===I||Qr(d)?!1:l===null||ir(d)!==l);if(G.length===0)return null;let t=e.indexOf(I);return(t===-1?e:[...e.slice(t+1),...e.slice(0,t)]).find(d=>G.includes(d))??G[0]}function k5(e){return e instanceof wG.TFile?!0:typeof e=="object"&&e!==null&&"path"in e&&typeof e.path=="string"}function O5(e,I,l,G){if(G&&(I==="tab"||I==="reuse")&&Qr(G))return E5(A5(e),G)??e.workspace.getLeaf("tab");switch(I){case"reuse":return e.workspace.getLeaf(!1);case"tab":return e.workspace.getLeaf("tab");case"split":return e.workspace.getLeaf("split",l);case"window":return e.workspace.getLeaf("window");case"left-sidebar":return e.workspace.getLeftLeaf(!0);case"right-sidebar":return e.workspace.getRightLeaf(!0);default:return e.workspace.getLeaf("tab")}}async function Cd(e,I,l={}){let{location:G="tab",direction:t="vertical",mode:c,focus:d=!0,eState:b,originLeaf:a}=l,n=typeof I=="string"?e.vault.getAbstractFileByPath(I):I;if(!k5(n)){let W=typeof I=="string"?I:I.path;throw new Error(`File not found: ${W}`)}let Z=a??dh(e),m=O5(e,G,t,Z);if(!m)throw new Error("Could not obtain a workspace leaf.");if(await m.openFile(n),c&&c!=="default"&&!(typeof c=="object"&&c.mode==="default")){let W=m.getViewState(),N={...W.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 m.setViewState({...W,state:{...N,...b}})}return d&&e.workspace.setActiveLeaf(m,{focus:!0}),m}function ur(e){return(0,wG.normalizePath)(e).replace(/\/{2,}/g,"/").replace(/^\/+/,"")}function K5(e,I){return ur(e)===ur(I)}function Dm(e,I,l=!0){let G;return e.workspace.iterateRootLeaves(t=>{let c=t.view;if(c instanceof wG.FileView&&c.file&&(c.file===I||K5(I.path,c.file.path))){G=t;return}}),G!==void 0?(l&&e.workspace.setActiveLeaf(G,{focus:!0}),G):null}async function Zt(e,I){let l=I.vault.getAbstractFileByPath(e.path);if(!l){k.logError(`failed to load file ${e.path}.`);return}if(l instanceof wG.TFile){let G=m=>window.require&&window.require(m),t={},c={exports:t},d=await I.vault.read(l);window.eval(`(function(require, module, exports) { ${d}
})`)(G,c,t);let a=t.default||c.exports;if(!a)return;let n=a,{memberAccess:Z}=Bm(e.name);if(Z&&Z.length>0){let m;for(;m=Z.shift();)n=n[m]}return n}}function Rr(e,I){let l=jI(e);for(let G of I)delete l[G];return l}function TN(e,I){let l=e.vault.getAbstractFileByPath(I);return!!l&&l instanceof wG.TFolder}function sc(e,I){return e.vault.getMarkdownFiles().filter(l=>l.path.startsWith(I))}function x5(e){let I=e.frontmatter;if(!I)return[];let l=Object.entries(I);if(!l.length)return[];let G=l.filter(([c,d])=>{let b=c.toLowerCase();return b==="tags"||b==="tag"});return G?G.flatMap(([c,d])=>{if(typeof d=="string")return d.split(/,|\s+/).map(b=>b.trim());if(Array.isArray(d))return d}).filter(c=>!!c):[]}function U5(e,I){let l=e.metadataCache.getFileCache(I);if(!l)return[];let G=[];return l.frontmatter&&G.push(...x5(l)),l.tags&&Array.isArray(l.tags)&&G.push(...l.tags.map(t=>t.tag.replace(/^#/,""))),G}function qN(e,I){let l=I.replace(/^#/,"");return e.vault.getMarkdownFiles().filter(G=>U5(e,G).includes(l))}function PN(e){let l=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(e);return l?[0,l[0].length]:null}function Lr(e,I,l,G){let[t,c]=G??[Number.NaN,Number.NaN];if(!(G!==null&&I>=t&&I<=c))return{isInYaml:!1,isQuoted:!1,lineStart:0,lineEnd:0,baseIndent:"",isKeyValuePosition:!1};let b=e.lastIndexOf(`
`,I-1)+1,a=e.indexOf(`
`,I),n=a===-1?e.length:a,Z=e.slice(b,I),m=e.slice(l,n),W=(Z.match(/^\s*/)||[""])[0],N=e[I-1]==='"'&&e[l]==='"'||e[I-1]==="'"&&e[l]==="'",s=Z.replace(/["']$/,""),i=m.replace(/^["']/,""),Y=/:\s*$/.test(s)&&i.trim().length===0;return{isInYaml:!0,isQuoted:N,lineStart:b,lineEnd:n,baseIndent:W,isKeyValuePosition:Y}}var Fr={"[":"]","(":")","{":"}","<":">"};function z5(e,I=","){let l=[],G="",t=[],c=null;for(let b=0;b<e.length;b++){let a=e[b];if(c){if(G+=a,a===c){let n=0;for(let Z=b-1;Z>=0&&e[Z]==="\\";Z--)n++;n%2===0&&(c=null)}continue}if(a==='"'||a==="'"){c=a,G+=a;continue}if(a in Fr){t.push(Fr[a]),G+=a;continue}if(t.length>0){let n=t[t.length-1];a===n&&t.pop(),G+=a;continue}if(a===I){let n=G.trim();n.length>0&&l.push(n),G="";continue}G+=a}let d=G.trim();return d.length>0&&l.push(d),l}function B5(e){return e.includes(`
`)?e.replace(/\r?\n/g,`
`):e.includes("\\n")?e.replace(/\\n/g,`
`):e}function D5(e,I){if(!e||!I)return null;let l=e.metadataCache,G=e.metadataTypeManager??l?.app?.metadataTypeManager;if(!G||typeof G.getTypeInfo!="function")return null;let t=G.getTypeInfo(I),c=t?.expected?.type??t?.inferred?.type;return typeof c=="string"?c:null}function f5(e){if(!e)return!1;let I=e.toLowerCase();return I==="list"||I==="tags"||I==="multitext"}function gr(e,I){let l=e.trim();if(!l)return;let G=B5(l),t=I?.propertyType??D5(I?.app,I?.propertyKey),c=f5(t),b=c||t===null,n=G.split(/\n/).map(Z=>Z.trim()).filter(Z=>Z.length>0);if(b&&n.length>0&&n.every(Z=>/^-\s+/.test(Z)))return n.map(Z=>Z.replace(/^-[\s]*/,"").trim());if(G.startsWith("[")&&G.endsWith("]")||G.startsWith("{")&&G.endsWith("}")){if(t&&!c&&t!=="list")return;try{return JSON.parse(G)}catch{}}if(G.includes(",")&&b){let Z=z5(G);if(Z.length>1)return Z}}function wr(e){if(typeof e=="string"&&e.startsWith("@date:")){let I=e.substring(6),l=new Date(I);if(!Number.isNaN(l.getTime()))return l}return e}function bh(e){return typeof e!="string"&&(Array.isArray(e)||typeof e=="object"&&e!==null||typeof e=="number"||typeof e=="boolean"||e===null)}function vr(e){if(bh(e))return Array.isArray(e)?"[]":e===null?"null":typeof e=="object"?"{}":String(e)}var Hr="\0",Yc=class{constructor(I){this.app=I;this.map=new Map;this.propertyTypeCache=new Map}maybeCollect(I){let{input:l,matchStart:G,matchEnd:t,rawValue:c,fallbackKey:d,featureEnabled:b}=I;if(!b)return;let a=PN(l),n=Lr(l,G,t,a);if(!n.isInYaml)return;let Z=l.slice(n.lineStart,n.lineEnd),m=Z.trim(),W=Z.match(/^\s*([^:]+):/),N=W?W[1].trim():d,s=/^-\s*['"]?\{\{VALUE:[^}]+\}\}['"]?\s*$/i,i=null;if(n.isKeyValuePosition?i=[N]:s.test(m)&&(i=this.findListParentPath(l,n.lineStart,n.baseIndent??"")),!i||i.length===0)return;let Y=i[i.length-1],p=c;if(typeof c=="string"){let o=gr(c,this.buildParseOptions(Y));o!==void 0&&(p=o)}if(!bh(p))return;let u=i.join(Hr);return this.map.set(u,p),p}drain(){let I=new Map(this.map);return this.map.clear(),I}buildParseOptions(I){return{propertyKey:I,propertyType:this.resolvePropertyType(I),app:this.app}}findListParentPath(I,l,G){let t=l-1,c=[],d=G.length;for(;t>=0;){let b=I.lastIndexOf(`
`,t),a=b===-1?0:b+1,n=I.slice(a,t+1),Z=n.trim();if(Z.length===0){t=a-2;continue}if(Z==="---"||Z==="...")break;if(Z.startsWith("-")){t=a-2;continue}let m=n.match(/^(\s*)([^:\n]+):/);if(m){let N=(m[1]??"").length;if(N<d&&(c.unshift(m[2].trim()),d=N,d===0))break}t=a-2}return c.length>0?c:null}resolvePropertyType(I){if(!this.app)return null;if(this.propertyTypeCache.has(I))return this.propertyTypeCache.get(I)??null;let l=this.app,G=l.metadataTypeManager??l.metadataCache?.app?.metadataTypeManager;if(!G||typeof G.getTypeInfo!="function")return this.propertyTypeCache.set(I,null),null;let t=G.getTypeInfo(I),c=t?.expected?.type??t?.inferred?.type??null,d=typeof c=="string"?c:null;return this.propertyTypeCache.set(I,d),d}};Yc.PATH_SEPARATOR=Hr;var yr=/[\u0000-\u001F]/u,Jr=/[\\/:*?"<>|]/u,Ar=/[. ]$/u,M5=new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]);function _N(e){return M5.has(e.toUpperCase())}function j5(e){if(!e)return null;let I=e.trim().toLowerCase();switch(I){case"kebab":case"snake":case"camel":case"pascal":case"title":case"lower":case"upper":case"slug":return I;default:return null}}function ah(e){if(!e)return e;let I=e.toLowerCase();return I.slice(0,1).toUpperCase()+I.slice(1)}function nh(e){return/\p{L}/u.test(e)?/\p{Lu}/u.test(e)&&!/\p{Ll}/u.test(e):!1}function $N(e){return/\p{Lu}/u.test(e)&&/\p{Ll}/u.test(e)}function S5(e){return/^\p{Ll}/u.test(e)&&$N(e)}function T5(e){if(!e)return[];{let l=e.match(/^([\p{Ll}][\p{Lu}]{2,})([\p{N}]+)?$/u);if(l){let G=[l[1]];return l[2]&&G.push(l[2]),G}}if(/^[\p{Ll}][\p{Lu}][\p{Ll}]+(?:[\p{Lu}][\p{Ll}]+)*$/u.test(e))return[e];let I=e;return I=I.replace(/([\p{Lu}]+)([\p{Lu}][\p{Ll}])/gu,"$1 $2"),I=I.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu,"$1 $2"),I=I.replace(/([\p{L}])([\p{N}])/gu,"$1 $2"),I=I.replace(/([\p{N}])([\p{L}])/gu,"$1 $2"),I.trim().split(/\s+/u).map(l=>l.trim()).filter(Boolean)}function q5(e){return e.split(/[^\p{L}\p{N}\p{M}]+/gu).filter(Boolean).flatMap(T5).filter(Boolean)}function Is(e,I){let l=j5(I);if(!l)return e;if(l==="lower")return e.toLowerCase();if(l==="upper")return e.toUpperCase();let G=q5(e);if(G.length===0)return"";switch(l){case"kebab":return G.map(t=>t.toLowerCase()).join("-");case"snake":return G.map(t=>t.toLowerCase()).join("_");case"camel":{let[t,...c]=G,d=t?S5(t)?t:t.toLowerCase():"",b=c.map(a=>nh(a)||$N(a)?a:ah(a));return[d,...b].join("")}case"pascal":return G.map(t=>nh(t)||$N(t)?t:ah(t)).join("");case"title":return G.map(t=>nh(t)||$N(t)?t:ah(t)).join(" ");case"slug":{let t=G.map(c=>c.toLowerCase()).join("-");return _N(t)?`${t}-`:t}default:return e}}function fm(e){return e.split("|")}function Er(e){return e.startsWith("|")?e.slice(1):e}function Mm(e){let I=e.indexOf(":");if(I===-1)return null;let l=e.slice(0,I).trim().toLowerCase();if(!l)return null;let G=e.slice(I+1).trim();return{key:l,value:G}}var kr="",Or=new Set(["label","default","custom","type","case","text"]);function P5(e,I,l){return l&&I?`${e}${kr}${I}`:e}function jm(e){let I=e.indexOf(kr);return I===-1?e:e.slice(0,I)}function _5(e,I){let l=I.toLowerCase(),G=null;for(let t of e.keys())if(t.toLowerCase()===l&&e.get(t)!==void 0){if(G)return null;G=t}return G}function ls(e,I){if(!I)return null;let l=[I],G=jm(I);G!==I&&l.push(G);for(let t of l){if(e.has(t)&&e.get(t)!==void 0)return t;let c=_5(e,t);if(c)return c}return null}function $5(e){if(!e)return!0;let I=e.trim().toLowerCase();return!["false","no","0","off"].includes(I)}function IJ(e){let I=e.trim();if(!I)return!1;let l=Mm(I);return l?Or.has(l.key):!1}function Kr(e,I){if(e.length===0)return{defaultValue:"",allowCustomInput:!1,usesOptions:!1};let l=e.some(IJ),G=I&&e.some(m=>m.trim().toLowerCase()==="custom");if(!(l||G))return{defaultValue:e.join("|").trim(),allowCustomInput:!1,usesOptions:!1};let c,d,b="",a=!1,n,Z;for(let m of e){let W=m.trim();if(!W)continue;if(I&&W.toLowerCase()==="custom"){a=!0;continue}let N=Mm(W);if(!N)continue;let{key:s,value:i}=N;if(Or.has(s))switch(s){case"label":i&&(c=i);break;case"case":i&&(d=i);break;case"defaul
`,G++):c=="\\"?(l+="\\",G++):l+="\\":l+=t}return l}replaceRandomInString(I){let l=I;for(;cu.test(l);){let G=cu.exec(l);if(!G||!G[1])continue;let t=parseInt(G[1]);if(t<=0||t>100)throw new Error(`Random string length must be between 1 and 100. Got: ${t}`);let c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",d="";for(let b=0;b<t;b++)d+=c.charAt(Math.floor(Math.random()*c.length));l=l.replace(G[0],d)}return l}replaceTitleInString(I){let l=I,G=this.getVariableValue("title");for(;Gu.test(l);)l=this.replacer(l,Gu,G);return l}};es.FIELD_VARIABLE_PREFIX="FIELD:";var mt=es;var dJ={title:"My Document Title",name:"Document Name",project:"Project Alpha",category:"Notes",author:"Your Name",status:"Draft",priority:"High",tag:"important",type:"meeting",client:"Acme Corp"},bJ={clipboard:"clipboard_content",date:"formatted_date",time:"current_time",random:"random_value",uuid:"unique_id"},aJ=[{pattern:/date|time/i,example:"2024-01-15"},{pattern:/title|name/i,example:"Example Title"},{pattern:/tag/i,example:"important"},{pattern:/category|type/i,example:"Notes"},{pattern:/author|user/i,example:"Your Name"},{pattern:/project/i,example:"Project Alpha"},{pattern:/status/i,example:"In Progress"},{pattern:/priority/i,example:"High"},{pattern:/number|count|id/i,example:"001"}];function ts(e){let I=e.toLowerCase(),l=dJ[I];return l||`${e}_example`}function cs(e){return bJ[e.toLowerCase()]||`${e}_output`}function ds(e){for(let{pattern:I,example:l}of aJ)if(I.test(e))return l;return`${e}_value`}function bs(e){return e.length>0?`${e[0]} (${e.length} options)`:"suggestion_list"}function as(e){return e?.path?e.basename:"current_file"}function ns(e){return e?.basename||"current_filename"}var Wt=class{static generate(I,l=new Date){let G=l.getFullYear(),t=(l.getMonth()+1).toString().padStart(2,"0"),c=l.getDate().toString().padStart(2,"0"),d=l.getHours().toString().padStart(2,"0"),b=l.getMinutes().toString().padStart(2,"0"),a=l.getSeconds().toString().padStart(2,"0");return I.replace(/YYYY/g,G.toString()).replace(/YY/g,G.toString().slice(-2)).replace(/MMMM/g,this.MONTH_NAMES[l.getMonth()]).replace(/MMM/g,this.MONTH_NAMES_SHORT[l.getMonth()]).replace(/MM/g,t).replace(/M/g,(l.getMonth()+1).toString()).replace(/dddd/g,this.DAY_NAMES[l.getDay()]).replace(/ddd/g,this.DAY_NAMES_SHORT[l.getDay()]).replace(/DD/g,c).replace(/D/g,l.getDate().toString()).replace(/HH/g,d).replace(/H/g,l.getHours().toString()).replace(/mm/g,b).replace(/m/g,l.getMinutes().toString()).replace(/ss/g,a).replace(/s/g,l.getSeconds().toString()).replace(/ww/g,this.getWeekNumber(l).toString().padStart(2,"0")).replace(/w/g,this.getWeekNumber(l).toString())}static getWeekNumber(I){let l=new Date(I.getFullYear(),0,1),G=(I.getTime()-l.getTime())/864e5;return Math.ceil((G+l.getDay()+1)/7)}};Wt.MONTH_NAMES=["January","February","March","April","May","June","July","August","September","October","November","December"],Wt.MONTH_NAMES_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Wt.DAY_NAMES=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Wt.DAY_NAMES_SHORT=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];var kb=class extends mt{constructor(l,G,t){super(l);this.plugin=G;this.dateParser=t||xe}async format(l){let G=l;try{G=await this.replaceGlobalVarInString(G),G=await this.replaceMacrosInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=await this.replaceValueInString(G),G=await this.replaceSelectedInString(G),G=await this.replaceClipboardInString(G),G=await this.replaceDateVariableInString(G),G=await this.replaceVariableInString(G),G=await this.replaceFieldVarInString(G),G=await this.replaceCurrentFileNameInString(G),G=this.replaceRandomInString(G)}catch{return l}return G}async replaceGlobalVarInString(l){let G=l,t=0,c=new RegExp(dc.source,"gi");for(;c.test(G)&&!(++t>5);)G=G.replace(c,(d,b)=>{let a=String(b??"").trim();if(!a)return d;let n=this.plugin?.settings?.globalVariables?.[a];return typeof n=="string"?n:""});return G}promptForValue(l){return l||"user input"}getVariableValue(l){let G=this.variables.get(l)
2026-07-27 09:55:55 +08:00
`).filter(Boolean).reduce((G,t)=>{let[c,d,...b]=t.split(" "),a=Number.parseInt(d,10);return b.forEach((n,Z)=>G[n]=a+Z),G},{});for(let[G,t]of Object.entries(l)){let c=AX.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=jh.specialTokenRegex(Object.keys(this.specialTokens)),c=[],d=new Set(I==="all"?Object.keys(this.specialTokens):I),b=new Set(l==="all"?Object.keys(this.specialTokens).filter(n=>!d.has(n)):l);if(b.size>0){let n=jh.specialTokenRegex([...b]),Z=e.match(n);if(Z!=null)throw new Error(`The text contains a special token that is not allowed: ${Z[0]}`)}let a=0;for(;;){let n=null,Z=a;for(;t.lastIndex=Z,n=t.exec(e),!(n==null||d.has(n[0]));)Z=n.index+1;let m=n?.index??e.length;for(let N of e.substring(a,m).matchAll(G)){let s=this.textEncoder.encode(N[0]),i=this.rankMap.get(s.join(","));if(i!=null){c.push(i);continue}c.push(...OA(s,this.rankMap))}if(n==null)break;let W=this.specialTokens[n[0]];c.push(W),a=n.index+n[0].length}return c}decode(e){let I=[],l=0;for(let c=0;c<e.length;++c){let d=e[c],b=this.textMap.get(d)??this.inverseSpecialTokens[d];b!=null&&(I.push(b),l+=b.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)}},vs=jh;EA(vs,"specialTokenRegex",e=>new RegExp(e.map(I=>KA(I)).join("|"),"g"));function Sh(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":case"
2026-07-23 20:36:13 +08:00
${I}`:""}`;function Js(e){if(e){let I=new BX.Notice(zX("starting",""),1e6);return{setMessage:(l,G)=>{I.setMessage(zX(l,G))},hide:()=>I.hide()}}return{setMessage:()=>{},hide:()=>{}}}var DX={cl100k_base:EX,o200k_base:kX},fX=new Map;function MA(e){let I=e in DX?e:"cl100k_base",l=fX.get(I);if(l)return l;let G=new vs(DX[I]);return fX.set(I,G),G}var Ie=(e,I)=>{let l="cl100k_base";try{l=Sh(I.name)}catch{l="cl100k_base"}return(l==="p50k_base"||l==="p50k_edit"||l==="r50k_base"||l==="gpt2")&&(l="cl100k_base"),MA(l).encode(e).length},MX=25,Ve=[];function Ph(e){return{...e,modelOptions:{...e.modelOptions},usage:e.usage?{...e.usage}:void 0}}function UX(e){let I=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,l=Date.now();return Ve.push({...e,modelOptions:{...e.modelOptions??{}},id:I,createdAt:l,status:"pending"}),TX(),I}function Th(e,I){let l=Ve.find(G=>G.id===e);l&&(l.status=I.status,l.durationMs=I.durationMs,l.usage=I.usage,l.errorMessage=I.errorMessage,TX())}function SX(e=10){Number.isFinite(e)||(e=10);let I=Math.floor(e);return I<=0?[]:Ve.slice(-I).map(Ph).reverse()}function TX(){if(Ve.length<=MX)return;let e=Ve.length-MX;for(;e>0;){let I=Ve.findIndex(l=>l.status!=="pending");if(I===-1)break;Ve.splice(I,1),e-=1}}function qX(e){let I=Ve.find(l=>l.id===e);return I?Ph(I):null}function PX(){let e=Ve[Ve.length-1];return e?Ph(e):null}function _X(){Ve.splice(0,Ve.length)}async function jA(e,I,l){if(typeof e!="function")throw new TypeError("Callback must be a function.");if(!(I instanceof Promise))throw new TypeError("Promise must be an instance of Promise.");if(typeof l!="number"||l<=0)throw new TypeError("Interval must be a positive number.");let G=!1;for(I.then(()=>{G=!0},()=>{G=!0});!G;)e(),await sleep(l)}function SA(e){return e instanceof Error?e:new Error(String(e))}async function TA(e,I,l){let G;if(I.enable)G=l.find(b=>b.path.endsWith(I.name));else{let b=l.map(a=>a.basename);G=await VG.Suggest(e,b,l)}$G(G,"Prompt template does not exist");let t=G.path,c=e.vault.getAbstractFileByPath(t);$G(c instanceof jX.TFile,`${t} is not a file`);let d=await e.vault.cachedRead(c);return[G.basename,d]}async function $X(e,I,l){if(S.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=Js(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:d,promptTemplate:b,systemPrompt:a,promptTemplateFolder:n}=I,Z=sc(e,n),[m,W]=await TA(e,b,Z);G.setMessage("waiting","QuickAdd is formatting the prompt template.");let N=await l(W),s=["prompting",`Using prompt template "${m}".`];G.setMessage(s[0],s[1]);let Y=ys(e,t,c,a,I.modelOptions)(N),u=(await _h(Y,100,Q=>{G.setMessage(s[0],`${s[1]} (${(Q/1e3).toFixed(2)}s)`)},Q=>{G.setMessage("finished",`Took ${(Q/1e3).toFixed(2)}s.`)})).content,o=("> "+u).replace(/\n/g,`
> `),C={[d]:u,[`${d}-quoted`]:o};return window.setTimeout(()=>G.hide(),5e3),C}catch(t){throw G.setMessage("dead",t.message),window.setTimeout(()=>G.hide(),5e3),ol(t)?new vI("Input cancelled by user"):t}}async function _h(e,I,l,G){let t=Date.now();return await jA(()=>l(Date.now()-t),e,I),G(Date.now()-t),await e}async function IQ(e,I,l){if(S.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=Js(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:d,systemPrompt:b,prompt:a,modelOptions:n}=I;G.setMessage("waiting","QuickAdd is formatting the prompt template.");let Z=await l(a),m=["prompting","Using custom prompt."];G.setMessage(m[0],m[1]);let N=ys(e,t,c,b,n)(Z),i=(await _h(N,100,u=>{G.setMessage(m[0],`${m[1]} (${(u/1e3).toFixed(2)}s)`)},u=>{G.setMessage("finished",`Took ${(u/1e3).toFixed(2)}s.`)})).content,Y=("> "+i).replace(/\n/g,`
> `),p={[d]:i,[`${d}-quoted`]:Y};return window.setTimeout(()=>G.hide(),5e3),p}catch(t){throw G.setMessage("dead",t.message),window.setTimeout(()=>G.hide(),5e3),t}}var qh=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(SA(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.then(()=>{this.pendingPromises=this.pendingPromises.filter(G=>G!==l),this.schedule()},()=>{this.pendingPromises=this.pendingPromises.filter(G=>G!==l),this.schedule()}),window.setTimeout(()=>this.schedule(),this.intervalMs)}};async function lQ(e,I,l){if(S.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=Js(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:d,systemPrompt:b,promptTemplate:a,text:n,modelOptions:Z}=I;G.setMessage("chunking","Creating prompt chunks with text and prompt template");let m=I.chunkSeparator||/\n/g,W=n.split(m),N=Ie(b,c),s=await l(a,{chunk:" "}),i=Ie(s,c),Y=xX(c.name)/2-N,p=I.shouldMerge??!0,u=[],o=Y-i;if(p){let B=[],f="",z=0;for(let y of W){let H=Ie(y,c)+1;if(H>o)throw new Error(`The chunk "${y.slice(0,25)}..." is too large to fit in a single prompt.`);z+H<o?(f+=y,z+=H):(B.push(f),f=y,z=H)}f!==""&&B.push(f);for(let y of B){let H=await l(a,{chunk:y});u.push(H)}}else for(let B of W){let f=Ie(B,c);if(f>Y)throw new Error(`Chunk size (${f}) is larger than the maximum chunk size (${Y}). Please check your chunk separator.`);let z=await l(a,{chunk:B});u.push(z)}let C=ys(e,t,c,b,Z),Q=["prompting",`${u.length} prompts being sent.`];G.setMessage(Q[0],Q[1]);let g=new qh(5,1e3*30),X=Promise.all(u.map(B=>g.add(()=>C(B)))),A=(await _h(X,100,B=>{G.setMessage(Q[0],`${Q[1]} (${(B/1e3).toFixed(2)}s)`)},B=>{G.setMessage("finished",`Took ${(B/1e3).toFixed(2)}s.`)})).map(B=>B.content).join(I.resultJoiner),j=("> "+A).replace(/\n/g,`
> `),x={[d]:A,[`${d}-quoted`]:j};return window.setTimeout(()=>G.hide(),5e3),x}catch(t){throw G.setMessage("dead",t.message),window.setTimeout(()=>G.hide(),5e3),t}}var qA="quickadd-ai";function PA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function _A(e){let I=e.name?.trim()||"provider";return`${qA}-${PA(I)}`}async function GQ(e,I){if(!e?.secretStorage?.getSecret)return null;try{return await Promise.resolve(e.secretStorage.getSecret(I))}catch(l){return k.logWarning(`Failed to read SecretStorage entry "${I}": ${l.message??l}`),null}}async function St(e,I){let l=I.apiKeyRef?.trim();if(l){let G=await GQ(e,l);if(G)return G}return I.apiKey??""}async function eQ(e,I,l){let G=l?.trim();if(!G||!e?.secretStorage?.getSecret||!e.secretStorage?.setSecret)return null;let t=_A(I),c=t,d=1;for(;;){let b=await GQ(e,c);if(!b)break;if(b===G)return c;d+=1,c=`${t}-${d}`}try{return await Promise.resolve(e.secretStorage.setSecret(c,G)),c}catch(b){return k.logWarning(`Failed to write SecretStorage entry "${c}": ${b.message??b}`),null}}var Pb=require("obsidian"),tW=class e extends Pb.Modal{constructor(l,G,t=[]){super(l);this.items=G;this.selectedItems=t;this._selectedItems=[...t],this.promise=new Promise((c,d)=>{this.resolvePromise=c,this.rejectPromise=d}),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 Pb.ToggleComponent(t).setTooltip(`Toggle ${l}`).setValue(this._selectedItems.contains(l)).onChange(d=>{if(d)this._selectedItems.push(l);else{let b=this._selectedItems.findIndex(a=>l===a);this._selectedItems.splice(b,1)}})}addSubmitButton(){let l=this.contentEl.createDiv("submitButtonContainer");new Pb.ButtonComponent(l).setButtonText("Submit").setCta().onClick(t=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};var As=require("obsidian"),cW=class e extends As.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 As.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 _b=require("obsidian");var oc=class e extends _b.Modal{constructor(l,G,t,c,d,b){super(l);this.header=G;this.linkSourcePath=d;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=b?.trim()||void 0,this.draftHandler=new Sb({kind:"multi",header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath}),this.input=this.draftHandler.hydrate(c??""),this.waitForClose=new Promise((a,n)=>{this.resolvePromise=a,this.rejectPromise=n}),this.display(),this.open(),this.fileSuggester=new fb(l,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new Mb(l,this.inputComponent.inputEl)}static Prompt(l,G,t,c,d){return new e(l,G,t,c,void 0,d).waitForClose}static PromptWithContext(l,G,t,c,d,b){return new e(l,G,t,c,d,b).waitForClose}display(){if(this.containerEl.addClass("quickAddModal","qaWideInputPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.header,this.description){let G=this.contentEl.cr
`,shouldMerge:b?.shouldMerge??!0},(u,o)=>{let C={...a,...o};return m(u,C,!1)});return p?(b?.shouldAssignVariables&&Object.entries(p).forEach(([u,o])=>{G.variables.set(u,o)}),p):(al(new Error("AI Assistant returned null"),"Chunked AI Prompt error"),{})},getModels:()=>ut(),getMaxTokens:t=>{let c=De(t);if(!c)throw new Error(`Model ${t} not found.`);return c.maxTokens},countTokens(t,c){return Ie(t,c)},getRequestLogs(t=10){return SX(t)},getRequestLogById(t){return qX(t)},getLastRequestLog(){return PX()},clearRequestLogs(){_X()}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async t=>await navigator.clipboard.writeText(t),getSelection:()=>{let t=I.workspace.getActiveViewOfType(E0.MarkdownView);return t?t.editor.getSelection()??"":""},getSelectedText:()=>{let t=I.workspace.getActiveViewOfType(E0.MarkdownView);if(!t){al(new Error("No active view"),"Could not get selected text");return}if(!t.editor.somethingSelected()){al(new Error("No text selected"),"Could not get selected text");return}return t.editor.getSelection()}},date:{now:(t,c)=>Ut({format:t,offset:c}),tomorrow:t=>Ut({format:t,offset:1}),yesterday:t=>Ut({format:t,offset:-1})},fieldSuggestions:{getFieldValues:async(t,c)=>{let d=c?.includeInlineCodeBlocks?.map(Z=>Z.trim().toLowerCase()).filter(Z=>Z.length>0),b={folder:c?.folder,tags:c?.tags,inline:c?.includeInline??!1,inlineCodeBlocks:d},a=I.vault.getMarkdownFiles();a=nY.filterFiles(a,b,Z=>I.metadataCache.getFileCache(Z));let n=new Set;for(let Z of a){let W=I.metadataCache.getFileCache(Z)?.frontmatter?.[t];if(W!=null){if(Array.isArray(W))W.forEach(N=>{let s=N.toString().trim();s&&n.add(s)});else if(typeof W!="object"){let N=W.toString().trim();N&&n.add(N)}}if(b.inline){let N=await I.vault.read(Z);ma.getFieldValues(N,t,{includeCodeBlocks:d}).forEach(i=>n.add(i))}}return Array.from(n).sort()},clearCache:t=>{ot.getInstance().clear(t)}}}}static async inputPrompt(I,l,G,t){try{return await rl.Prompt(I,l,G,t)}catch(c){Lc(c);return}}static async datePrompt(I,l,G){try{let t=await gd.Prompt(I,l,G?.placeholder,G?.defaultValue,G?.dateFormat);if(t&&t.startsWith("@date:")){let c=t.slice(6);return(G?.dateFormat?pc(c,G.dateFormat):null)??c}return t}catch(t){Lc(t);return}}static async wideInputPrompt(I,l,G,t){try{return await oc.Prompt(I,l,G,t)}catch(c){Lc(c);return}}static async yesNoPrompt(I,l,G){try{return await re.Prompt(I,l,G)}catch(t){Lc(t);return}}static async infoDialog(I,l,G){try{return await cW.Show(I,l,G)}catch(t){Lc(t);return}}static async suggester(I,l,G,t,c=!1,d){try{let b;return typeof l=="function"?b=G.map((a,n,Z)=>oG(l(a,n,Z))):b=l.map(a=>oG(a)),c?await mG.Suggest(I,b,G,{...t?{placeholder:t}:{},...d?.renderItem?{renderItem:d.renderItem}:{}}):await VG.Suggest(I,b,G,t,d?.renderItem)}catch(b){Lc(b);return}}static async checkboxPrompt(I,l,G){try{return await tW.Open(I,l,G)}catch(t){Lc(t);return}}};function Lc(e){if(e instanceof vI)throw e;if(ol(e))throw new vI("Input cancelled by user")}var sa=class extends Ob{};var WG=[];for(let e=0;e<256;++e)WG.push((e+256).toString(16).slice(1));function xR(e,I=0){return(WG[e[I+0]]+WG[e[I+1]]+WG[e[I+2]]+WG[e[I+3]]+"-"+WG[e[I+4]]+WG[e[I+5]]+"-"+WG[e[I+6]]+WG[e[I+7]]+"-"+WG[e[I+8]]+WG[e[I+9]]+"-"+WG[e[I+10]]+WG[e[I+11]]+WG[e[I+12]]+WG[e[I+13]]+WG[e[I+14]]+WG[e[I+15]]).toLowerCase()}var k0,aO=new Uint8Array(16);function O0(){if(!k0){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");k0=crypto.getRandomValues.bind(crypto)}return k0(aO)}var nO=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),K0={randomUUID:nO};function ZO(e,I,l){if(K0.randomUUID&&!I&&!e)return K0.randomUUID();e=e||{};let G=e.random??e.rng?.()??O0();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(`UUID byte range ${l}:${l+15} is out of buffer bounds`);for(let t=0;t<16;++t)I[l+t]=G[t];return I}return xR(G)}var rG=ZO;var eG=class{constructor(I,l){this.n
`)}var _R=require("obsidian");function Qa(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)}}async function fR(e,I){return e.mode==="script"?await I.evaluateScriptCondition(e):mO(e,I.variables)}function mO(e,I){let l=e.variableName?.trim();if(!l)return k.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(l in I))return k.logWarning(`Conditional command skipped: Variable '${l}' is not defined.`),!1;let G=I[l];switch(e.operator){case"isTruthy":return!!G;case"isFalsy":return!G}if(uc(e.operator)){let t=fr(e);return t===void 0?(k.logWarning(`Conditional command: Operator '${e.operator}' requires a comparison value.`),!1):e.operator==="contains"?DR(G,t,e):e.operator==="notContains"?!DR(G,t,e):WO(G,t,e)}return!1}function DR(e,I,l){if(e==null)return!1;if(typeof I=="string"&&I.length===0)return k.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1;if(Array.isArray(e))return e.map(c=>mh(c,l.valueType)).some(c=>c===I);if(typeof e=="string")return e.includes(ic(I));if(typeof e=="number"&&typeof I=="number")return e===I;let G=ic(e),t=ic(I);return typeof G=="string"&&G.includes(t)}function WO(e,I,l){let G=mh(e,l.valueType);switch(l.operator){case"equals":return G===I;case"notEquals":return G!==I;case"lessThan":return ZY(G,I,(t,c)=>t<c);case"lessThanOrEqual":return ZY(G,I,(t,c)=>t<=c);case"greaterThan":return ZY(G,I,(t,c)=>t>c);case"greaterThanOrEqual":return ZY(G,I,(t,c)=>t>=c);default:return!1}}function ZY(e,I,l){let G=Number(e),t=Number(I);return Number.isNaN(G)||Number.isNaN(t)?(k.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):l(G,t)}var MR=require("obsidian");function Fc(e,{logPrefix:I,noticePrefix:l=I,defaultReason:G}){if(!(e instanceof vI))return!1;let t=typeof e.message=="string"&&e.message.trim().length>0?e.message:G;return k.logMessage(`${I}: ${t}`),(!(typeof e.message=="string"&&e.message.toLowerCase().includes("cancelled by user"))||S.getState().showInputCancellationNotification)&&new MR.Notice(`${l}: ${t}`),!0}function jR(e,I=void 0){return e==="horizontal"?"horizontal":e==="vertical"?"vertical":I}function gc(e,I,l){return l?{location:e,direction:l,focus:I,mode:"default"}:{location:e,focus:I,mode:"default"}}function TR(e){let I=e.focus??!0;if(e.location)switch(e.location){case"reuse":return gc("reuse",I);case"tab":return gc("tab",I);case"split":return gc("split",I,jR(e.direction,"vertical"));case"window":return gc("window",I);case"left-sidebar":return gc("left-sidebar",I);case"right-sidebar":return gc("right-sidebar",I);default:break}let l=e.openInNewTab??!1,G=jR(e.direction);return l?gc("split",I,G??"vertical"):gc("reuse",I)}function qR(e){let I={hasOwnProperty:l=>e.has(l)};return new Proxy(I,{get(l,G){if(G==="hasOwnProperty")return I.hasOwnProperty;if(typeof G=="string")return e.get(G)},set(l,G,t){return typeof G!="string"||e.set(G,t),!0},deleteProperty(l,G){return typeof G!="string"||e.delete(G),!0},has(l,G){return typeof G=="string"&&e.has(G)},ownKeys(){return Array.from(e.keys())},getOwnPropertyDescriptor(l,G){if(G==="hasOwnProperty")return{value:I.hasOwnProperty,writable:!1,configurable:!1,enumerable:!1};if(!(typeof G!="string"||!e.has(G)))return{value:e.get(G),writable:!0,configurable:!0,enumerable:!0}}})}function Pt(e,I){return U0(e)&&e.type===I}function sO(e){return Pt(e,"Obsidian")}function YO(e){return Pt(e,"UserScript")}function iO(e){return Pt(e,"Choice")}function uO(e){return Pt(e,"Wait")}function CO(e){return Pt(e,"NestedChoice")}function hO(e){return Pt(e,"EditorCommand")}function pO(e){return Pt(e,"AIAssistant")}function oO(e){return Pt(e,"OpenFile")}function VO(e){return Pt(e,"Conditional")}function U0(e){return e!==null&&typeof e=="object"}function rO(e){return typeof e=="function"}function $R(e){return U0(e)}function XO(e){if(!$R(e))return;let{settings:I}=e;return U0(I)?I:void 0}function PR(e){return`${e.scriptPath}::${e.exportName??"default"}`}var Vt=class extends
\u261A
\\end{${e}}\u261A`}var IL=[...LO,...FO.map(gO)];var lL=require("obsidian");var wO=new RegExp(/\\([a-z{}A-Z0-9]*)$/),NY=class extends GG{constructor(l){super(Il.instance.app,l);this.inputEl=l;this.lastInput="";this.symbols=Object.assign([],IL),this.elementsRendered=this.symbols.reduce((G,t)=>{try{G[t.toString()]=(0,lL.renderMath)(t,!0)}catch{}return G},{})}getSuggestions(l){if(this.inputEl.selectionStart===null)return[];let G=this.inputEl.selectionStart,t=l.slice(0,G),c=t.lastIndexOf("\\"),d=t.slice(c),b=wO.exec(d),a=[];return b&&(this.lastInput=b[1],a=this.symbols.filter(m=>m.toLowerCase().contains(this.lastInput))),new zG(a,{findAllMatches:!0,threshold:.8}).search(this.lastInput).map(m=>m.item)}renderSuggestion(l,G){l&&(G.setText(l),G.append(this.elementsRendered[l]))}selectSuggestion(l){if(this.inputEl.selectionStart===null)return;let G=this.inputEl.selectionStart,t=this.lastInput.length,c=this.inputEl.value,d=0,b=l.replace(/\\\\/g,"\\");if(this.inputEl.value=`${c.slice(0,G-t-1)}${b}${c.slice(G)}`,d=G-t+l.length-1,this.inputEl.trigger("input"),this.close(),l.contains("\u261A")){let a=this.inputEl.value.indexOf("\u261A");this.inputEl.value=this.inputEl.value.replace("\u261A",""),this.inputEl.setSelectionRange(a,a)}else this.inputEl.setSelectionRange(d,d)}};var sY=class e extends DG.Modal{constructor(){super(Il.instance.app);this.didSubmit=!1;this.keybindListener=l=>{l.ctrlKey&&l.key==="Enter"&&this.submit(),l.key==="Tab"&&(l.preventDefault(),this.cursorToGoTo())};this.submitClickCallback=l=>this.submit();this.cancelClickCallback=l=>this.cancel();this.open(),this.display(),this.waitForClose=new Promise((l,G)=>{this.resolvePromise=l,this.rejectPromise=G}),new NY(this.inputEl),this.inputEl.focus(),this.inputEl.select()}static Prompt(){return new e().waitForClose}display(){this.containerEl.addClass("quickAddModal","qaMathModal"),this.contentEl.empty();let l=this.contentEl.createDiv();l.className="math math-block is-loaded";let G=new DG.TextAreaComponent(this.contentEl);G.inputEl.style.width="100%",G.inputEl.style.height="10rem",this.inputEl=G.inputEl,G.onChange((0,DG.debounce)(async t=>await this.mathjaxLoop(l,t),50)),G.inputEl.addEventListener("keydown",this.keybindListener),this.createButtonBar(this.contentEl.createDiv())}async onOpen(){super.onOpen(),await(0,DG.loadMathJax)()}async mathjaxLoop(l,G){let t=(0,DG.renderMath)(G,!0);await(0,DG.finishRenderMath)(),l.empty(),l.append(t)}cursorToGoTo(){if(this.inputEl.value.contains("\u261A")){let l=this.inputEl.value.indexOf("\u261A");this.inputEl.value=this.inputEl.value.replace("\u261A",""),this.inputEl.setSelectionRange(l,l)}}createButton(l,G,t){let c=new DG.ButtonComponent(l);return c.setButtonText(G).onClick(t),c}createButtonBar(l){let G=l.createDiv();this.createButton(G,"Ok",this.submitClickCallback).setCta().buttonEl.style.marginRight="0",this.createButton(G,"Cancel",this.cancelClickCallback),G.style.display="flex",G.style.flexDirection="row-reverse",G.style.justifyContent="flex-start",G.style.marginTop="1rem",G.style.gap="0.5rem"}removeInputListeners(){this.inputEl.removeEventListener("keydown",this.keybindListener)}resolveInput(){let l=this.inputEl.value.replace("\\n","\\\\n").replace(new RegExp("\u261A","g"),"");this.didSubmit?this.resolvePromise(l):this.rejectPromise("No input given.")}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListeners()}};var Te=class extends mt{constructor(l,G,t,c){super(l);this.app=l;this.plugin=G;this.choiceExecutor=t;this.dateParser=c||xe,t&&(this.variables=t?.variables)}async format(l){let G=l;return G=await this.replaceInlineJavascriptInString(G),G=await this.replaceMacrosInString(G),G=await this.replaceTemplateInString(G),G=await this.replaceGlobalVarInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=await this.replaceValueInString(G),G=await this.replaceSelectedInString(G),G=await this.replaceClipboardInString(G),G=await this.replaceDateVariableInString(G),G=await this.replaceVariableInString(G),G=await this.replaceFieldVarInString(G),G
Suggested values for ${G}: ${n.slice(0,3).join(", ")}`)}return await rl.PromptWithContext(this.app,`Enter value for ${G}`,a,void 0,this.getLinkSourcePath()??void 0)}let b=`Enter value for ${G}`;return d&&(b=`Enter value for ${G} (default: ${t.defaultValue})`),await mG.Suggest(this.app,c,c,{placeholder:b})}catch(G){throw ol(G)?new vI("Input cancelled by user"):G}}generateCacheKey(l){return cY(l)}async getMacroValue(l,G){let t=new WY(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),c=await t.runAndGetOutput(l,G)??"";return t.getVariables().forEach((d,b)=>{this.variables.set(b,d)}),c}async getTemplateContent(l){return await new vc(this.app,this.plugin,l,this.choiceExecutor).run()}async getSelectedText(){let l=this.app.workspace.getActiveViewOfType(GL.MarkdownView);return l?l.editor.getSelection():""}async getClipboardContent(){try{return await navigator.clipboard.readText()}catch{return""}}isTemplatePropertyTypesEnabled(){return this.plugin.settings.enableTemplatePropertyTypes}async replaceInlineJavascriptInString(l){let G=l;for(;cn.test(G);){let c=cn.exec(G)?.at(1)?.trim();if(c){let d=new mY(this.app,this.plugin,this.choiceExecutor,this.variables),b=await d.runAndGetOutput(c);for(let a in d.params.variables)this.variables.set(a,d.params.variables[a]);G=typeof b=="string"?this.replacer(G,cn,b):this.replacer(G,cn,"")}}return G}async collectValuesManually(l,G){return await dY(this.app,l,G)}};var La=require("obsidian");var eL=require("obsidian");function pW(e){return((0,eL.normalizePath)(e).split("/").pop()??"").replace(/\.(md|canvas|base)$/i,"")}var rt=class extends Error{constructor(I){super(I),this.name="InvalidFolderPathError"}};function z0(e){return e instanceof vI||!!e&&typeof e=="object"&&"name"in e&&e.name==="MacroAbortError"}var Fa=class extends Ob{constructor(l,G,t){super(l);this.plugin=G;this.templater=ch(l),this.formatter=new Te(l,G,t)}async getOrCreateFolder(l,G={}){let t=this.buildFolderSelectionContext(l,G);if(!this.shouldPromptForFolder(t))return await this.handleSingleSelection(t);let c=await this.promptUntilAllowed(t);return c.isEmpty?"":c.resolved}buildFolderSelectionContext(l,G){let t=G.allowCreate??!1,c=G.allowedRoots?.map(m=>this.normalizeFolderPath(m))??[],{items:d,displayItems:b,normalizedItems:a,canonicalByNormalized:n,displayByNormalized:Z}=this.buildFolderSuggestions(l,G.topItems??[],c.length>0?c:void 0);return{items:d,displayItems:b,normalizedItems:a,canonicalByNormalized:n,displayByNormalized:Z,existingSet:new Set(a),allowCreate:t,allowedRoots:c,placeholder:G.placeholder}}shouldPromptForFolder(l){return l.items.length>1||l.allowCreate&&l.items.length===0}async promptForFolder(l){try{return l.allowCreate?await mG.Suggest(this.app,l.displayItems,l.items,{placeholder:l.placeholder??"Choose a folder or type to create one",renderItem:(G,t)=>{this.renderFolderSuggestion(G,t,l.existingSet,l.displayByNormalized)}}):await VG.Suggest(this.app,l.displayItems,l.items,l.placeholder)}catch(G){throw ol(G)?new vI("Input cancelled by user"):G}}async resolveSelection(l,G){let t=this.normalizeFolderPath(l),c=t.length===0,d=G.canonicalByNormalized.get(t),b=d??t,a=c?!1:d!==void 0||await this.app.vault.adapter.exists(b),n=G.allowedRoots.length===0?!0:this.isPathAllowed(c?"":b,G.allowedRoots);return{raw:l,normalized:t,resolved:b,exists:a,isAllowed:n,isEmpty:c}}async promptUntilAllowed(l){for(;;){let G=await this.promptForFolder(l),t=await this.resolveSelection(G,l);if(t.isEmpty){if(!t.isAllowed){this.showFolderNotAllowedNotice(l.allowedRoots);continue}return t}if(!t.isAllowed){this.showFolderNotAllowedNotice(l.allowedRoots);continue}try{this.validateFolderPath(t.resolved)}catch(c){if(c instanceof rt){new La.Notice(c.message);continue}throw c}return await this.ensureFolderExists(t),t}}async ensureFolderExists(l){l.isEmpty||l.exists||await this.createFolder(l.resolved)}async handleSingleSelection(l){let G=l.items[0]??"",t=await this.resolveSelection(G,l);if(t.isEmpty)return"";if(!t.isAllowed)throw this.showFolderNotAllowedNotice(l.allowedRoots),new vI("Selected folder not allowed.");if
${a}`:`${a}
${b}`;return await this.app.vault.modify(l,n),l}catch(c){if(z0(c))throw c;return al(c,"Could not append to file with template"),null}}async getTemplateContent(l){let G=this.stripLeadingSlash(l);!CG.test(l)&&!hG.test(l)&&!ae.test(l)&&(G+=".md");let t=this.app.vault.getAbstractFileByPath(G);if(!(t instanceof La.TFile))throw new Error(`Template file not found at path "${G}".`);return await this.app.vault.cachedRead(t)}};var vc=class extends Fa{constructor(l,G,t,c){super(l,G,c);this.templatePath=t}async run(){let l=await this.getTemplateContent(this.templatePath);return l||k.logError(`Template ${this.templatePath} not found.`),l=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.formatFileContent(l)),l}getAndClearTemplatePropertyVars(){return this.formatter.getAndClearTemplatePropertyVars()}};var yG=class extends mt{constructor(l,G,t){super(l);this.plugin=G;this.dateParser=t||xe}async format(l){let G=l;try{G=await this.replaceGlobalVarInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=await this.replaceValueInString(G),G=await this.replaceSelectedInString(G),G=await this.replaceClipboardInString(G),G=await this.replaceDateVariableInString(G),G=await this.replaceVariableInString(G),G=await this.replaceLinkToCurrentFileInString(G),G=await this.replaceCurrentFileNameInString(G),G=await this.replaceMacrosInString(G),G=await this.replaceTemplateInString(G),G=await this.replaceFieldVarInString(G),G=this.replaceRandomInString(G),G=this.replaceLinebreakInString(G)}catch{return l}return G}async replaceGlobalVarInString(l){let G=l,t=0,c=new RegExp(dc.source,"gi");for(;c.test(G)&&!(++t>5);)G=G.replace(c,(d,b)=>{let a=String(b??"").trim();if(!a)return d;let n=this.plugin?.settings?.globalVariables?.[a];return typeof n=="string"?n:""});return G}promptForValue(l){return l||"user input"}getVariableValue(l){let G=this.variables.get(l);if(typeof G=="string")return G;let t=jm(l);return ts(t)}getCurrentFileLink(){return this.app?as(this.app.workspace.getActiveFile()):null}getCurrentFileName(){return this.app?ns(this.app.workspace.getActiveFile()):"current_filename"}suggestForValue(l,G=!1,t){return bs(t?.displayValues??l)}getMacroValue(l,G){return cs(l)}promptForMathValue(){return Promise.resolve("calculation_result")}promptForVariable(l,G){return Promise.resolve(ds(l))}async getTemplateContent(l){let G=this.app;if(!G)return`Template (app unavailable): ${l}`;try{return await new vc(G,this.plugin,l,void 0).run()}catch{return`Template (not found): ${l}`}}async getSelectedText(){return"selected_text"}async getClipboardContent(){return"clipboard_content"}async suggestForField(l){return Promise.resolve(`${l}_field_value`)}async replaceDateVariableInString(l){let G=l;return G=G.replace(new RegExp(Sc.source,"gi"),(t,c,d,b)=>{let a=c?.trim(),n=d?.trim(),Z=b?.trim();if(!a||!n)return t;let m=new Date,W;try{W=Wt.generate(n,m)}catch{W=`[${n} format]`}return Z&&(W+=` (default: ${Z})`),W}),G}replaceRandomInString(l){let G=l;return G=G.replace(/{{RANDOM:(\d+)}}/gi,(t,c)=>{let d=parseInt(c);if(d<=0||d>100)return t;let b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a="";for(let n=0;n<Math.min(d,8);n++)a+=b.charAt(Math.floor(Math.random()*b.length));return d>8&&(a+=`... (${d} chars)`),a}),G}isTemplatePropertyTypesEnabled(){return!1}};var vO=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),HO=new Intl.Collator(void 0,{numeric:!0,sensitivity:"variant"});function YY(e){return e.trim().replace(/^\/+/,"").replace(/\/+$/,"")}function yO(e,I){let l=YY(e),G=YY(I);if(l===G)return 0;let t=l===""?[]:l.split("/"),c=G===""?[]:G.split("/"),d=Math.min(t.length,c.length);for(let b=0;b<d;b++){let a=vO.compare(t[b],c[b]);if(a!==0)return a;let n=HO.compare(t[b],c[b]);if(n!==0)return n}return t.length-c.length}function Kd(e){return[...e].sort(yO)}function JO(e,I){let l=YY(e),G=YY(I);return G?l===G||l.startsWith(`${G}/`):!0}function tL(e,I){return e.filter(l=>I.some(G=>JO(l,G)))}var iY=require("obsidian");var XG=class extends GG{constructor(l,G,t,c=1/0){super(l,G);this.app=l;this.inputEl=G;this.items=t;this.max
`).map(o=>o.trim()).filter(o=>o.length>0),Y=this.truncatePickerText(i[0]??"(empty text card)",90),p=[`${i.length} line${i.length===1?"":"s"}`];Z&&p.push(Z);let u=p.join(" \xB7 ");return{id:a.id,type:n,title:Y,subtitle:u,searchText:`${a.id} ${Y} ${u}`.toLowerCase(),capturable:!0,capturableReason:""}}if(n==="file"){let s=this.getCanvasNodeFilePath(a.file),i=CG.test(s),Y=i?"":"Canvas file cards must link to markdown files (.md).",p=this.truncatePickerText(s.split("/").pop()??s,90),u=[this.truncatePickerText(s,120)];Z&&u.push(Z),i||u.push("Not capturable in this version");let o=u.join(" \xB7 ");return{id:a.id,type:n,title:p,subtitle:o,searchText:`${a.id} ${p} ${o}`.toLowerCase(),capturable:i,capturableReason:Y}}let W=`Unsupported node (${typeof a.type=="string"&&a.type.length>0?a.type:"unknown"})`,N=Z||"Type is not currently capturable";return{id:a.id,type:n,title:W,subtitle:N,searchText:`${a.id} ${W} ${N}`.toLowerCase(),capturable:!1,capturableReason:"This Canvas node type is not capturable."}}),b={text:0,file:1,other:2};return d.sort((a,n)=>{let Z=b[a.type]-b[n.type];return Z!==0?Z:a.title.localeCompare(n.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 LI.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=Nc(this.choice.appendLink),G=l.linkType??"link",t=l.enabled?l.requireActiveFile?"required":"optional":"disabled";new LI.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(d=>{d.addOption("required","Enabled (requires active file)"),d.addOption("optional","Enabled (skip if no active file)"),d.addOption("disabled","Disabled"),d.setValue(t),d.onChange(b=>{switch(b){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 LI.Setting(this.contentEl).setName("Link placement").setDesc("Where to place the link when appending").addDropdown(b=>{b.addOption("replaceSelection","Replace selection"),b.addOption("afterSelection","After selection"),b.addOption("endOfLine","End of line"),b.addOption("newLine","New line"),b.setValue(l.placement),b.onChange(a=>{let n=this.choice.appendLink,Z=typeof n=="boolean"?l.requireActiveFile:n.requireActiveFile,m=typeof n=="boolean"?G:n.linkType??G,W=xt(a)?m:"link";this.choice.appendLink={enabled:!0,placement:a,requireActiveFile:Z,linkType:W},this.reload()})}),xt(l.placement)&&new LI.Setting(this.contentEl).setName("Link type").setDesc("Choose whether to insert a regular link or an embed when replacing the selection.").addDropdown(a=>{a.addOption("link","Link"),a.addOption("embed","Embed"),a.setValue(G),a.onChange(n=>{let Z=this.choice.appendLink,m=typeof Z=="boolean"?l.requireActiveFile:Z.requireActiveFile,W=typeof Z=="boolean"?l.placement:Z.placement;this.choice.appendLink={enabled:!0,placement:W,requireActiveFile:m,linkType:n}})}))}addWritePositionSetting(){let l=new LI.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
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function I3(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gW(e,I){var l=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!l){if(Array.isArray(e)||(l=lp(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(a){throw a},f:t}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var c=!0,d=!1,b;return{s:function(){l=l.call(e)},n:function(){var a=l.next();return c=a.done,a},e:function(a){d=!0,b=a},f:function(){try{!c&&l.return!=null&&l.return()}finally{if(d)throw b}}}}var l3="finalize",G3="consider";function ka(e,I,l){e.dispatchEvent(new CustomEvent(l3,{detail:{items:I,info:l}}))}function Ac(e,I,l){e.dispatchEvent(new CustomEvent(G3,{detail:{items:I,info:l}}))}var gY="draggedEntered",wW="draggedLeft",wY="draggedOverIndex",Gp="draggedLeftDocument",rY={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function e3(e,I,l){e.dispatchEvent(new CustomEvent(gY,{detail:{indexObj:I,draggedEl:l}}))}function t3(e,I,l){e.dispatchEvent(new CustomEvent(wW,{detail:{draggedEl:I,type:rY.LEFT_FOR_ANOTHER,theOtherDz:l}}))}function c3(e,I){e.dispatchEvent(new CustomEvent(wW,{detail:{draggedEl:I,type:rY.OUTSIDE_OF_ANY}}))}function d3(e,I,l){e.dispatchEvent(new CustomEvent(wY,{detail:{indexObj:I,draggedEl:l}}))}function b3(e){window.dispatchEvent(new CustomEvent(Gp,{detail:{draggedEl:e}}))}var EG={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:gY,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:wY,DRAGGED_LEFT:wW,DRAGGED_LEFT_ALL:"draggedLeftAll",DROPPED_INTO_ZONE:"droppedIntoZone",DROPPED_INTO_ANOTHER:"droppedIntoAnother",DROPPED_OUTSIDE_OF_ANY:"droppedOutsideOfAny",DRAG_STOPPED:"dragStopped"},LG={POINTER:"pointer",KEYBOARD:"keyboard"},vY="isDndShadowItem",HY="data-is-dnd-shadow-item-internal",a3="data-is-dnd-shadow-item-hint",Dd="id:dnd-shadow-placeholder-0000",n3="dnd-action-dragged-el",aG="id",S0=0;function HL(){S0++}function yL(){if(S0===0)throw new Error("Bug! trying to decrement when there are no dropzones");S0--}var ep=typeof window>"u",HI=function(){};function T0(e){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,l,G=I?N3(e):e.getBoundingClientRect(),t=getComputedStyle(e),c=t.transform;if(c){var d,b,a,n;if(c.startsWith("matrix3d("))l=c.slice(9,-1).split(/, /),d=+l[0],b=+l[5],a=+l[12],n=+l[13];else if(c.startsWith("matrix("))l=c.slice(7,-1).split(/, /),d=+l[0],b=+l[3],a=+l[4],n=+l[5];else return G;var Z=t.transformOrigin,m=G.x-a-(1-d)*parseFloat(Z),W=G.y-n-(1-b)*parseFloat(Z.slice(Z.indexOf(" ")+1)),N=d?G.width/d:e.offsetWidth,s=b?G.height/b:e.offsetHeight;return{x:m,y:W,width:N,height:s,top:W,right:m+N,bottom:W+s,left:m}}else return G}function JL(e){var I=T0(e);return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}function AL(e){var I=e.getBoundingClientRect();return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}function EL(e){return{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}}function Z3(e,I){return Math.sqrt(Math.pow(e.x-I.x,2)+Math.pow(e.y-I.y,2))}function yY(e,I){return e.y<=I.bottom&&e.y>=I.top&&e.x>=I.left&&e.x<=I.right}function RW(e){return EL(AL(e))}function oL(e,I){var l=RW(e),G=JL(I);return yY(l,G)}function m3(e,I){var l=RW(e),G=RW(I);return Z3(l,G)}function W3(e){var I=AL(e);return I.right<0||I.left>document.documentElement.scrollWidth||I.bottom<0||I.top>document.documentElement.scrollHeight}function N3(e){for(var I=e.getBoundingClientRect(),l={top:I.top,bottom:I.bottom,left:I.left,right:I.right},G=e.parentElement;G&&G!==document.body;){var t=G.getBoundingClientRect(),c=window.getComputedStyle(G).overflowY,d=window.getComputedStyle(G).overflowX,b=c==="scroll"||c==="auto",a=d==="scroll"||d==="auto";b&&(l.top=Math.max(l.top,t.top),l.bottom=Math.min(l.bottom,t.bottom)),a&&(l.left=Math.max(l.left,t.left),l.right=Math.min(l.right,t.right)),G=G.parentElement}return l.top=Math.max(l.top,0),l.bottom=Math.min(l.bottom,window.innerHeight),l.left=Math.max(l.left,0),l.right=Math.min(l.right,window.innerWidth),{top:l.top,bottom:l.bottom,left:l.left,right:l.right,width:Math.max(0,l.right-l.left),height:Math.max(0,l.bottom-l.top)}}var Ja;function tp(){HI(function(){return"resetting indexes cache"}),Ja=new Map}tp();function s3(e){var I=Array.from(e.children).f
${l?"Deleting this choice will delete all ("+e.choices.length+") choices inside it!":""}
${G?"Deleting this choice will delete its macro commands!":""}
`)}async function WF(e,I,l){if(e.type==="Multi")try{return await new _Y(I,e).waitForClose}catch{return}let G=E9(e,I,l);if(!G)throw new Error("Invalid choice type");return await G.waitForClose}function NF(e){return{...e,command:!e.command}}var Ii=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 sF(e,I,l){if(!I||!l)return e;let G=ip(e,I),t=ip(e,l);if(!G||!t||t.type!=="Multi"||G.type==="Multi"&&(G.id===t.id||k9(G).has(t.id)))return e;let{updated:c,removed:d}=YF(e,I);return d?iF(c,l,d)??e:e}function ip(e,I){for(let l of e){if(l.id===I)return l;if(l.type==="Multi"){let G=ip(l.choices,I);if(G)return G}}}function k9(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 YF(e,I){let l;return{updated:e.map(t=>{if(t.id===I){l=t;return}if(t.type!=="Multi")return t;let c=YF(t.choices,I);return c.removed&&(l=c.removed),c.removed?{...t,choices:c.updated}:t}).filter(Boolean),removed:l}}function iF(e,I,l){let G=!1,t=e.map(c=>{if(c.id===I&&c.type==="Multi"){G=!0;let b=c;return{...b,choices:[...b.choices,l]}}if(c.type!=="Multi")return c;let d=iF(c.choices,I,l);return d?(G=!0,{...c,choices:d}):c});return G?t:void 0}var wt=require("obsidian");var Fl=require("obsidian");var uF=require("obsidian");var li=null,O9=1440*60*1e3;async function CF(){if(li&&Date.now()-li.fetchedAt<O9)return li.data;if(S.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let I=await(await(0,uF.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;return li={data:I,fetchedAt:Date.now()},I}function hp(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 hF(e){return e.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}function pp(e,I){let l=new Set(e.map(t=>t.name)),G=I.filter(t=>!l.has(t.name));return e.concat(G)}var VF=require("obsidian");var K9=128e3;async function Gi(e,I){let l=e.modelSource??"providerApi";if(l==="modelsDev")return pF(e);if(l==="providerApi")return oF(e,I);try{return await oF(e,I)}catch(G){if(!hp(e.endpoint))throw G;return pF(e,G)}}async function pF(e,I){try{let l=await CF(),G=hp(e.endpoint);if(!G||!(G in l))throw new Error(`models.dev does not list a provider that matches ${e.endpoint}.`);let t=Object.values(l[G].models);return hF(t)}catch(l){throw I?new Error(`Provider API failed (${I.message}). Fallback to models.dev also failed: ${l.message}`):l}}async function oF(e,I){let{disableOnlineFeatures:l}=S.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 endpoin
`),b=nI(d),V(I,"class","warning svelte-iqd8ho")},m(a,n){cI(a,I,n),h(I,l),h(I,G),h(I,t),h(t,c),h(t,b)},p(a,n){n[0]&256&&d!==(d=a[8].missingChoiceIds.join(", ")+"")&&oI(b,d)},d(a){a&&eI(I)}}}function mg(e){let I,l,G,t,c=e[4].missingChoices.length>0&&Wg(e),d=e[4].missingAssets.length>0&&Ng(e);return{c(){I=L("section"),l=L("h4"),l.textContent="Warnings",G=U(),c&&c.c(),t=U(),d&&d.c(),V(I,"class","warning svelte-iqd8ho")},m(b,a){cI(b,I,a),h(I,l),h(I,G),c&&c.m(I,null),h(I,t),d&&d.m(I,null)},p(b,a){b[4].missingChoices.length>0?c?c.p(b,a):(c=Wg(b),c.c(),c.m(I,t)):c&&(c.d(1),c=null),b[4].missingAssets.length>0?d?d.p(b,a):(d=Ng(b),d.c(),d.m(I,null)):d&&(d.d(1),d=null)},d(b){b&&eI(I),c&&c.d(),d&&d.d()}}}function Wg(e){let I,l,G=e[4].missingChoices.map(e[23]).join(", ")+"",t;return{c(){I=L("p"),l=nI(`Missing choices:
`),t=nI(G)},m(c,d){cI(c,I,d),h(I,l),h(I,t)},p(c,d){d[0]&144&&G!==(G=c[4].missingChoices.map(c[23]).join(", ")+"")&&oI(t,G)},d(c){c&&eI(I)}}}function Ng(e){let I,l,G,t,c=Nl(e[4].missingAssets),d=[];for(let b=0;b<c.length;b+=1)d[b]=sg(dg(e,c,b));return{c(){I=L("div"),l=L("p"),l.textContent="Missing assets:",G=U(),t=L("ul");for(let b=0;b<d.length;b+=1)d[b].c();V(t,"class","svelte-iqd8ho")},m(b,a){cI(b,I,a),h(I,l),h(I,G),h(I,t);for(let n=0;n<d.length;n+=1)d[n]&&d[n].m(t,null)},p(b,a){if(a[0]&528){c=Nl(b[4].missingAssets);let n;for(n=0;n<c.length;n+=1){let Z=dg(b,c,n);d[n]?d[n].p(Z,a):(d[n]=sg(Z),d[n].c(),d[n].m(t,null))}for(;n<d.length;n+=1)d[n].d(1);d.length=c.length}},d(b){b&&eI(I),Jt(d,b)}}}function sg(e){let I,l=e[28].path+"",G,t,c,d,b=e[9][e[28].kind]+"",a,n;return{c(){I=L("li"),G=nI(l),t=U(),c=L("span"),d=nI("("),a=nI(b),n=nI(")"),V(c,"class","assetKind svelte-iqd8ho")},m(Z,m){cI(Z,I,m),h(I,G),h(I,t),h(I,c),h(c,d),h(c,a),h(c,n)},p(Z,m){m[0]&16&&l!==(l=Z[28].path+"")&&oI(G,l),m[0]&16&&b!==(b=Z[9][Z[28].kind]+"")&&oI(a,b)},d(Z){Z&&eI(I)}}}function HK(e){let I;return{c(){I=nI("Copy JSON")},m(l,G){cI(l,I,G)},d(l){l&&eI(I)}}}function yK(e){let I;return{c(){I=nI("Copying\u2026")},m(l,G){cI(l,I,G)},d(l){l&&eI(I)}}}function JK(e){let I;return{c(){I=nI("Save to file")},m(l,G){cI(l,I,G)},d(l){l&&eI(I)}}}function AK(e){let I;return{c(){I=nI("Saving\u2026")},m(l,G){cI(l,I,G)},d(l){l&&eI(I)}}}function EK(e){let I,l,G,t,c,d,b,a,n,Z,m,W,N,s,i,Y,p,u,o,C,Q=e[8].rootCount+"",g,X,w,R,A,j,x=e[8].totalChoices+"",B,f,z,y,H,J,_=e[8].dependencyCount+"",bI,rI,QI,BI,yI,hI,YI=e[8].userScripts+e[8].conditionalScripts+"",DI,gG,kG,OG,nG,ye,jG=e[8].templateFiles+e[8].captureTemplates+"",SG,sG,YG,T,KI,fI,qI,ce,iG,TG,Ic,yt,de,lc,Kc,Gc,Je,TW,Ae,xc,Pa,Uc,Ee,qW,r,v,O;function M(Ml,Cl){return Ml[6].length===0?vK:wK}let lI=M(e,[-1,-1]),GI=lI(e),II=e[8].missingChoiceIds.length>0&&Zg(e),mI=e[4]&&mg(e);function el(Ml,Cl){return Ml[5]==="copy"?yK:HK}let Hl=el(e,[-1,-1]),nl=Hl(e);function be(Ml,Cl){return Ml[5]==="save"?AK:JK}let Dl=be(e,[-1,-1]),fl=Dl(e);return{c(){I=L("div"),l=L("header"),l.innerHTML='<h2>Export QuickAdd Package</h2> <p class="svelte-iqd8ho">Select choices to bundle. Dependencies are added automatically.</p>',G=U(),t=L("section"),c=L("input"),b=U(),a=L("div"),n=L("button"),n.textContent="Select visible",Z=U(),m=L("button"),m.textContent="Clear selection",W=U(),N=L("section"),GI.c(),s=U(),i=L("section"),Y=L("h3"),Y.textContent="Package summary",p=U(),u=L("div"),o=L("div"),C=L("strong"),g=nI(Q),X=U(),w=L("span"),w.textContent="Selected choices",R=U(),A=L("div"),j=L("strong"),B=nI(x),f=U(),z=L("span"),z.textContent="Total packaged",y=U(),H=L("div"),J=L("strong"),bI=nI(_),rI=U(),QI=L("span"),QI.textContent="Auto-included",BI=U(),yI=L("div"),hI=L("strong"),DI=nI(YI),gG=U(),kG=L("span"),kG.textContent="Scripts embedded",OG=U(),nG=L("div"),ye=L("strong"),SG=nI(jG),sG=U(),YG=L("span"),YG.textContent="Templates embedded",T=U(),II&&II.c(),KI=U(),mI&&mI.c(),fI=U(),qI=L("section"),ce=L("div"),iG=L("button"),nl.c(),Ic=U(),yt=L("div"),de=L("label"),lc=L("span"),lc.textContent="Save to file",Kc=U(),Gc=L("div"),Je=L("input"),TW=U(),Ae=L("button"),fl.c(),Pa=U(),Uc=L("section"),Ee=L("button"),qW=nI("Cancel"),V(l,"class","svelte-iqd8ho"),V(c,"type","text"),V(c,"placeholder","Filter choices"),V(c,"autocapitalize","off"),V(c,"autocorrect","off"),V(c,"spellcheck",d=!1),V(c,"class","svelte-iqd8ho"),V(n,"type","button"),V(n,"class","svelte-iqd8ho"),V(m,"type","button"),V(m,"class","svelte-iqd8ho"),V(a,"class","controlButtons svelte-iqd8ho"),V(t,"class","controls svelte-iqd8ho"),V(N,"class","choiceList svelte-iqd8ho"),V(Y,"class","svelte-iqd8ho"),V(C,"class","svelte-iqd8ho"),V(o,"class","svelte-iqd8ho"),V(j,"class","svelte-iqd8ho"),V(A,"class","svelte-iqd8ho"),V(J,"class","svelte-iqd8ho"),V(H,"class","svelte-iqd8ho"),V(hI,"class","svelte-iqd8ho"),V(yI,"class","svelte-iqd8ho"),V(ye,"class","svelte-iqd8ho"),V(nG,"class","svelte-iqd8ho"),V(u,"class","summaryGrid svelte-iqd8ho"),V(i,"class","summary svelte-iqd8ho"),V(iG,"type","button"),V(iG,"class","secondary svel
tm = tomorrow
yd = yesterday`).setValue(_i(S.getState().dateAliases)).onChange(d=>{S.setState({dateAliases:Yo(d)})}),c.inputEl.addClass("qa-date-alias-input")}),G.addButton(c=>{c.setButtonText("Reset to defaults").onClick(()=>{S.setState({dateAliases:Ib}),t&&t.setValue(_i(Ib))}),c.buttonEl.addClass("qa-date-alias-reset")})})}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(S.getState().disableOnlineFeatures).onChange(c=>{S.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(S.getState().enableRibbonIcon).onChange(c=>{S.setState({enableRibbonIcon:c}),this.display()})})})}};var fa=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 xW=class extends fa{constructor(){super(...arguments);this.ErrorLog=[]}logError(l,G,t){let c=this.getQuickAddError(l,"ERROR",G,t);this.addMessageToErrorLog(c);let d=t||new Error(l);console.error(this.formatOutputString(c),d)}logWarning(l,G,t){let c=this.getQuickAddError(l,"WARNING",G,t);this.addMessageToErrorLog(c);let d=t||new Error(l);console.warn(this.formatOutputString(c),d)}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>lh&&(this.ErrorLog=this.ErrorLog.slice(-lh))}clearErrorLog(){this.ErrorLog=[]}};var kp=require("obsidian");var ri=class extends fa{constructor(l){super();this.plugin=l}logError(l,G,t){let c=this.getQuickAddError(l,"ERROR",G,t);new kp.Notice(this.formatOutputString(c),15e3)}logWarning(l,G,t){let c=this.getQuickAddError(l,"WARNING",G,t);new kp.Notice(this.formatOutputString(c))}logMessage(l,G,t){}};var Xi=class{constructor(I,l,G,t){this.app=I;this.plugin=l;this.choices=G;this.choiceExecutor=t}async run(){let I=Pe(this.choices).filter(l=>l.type==="Macro"&&l.runOnStartup);for(let l of I)await new Vt(this.app,this.plugin,l,this.choiceExecutor,new Map).run()}};var Op=require("obsidian"),Kg=require("obsidian");var Qi=class extends Fa{constructor(l,G,t,c,d=null){super(l,G,c);this.originLeaf=d;this.choiceExecutor=c,this.choice=t}async run(){try{$G(this.choice.templatePath,()=>`Invalid template path for ${this.choice.name}. ${this.choice.templatePath.length===0?"Template path is empty.":`Template path is not valid: ${this.choice.templatePath}`}`);let l=Nc(this.choice.appendLink);this.setLinkToCurrentFileBehavior(l.enabled&&!l.requireActiveFile?"optional":"required");let G="";if(this.choice.folder.enabled)G=await this.getFolderPath();else{let W=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");G=W===this.app.vault.getRoot()?"":W.path}let t=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:jc,c=await this.formatter.formatFileName(t,this.choice.name),{fileName:d,strippedPrefix:b}=this.stripDuplicateFolderPrefix(c,G),a=this.shouldTreatFormattedNameAsVaultRelativePath(c,b),n=this.normalizeTemplateFilePath(a?"":G,d,this.choice.templatePath),Z,m=!1;if(await this.app.vault.adapter.exists(n)){let W=await this.getSelectedFileExistsMode(),N=va(W),s=N.requiresExistingFile?this.findExistingFile(n):null;if(N.requiresExistingFile&&(!(s instanceof Op.TFile)||s.extension!=="md"&&s.extension!=="canvas"&&s.extension!=="base")){k.logError(`'${n}' already exists but could not be resolved as a markdown, canvas, or base file.`);return}({createdFile:Z,shouldAutoOpen:m}=await this.applyFileExis
`)}}).join(`
`)}}var Ug=e=>e.join(""),ex=e=>e.split(/\b/),tx=xg("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",Ug),cx={splitFunction:ex,joinFunction:Ug,conflictFunction:tx};function Dp(e,I,l,G={}){G=Object.assign({},cx,G);let[t,c,d]=[e,I,l].map(n=>G.splitFunction.call(G,n)),b=BW.merge(t,c,d);return DW.collateMerge(b,G.joinFunction,G.conflictFunction)}var zg=Dp;var fp=require("obsidian");var MI=class extends vI{};function Bg(e,I){return e.line===I.line}function dx(e){let I=[];return e.forEach((l,G)=>{let t=l.match(/^(#+)[\s]+(.*)$/);t&&I.push({level:t[1].length,text:t[2],line:G})}),I}function wi(e,I,l=!1){let G=dx(e),t=G.find(n=>n.line===I),c=!!t;if(!c&&l)throw new Error(`Target line ${I} is not a heading, but we are trying to find the end of its section.`);if(!c&&!l){let n=Dg(e,I,Z=>Z.trim()==="");return n!==null&&n>I?n-1:I}let d=e.length-1,b=bx(t,G,e,l),a=Zx(e,b,n=>n.trim()!=="");if(a!==null){if(a<I)return I;let n=e[a+1].trim()==="";return a+1===d&&!n?b:a===0?a+1:a}return b}function bx(e,I,l,G){let t=I.findIndex(Z=>Bg(Z,e)),c=t===I.length-1,d=l.length-1;if(c)return d;let[b,a]=ax(e,I);if(a&&b===I.length)return d;if(a&&G)return I[b].line-1;if(a&&!G)return I[t+1].line;if(!G&&!a){let Z=nx(e.line,I);return Z===null?d:Z}return d}function ax(e,I){let l=I.findIndex(t=>Bg(t,e)),G=Dg(I,l,t=>t.level<=e.level);return G===null?[-1,!1]:[G,!0]}function nx(e,I){let l=I.find(G=>G.line>e);return l?l.line:null}function Zx(e,I,l){for(let G=I-1;G>=0;G--)if(l(e[G]))return G;return null}function Dg(e,I,l){for(let G=I+1;G<e.length;G++)if(l(e[G]))return G;return null}var vi=class extends Te{constructor(){super(...arguments);this.file=null;this.fileContent="";this.sourcePath=null;this.useSelectionAsCaptureValue=!0;this.templaterProcessed=!1}setDestinationFile(l){this.file=l,this.sourcePath=l.path}setDestinationSourcePath(l){this.sourcePath=l,this.file=null}setUseSelectionAsCaptureValue(l){this.useSelectionAsCaptureValue=l}shouldUseSelectionForValue(){return this.useSelectionAsCaptureValue}async getSelectedTextForValue(){let l=await this.getSelectedText();return l.trim().length>0?l:""}getLinkSourcePath(){return this.sourcePath??this.file?.path??null}getCurrentFileLink(){let l=this.app.workspace.getActiveFile();if(!l)return null;let G=this.sourcePath??this.file?.path??"";return this.app.fileManager.generateMarkdownLink(l,G)}async formatContentWithFile(l,G,t,c){if(this.choice=G,this.file=c,this.fileContent=t,!G||!c||t===null)return l;let d=G.insertAfter.enabled||G.prepend||!G.captureToActiveFile||G.activeFileWritePosition==="top"||G.activeFileWritePosition==="bottom";return await this.formatFileContent(l,d)}async formatContent(l,G){return this.choice=G,G?await this.formatFileContent(l):l}async formatFileContent(l,G=!0){let t=await super.formatFileContent(l);if(t=this.replaceLinebreakInString(t),G&&this.file&&!this.templaterProcessed){let a=await Ab(this.app,t,this.file);a&&(t=a),this.templaterProcessed=!0}if(t.trim()==="")return this.fileContent;if(this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom"){let a=!this.choice.task,n=this.fileContent.length>0&&!this.fileContent.endsWith(`
`)&&!t.startsWith(`
`),Z=a||n?`
`:"";return`${this.fileContent}${Z}${t}`}if(this.choice.insertAfter.enabled)return await this.insertAfterHandler(t);let b=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):null;return b==null||b<0?`${t}${this.fileContent}`:this.insertTextAfterPositionInBody(t,this.fileContent,b)}async formatContentOnly(l){let G=await super.formatFileContent(l);return G=this.replaceLinebreakInString(G),G.trim()===""?this.fileContent:G}normalizeTarget(l){return l.replace("\\n","").trimEnd()}findInsertAfterIndex(l,G){let t=this.normalizeTarget(G),c=-1;for(let d=0;d<l.length;d++){let b=l[d].trimStart();if(b===t)return d;if(b.startsWith(t)){let n=b.slice(t.length);if(/^\s*$/.test(n))return d;c===-1&&(c=d);continue}let a=b.indexOf(t);if(a!==-1){let n=b.slice(a+t.length);if(/^\s*$/.test(n))return d;c===-1&&(c=d)}}return c}shouldSkipBlankLinesAfterMatch(l,G){return l==="skip"?!0:l==="none"?!1:this.isAtxHeading(G)}isAtxHeading(l){return/^\s{0,3}#{1,6}\s+\S/.test(l)}findInsertAfterPositionWithBlankLines(l,G,t,c){if(G<0)return G;let d=l[G]??"";if(!this.shouldSkipBlankLinesAfterMatch(c,d))return G;let a=t.endsWith(`
`)?Math.max(l.length-1,0):l.length,n=G;for(let Z=G+1;Z<a;Z++){if(l[Z].trim().length===0){n=Z;continue}break}return n}findInsertAfterPositionAtSectionEnd(l,G,t,c){if(G<0)return G;let d=G,b=G+1;for(;b<l.length&&l[b].trim().length===0;)d=b,b++;return d===G||b!==l.length||!c.endsWith(`
`)?G:t.endsWith(`
`)?Math.max(G,d-1):d}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=x0(this.fileContent),c=this.findInsertAfterIndex(t,G);if(c===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(l);throw new MI(`Insert-after target not found: '${G}'.`)}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let b=wi(t,c,!!this.choice.insertAfter.considerSubsections);c=this.findInsertAfterPositionAtSectionEnd(t,b??t.length-1,this.fileContent,l)}else{let b=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";c=this.findInsertAfterPositionWithBlankLines(t,c,this.fileContent,b)}return this.insertTextAfterPositionInBody(l,this.fileContent,c)}hasInlineTargetLinebreak(l){return l.includes(`
`)||l.includes("\r")}getInlineEndOfLine(l){let G=this.fileContent.indexOf(`
`,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 al(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 MI(`Inline insert-after target not found: '${G}'.`)}let c=t+G.length;if(this.choice.insertAfter?.replaceExisting){let d=this.getInlineEndOfLine(c);return this.fileContent.slice(0,c)+l+this.fileContent.slice(d)}return this.fileContent.slice(0,c)+l+this.fileContent.slice(c)}async createInsertAfterIfNotFound(l){let t=`${this.replaceLinebreakInString(await this.formatLocationString(this.choice.insertAfter.after))}
${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===lb){let c=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(t,this.fileContent,c)}if(this.choice.insertAfter?.createIfNotFoundLocation===Gn)return`${this.fileContent}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===en)try{let c=this.app.workspace.getActiveViewOfType(fp.MarkdownView);if(!c)throw new Error("No active view.");let b=c.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let n=x0(this.fileContent),Z=wi(n,b,!!this.choice.insertAfter.considerSubsections);b=this.findInsertAfterPositionAtSectionEnd(n,Z??n.length-1,this.fileContent,t)}return this.insertTextAfterPositionInBody(t,this.fileContent,b)}catch{throw new MI(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position.`)}throw new MI(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`)}async createInlineInsertAfterIfNotFound(l,G){let t=`${G}${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===lb){let c=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(t,this.fileContent,c)}if(this.choice.insertAfter?.createIfNotFoundLocation===Gn)return`${this.fileContent}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===en)try{let c=this.app.workspace.getActiveViewOfType(fp.MarkdownView);if(!c)throw new Error("No active view.");let b=c.editor.getCursor().line;return this.insertTextAfterPositionInBody(t,this.fileContent,b)}catch{throw new MI(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position.`)}throw new MI(`Unknown createIfNotFoundLocation: ${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 k.logMessage("could not get frontmatter. Maybe there isn't any."),-1}inferFrontmatterEndLineFromContent(l){let G=PN(l);if(!G)return null;let t=l.slice(0,G[1]),c=t.split(/\r?\n/);return c.length===0?null:t.endsWith(`
`)?c.length-2:c.length-1}insertTextAfterPositionInBody(l,G,t){if(t===-1){let a=!this.choice.task;return`${l}${a?`
`:""}${G}`}let c=G.split(`
`),d=c.slice(0,t+1).join(`
`),b=c.slice(t+1).join(`
`);return`${d}
${l}${b}`}};function fg(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 Mp(e){return e?.type==="text"?"text":e?.type==="file"||e?.file?"file":typeof e?.text=="string"?"text":"unsupported"}function mx(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 Mg(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 Wx(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 jp(e){return!!e&&"path"in e&&"extension"in e}function Nx(e){let l=(e.workspace.activeLeaf??e.workspace.getMostRecentLeaf?.()??null)?.view;return!l||l.getViewType?.()!=="canvas"?null:l}function sx(e,I){let l=I.file??e.workspace.getActiveFile?.();if(!l)throw new MI("Cannot capture to Canvas because no active Canvas file is available.");return l}function Yx(e){let I=e.selection?Array.from(e.selection):[];if(I.length!==1)throw new MI("Canvas capture requires exactly one selected node.");return I[0]}function jg(e){let I=Wx(e);if(!I)throw new MI("Selected Canvas file card does not have a valid linked file path.");if(!CG.test(I))throw new MI("Canvas file card targets markdown files only in this version.");return I}function ix(e,I){let l=jg(I),G=e.vault.getAbstractFileByPath(l);if(!jp(G))throw new MI(`Selected Canvas file card target not found: ${l}`);return G}function ux(e,I){let l=jg(I),G=e.vault.getAbstractFileByPath(l);if(!G)return{targetPath:l};if(!jp(G))throw new MI(`Selected Canvas file card target not found: ${l}`);return{targetPath:l,targetFile:G}}function Cx(e,I){let l;try{l=JSON.parse(e)}catch{throw new MI(`Canvas file is not valid JSON: ${I}`)}if(!l||typeof l!="object")throw new MI(`Canvas file has invalid structure: ${I}`);if(!Array.isArray(l.nodes))throw new MI(`Canvas file has no nodes array: ${I}`);return l}function Sg(e,I){let l=e,G=Nx(l);if(!G)return null;let t=G.canvas;if(!t)throw new MI("Canvas capture is unavailable in this Obsidian version.");let c=sx(l,G),d=Yx(t),b=mx(t,d),a=Mp(d);if(a==="unsupported"&&b&&(a=Mp(b)),a==="unsupported")throw new MI("Canvas capture currently supports only text and file cards.");let n=Mg(a,I);if(n)throw new MI(n);if(a==="text")return{kind:"text",source:"active",canvas:t,canvasFile:c,node:d,nodeData:b};let Z=d.file||!b?.file?d:{...d,file:b.file};return{kind:"file",source:"active",canvasFile:c,node:Z,targetFile:ix(l,Z)}}async function Tg(e,I,l,G){let t=l.trim();if(!t)throw new MI("Canvas node id is required for Canvas node capture.");let c=e.vault.getAbstractFileByPath(I);if(!jp(c))throw new MI(`Canvas target not found: ${I}`);if(!hG.test(c.path))throw new MI("Canvas node capture requires the target path to be a .canvas file.");let d=await e.vault.read(c),b=Cx(d,c.path),a=b.nodes.findIndex(i=>i.id===t);if(a===-1)throw new MI(`Canvas node id '${t}' was not found in ${c.path}.`);let n=b.nodes[a],Z=Mp(n);if(Z==="unsupported")throw new MI("Canvas capture currently supports only text and file cards.");let m=Mg(Z,G);if(m)throw new MI(m);if(Z==="text")return{kind:"text",source:"configured",canvasFile:c,rawCanvas:d,canvasData:b,nodeData:n,nodeIndex:a};let W=e,{targetPath:N,targetFile:s}=ux(W,n);return{kind:"file",source:"configured",canvasFile:c,nodeData:n,targetPath:N,targetFile:s}}functio
`),l}async getFormattedPathToCaptureTo(l){let G=this.choiceExecutor?.variables?.get(dn);if(!l&&G&&typeof G=="string"&&G.length>0)return this.normalizeCaptureFilePath(G);if(l){let b=this.app.workspace.getActiveFile();return $G(b,"Cannot capture to active file - no active file."),b.path}let t=this.choice.captureTo,c=await this.formatter.formatFileName(t,this.choice.name),d=this.resolveCaptureTarget(c);switch(d.kind){case"vault":return this.selectFileInFolder("",!0);case"tag":return this.selectFileWithTag(d.tag);case"folder":return this.selectFileInFolder(d.folder,!1);case"file":return this.normalizeCaptureFilePath(d.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(ae.test(G))throw new MI(`Capture to '.base' files is not supported (${G}). Use a Template choice instead.`);let t=G.endsWith("/"),c=G.replace(/\/+$/,"");if(t)return{kind:"folder",folder:c};if(CG.test(G)||hG.test(G))return{kind:"file",path:G};let d=this.normalizeMarkdownFilePath("",c),a=!!this.app.vault.getAbstractFileByPath(d);return TN(this.app,c)&&!a?{kind:"folder",folder:c}:{kind:"file",path:G}}async selectFileInFolder(l,G){let t=l.endsWith("/")||G?l:`${l}/`,c=sc(this.app,t);$G(c.length>0,`Folder ${t} is empty.`);let d=c.map(n=>n.path),b;try{b=await mG.Suggest(this.app,d.map(n=>n.replace(t,"")),d)}catch(n){throw ol(n)?new vI("Input cancelled by user"):n}$G(!!b&&b.length>0,"No file selected for capture.");let a=b.startsWith(`${t}`)?b:`${t}/${b}`;return await this.formatFilePath(a)}async selectFileWithTag(l){let G=l.startsWith("#")?l:`#${l}`,t=qN(this.app,G);$G(t.length>0,`No files with tag ${l}.`);let c=t.map(b=>b.path),d;try{d=await mG.Suggest(this.app,c,c)}catch(b){throw ol(b)?new vI("Input cancelled by user"):b}return $G(!!d&&d.length>0,"No file selected for capture."),await this.formatFilePath(d)}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.withTemplatePropertyCollection(()=>this.formatter.formatContentOnly(G));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let d=await this.app.vault.read(t),b=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.formatContentWithFile(c,this.choice,d,t));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let a=await this.app.vault.read(t),n=b;if(a!==d){let Z=zg(a,d,b);$G(!Z.isSuccess,()=>`The file ${l} has been modified since the last read.
QuickAdd could not merge the versions two without conflicts, and will not modify the file.
This is in order to prevent data loss.`),n=Z.joinedResults()}return{file:t,newFileContent:n,captureContent:c}}async onCreateFileIfItDoesntExist(l,G,t){let c=pW(l);this.formatter.setTitle(c),this.formatter.setDestinationSourcePath(l);let d=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.formatContentOnly(G));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let b="";if(this.choice.createFileIfItDoesntExist.createWithTemplate){let m=new vc(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);t?.enabled&&!t.requireActiveFile&&m.setLinkToCurrentFileBehavior("optional"),b=await m.run();let W=m.getAndClearTemplatePropertyVars();k.logMessage(`CaptureChoiceEngine: Collected ${W.size} template property variables`),W.size>0&&k.logMessage(`Variables: ${Array.from(W.keys()).join(", ")}`),this.templatePropertyVars=W}let a=await this.createFileWithInput(l,b,{suppressTemplaterOnCreate:this.choice.createFileIfItDoesntExist.createWithTemplate});this.choice.createFileIfItDoesntExist.createWithTemplate&&this.templatePropertyVars&&this.shouldPostProcessFrontMatter(a,this.templatePropertyVars)&&await this.postProcessFrontMatter(a,this.templatePropertyVars),this.choice.createFileIfItDoesntExist.createWithTemplate&&b?await Jb(this.app,a):jN(this.app)&&await Cr(this.app,a);let n=await this.app.vault.read(a),Z=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.formatContentWithFile(d,this.choice,n,a));return this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),{file:a,newFileContent:Z,captureContent:d}}async formatFilePath(l){let G=await this.formatter.formatFileName(l,this.choice.name);return this.normalizeCaptureFilePath(G)}normalizeCaptureFilePath(l){let G=this.stripLeadingSlash(l);if(ae.test(G))throw new MI(`Capture to '.base' files is not supported (${G}). Use a Template choice instead.`);return CG.test(G)||hG.test(G)?G:this.normalizeMarkdownFilePath("",G)}mergeCapturePropertyVars(l){if(!(!l||l.size===0)){for(let[G,t]of l)this.capturePropertyVars.set(G,t);k.logMessage(`CaptureChoiceEngine: Accumulated ${this.capturePropertyVars.size} structured capture variables`)}}async applyCapturePropertyVars(l){if(this.capturePropertyVars.size!==0){if(!this.shouldPostProcessFrontMatter(l,this.capturePropertyVars)){this.capturePropertyVars.clear();return}k.logMessage(`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`),await this.postProcessFrontMatter(l,this.capturePropertyVars),this.capturePropertyVars.clear()}}};var yi=require("obsidian");var Tp="\u2190 Back",kc=class e extends yi.FuzzySuggestModal{constructor(l,G,t){super(l.app);this.plugin=l;this.choices=G;this.choiceExecutor=new ve(this.app,this.plugin);this.placeholderStack=[];t?.choiceExecutor&&(this.choiceExecutor=t.choiceExecutor),this.placeholderStack=t?.placeholderStack??[],this.currentPlaceholder=t?.placeholder?.trim()||void 0,this.currentPlaceholder&&this.setPlaceholder(this.currentPlaceholder)}static Open(l,G,t){new e(l,G,t).open()}renderSuggestion(l,G){G.empty(),yi.MarkdownRenderer.render(this.app,l.item.name,G,"",this.plugin).catch(t=>{G.textContent=l.item.name,k.logError(`Failed to render choice suggestion: ${t}`)}),G.classList.add("quickadd-choice-suggestion"),l.item.name===Tp&&G.classList.add("quickadd-choice-suggestion-back")}getItemText(l){return l.name}getItems(){return this.choices}onChooseItem(l,G){l.type==="Multi"?this.onChooseMultiType(l):this.choiceExecutor.execute(l).catch(t=>{k.logError(`Failed to execute selected choice: ${t}`)})}onChooseMultiType(l){let G=[...l.choices],t=l.name===Tp;t||G.push(new Da(Tp).addChoices(this.choices));let c=t?this.placeholderStack[this.placeholderStack.length-1]:l.placeholder?.trim()||l.name,d=t?this.placeholderStack.slice(0,-1):[...this.placeholderStack,this.currentPlaceholder];e.Open(this.plugin,G,{choiceExecutor:this.choiceExecutor,placeholder:c,placeholderStack:d})}};var Ji=require("obsidian");var fW=class extends mt{constructor(l,G,t){super(l);this.a
${c}
QuickAdd will now revert to backup.`),e.settings=G,S.replaceState(jI(e.settings))}}e.saveSettings()}var Yw=Dx;var Oc=require("obsidian");async function fx(e,I,l){let G=await(0,Oc.requestUrl)({url:`https://api.github.com/repos/${e}/${I}/releases`,throw:!1}),t=G.json;if(G.status>=400&&"message"in t||!Array.isArray(t))throw new Error(`Failed to fetch releases: ${t.message??"Unknown error"}`);let c=t.findIndex(d=>d.tag_name===l);if(c===-1)throw new Error(`Could not find release with tag ${l}`);return t.slice(0,c).filter(d=>!d.draft&&!d.prerelease)}function Mx(e,I=1){let l=e.split(`
`);for(let G=0;G<l.length;G++)l[G].startsWith("#")&&(l[G]="#".repeat(I)+l[G]);return l.join(`
`)}var Ui=class extends Oc.Modal{constructor(I,l){super(I),this.previousVersion=l,this.releaseNotesPromise=fx("chhoumann","quickadd",l),this.releaseNotesPromise.then(G=>{if(this.releases=G,this.releases.length===0){this.close();return}this.display()}).catch(G=>{k.logError(`Failed to fetch release notes: ${G}`)})}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}
`,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"),d=this.releases.map(Z=>Z.body).join(`
---
`),b=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,n=`${l}
${G}
${t}
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.
${b}
---
${Mx(d)}`;Oc.MarkdownRenderer.render(this.app,n,c,this.app.vault.getRoot().path,new Oc.Component)}};var Bl=require("obsidian");var zi=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=De(this.settings.model);return l?Ie(this.settings.systemPrompt,l):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();let l=this.contentEl.createEl("h2",{text:`${this.settings.name} Settings`});l.addClass("qa-clickable-modal-title"),l.addEventListener("click",async()=>{try{let G=await rl.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=ut();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",{cls:"qa-ai-token-count"}),c=G.createEl("div",{text:"Exact for OpenAI models; estimates for others.",cls:"qa-ai-token-note"});G.appendChild(t),G.appendChild(c);let d=new Bl.TextAreaComponent(l);d.setValue(this.settings.systemPrompt).onChange(async Z=>{this.settings.systemPrompt=Z,a.innerText=await b.format(Z),n()}),new cG(this.app,d.inputEl,Il.instance);let b=new yG(this.app,Il.instance);d.inputEl.addClass("qa-ai-prompt-textarea");let a=this.contentEl.createEl("span"),n=(0,Bl.debounce)(()=>{t.innerText=`Token count: ${this.systemPromptTokenLength}`},50);n(),(async()=>a.innerText=await b.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,.1),G.setDynamicTooltip(),G.setValue(this.settings.modelParameters.top_p??1),G.onChange(t=>{this.settings.modelParameters.top_p=t})})}addFrequencyPenaltySetting(l){new Bl.Setting(l).setName("Frequency
/* nosourcemap */