Files
my-vault/.obsidian/plugins/quickadd/main.js
T

112 lines
4.0 MiB
JavaScript
Raw Normal View History

2026-01-05 19:25:56 +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
*/
2026-01-31 08:25:19 +08:00
var QF=Object.create;var vZ=Object.defineProperty;var RF=Object.getOwnPropertyDescriptor;var rF=Object.getOwnPropertyNames;var LF=Object.getPrototypeOf,FF=Object.prototype.hasOwnProperty;var wF=(e,I,l)=>I in e?vZ(e,I,{enumerable:!0,configurable:!0,writable:!0,value:l}):e[I]=l;var lW=(e,I)=>()=>(I||e((I={exports:{}}).exports,I),I.exports),HG=(e,I)=>{for(var l in I)vZ(e,l,{get:I[l],enumerable:!0})},E0=(e,I,l,G)=>{if(I&&typeof I=="object"||typeof I=="function")for(let c of rF(I))!FF.call(e,c)&&c!==l&&vZ(e,c,{get:()=>I[c],enumerable:!(G=RF(I,c))||G.enumerable});return e};var UI=(e,I,l)=>(l=e!=null?QF(LF(e)):{},E0(I||!e||!e.__esModule?vZ(l,"default",{value:e,enumerable:!0}):l,e)),gF=e=>E0(vZ({},"__esModule",{value:!0}),e);var GI=(e,I,l)=>wF(e,typeof I!="symbol"?I+"":I,l);var Lp=lW((tu,bu)=>{(function(e,I){typeof tu=="object"&&typeof bu<"u"?bu.exports=I():typeof define=="function"&&define.amd?define(I):(e=typeof globalThis<"u"?globalThis:e||self).dayjs_plugin_quarterOfYear=I()})(tu,function(){"use strict";var e="month",I="quarter";return function(l,G){var c=G.prototype;c.quarter=function(d){return this.$utils().u(d)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(d-1))};var t=c.add;c.add=function(d,Z){return d=Number(d),this.$utils().p(Z)===I?this.add(3*d,e):t.bind(this)(d,Z)};var b=c.startOf;c.startOf=function(d,Z){var m=this.$utils(),a=!!m.u(Z)||Z;if(m.p(d)===I){var n=this.quarter()-1;return a?this.month(3*n).startOf(e).startOf("day"):this.month(3*n+2).endOf(e).endOf("day")}return b.bind(this)(d,Z)}}})});var BI=lW((du,Zu)=>{(function(e,I){typeof du=="object"&&typeof Zu<"u"?Zu.exports=I():typeof define=="function"&&define.amd?define(I):(e=typeof globalThis<"u"?globalThis:e||self).dayjs=I()})(du,function(){"use strict";var e=1e3,I=6e4,l=36e5,G="millisecond",c="second",t="minute",b="hour",d="day",Z="week",m="month",a="quarter",n="year",W="date",N="Invalid Date",Y=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,u=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,C={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(k){var A=["th","st","nd","rd"],E=k%100;return"["+k+(A[(E-20)%10]||A[E]||A[0])+"]"}},p=function(k,A,E){var L=String(k);return!L||L.length>=A?k:""+Array(A+1-L.length).join(E)+k},o={s:p,z:function(k){var A=-k.utcOffset(),E=Math.abs(A),L=Math.floor(E/60),y=E%60;return(A<=0?"+":"-")+p(L,2,"0")+":"+p(y,2,"0")},m:function k(A,E){if(A.date()<E.date())return-k(E,A);var L=12*(E.year()-A.year())+(E.month()-A.month()),y=A.clone().add(L,m),v=E-y<0,x=A.clone().add(L+(v?-1:1),m);return+(-(L+(E-y)/(v?y-x:x-y))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:m,y:n,w:Z,d,D:W,h:b,m:t,s:c,ms:G,Q:a}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},R="en",s={};s[R]=C;var Q="$isDayjsObject",r=function(k){return k instanceof O||!(!k||!k[Q])},V=function k(A,E,L){var y;if(!A)return R;if(typeof A=="string"){var v=A.toLowerCase();s[v]&&(y=v),E&&(s[v]=E,y=v);var x=A.split("-");if(!y&&x.length>1)return k(x[0])}else{var D=A.name;s[D]=A,y=D}return!L&&y&&(R=y),y||!L&&R},w=function(k,A){if(r(k))return k.clone();var E=typeof A=="object"?A:{};return E.date=k,E.args=arguments,new O(E)},H=o;H.l=V,H.i=r,H.w=function(k,A){return w(k,{locale:A.$L,utc:A.$u,x:A.$x,$offset:A.$offset})};var O=function(){function k(E){this.$L=V(E.locale,null,!0),this.parse(E),this.$x=this.$x||E.x||{},this[Q]=!0}var A=k.prototype;return A.parse=function(E){this.$d=function(L){var y=L.date,v=L.utc;if(y===null)return new Date(NaN);if(H.u(y))return new Date;if(y instanceof Date)return new Date(y);if(typeof y=="string"&&!/Z$/i.test(y)){var x=y.match(Y);if(x){var D=x[2]-1||0,$=(x[7]||"0").substring(0,3);return v?new Date(Date.UTC(x[1],D,x[3]||1,x[4]||0,x[5]||0,x[6]||0,$)):new Date(x[1],D,x[3]||1,x[4]||0,x[5]||0,x[6]||0,$)}}return new Date(y)}(E),this.init()},A.init=f
`||X.charAt(_)==="\r"&&X.charAt(_+1)!==`
`)&&(II++,lI===0&&(lI=_+1)),_--}var NI=j+II,Il=J-lI;return U[J]={line:NI,lineStart:lI},{offset:J,line:NI+1,column:Il+1}}function k(X){if(!s(X))throw new Error("not a parser: "+X)}function A(X,J){return typeof X=="string"?X.charAt(J):X[J]}function E(X){if(typeof X!="number")throw new Error("not a number: "+X)}function L(X){if(typeof X!="function")throw new Error("not a function: "+X)}function y(X){if(typeof X!="string")throw new Error("not a string: "+X)}var v=2,x=3,D=8,$=5*D,aI=4*D,nI=" ";function VI(X,J){return new Array(J+1).join(X)}function rI(X,J,U){var j=J-X.length;return j<=0?X:VI(U,j)+X}function CI(X,J,U,j){return{from:X-J>0?X-J:0,to:X+U>j?j:X+U}}function WI(X,J){var U,j,II,lI,_,NI=J.index,Il=NI.offset,gl=1;if(Il===X.length)return"Got the end of the input";if(r(X)){var cl=Il-Il%D,Ge=Il-cl,zl=CI(cl,$,aI+D,X.length),Bl=m(function(El){return m(function(Hb){return rI(Hb.toString(16),2,"0")},El)},function(El,Hb){var vb=El.length,Rt=[],yb=0;if(vb<=Hb)return[El.slice()];for(var Jb=0;Jb<vb;Jb++)Rt[yb]||Rt.push([]),Rt[yb].push(El[Jb]),(Jb+1)%Hb==0&&yb++;return Rt}(X.slice(zl.from,zl.to).toJSON().data,D));lI=function(El){return El.from===0&&El.to===1?{from:El.from,to:El.to}:{from:El.from/D,to:Math.floor(El.to/D)}}(zl),j=cl/D,U=3*Ge,Ge>=4&&(U+=1),gl=2,II=m(function(El){return El.length<=4?El.join(" "):El.slice(0,4).join(" ")+" "+El.slice(4).join(" ")},Bl),(_=(8*(lI.to>0?lI.to-1:lI.to)).toString(16).length)<2&&(_=2)}else{var Dl=X.split(/\r\n|[\n\r\u2028\u2029]/);U=NI.column-1,j=NI.line-1,lI=CI(j,v,x,Dl.length),II=Dl.slice(lI.from,lI.to),_=lI.to.toString().length}var ul=j-lI.from;return r(X)&&(_=(8*(lI.to>0?lI.to-1:lI.to)).toString(16).length)<2&&(_=2),Z(function(El,Hb,vb){var Rt,yb=vb===ul,Jb=yb?"> ":nI;return Rt=r(X)?rI((8*(lI.from+vb)).toString(16),_,"0"):rI((lI.from+vb+1).toString(),_," "),[].concat(El,[Jb+Rt+" | "+Hb],yb?[nI+VI(" ",_)+" | "+rI("",U," ")+VI("^",gl)]:[])},[],II).join(`
`)}function LI(X,J){return[`
`,"-- PARSING FAILED "+VI("-",50),`
2026-01-05 19:25:56 +08:00
2026-01-31 08:25:19 +08:00
`,WI(X,J),`
2026-01-05 19:25:56 +08:00
2026-01-31 08:25:19 +08:00
`,(U=J.expected,U.length===1?`Expected:
2026-01-05 19:25:56 +08:00
2026-01-31 08:25:19 +08:00
`+U[0]:`Expected one of the following:
2026-01-05 19:25:56 +08:00
2026-01-31 08:25:19 +08:00
`+U.join(", ")),`
`].join("");var U}function $I(X){return X.flags!==void 0?X.flags:[X.global?"g":"",X.ignoreCase?"i":"",X.multiline?"m":"",X.unicode?"u":"",X.sticky?"y":""].join("")}function sl(){for(var X=[].slice.call(arguments),J=X.length,U=0;U<J;U+=1)k(X[U]);return t(function(j,II){for(var lI,_=new Array(J),NI=0;NI<J;NI+=1){if(!(lI=H(X[NI]._(j,II),lI)).status)return lI;_[NI]=lI.value,II=lI.index}return H(V(II,_),lI)})}function wl(){var X=[].slice.call(arguments);if(X.length===0)throw new Error("seqMap needs at least one argument");var J=X.pop();return L(J),sl.apply(null,X).map(function(U){return J.apply(null,U)})}function Cl(){var X=[].slice.call(arguments),J=X.length;if(J===0)return S("zero alternates");for(var U=0;U<J;U+=1)k(X[U]);return t(function(j,II){for(var lI,_=0;_<X.length;_+=1)if((lI=H(X[_]._(j,II),lI)).status)return lI;return lI})}function Qe(X,J){return zG(X,J).or(WG([]))}function zG(X,J){return k(X),k(J),wl(X,J.then(X).many(),function(U,j){return[U].concat(j)})}function BG(X){y(X);var J="'"+X+"'";return t(function(U,j){var II=j+X.length,lI=U.slice(j,II);return lI===X?V(II,lI):w(j,J)})}function nG(X,J){(function(II){if(!(II instanceof RegExp))throw new Error("not a regexp: "+II);for(var lI=$I(II),_=0;_<lI.length;_++){var NI=lI.charAt(_);if(NI!=="i"&&NI!=="m"&&NI!=="u"&&NI!=="s")throw new Error('unsupported regexp flag "'+NI+'": '+II)}})(X),arguments.length>=2?E(J):J=0;var U=function(II){return RegExp("^(?:"+II.source+")",$I(II))}(X),j=""+X;return t(function(II,lI){var _=U.exec(II.slice(lI));if(_){if(0<=J&&J<=_.length){var NI=_[0],Il=_[J];return V(lI+NI.length,Il)}return w(lI,"valid match group (0 to "+_.length+") in "+j)}return w(lI,j)})}function WG(X){return t(function(J,U){return V(U,X)})}function S(X){return t(function(J,U){return w(U,X)})}function EI(X){if(s(X))return t(function(J,U){var j=X._(J,U);return j.index=U,j.value="",j});if(typeof X=="string")return EI(BG(X));if(X instanceof RegExp)return EI(nG(X));throw new Error("not a string, regexp, or parser: "+X)}function KI(X){return k(X),t(function(J,U){var j=X._(J,U),II=J.slice(U,j.index);return j.status?w(U,'not "'+II+'"'):V(U,null)})}function MI(X){return L(X),t(function(J,U){var j=A(J,U);return U<J.length&&X(j)?V(U+1,j):w(U,"a character/byte matching "+X)})}function Ie(X,J){arguments.length<2&&(J=X,X=void 0);var U=t(function(j,II){return U._=J()._,U._(j,II)});return X?U.desc(X):U}function NG(){return S("fantasy-land/empty")}b.parse=function(X){if(typeof X!="string"&&!r(X))throw new Error(".parse must be called with a string or Buffer as its argument");var J,U=this.skip(le)._(X,0);return J=U.status?{status:!0,value:U.value}:{status:!1,index:f(X,U.furthest),expected:U.expected},delete O[X],J},b.tryParse=function(X){var J=this.parse(X);if(J.status)return J.value;var U=LI(X,J),j=new Error(U);throw j.type="ParsimmonError",j.result=J,j},b.assert=function(X,J){return this.chain(function(U){return X(U)?WG(U):S(J)})},b.or=function(X){return Cl(this,X)},b.trim=function(X){return this.wrap(X,X)},b.wrap=function(X,J){return wl(X,this,J,function(U,j){return j})},b.thru=function(X){return X(this)},b.then=function(X){return k(X),sl(this,X).map(function(J){return J[1]})},b.many=function(){var X=this;return t(function(J,U){for(var j=[],II=void 0;;){if(!(II=H(X._(J,U),II)).status)return H(V(U,j),II);if(U===II.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");U=II.index,j.push(II.value)}})},b.tieWith=function(X){return y(X),this.map(function(J){if(function(II){if(!Q(II))throw new Error("not an array: "+II)}(J),J.length){y(J[0]);for(var U=J[0],j=1;j<J.length;j++)y(J[j]),U+=X+J[j];return U}return""})},b.tie=function(){return this.tieWith("")},b.times=function(X,J){var U=this;return arguments.length<2&&(J=X),E(X),E(J),t(function(j,II){for(var lI=[],_=void 0,NI=void 0,Il=0;Il<X;Il+=1){if(NI=H(_=U._(j,II),NI),!_.status)return NI;II=_.index,lI.push(_.value)}for(;Il<J&&(NI=H(_=U._(j,II),NI),_.status);Il+=1)II=_.index,lI.push(_.value);return H(V(II,lI),NI)})},b.result=function(X){return thi
`),Qt=BG(`\r
`),Le=Cl(Qt,HZ,Xt).desc("newline"),IW=Cl(Le,le);t.all=ic,t.alt=Cl,t.any=Uc,t.cr=Xt,t.createLanguage=function(X){var J={};for(var U in X)({}).hasOwnProperty.call(X,U)&&function(j){J[j]=Ie(function(){return X[j](J)})}(U);return J},t.crlf=Qt,t.custom=function(X){return t(X(V,w))},t.digit=xc,t.digits=ot,t.empty=NG,t.end=IW,t.eof=le,t.fail=S,t.formatError=LI,t.index=DG,t.isParser=s,t.lazy=Ie,t.letter=zc,t.letters=Re,t.lf=HZ,t.lookahead=EI,t.makeFailure=w,t.makeSuccess=V,t.newline=Le,t.noneOf=function(X){return MI(function(J){return X.indexOf(J)<0}).desc("none of '"+X+"'")},t.notFollowedBy=KI,t.of=WG,t.oneOf=function(X){for(var J=X.split(""),U=0;U<J.length;U++)J[U]="'"+J[U]+"'";return MI(function(j){return X.indexOf(j)>=0}).desc(J)},t.optWhitespace=$n,t.Parser=t,t.range=function(X,J){return MI(function(U){return X<=U&&U<=J}).desc(X+"-"+J)},t.regex=nG,t.regexp=nG,t.sepBy=Qe,t.sepBy1=zG,t.seq=sl,t.seqMap=wl,t.seqObj=function(){for(var X,J={},U=0,j=(X=arguments,Array.prototype.slice.call(X)),II=j.length,lI=0;lI<II;lI+=1){var _=j[lI];if(!s(_)){if(Q(_)&&_.length===2&&typeof _[0]=="string"&&s(_[1])){var NI=_[0];if(Object.prototype.hasOwnProperty.call(J,NI))throw new Error("seqObj: duplicate key "+NI);J[NI]=!0,U++;continue}throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(U===0)throw new Error("seqObj expects at least one named parser, found zero");return t(function(Il,gl){for(var cl,Ge={},zl=0;zl<II;zl+=1){var Bl,Dl;if(Q(j[zl])?(Bl=j[zl][0],Dl=j[zl][1]):(Bl=null,Dl=j[zl]),!(cl=H(Dl._(Il,gl),cl)).status)return cl;Bl&&(Ge[Bl]=cl.value),gl=cl.index}return H(V(gl,Ge),cl)})},t.string=BG,t.succeed=WG,t.takeWhile=function(X){return L(X),t(function(J,U){for(var j=U;j<J.length&&X(A(J,j));)j++;return V(j,J.slice(U,j))})},t.test=MI,t.whitespace=re,t["fantasy-land/empty"]=NG,t["fantasy-land/of"]=WG,t.Binary={bitSeq:N,bitSeqObj:function(X){W();var J={},U=0,j=m(function(lI){if(Q(lI)){var _=lI;if(_.length!==2)throw new Error("["+_.join(", ")+"] should be length 2, got length "+_.length);if(y(_[0]),E(_[1]),Object.prototype.hasOwnProperty.call(J,_[0]))throw new Error("duplicate key in bitSeqObj: "+_[0]);return J[_[0]]=!0,U++,_}return E(lI),[null,lI]},X);if(U<1)throw new Error("bitSeqObj expects at least one named pair, got ["+X.join(", ")+"]");var II=m(function(lI){return lI[0]},j);return N(m(function(lI){return lI[1]},j)).map(function(lI){return Z(function(_,NI){return NI[0]!==null&&(_[NI[0]]=NI[1]),_},{},m(function(_,NI){return[_,lI[NI]]},II))})},byte:function(X){if(W(),E(X),X>255)throw new Error("Value specified to byte constructor ("+X+"=0x"+X.toString(16)+") is larger in value than a single byte.");var J=(X>15?"0x":"0x0")+X.toString(16);return t(function(U,j){var II=A(U,j);return II===X?V(j+1,II):w(j,J)})},buffer:function(X){return Y("buffer",X).map(function(J){return Buffer.from(J)})},encodedString:function(X,J){return Y("string",J).map(function(U){return U.toString(X)})},uintBE:C,uint8BE:C(1),uint16BE:C(2),uint32BE:C(4),uintLE:p,uint8LE:p(1),uint16LE:p(2),uint32LE:p(4),intBE:o,int8BE:o(1),int16BE:o(2),int32BE:o(4),intLE:R,int8LE:R(1),int16LE:R(2),int32LE:R(4),floatBE:Y("floatBE",4).map(function(X){return X.readFloatBE(0)}),floatLE:Y("floatLE",4).map(function(X){return X.readFloatLE(0)}),doubleBE:Y("doubleBE",8).map(function(X){return X.readDoubleBE(0)}),doubleLE:Y("doubleLE",8).map(function(X){return X.readDoubleLE(0)})},l.exports=t}])})})(GY,GY.exports);var g=GY.exports,hh=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2
`)[0];let G=l.substring(2).trim();return g.makeSuccess(I+l.length,G)}),namedField:e=>g.alt(e.explicitNamedField,oJ(ke.field).map(([I,l])=>cY.named(XJ(l),I))),sortField:e=>g.seqMap(ke.field.skip(g.optWhitespace),g.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 mQ(()=>({type:I,fields:[],showId:!0}),g.seqMap(g.regexp(/WITHOUT\s+ID/i).skip(g.optWhitespace).atMost(1),g.sepBy(e.namedField,g.string(",").trim(g.optWhitespace)),(l,G)=>({type:I,fields:G,showId:l.length==0})));case"list":return mQ(()=>({type:I,format:void 0,showId:!0}),g.seqMap(g.regexp(/WITHOUT\s+ID/i).skip(g.optWhitespace).atMost(1),ke.field.atMost(1),(l,G)=>({type:I,format:G.length==1?G[0]:void 0,showId:l.length==0})));case"task":return g.succeed({type:I});case"calendar":return g.whitespace.then(g.seqMap(e.namedField,l=>({type:I,showId:!0,field:l})));default:return g.fail(`Unrecognized query type '${I}'`)}}).desc("TABLE or LIST or TASK or CALENDAR"),fromClause:e=>g.seqMap(g.regexp(/FROM/i),g.whitespace,ke.source,(I,l,G)=>G),whereClause:e=>g.seqMap(g.regexp(/WHERE/i),g.whitespace,ke.field,(I,l,G)=>({type:"where",clause:G})).desc("WHERE <expression>"),sortByClause:e=>g.seqMap(g.regexp(/SORT/i),g.whitespace,e.sortField.sepBy1(g.string(",").trim(g.optWhitespace)),(I,l,G)=>({type:"sort",fields:G})).desc("SORT field [ASC/DESC]"),limitClause:e=>g.seqMap(g.regexp(/LIMIT/i),g.whitespace,ke.field,(I,l,G)=>({type:"limit",amount:G})).desc("LIMIT <value>"),flattenClause:e=>g.seqMap(g.regexp(/FLATTEN/i).skip(g.whitespace),e.namedField,(I,l)=>({type:"flatten",field:l})).desc("FLATTEN <value> [AS <name>]"),groupByClause:e=>g.seqMap(g.regexp(/GROUP BY/i).skip(g.whitespace),e.namedField,(I,l)=>({type:"group",field:l})).desc("GROUP BY <value> [AS <name>]"),clause:e=>g.alt(e.fromClause,e.whereClause,e.sortByClause,e.limitClause,e.groupByClause,e.flattenClause),query:e=>g.seqMap(e.headerClause.trim(Mi),e.fromClause.trim(Mi).atMost(1),e.clause.trim(Mi).many(),(I,l,G)=>({header:I,source:l.length==0?cc.folder(""):l[0],operations:G,settings:ih}))}),Mi=g.alt(g.whitespace,mR.comment).many().map(e=>e.join("")),QJ=e=>e?e.plugins.plugins.dataview?.api:window.DataviewAPI,RJ=e=>e.plugins.enabledPlugins.has("dataview");tc.DATE_SHORTHANDS=ah;tc.DURATION_TYPES=mh;tc.EXPRESSION=ke;tc.KEYWORDS=nh;tc.QUERY_LANGUAGE=mR;tc.getAPI=QJ;tc.isPluginEnabled=RJ;tc.parseField=VJ});var BO={};HG(BO,{default:()=>PI});module.exports=gF(BO);var XF=require("obsidian");var oe=require("obsidian");function TI(){}function xs(e){return e()}function GW(){return Object.create(null)}function XI(e){e.forEach(xs)}function yI(e){return typeof e=="function"}function kI(e,I){return e!=e?I==I:e!==I||e&&typeof e=="object"||typeof e=="function"}function k0(e){return Object.keys(e).length===0}function zs(e){return e??""}function rt(e){return e&&yI(e.destroy)?e.destroy:TI}var yZ=typeof window<"u"?window:typeof globalThis<"u"?globalThis:global;var eW=class e{constructor(I){GI(this,"_listeners","WeakMap"in yZ?new WeakMap:void 0);GI(this,"_observer");GI(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)}))}};eW.entries="WeakMap"in yZ?new WeakMap:void 0;var O0=!1;function K0(){O0=!0}function U0(){O0=!1}function i(e,I){e.appendChild(I)}function tl(e,I,l){let G=x0(e);if(!G.getElementById(I)){let c=F("style");c.id=I,c.textContent=l,yF(G,c)}}function x0(e){if(!e)return document;let I=e.getRootNode?e.getRootNode():e.ownerDocument;return I&&I.host?I:e.ownerDocument}function yF(e,I){return i(e.head||e,I),I.sheet}function tI(e,I,l){e.insertBefore(I,l||null)}function eI(e){e.parentNode&&e.parentNode.removeChild(e)}function hc(e,I){for(let l=0;l<e.length;l+=1)
`)}function JZ(e){let I=Object.entries(e);if(I.length===0)return[];let G=["t","tm","yd"].map(b=>{let d=e[b];return d?[b,d]:null}).filter(b=>b!==null),c=new Set(G.map(([b])=>b)),t=I.filter(([b])=>!c.has(b)).sort((b,d)=>{let Z=b[0].length-d[0].length;return Z!==0?Z:b[0].localeCompare(d[0])});return[...G,...t]}function nW(e){return JZ(e).map(([I,l])=>`${I}=${l}`).join(", ")}var WW={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:Ob,ai:{defaultModel:"Ask me",defaultSystemPrompt:'As an AI assistant within Obsidian, your primary goal is to help users manage their ideas and knowledge more effectively. Format your responses using Markdown syntax. Please use the [[Obsidian]] link format. You can write aliases for the links by writing [[Obsidian|the alias after the pipe symbol]]. To use mathematical notation, use LaTeX syntax. LaTeX syntax for larger equations should be on separate lines, surrounded with double dollar signs ($$). You can also inline math expressions by wrapping it in $ symbols. For example, use $$w_{ij}^{ ext{new}}:=w_{ij}^{ ext{current}}+etacdotdelta_jcdot x_{ij}$$ on a separate line, but you can write "($eta$ = learning rate, $delta_j$ = error term, $x_{ij}$ = input)" inline.',promptTemplatesFolderPath:"",showAssistant:!0,providers:mW},migrations:{migrateToMacroIDFromEmbeddedMacro:!0,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1}};function Gl(e){let I=globalThis.structuredClone;if(typeof I=="function")try{return I(e)}catch{}return Mc(e,new Map)}function Mc(e,I){if(e===null||typeof e!="object")return e;if(I.has(e))return I.get(e);if(e instanceof Date){let c=new Date(e.getTime());return I.set(e,c),c}if(Array.isArray(e)){let c=[];I.set(e,c);for(let t of e)c.push(Mc(t,I));return c}if(e instanceof Map){let c=new Map;I.set(e,c);for(let[t,b]of e.entries())c.set(Mc(t,I),Mc(b,I));return c}if(e instanceof Set){let c=new Set;I.set(e,c);for(let t of e.values())c.add(Mc(t,I));return c}if(e instanceof RegExp){let c=new RegExp(e.source,e.flags);return c.lastIndex=e.lastIndex,I.set(e,c),c}if(e instanceof ArrayBuffer){let c=e.slice(0);return I.set(e,c),c}if(ArrayBuffer.isView(e)){if(e instanceof DataView){let d=new DataView(Mc(e.buffer,I),e.byteOffset,e.byteLength);return I.set(e,d),d}let c=e,t=Mc(c.buffer,I),b=new c.constructor(t,c.byteOffset,c.length);return I.set(e,b),b}let l=Object.getPrototypeOf(e),G=Object.create(l);I.set(e,G);for(let[c,t]of Object.entries(e))Object.defineProperty(G,c,{value:Mc(t,I),writable:!0,enumerable:!0,configurable:!0});return G}var P=(()=>{let e=q0((c,t)=>({...Gl(WW)})),{getState:I,setState:l,subscribe:G}=e;return{getState:I,setState:l,subscribe:G}})();var ll=require("obsidian");var gt="{{value}}",Ps="{{date}}",_0="{{time}}",_s="{{name}}",SF="{{value:<variable name>}}",TF="{{value:<variable name>|<default value>}}",qF="{{value:<variable name>|default:<value>}}",PF="{{value:<variable name>|label:<helper text>}}",_F="{{field:<field name>}}",$0="{{mvalue}}",Ip="{{linkcurrent}}",lp="{{filenamecurrent}}",Gp="{{title}}",ep="{{selected}}",cp="{{clipboard}}",$F="{{random:<length>}}",Iw="{{global_var:<name>}}";var tp=[Ps,"{{date:<dateformat>}}","{{vdate:<variable name>, <date format>}}","{{vdate:<variable name>, <date format>|<default value>}}",Iw,gt,_s,SF,TF,qF,PF,_F,$F];var $s=new RegExp(/^-?[0-9]*$/),Kb="top",AZ="bottom",EZ="cursor",NW=new RegExp(/{{DATE(\+-?[0-9]+)?}}/i),Ub=new RegExp(/{{DATE:([^}\n\r+]*)(\+-?[0-9]+)?}}/i),xb=new RegExp(/{{TIME}}/i),zb=new RegExp(/{{TIME:([^}\n\r+]*)}}/i),YW=ne
2026-01-05 19:25:56 +08:00
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
2026-01-31 08:25:19 +08:00
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,au.default)(this.dateWithoutTimezoneAdjustment())}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}static createRelativeFromReference(I,l){let G=vp(I.getDateWithAdjustedTimezone(),l),c=new e(I);return c.addTag("result/relativeDate"),l.hour||l.minute||l.second?(c.addTag("result/relativeDateAndTime"),wp(c,G),Fp(c,G),c.assign("timezoneOffset",I.getTimezoneOffset())):(gp(c,G),c.imply("timezoneOffset",I.getTimezoneOffset()),l.day?(c.assign("day",G.getDate()),c.assign("month",G.getMonth()+1),c.assign("year",G.getFullYear()),c.assign("weekday",G.getDay())):l.week?(c.assign("day",G.getDate()),c.assign("month",G.getMonth()+1),c.assign("year",G.getFullYear()),c.imply("weekday",G.getDay())):(c.imply("day",G.getDate()),l.month?(c.assign("month",G.getMonth()+1),c.assign("year",G.getFullYear())):(c.imply("month",G.getMonth()+1),l.year?c.assign("year",G.getFullYear()):c.imply("year",G.getFullYear())))),c}},xI=class e{constructor(I,l,G,c,t){GI(this,"refDate");GI(this,"index");GI(this,"text");GI(this,"reference");GI(this,"start");GI(this,"end");this.reference=I,this.refDate=I.instant,this.index=l,this.text=G,this.start=c||new q(I),this.end=t}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 QG(e,I,l="\\s{0,5},?\\s{0,5}"){let G=I.replace(/\((?!\?)/g,"(?:");return`${e}${G}(?:${l}${G}){0,10}`}function ew(e){let I;return e instanceof Array?I=[...e]:e instanceof Map?I=Array.from(e.keys()):I=Object.keys(e),I}function bI(e){return`(?:${ew(e).sort((l,G)=>G.length-l.length).join("|").replace(/\./g,"\\.")})`}var Jp=UI(BI(),1);function vG(e){return e<100&&(e>50?e=e+1900:e=e+2e3),e}function fI(e,I,l){let G=(0,Jp.default)(e),c=G;c=c.month(l-1),c=c.date(I),c=c.year(G.year());let t=c.add(1,"y"),b=c.add(-1,"y");return Math.abs(t.diff(G))<Math.abs(c.diff(G))?c=t:Math.abs(b.diff(G))<Math.abs(c.diff(G))&&(c=b),c.year()}var pW={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},Nu={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},ee={...Nu,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},nu={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},Wu={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
`,{line:b,ch:0}),c.setCursor({line:b,ch:e.length});else{let d=c.getLine(b);c.replaceRange(`
`+e,{line:b,ch:d.length}),c.setCursor({line:b+1,ch:e.length})}}catch{K.logError(`unable to insert '${e}' on new line ${I}.`)}}function Yo(e,I){No(e,"above",I)}function so(e,I){No(e,"below",I)}function i4(e,I,l="replaceSelection",G={}){let{requireActiveView:c=!0}=G,t=e.workspace.getActiveViewOfType(ne.MarkdownView);if(!t){let a="Cannot append link because no active Markdown view is available.";if(c)throw new Error(a);K.logMessage(a);return}let b=t.editor,d=b.listSelections().map(a=>({anchor:{...a.anchor},head:{...a.head}}));if(l==="replaceSelection"){b.replaceSelection(I);return}let Z=({line:a,ch:n})=>b.posToOffset({line:a,ch:n}),m=d.sort((a,n)=>Z(n.head)-Z(a.head));for(let a of m){let n=Z(a.anchor)>Z(a.head)?a.anchor:a.head;switch(l){case"afterSelection":{b.replaceRange(I,n);break}case"endOfLine":{let W=b.getLine(n.line),N={line:n.line,ch:W.length};b.replaceRange(I,N);break}case"newLine":{let W=b.getLine(n.line),N={line:n.line,ch:W.length},u=W.length===0?"":`
`;b.replaceRange(u+I,N);break}}}}function h4(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 p4(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 c=h4(e);return c?`![[${c}]]`:e.startsWith("!")?e:`!${e}`}function GN(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(ne.MarkdownView)){if(l.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}let t=G?.path??"",b=e.fileManager.generateMarkdownLink(I,t),Z=l.linkType==="embed"&&Rc(l.placement)?p4(b):b;return i4(e,Z,l.placement,{requireActiveView:!1}),!0}function V4(e,I){return e.commands.findCommand(I)}function uo(e,I){V4(e,I)&&(delete e.commands.commands[I],delete e.commands.editorCommands[I])}function _a(e){return e.vault.getAllLoadedFiles().filter(I=>I instanceof ne.TFolder).map(I=>I.path)}function $a(e){let I=e.split("::").map(l=>l.trim()).filter(Boolean);return{basename:I[0],memberAccess:I.slice(1)}}async function Vd(e,I,l={}){let{location:G="tab",direction:c="vertical",mode:t,focus:b=!0,eState:d}=l,Z=typeof I=="string"?e.vault.getAbstractFileByPath(I):I;if(!Z)throw new Error(`File not found: ${String(I)}`);let m;switch(G){case"reuse":m=e.workspace.getLeaf(!1);break;case"tab":m=e.workspace.getLeaf("tab");break;case"split":m=e.workspace.getLeaf("split",c);break;case"window":m=e.workspace.getLeaf("window");break;case"left-sidebar":m=e.workspace.getLeftLeaf(!0);break;case"right-sidebar":m=e.workspace.getRightLeaf(!0);break;default:m=e.workspace.getLeaf("tab")}if(!m)throw new Error("Could not obtain a workspace leaf.");if(await m.openFile(Z),t&&t!=="default"&&!(typeof t=="object"&&t.mode==="default")){let a=m.getViewState(),n={...a.state??{}};t==="preview"||typeof t=="object"&&t.mode==="preview"?(n.mode="preview",delete n.source):t==="source"?(n.mode="source",n.source=!0):t==="live"||t==="live-preview"?(n.mode="source",n.source=!1):typeof t=="object"&&t.mode==="source"&&(n.mode="source",n.source=t.source),await m.setViewState({...a,state:{...n,...d}})}return b&&e.workspace.setActiveLeaf(m,{focus:!0}),m}function eN(e,I,l=!0){let G;return e.workspace.iterateRootLeaves(c=>{let t=c.view;if(t instanceof ne.FileView&&t.file&&I.path===t.file.path){G=c;return}}),G!==void 0?(l&&e.workspace.setActiveLeaf(G,{focus:!0}),G):null}async function Lc(e,I){let l=I.vault.getAbstractFileByPath(e.path);if(!l){K.logError(`failed to load file ${e.path}.`);return}if(l instanceof ne.TFile){let G=n=>window.require&&window.require(n),c={},t={exports:c},b=await I.vault.read(l);window.eval(`(function(require, module, exports) { ${b}
})`)(G,t,c);let Z=c.default||t.exports;if(!Z)return;let m=Z,{memberAccess:a}=$a(e.name);if(a&&a.length>0){let n;for(;n=a.shift();)m=m[n]}return m}}function Co(e,I){let l=Gl(e);for(let G of I)delete l[G];return l}function cN(e,I){let l=e.vault.getAbstractFileByPath(I);return!!l&&l instanceof ne.TFolder}function Gt(e,I){return e.vault.getMarkdownFiles().filter(l=>l.path.startsWith(I))}function o4(e){let I=e.frontmatter;if(!I)return[];let l=Object.entries(I);if(!l.length)return[];let G=l.filter(([t,b])=>{let d=t.toLowerCase();return d==="tags"||d==="tag"});return G?G.flatMap(([t,b])=>{if(typeof b=="string")return b.split(/,|\s+/).map(d=>d.trim());if(Array.isArray(b))return b}).filter(t=>!!t):[]}function X4(e,I){let l=e.metadataCache.getFileCache(I);if(!l)return[];let G=[];return l.frontmatter&&G.push(...o4(l)),l.tags&&Array.isArray(l.tags)&&G.push(...l.tags.map(c=>c.tag.replace(/^\#/,""))),G}function tN(e,I){let l=I.replace(/^\#/,"");return e.vault.getMarkdownFiles().filter(G=>X4(e,G).includes(l))}function bN(e){let l=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(e);return l?[0,l[0].length]:null}function io(e,I,l,G){if(!(G!==null&&I>=G[0]&&I<=G[1]))return{isInYaml:!1,isQuoted:!1,lineStart:0,lineEnd:0,baseIndent:"",isKeyValuePosition:!1};let t=e.lastIndexOf(`
`,I-1)+1,b=e.indexOf(`
`,I),d=b===-1?e.length:b,Z=e.slice(t,I),m=e.slice(l,d),a=(Z.match(/^\s*/)||[""])[0],n=e[I-1]==='"'&&e[l]==='"'||e[I-1]==="'"&&e[l]==="'",W=Z.replace(/["']$/,""),N=m.replace(/^["']/,""),Y=/:\s*$/.test(W)&&N.trim().length===0;return{isInYaml:!0,isQuoted:n,lineStart:t,lineEnd:d,baseIndent:a,isKeyValuePosition:Y}}var ho={"[":"]","(":")","{":"}","<":">"};function Q4(e,I=","){let l=[],G="",c=[],t=null;for(let d=0;d<e.length;d++){let Z=e[d];if(t){if(G+=Z,Z===t){let m=0;for(let a=d-1;a>=0&&e[a]==="\\";a--)m++;m%2===0&&(t=null)}continue}if(Z==='"'||Z==="'"){t=Z,G+=Z;continue}if(Z in ho){c.push(ho[Z]),G+=Z;continue}if(c.length>0){let m=c[c.length-1];Z===m&&c.pop(),G+=Z;continue}if(Z===I){let m=G.trim();m.length>0&&l.push(m),G="";continue}G+=Z}let b=G.trim();return b.length>0&&l.push(b),l}function R4(e){return e.includes(`
`)?e.replace(/\r?\n/g,`
`):e.includes("\\n")?e.replace(/\\n/g,`
`):e}function r4(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 c=G.getTypeInfo(I),t=c?.expected?.type??c?.inferred?.type;return typeof t=="string"?t:null}function L4(e){if(!e)return!1;let I=e.toLowerCase();return I==="list"||I==="tags"||I==="multitext"}function po(e,I){let l=e.trim();if(!l)return;let G=R4(l),c=I?.propertyType??r4(I?.app,I?.propertyKey),t=L4(c),d=t||c===null,m=G.split(/\n/).map(a=>a.trim()).filter(a=>a.length>0);if(d&&m.length>0&&m.every(a=>/^-\s+/.test(a)))return m.map(a=>a.replace(/^-[\s]*/,"").trim());if(G.startsWith("[")&&G.endsWith("]")||G.startsWith("{")&&G.endsWith("}")){if(c&&!t&&c!=="list")return;try{return JSON.parse(G)}catch{}}if(G.includes(",")&&d){let a=Q4(G);if(a.length>1)return a}}var Vo="\0",et=class{constructor(I){this.app=I;this.map=new Map;this.propertyTypeCache=new Map}maybeCollect(I){let{input:l,matchStart:G,matchEnd:c,rawValue:t,fallbackKey:b,featureEnabled:d}=I;if(!d)return;let Z=bN(l),m=io(l,G,c,Z);if(!m.isInYaml)return;let a=l.slice(m.lineStart,m.lineEnd),n=a.trim(),W=a.match(/^\s*([^:]+):/),N=W?W[1].trim():b,Y=/^-\s*['"]?\{\{VALUE:[^}]+\}\}['"]?\s*$/i,u=null;if(m.isKeyValuePosition?u=[N]:Y.test(n)&&(u=this.findListParentPath(l,m.lineStart,m.baseIndent??"")),!u||u.length===0)return;let C=u[u.length-1],p=t;if(typeof t=="string"){let s=po(t,this.buildParseOptions(C));s!==void 0&&(p=s)}if(!(typeof p!="string"&&(Array.isArray(p)||typeof p=="object"&&p!==null||typeof p=="number"||typeof p=="boolean"||p===null)))return;let R=u.join(Vo);this.map.set(R,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 c=l-1,t=[],b=G.length;for(;c>=0;){let d=I.lastIndexOf(`
`,c),Z=d===-1?0:d+1,m=I.slice(Z,c+1),a=m.trim();if(a.length===0){c=Z-2;continue}if(a==="---"||a==="...")break;if(a.startsWith("-")){c=Z-2;continue}let n=m.match(/^(\s*)([^:\n]+):/);if(n){let N=(n[1]??"").length;if(N<b&&(t.unshift(n[2].trim()),b=N,b===0))break}c=Z-2}return t.length>0?t: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 c=G.getTypeInfo(I),t=c?.expected?.type??c?.inferred?.type??null,b=typeof t=="string"?t:null;return this.propertyTypeCache.set(I,b),b}};et.PATH_SEPARATOR=Vo;var oo="",Xo=new Set(["label","default","custom","type"]);function F4(e,I,l){return l&&I?`${e}${oo}${I}`:e}function In(e){let I=e.indexOf(oo);return I===-1?e:e.slice(0,I)}function w4(e,I){let l=I.toLowerCase(),G=null;for(let c of e.keys())if(c.toLowerCase()===l&&e.get(c)!==void 0){if(G)return null;G=c}return G}function dN(e,I){if(!I)return null;let l=[I],G=In(I);G!==I&&l.push(G);for(let c of l){if(e.has(c)&&e.get(c)!==void 0)return c;let t=w4(e,c);if(t)return t}return null}function g4(e){if(!e)return!0;let I=e.trim().toLowerCase();return!["false","no","0","off"].includes(I)}function H4(e){let I=e.trim();if(!I||!I.includes(":"))return!1;let l=I.split(":",1)[0]?.trim().toLowerCase();return!!l&&Xo.has(l)}function Qo(e,I){if(e.length===0)return{defaultValue:"",allowCustomInput:!1,usesOptions:!1};let l=e.some(H4),G=I&&e.some(m=>m.trim().toLowerCase()==="custom");if(!(l||G))return{defaultValue:e.join("|").trim(),allowCustomInput:!1,usesOptions:!1};let t,b="",d=!1,Z;for(let m of e){let a=m.trim();if(!a)continue;if(I&&a.toLowerCase()==="custom"){d=!0;continue}let n=a.indexOf(":");if(n===-1)continue;let W=a.slice(0,n).trim().toLowerCase(),N=a.slice(n+1).trim();if(Xo.has(W))switch(W){case"label":N&&(t=N);break;case"default":b=N;break;case"custom":d=g4(N);break;case"type":N&&(Z=N);break;default:break}}return{label:t,defaultValue:b,allowCustomInput:d,usesOptions:!0,inputTypeOverride:Z}}function Ro(e,{tokenDisplay:I,hasOptions:l,allowCustomInput:G}){if(!e)return;if(e.trim().toLowerCase()!=="multiline"){console.warn(`QuickAdd: Unsupported VALUE type "${e}" in token "${I}". Supported types: multiline.`);return}if(l||G){console.warn(`QuickAdd: Ignoring type:multiline for option-list VALUE token "${I}".`);return}return"multiline"}function ZN(e){if(!e)return null;let I=e.split("|"),l=(I.shift()??"").trim();if(!l)return null;let G=l.split(",").map(W=>W.trim()).filter(Boolean),c=G.length>1,t=Qo(I,c),{label:b,defaultValue:d,allowCustomInput:Z}=t;if(!t.usesOptions){let W=d;Z=c&&W.toLowerCase()==="custom",d=Z?"":W}let m=`{{VALUE:${e}}}`,a=Ro(t.inputTypeOverride,{tokenDisplay:m,hasOptions:c,allowCustomInput:Z}),n=F4(l,b,c);return{raw:e,variableName:l,variableKey:n,label:b,defaultValue:d,allowCustomInput:Z,suggestedValues:G,hasOptions:c,inputTypeOverride:a}}function ro(e){let l=(e.startsWith("|")?e.slice(1):e).split("|").map(Z=>Z.trim()).filter(Boolean);if(l.length===0)return{defaultValue:""};let G=Qo(l,!1),{label:c,defaultValue:t}=G;G.usesOptions||(t=t.trim());let b=`{{VALUE${e}}}`,d=Ro(G.inputTypeOverride,{tokenDisplay:b,hasOptions:!1,allowCustomInput:G.allowCustomInput});return{label:c,defaultValue:t,inputTypeOverride:d}}function Lo(e){if(!e)return null;let I=e.indexOf("|");if(I===-1){let t=e.trim();return t?{macroName:t}:null}let l=e.slice(0,I).trim();if(!l)return null;let G=e.slice(I+1).trim();if(!G)return{macroName:l};if(!G.toLowerCase().startsWith("label:"))return null;let c=G.slice(6).trim();return{macroName:l,label:c||void 0}}var mN=class mN{constructor(I){this.app=I;this.variables=new Map;this.linkToCurrentFileBehavior="required";this.propertyCollector=new et(I)}hasConcreteVariable(I){return this.variables.has(I)?this.variables.get(I)!==void 0:!1}setTitle(I){this.hasConcreteVariable("title")||this.variables.set("title",I)}replacer(I,l,G){return I.replace(l,function(){return G})}replaceDateInString(I){let
`,G++):t=="\\"?(l+="\\",G++):l+="\\":l+=c}return l}replaceRandomInString(I){let l=I;for(;eu.test(l);){let G=eu.exec(l);if(!G||!G[1])continue;let c=parseInt(G[1]);if(c<=0||c>100)throw new Error(`Random string length must be between 1 and 100. Got: ${c}`);let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",b="";for(let d=0;d<c;d++)b+=t.charAt(Math.floor(Math.random()*t.length));l=l.replace(G[0],b)}return l}replaceTitleInString(I){let l=I,G=this.getVariableValue("title");for(;Iu.test(l);)l=this.replacer(l,Iu,G);return l}};mN.FIELD_VARIABLE_PREFIX="FIELD:";var Pe=mN;var v4={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"},y4={clipboard:"clipboard_content",date:"formatted_date",time:"current_time",random:"random_value",uuid:"unique_id"},J4=[{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 aN(e){let I=e.toLowerCase(),l=v4[I];return l||`${e}_example`}function nN(e){return y4[e.toLowerCase()]||`${e}_output`}function WN(e){for(let{pattern:I,example:l}of J4)if(I.test(e))return l;return`${e}_value`}function NN(e){return e.length>0?`${e[0]} (${e.length} options)`:"suggestion_list"}function YN(e){return e?.path?e.basename:"current_file"}function sN(e){return e?.basename||"current_filename"}var _e=class{static generate(I,l=new Date){let G=l.getFullYear(),c=(l.getMonth()+1).toString().padStart(2,"0"),t=l.getDate().toString().padStart(2,"0"),b=l.getHours().toString().padStart(2,"0"),d=l.getMinutes().toString().padStart(2,"0"),Z=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,c).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,t).replace(/D/g,l.getDate().toString()).replace(/HH/g,b).replace(/H/g,l.getHours().toString()).replace(/mm/g,d).replace(/m/g,l.getMinutes().toString()).replace(/ss/g,Z).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)}};_e.MONTH_NAMES=["January","February","March","April","May","June","July","August","September","October","November","December"],_e.MONTH_NAMES_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],_e.DAY_NAMES=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],_e.DAY_NAMES_SHORT=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];var od=class extends Pe{constructor(l,G,c){super(l);this.plugin=G;this.dateParser=c||ge}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,c=0,t=new RegExp(jc.source,"gi");for(;t.test(G)&&!(++c>5);)G=G.replace(t,(b,d)=>{let Z=String(d??"").trim();if(!Z)return b;let m=this.plugin?.settings?.globalVariables?.[Z];return typeof m=="string"?m:""});return G}promptForValue(l){return l||"user input"}getVariableValue(l){let G=this.variables.get(l)
2026-01-05 19:25:56 +08:00
<div class="qa-suggestion-content">
<span class="suggestion-main-text">${d}</span>
2026-01-31 08:25:19 +08:00
${m}
2026-01-05 19:25:56 +08:00
</div>
2026-01-31 08:25:19 +08:00
<span class="suggestion-sub-text">${Z}</span>
`,this.addHoverTooltip(G,c)}addHoverTooltip(l,G){let c,t=()=>{clearTimeout(c),document.querySelector(".qa-file-tooltip")?.remove()};l.addEventListener("mouseenter",()=>{t(),c=setTimeout(async()=>{let d=this.createTooltip(G);d&&(document.body.appendChild(d),this.positionTooltip(d,l))},200)}),l.addEventListener("mouseleave",t),l.addEventListener("blur",t);let b=()=>t();document.addEventListener("scroll",b,{passive:!0}),l._tooltipCleanup=()=>{t(),document.removeEventListener("scroll",b)}}createTooltip(l){let G=this.app.vault.getAbstractFileByPath(l.path);if(!G||!(G instanceof Hi.TFile))return null;let c=document.createElement("div");return c.className="qa-file-tooltip",c.innerHTML=`
<div class="qa-tooltip-header">${G.basename}</div>
2026-01-05 19:25:56 +08:00
<div class="qa-tooltip-content">
2026-01-31 08:25:19 +08:00
<div>Path: ${G.path}</div>
<div>Modified: ${new Date(G.stat.mtime).toLocaleDateString()}</div>
2026-01-05 19:25:56 +08:00
</div>
2026-01-31 08:25:19 +08:00
`,c}positionTooltip(l,G){let c=G.getBoundingClientRect();l.style.position="fixed",l.style.left=`${c.right+10}px`,l.style.top=`${c.top}px`,l.style.zIndex="1000"}close(){document.querySelectorAll(".qaFileSuggestionItem").forEach(c=>{let t=c;t._tooltipCleanup&&t._tooltipCleanup()}),document.querySelectorAll(".qa-file-tooltip").forEach(c=>c.remove()),super.close()}async selectSuggestion(l){if(this.inputEl.selectionStart===null)return;let G=this.inputEl.selectionStart,c=this.lastInput.length,t=this.inputEl.value,b=0,d=this.inputEl.value.slice(G-this.lastInput.length-3,G-this.lastInput.length)==="![[";if(l.matchType==="unresolved")b=this.makeLinkManually(t,l.displayText.replace(/.md$/,""),G,c);else if(l.matchType==="heading"||l.matchType==="block"){let Z=l.displayText;b=this.makeLinkManually(t,Z,G,c)}else if(d)b=this.makeLinkManually(t,l.displayText,G,c);else{let Z=this.app.vault.getAbstractFileByPath(l.file.path);if(Z instanceof Hi.TFile){let m=l.matchType==="alias"?l.displayText:void 0;b=this.makeLinkObsidianMethod(Z,t,G,c,m)}else b=this.makeLinkManually(t,l.displayText,G,c)}this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(b,b)}makeLinkObsidianMethod(l,G,c,t,b){let d=this.app.vault.getAbstractFileByPath(l.path),Z=this.app.fileManager.generateMarkdownLink(d,this.getSourcePath(),"",b??"");return this.inputEl.value=this.getNewInputValueForFileLink(G,Z,c,t),c-t+Z.length+2}makeLinkManually(l,G,c,t){return this.inputEl.value=this.getNewInputValueForFileName(l,G,c,t),c-t+G.length+2}getNewInputValueForFileLink(l,G,c,t){return`${l.substr(0,c-t-2)}${G}${l.substr(c)}`}getNewInputValueForFileName(l,G,c,t){return`${l.substr(0,c-t)}${G}]]${l.substr(c)}`}};var Hd=class extends IG{constructor(l,G){super(l,G);this.app=l;this.inputEl=G;this.lastInput="";this.lastInputStart=0;this.lastInputLength=0;this.refreshTagIndex(),PI.instance.registerEvent(this.app.metadataCache.on("resolved",()=>this.refreshTagIndex()))}refreshTagIndex(){let l=this.app.metadataCache.getTags(),G=Object.keys(l);this.tagSet=new Set(G),this.sortedTags=G.sort((c,t)=>c.length!==t.length?c.length-t.length:c.localeCompare(t)),this.fuse=new EG(this.sortedTags,{threshold:.4,includeScore:!0,keys:[""]})}getSuggestions(l){if(this.inputEl.selectionStart===null)return[];let G=this.inputEl.selectionStart,c=l.slice(0,G),t=Zp.exec(c);if(!t)return[];let b=c.lastIndexOf("[[");if(t.index===void 0)return[];if(b!==-1&&b<t.index)return[];let d=t[1];this.lastInput=d,this.lastInputStart=t.index,this.lastInputLength=t[0].length;let Z=this.sortedTags.filter(W=>W.toLowerCase().startsWith(d.toLowerCase())).slice(0,5),m=this.fuse.search(d).filter(W=>W.score!==void 0&&W.score<.8).map(W=>W.item).slice(0,10),a=new Set(Z),n=[...Z];for(let W of m)!a.has(W)&&n.length<15&&(n.push(W),a.add(W));return n}renderSuggestion(l,G){this.renderMatch(G,l,this.lastInput)}selectSuggestion(l){let G=this.inputEl;if(G.selectionStart===null)return;let c=this.lastInputStart,t=c+this.lastInputLength,b=l.startsWith("#")?l:`#${l}`;XN(G,c,t,b,{fromCompletion:!0}),this.close()}};var vd=class e{constructor(){this.drafts=new Map;this.MAX_ENTRIES=100}static getInstance(){return e.instance||(e.instance=new e),e.instance}makeKey(I){return JSON.stringify({v:1,kind:I.kind,header:I.header,placeholder:I.placeholder??"",linkSourcePath:I.linkSourcePath??""})}get(I){let l=this.drafts.get(I);if(l)return l.timestamp=Date.now(),l.value}set(I,l){this.drafts.size>=this.MAX_ENTRIES&&!this.drafts.has(I)&&this.evictOldest(1),this.drafts.set(I,{value:l,timestamp:Date.now()})}clear(I){this.drafts.delete(I)}clearAll(){this.drafts.clear()}evictOldest(I){let l=Array.from(this.drafts.entries()).sort(([,G],[,c])=>G.timestamp-c.timestamp).slice(0,I);for(let[G]of l)this.drafts.delete(G)}};var yd=class{constructor(I,l){this.store=vd.getInstance();this.initialValue="";this.didChange=!1;this.draftKey=this.store.makeKey(I),this.shouldPersist=l??(()=>P.getState().persistInputPromptDrafts)}hydrate(I){return this.initialValue=I,this.shouldPersist()?this.store.get(this.draftKey)??I:I}markChanged(){this.didChange=!0}persist(I,l){if(this.s
`).filter(Boolean).reduce((G,c)=>{let[t,b,...d]=c.split(" "),Z=Number.parseInt(b,10);return d.forEach((m,a)=>G[m]=Z+a),G},{});for(let[G,c]of Object.entries(l)){let t=iX.default.toByteArray(G);this.rankMap.set(t.join(","),c),this.textMap.set(c,t)}this.specialTokens={...e.special_tokens,...I},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((G,[c,t])=>(G[t]=this.textEncoder.encode(c),G),{})}encode(e,I=[],l="all"){let G=new RegExp(this.patStr,"ug"),c=Ji.specialTokenRegex(Object.keys(this.specialTokens)),t=[],b=new Set(I==="all"?Object.keys(this.specialTokens):I),d=new Set(l==="all"?Object.keys(this.specialTokens).filter(m=>!b.has(m)):l);if(d.size>0){let m=Ji.specialTokenRegex([...d]),a=e.match(m);if(a!=null)throw new Error(`The text contains a special token that is not allowed: ${a[0]}`)}let Z=0;for(;;){let m=null,a=Z;for(;c.lastIndex=a,m=c.exec(e),!(m==null||b.has(m[0]));)a=m.index+1;let n=m?.index??e.length;for(let N of e.substring(Z,n).matchAll(G)){let Y=this.textEncoder.encode(N[0]),u=this.rankMap.get(Y.join(","));if(u!=null){t.push(u);continue}t.push(...my(Y,this.rankMap))}if(m==null)break;let W=this.specialTokens[m[0]];t.push(W),Z=m.index+m[0].length}return t}decode(e){let I=[],l=0;for(let t=0;t<e.length;++t){let b=e[t],d=this.textMap.get(b)??this.inverseSpecialTokens[b];d!=null&&(I.push(d),l+=d.length)}let G=new Uint8Array(l),c=0;for(let t of I)G.set(t,c),c+=t.length;return this.textDecoder.decode(G)}},EN=Ji;dy(EN,"specialTokenRegex",e=>new RegExp(e.map(I=>ay(I)).join("|"),"g"));function Ai(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":retur
2026-01-05 19:25:56 +08:00
2026-01-31 08:25:19 +08:00
${I}`:""}`;function KN(e){if(e){let I=new RX.Notice(QX("starting",""),1e6);return{setMessage:(l,G)=>{I.setMessage(QX(l,G))},hide:()=>I.hide()}}return{setMessage:(I,l)=>{K.logMessage(`(${I}) ${l}`)},hide:()=>{}}}var rX={cl100k_base:hX,o200k_base:pX},LX=new Map;function Cy(e){let I=e in rX?e:"cl100k_base",l=LX.get(I);if(l)return l;let G=new EN(rX[I]);return LX.set(I,G),G}var TG=(e,I)=>{let l="cl100k_base";try{l=Ai(I.name)}catch{l="cl100k_base"}return(l==="p50k_base"||l==="p50k_edit"||l==="r50k_base"||l==="gpt2")&&(l="cl100k_base"),Cy(l).encode(e).length};async function iy(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.finally(()=>{G=!0});!G;)e(),await sleep(l)}async function hy(e,I,l){let G;if(I.enable)G=l.find(d=>d.path.endsWith(I.name));else{let d=l.map(Z=>Z.basename);G=await CG.Suggest(e,d,l)}SG(G,"Prompt template does not exist");let c=G.path,t=e.vault.getAbstractFileByPath(c);SG(t instanceof FX.TFile,`${c} is not a file`);let b=await e.vault.cachedRead(t);return[G.basename,b]}async function wX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=KN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,promptTemplate:d,systemPrompt:Z,promptTemplateFolder:m}=I,a=Gt(e,m),[n,W]=await hy(e,d,a);G.setMessage("waiting","QuickAdd is formatting the prompt template.");let N=await l(W),Y=["prompting",`Using prompt template "${n}".`];G.setMessage(Y[0],Y[1]);let C=ON(e,c,t,Z,I.modelOptions)(N),o=(await ki(C,100,Q=>{G.setMessage(Y[0],`${Y[1]} (${(Q/1e3).toFixed(2)}s)`)},Q=>{G.setMessage("finished",`Took ${(Q/1e3).toFixed(2)}s.`)})).content,R=("> "+o).replace(/\n/g,`
> `),s={[b]:o,[`${b}-quoted`]:R};return setTimeout(()=>G.hide(),5e3),s}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),il(c)?new SI("Input cancelled by user"):c}}async function ki(e,I,l,G){let c=Date.now();return await iy(()=>l(Date.now()-c),e,I),G(Date.now()-c),await e}async function gX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=KN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,systemPrompt:d,prompt:Z,modelOptions:m}=I;G.setMessage("waiting","QuickAdd is formatting the prompt template.");let a=await l(Z),n=["prompting","Using custom prompt."];G.setMessage(n[0],n[1]);let N=ON(e,c,t,d,m)(a),u=(await ki(N,100,o=>{G.setMessage(n[0],`${n[1]} (${(o/1e3).toFixed(2)}s)`)},o=>{G.setMessage("finished",`Took ${(o/1e3).toFixed(2)}s.`)})).content,C=("> "+u).replace(/\n/g,`
> `),p={[b]:u,[`${b}-quoted`]:C};return setTimeout(()=>G.hide(),5e3),p}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),c}}var Ei=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(c){G(c)}}),this.schedule()})}schedule(){if(this.queue.length===0||this.pendingPromises.length>=this.maxRequests)return;let I=this.queue.shift();if(!I)return;let l=I();this.pendingPromises.push(l),l.finally(()=>{this.pendingPromises=this.pendingPromises.filter(G=>G!==l),this.schedule()}),setTimeout(()=>this.schedule(),this.intervalMs)}};async function HX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=KN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,systemPrompt:d,promptTemplate:Z,text:m,modelOptions:a}=I;G.setMessage("chunking","Creating prompt chunks with text and prompt template");let n=I.chunkSeparator||/\n/g,W=m.split(n),N=TG(d,t),Y=await l(Z,{chunk:" "}),u=TG(Y,t),C=XX(t.name)/2-N,p=I.shouldMerge??!0,o=[],R=C-u;if(p){let A=[],E="",L=0;for(let y of W){let v=TG(y,t)+1;if(v>R)throw new Error(`The chunk "${y.slice(0,25)}..." is too large to fit in a single prompt.`);L+v<R?(E+=y,L+=v):(A.push(E),E=y,L=v)}E!==""&&A.push(E);for(let y of A){let v=await l(Z,{chunk:y});o.push(v)}}else for(let A of W){let E=TG(A,t);if(E>C)throw new Error(`Chunk size (${E}) is larger than the maximum chunk size (${C}). Please check your chunk separator.`);let L=await l(Z,{chunk:A});o.push(L)}let s=ON(e,c,t,d,a),Q=["prompting",`${o.length} prompts being sent.`];G.setMessage(Q[0],Q[1]);let r=new Ei(5,1e3*30),V=Promise.all(o.map(A=>r.add(()=>s(A)))),O=(await ki(V,100,A=>{G.setMessage(Q[0],`${Q[1]} (${(A/1e3).toFixed(2)}s)`)},A=>{G.setMessage("finished",`Took ${(A/1e3).toFixed(2)}s.`)})).map(A=>A.content).join(I.resultJoiner),f=("> "+O).replace(/\n/g,`
> `),k={[b]:O,[`${b}-quoted`]:f};return setTimeout(()=>G.hide(),5e3),k}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),c}}var py="quickadd-ai";function Vy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function oy(e){let I=e.name?.trim()||"provider";return`${py}-${Vy(I)}`}async function yc(e,I){let l=I.apiKeyRef?.trim();if(l&&e?.secretStorage?.getSecret)try{let G=await Promise.resolve(e.secretStorage.getSecret(l));if(G)return G}catch(G){K.logWarning(`Failed to read SecretStorage entry "${l}": ${G.message??G}`)}return I.apiKey??""}async function vX(e,I,l){let G=l?.trim();if(!G||!e?.secretStorage?.getSecret||!e.secretStorage?.setSecret)return null;let c=oy(I),t=c,b=1;for(;;){let d=null;try{d=await Promise.resolve(e.secretStorage.getSecret(t))}catch(Z){K.logWarning(`Failed to read SecretStorage entry "${t}": ${Z.message??Z}`)}if(!d)break;if(d===G)return t;b+=1,t=`${c}-${b}`}try{return await Promise.resolve(e.secretStorage.setSecret(t,G)),t}catch(d){return K.logWarning(`Failed to write SecretStorage entry "${t}": ${d.message??d}`),null}}var Ed=require("obsidian"),an=class e extends Ed.Modal{constructor(l,G,c=[]){super(l);this.items=G;this.selectedItems=c;this._selectedItems=[...c],this.promise=new Promise((t,b)=>{this.resolvePromise=t,this.rejectPromise=b}),this.display(),this.open()}static Open(l,G,c){return new e(l,G,c).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 c=G.createDiv("checkboxRow");c.createEl("span",{text:l}),new Ed.ToggleComponent(c).setTooltip(`Toggle ${l}`).setValue(this._selectedItems.contains(l)).onChange(b=>{if(b)this._selectedItems.push(l);else{let d=this._selectedItems.findIndex(Z=>l===Z);this._selectedItems.splice(d,1)}})}addSubmitButton(){let l=this.contentEl.createDiv("submitButtonContainer");new Ed.ButtonComponent(l).setButtonText("Submit").setCta().onClick(c=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};var UN=require("obsidian"),nn=class e extends UN.Modal{constructor(l,G,c){super(l);this.header=G;this.text=c;this.waitForClose=new Promise(t=>{this.resolvePromise=t}),this.open(),this.display()}static Show(l,G,c){return new e(l,G,c).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(c=>this.contentEl.createEl("p",{text:c}));let l=this.contentEl.createDiv(),G=new UN.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 kd=require("obsidian");var dt=class e extends kd.Modal{constructor(l,G,c,t,b,d){super(l);this.header=G;this.linkSourcePath=b;this.didSubmit=!1;this.submitClickCallback=l=>this.submit();this.cancelClickCallback=l=>this.cancel();this.submitEnterCallback=l=>{(l.ctrlKey||l.metaKey)&&l.key==="Enter"&&(l.preventDefault(),this.submit())};this.placeholder=c??"",this.description=d?.trim()||void 0,this.draftHandler=new yd({kind:"multi",header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath}),this.input=this.draftHandler.hydrate(t??""),this.waitForClose=new Promise((Z,m)=>{this.resolvePromise=Z,this.rejectPromise=m}),this.display(),this.open(),this.fileSuggester=new gd(l,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new Hd(l,this.inputComponent.inputEl)}static Prompt(l,G,c,t,b){return new e(l,G,c,t,void 0,b).waitForClose}static PromptWithContext(l,G,c,t,b,d){return new e(l,G,c,t,b,d).waitForClose}display(){if(this.containerEl.addClass("quickAddModal","qaWideInputPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.he
`,shouldMerge:d?.shouldMerge??!0},(o,R)=>{let s={...Z,...R};return n(o,s,!1)});return p?(d?.shouldAssignVariables&&Object.entries(p).forEach(([o,R])=>{G.variables.set(o,R)}),p):(qI(new Error("AI Assistant returned null"),"Chunked AI Prompt error"),{})},getModels:()=>Gc(),getMaxTokens:c=>{let t=Je(c);if(!t)throw new Error(`Model ${c} not found.`);return t.maxTokens},countTokens(c,t){return TG(c,t)}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async c=>await navigator.clipboard.writeText(c),getSelection:()=>{let c=I.workspace.getActiveViewOfType(Vh.MarkdownView);return c?c.editor.getSelection()??"":""},getSelectedText:()=>{let c=I.workspace.getActiveViewOfType(Vh.MarkdownView);if(!c){qI(new Error("No active view"),"Could not get selected text");return}if(!c.editor.somethingSelected()){qI(new Error("No text selected"),"Could not get selected text");return}return c.editor.getSelection()}},date:{now:(c,t)=>rc({format:c,offset:t}),tomorrow:c=>rc({format:c,offset:1}),yesterday:c=>rc({format:c,offset:-1})},fieldSuggestions:{getFieldValues:async(c,t)=>{let b={folder:t?.folder,tags:t?.tags,inline:t?.includeInline??!1},d=I.vault.getMarkdownFiles();d=NY.filterFiles(d,b,m=>I.metadataCache.getFileCache(m));let Z=new Set;for(let m of d){let n=I.metadataCache.getFileCache(m)?.frontmatter?.[c];if(n!=null){if(Array.isArray(n))n.forEach(W=>{let N=W.toString().trim();N&&Z.add(N)});else if(typeof n!="object"){let W=n.toString().trim();W&&Z.add(W)}}if(b.inline){let W=await I.vault.read(m);qd.getFieldValues(W,c).forEach(Y=>Z.add(Y))}}return Array.from(Z).sort()},clearCache:c=>{bc.getInstance().clear(c)}}}}static async inputPrompt(I,l,G,c){try{return await pl.Prompt(I,l,G,c)}catch(t){Wt(t);return}}static async datePrompt(I,l,G){try{let c=await Nb.Prompt(I,l,G?.placeholder,G?.defaultValue,G?.dateFormat);if(c&&c.startsWith("@date:")){let t=c.slice(6);return(G?.dateFormat?bt(t,G.dateFormat):null)??t}return c}catch(c){Wt(c);return}}static async wideInputPrompt(I,l,G,c){try{return await dt.Prompt(I,l,G,c)}catch(t){Wt(t);return}}static async yesNoPrompt(I,l,G){try{return await ue.Prompt(I,l,G)}catch(c){Wt(c);return}}static async infoDialog(I,l,G){try{return await nn.Show(I,l,G)}catch(c){Wt(c);return}}static async suggester(I,l,G,c,t=!1,b){try{let d;return typeof l=="function"?d=G.map(l):d=l,d=d.map(Z=>LG(Z)),t?await ZG.Suggest(I,d,G,{...c?{placeholder:c}:{},...b?.renderItem?{renderItem:b.renderItem}:{}}):await CG.Suggest(I,d,G,c,b?.renderItem)}catch(d){Wt(d);return}}static async checkboxPrompt(I,l,G){try{return await an.Open(I,l,G)}catch(c){Wt(c);return}}};function Wt(e){if(e instanceof SI)throw e;if(il(e))throw new SI("Input cancelled by user")}var $d=class extends Xd{};var mG=[];for(let e=0;e<256;++e)mG.push((e+256).toString(16).slice(1));function NR(e,I=0){return(mG[e[I+0]]+mG[e[I+1]]+mG[e[I+2]]+mG[e[I+3]]+"-"+mG[e[I+4]]+mG[e[I+5]]+"-"+mG[e[I+6]]+mG[e[I+7]]+"-"+mG[e[I+8]]+mG[e[I+9]]+"-"+mG[e[I+10]]+mG[e[I+11]]+mG[e[I+12]]+mG[e[I+13]]+mG[e[I+14]]+mG[e[I+15]]).toLowerCase()}var oh,vJ=new Uint8Array(16);function Xh(){if(!oh){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");oh=crypto.getRandomValues.bind(crypto)}return oh(vJ)}var yJ=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Qh={randomUUID:yJ};function JJ(e,I,l){if(Qh.randomUUID&&!I&&!e)return Qh.randomUUID();e=e||{};let G=e.random??e.rng?.()??Xh();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 c=0;c<16;++c)I[l+c]=G[c];return I}return NR(G)}var iG=JJ;var lG=class{constructor(I,l){this.name=I,this.type=l,this.id=iG()}};var YR=require("obsidian");var rl=class extends lG{constructor(I){super(I,"EditorCommand"),this.editorCommandType=I}static getSelectedText(I){return this.getActiveMarkdownView(I).editor.getSelection()}static getActiveMarkdownView(I){le
`)}var LR=require("obsidian");function bZ(e,I){if(I.options)for(let l in I.options){let G=e[l]===void 0,c="defaultValue"in I.options[l]&&I.options[l].defaultValue!==void 0;G&&c&&(e[l]=I.options[l].defaultValue)}}var AJ=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],CR=new Set(["true","1","yes","on"]),iR=new Set(["false","0","no","off"]);function Nt(e){return AJ.includes(e)}function hR(e){switch(e){case"lessThan":case"lessThanOrEqual":case"greaterThan":case"greaterThanOrEqual":return"number";case"equals":case"notEquals":return"string";case"contains":case"notContains":return"string";case"isTruthy":case"isFalsy":default:return"boolean"}}function pR(e){if(!Nt(e.operator)||e.expectedValue===void 0||e.expectedValue===null)return;let I=e.expectedValue.trim();switch(e.valueType){case"number":{let l=Number(I);return Number.isNaN(l)?NaN:l}case"boolean":{let l=I.toLowerCase();return CR.has(l)?!0:iR.has(l)?!1:!!I}case"string":default:return I}}function rh(e,I){switch(I){case"number":return typeof e=="number"?e:typeof e=="boolean"?e?1:0:Number(e);case"boolean":if(typeof e=="boolean")return e;if(typeof e=="string"){let l=e.trim().toLowerCase();if(CR.has(l))return!0;if(iR.has(l))return!1}return!!e;case"string":default:return e==null?"":String(e)}}function EJ(e){if(!Nt(e.operator))return"";let I=e.expectedValue??"";return I.length===0?"(empty)":e.valueType==="string"?`"${I}"`:I}function kJ(e){let I=e.variableName?`$${e.variableName}`:"(missing variable)",l=KJ(e.operator),G=Nt(e.operator)?` ${EJ(e)}`:"";return`${I} ${l}${G}`.trim()}function OJ(e){let I=e.exportName?`::${e.exportName}`:"";return`script ${e.scriptPath}${I}`}function dZ(e){return e.mode==="variable"?kJ(e):OJ(e)}function KJ(e){switch(e){case"equals":return"equals";case"notEquals":return"does not equal";case"lessThan":return"is less than";case"lessThanOrEqual":return"is less than or equal to";case"greaterThan":return"is greater than";case"greaterThanOrEqual":return"is greater than or equal to";case"contains":return"contains";case"notContains":return"does not contain";case"isTruthy":return"is truthy";case"isFalsy":return"is falsy";default:return e}}async function oR(e,I){return e.mode==="script"?await I.evaluateScriptCondition(e):UJ(e,I.variables)}function UJ(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(Nt(e.operator)){let c=pR(e);return c===void 0?(K.logWarning(`Conditional command: Operator '${e.operator}' requires a comparison value.`),!1):e.operator==="contains"?VR(G,c,e):e.operator==="notContains"?!VR(G,c,e):xJ(G,c,e)}return!1}function VR(e,I,l){return e==null?!1:typeof I=="string"&&I.length===0?(K.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1):Array.isArray(e)?e.map(G=>rh(G,l.valueType)).some(G=>G===I):typeof e=="string"?e.includes(String(I)):typeof e=="number"&&typeof I=="number"?e===I:String(e).includes(String(I))}function xJ(e,I,l){let G=rh(e,l.valueType);switch(l.operator){case"equals":return G===I;case"notEquals":return G!==I;case"lessThan":return YY(G,I,(c,t)=>c<t);case"lessThanOrEqual":return YY(G,I,(c,t)=>c<=t);case"greaterThan":return YY(G,I,(c,t)=>c>t);case"greaterThanOrEqual":return YY(G,I,(c,t)=>c>=t);default:return!1}}function YY(e,I,l){let G=Number(e),c=Number(I);return Number.isNaN(G)||Number.isNaN(c)?(K.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):l(G,c)}var XR=require("obsidian");function Yt(e,{logPrefix:I,noticePrefix:l=I,defaultReason:G}){if(!(e instanceof SI))return!1;let c=typeof e.message=="string"&&e.message.trim().length>0?e.message:G;return K.logMessage(`${I}: ${c}`),(!(typeof e.message=="string"&&e.message.toLowerCase().includes("cancelled by user"))||P.getState().showInputCancellationNotification)&&new XR.Notice(`${l}: ${c}`
${AI}
\\end{${e}}${AI}`}var FR=[...DJ,...MJ.map(jJ)];var wR=require("obsidian");var fJ=new RegExp(/\\([a-z{}A-Z0-9]*)$/),CY=class extends IG{constructor(l){super(PI.instance.app,l);this.inputEl=l;this.lastInput="";this.symbols=Object.assign([],FR),this.elementsRendered=this.symbols.reduce((G,c)=>{try{G[c.toString()]=(0,wR.renderMath)(c,!0)}catch{}return G},{})}getSuggestions(l){if(this.inputEl.selectionStart===null)return[];let G=this.inputEl.selectionStart,c=l.substr(0,G),t=c.lastIndexOf("\\"),b=c.substr(t),d=fJ.exec(b),Z=[];return d&&(this.lastInput=d[1],Z=this.symbols.filter(n=>n.toLowerCase().contains(this.lastInput))),new EG(Z,{findAllMatches:!0,threshold:.8}).search(this.lastInput).map(n=>n.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,c=this.lastInput.length,t=this.inputEl.value,b=0,d=l.replace(/\\\\/g,"\\");if(this.inputEl.value=`${t.substr(0,G-c-1)}${d}${t.substr(G)}`,b=G-c+l.length-1,this.inputEl.trigger("input"),this.close(),l.contains(AI)){let Z=this.inputEl.value.indexOf(AI);this.inputEl.value=this.inputEl.value.replace(AI,""),this.inputEl.setSelectionRange(Z,Z)}else this.inputEl.setSelectionRange(b,b)}};var iY=class e extends OG.Modal{constructor(){super(PI.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 CY(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 OG.TextAreaComponent(this.contentEl);G.inputEl.style.width="100%",G.inputEl.style.height="10rem",this.inputEl=G.inputEl,G.onChange((0,OG.debounce)(async c=>await this.mathjaxLoop(l,c),50)),G.inputEl.addEventListener("keydown",this.keybindListener),this.createButtonBar(this.contentEl.createDiv())}async onOpen(){super.onOpen(),await(0,OG.loadMathJax)()}async mathjaxLoop(l,G){let c=(0,OG.renderMath)(G,!0);await(0,OG.finishRenderMath)(),l.empty(),l.append(c)}cursorToGoTo(){if(this.inputEl.value.contains(AI)){let l=this.inputEl.value.indexOf(AI);this.inputEl.value=this.inputEl.value.replace(AI,""),this.inputEl.setSelectionRange(l,l)}}createButton(l,G,c){let t=new OG.ButtonComponent(l);return t.setButtonText(G).onClick(c),t}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(AI,"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 Ke=class extends Pe{constructor(l,G,c,t){super(l);this.app=l;this.plugin=G;this.choiceExecutor=c;this.dateParser=t||ge,c&&(this.variables=c?.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=await this.replaceMathValueInString(G)
2026-01-05 19:25:56 +08:00
2026-01-31 08:25:19 +08:00
Suggested values for ${G}: ${m.slice(0,3).join(", ")}`)}return await pl.PromptWithContext(this.app,`Enter value for ${G}`,Z,void 0,this.getLinkSourcePath()??void 0)}let d=`Enter value for ${G}`;return b&&(d=`Enter value for ${G} (default: ${c.defaultValue})`),await ZG.Suggest(this.app,t,t,{placeholder:d})}catch(G){throw il(G)?new SI("Input cancelled by user"):G}}generateCacheKey(l){return mY(l)}async getMacroValue(l,G){let c=new uY(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),t=await c.runAndGetOutput(l,G)??"";return c.getVariables().forEach((b,d)=>{this.variables.set(d,b)}),t}async getTemplateContent(l){return await new st(this.app,this.plugin,l,this.choiceExecutor).run()}async getSelectedText(){let l=this.app.workspace.getActiveViewOfType(gR.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(;KZ.test(G);){let t=KZ.exec(G)?.at(1)?.trim();if(t){let b=new sY(this.app,this.plugin,this.choiceExecutor,this.variables),d=await b.runAndGetOutput(t);for(let Z in b.params.variables)this.variables.set(Z,b.params.variables[Z]);G=typeof d=="string"?this.replacer(G,KZ,d):this.replacer(G,KZ,"")}}return G}async collectValuesManually(l,G){return await aY(this.app,l,G)}};var mZ=require("obsidian");var HR=require("obsidian");function vR(e){return((0,HR.normalizePath)(e).split("/").pop()??"").replace(/\.(md|canvas)$/i,"")}var yR=/[\u0000-\u001F]/u,JR=/[\\/:*?"<>|]/u,AR=/[. ]$/u,SJ=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 ER(e){return SJ.has(e.toUpperCase())}var Zc=class extends Error{constructor(I){super(I),this.name="InvalidFolderPathError"}};function Lh(e){return e instanceof SI||!!e&&typeof e=="object"&&"name"in e&&e.name==="MacroAbortError"}var aZ=class extends Xd{constructor(l,G,c){super(l);this.plugin=G;this.templater=_C(l),this.formatter=new Ke(l,G,c)}async getOrCreateFolder(l,G={}){let c=this.buildFolderSelectionContext(l,G);if(!this.shouldPromptForFolder(c))return await this.handleSingleSelection(c);let t=await this.promptUntilAllowed(c);return t.isEmpty?"":t.resolved}buildFolderSelectionContext(l,G){let c=G.allowCreate??!1,t=G.allowedRoots?.map(n=>this.normalizeFolderPath(n))??[],{items:b,displayItems:d,normalizedItems:Z,canonicalByNormalized:m,displayByNormalized:a}=this.buildFolderSuggestions(l,G.topItems??[],t.length>0?t:void 0);return{items:b,displayItems:d,normalizedItems:Z,canonicalByNormalized:m,displayByNormalized:a,existingSet:new Set(Z),allowCreate:c,allowedRoots:t,placeholder:G.placeholder}}shouldPromptForFolder(l){return l.items.length>1||l.allowCreate&&l.items.length===0}async promptForFolder(l){try{return l.allowCreate?await ZG.Suggest(this.app,l.displayItems,l.items,{placeholder:l.placeholder??"Choose a folder or type to create one",renderItem:(G,c)=>{this.renderFolderSuggestion(G,c,l.existingSet,l.displayByNormalized)}}):await CG.Suggest(this.app,l.displayItems,l.items,l.placeholder)}catch(G){throw il(G)?new SI("Input cancelled by user"):G}}async resolveSelection(l,G){let c=this.normalizeFolderPath(l),t=c.length===0,b=G.canonicalByNormalized.get(c),d=b??c,Z=t?!1:b!==void 0||await this.app.vault.adapter.exists(d),m=G.allowedRoots.length===0?!0:this.isPathAllowed(t?"":d,G.allowedRoots);return{raw:l,normalized:c,resolved:d,exists:Z,isAllowed:m,isEmpty:t}}async promptUntilAllowed(l){for(;;){let G=await this.promptForFolder(l),c=await this.resolveSelection(G,l);if(c.isEmpty){if(!c.isAllowed){this.showFolderNotAllowedNotice(l.allowedRoots);continue}return c}if(!c.isAllowed){this.showFolderNotAllowedNotice(l.allowedRoots);continue}try{this.validateFolderPath(c.resolved)}catch(t){if(t instanceof Zc){new mZ.Notice(t.message);continue}throw t}return await this.ensureFolderExists(c),c}}async ensureFolderExists(l){l.isEmpty||l.ex
${Z}`:`${Z}
${d}`;return await this.app.vault.modify(l,m),l}catch(t){if(Lh(t))throw t;return qI(t,"Could not append to file with template"),null}}async getTemplateContent(l){let G=this.stripLeadingSlash(l);!vt.test(l)&&!kZ.test(l)&&(G+=".md");let c=this.app.vault.getAbstractFileByPath(G);if(!(c instanceof mZ.TFile))throw new Error(`Template file not found at path "${G}".`);return await this.app.vault.cachedRead(c)}};var st=class extends aZ{constructor(l,G,c,t){super(l,G,t);this.templatePath=c}async run(){let l=await this.getTemplateContent(this.templatePath);return l||K.logError(`Template ${this.templatePath} not found.`),l=await this.formatter.formatFileContent(l),l}getAndClearTemplatePropertyVars(){return this.formatter.getAndClearTemplatePropertyVars()}};var FG=class extends Pe{constructor(l,G,c){super(l);this.plugin=G;this.dateParser=c||ge}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,c=0,t=new RegExp(jc.source,"gi");for(;t.test(G)&&!(++c>5);)G=G.replace(t,(b,d)=>{let Z=String(d??"").trim();if(!Z)return b;let m=this.plugin?.settings?.globalVariables?.[Z];return typeof m=="string"?m:""});return G}promptForValue(l){return l||"user input"}getVariableValue(l){let G=this.variables.get(l);if(typeof G=="string")return G;let c=In(l);return aN(c)}getCurrentFileLink(){return this.app?YN(this.app.workspace.getActiveFile()):null}getCurrentFileName(){return this.app?sN(this.app.workspace.getActiveFile()):"current_filename"}suggestForValue(l,G=!1,c){return NN(l)}getMacroValue(l,G){return nN(l)}promptForMathValue(){return Promise.resolve("calculation_result")}promptForVariable(l,G){return Promise.resolve(WN(l))}async getTemplateContent(l){let G=this.app;if(!G)return`Template (app unavailable): ${l}`;try{return await new st(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(Ht.source,"gi"),(c,t,b,d)=>{let Z=t?.trim(),m=b?.trim(),a=d?.trim();if(!Z||!m)return c;let n=new Date,W;try{W=_e.generate(m,n)}catch{W=`[${m} format]`}return a&&(W+=` (default: ${a})`),W}),G}replaceRandomInString(l){let G=l;return G=G.replace(/{{RANDOM:(\d+)}}/gi,(c,t)=>{let b=parseInt(t);if(b<=0||b>100)return c;let d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Z="";for(let m=0;m<Math.min(b,8);m++)Z+=d.charAt(Math.floor(Math.random()*d.length));return b>8&&(Z+=`... (${b} chars)`),Z}),G}isTemplatePropertyTypesEnabled(){return!1}};var hY=require("obsidian");var hG=class extends IG{constructor(l,G,c,t=1/0){super(l,G);this.app=l;this.inputEl=G;this.items=c;this.maxSuggestions=t;this.items=c.map(b=>LG(b))}getSuggestions(l){let G=Hc(l).toLowerCase(),c=this.items.filter(b=>b.toLowerCase().includes(G));return c.length===0&&this.close(),c.slice(0,this.maxSuggestions)}selectSuggestion(l){this.inputEl.value=l,this.inputEl.trigger("input"),this.close()}renderSuggestion(l,G){l&&this.renderMatch(G,l,this.getCurrentQuery())}getCurrentQuery(){return this.inputEl.value}};function Qb(e){let{app:I,parent:l,initialValue:G="",placeholder:c,required:t=!1,requiredMessage:b="This field is required",validator:d,suggestions:Z,maxSuggestions:m=1/0,attachSuggesters:a=[],inputKind:n="text",debounceMs:W=0,trim:N=!0,ariaHintId:Y,fullWidth:u=!0,marginBottomPx:C=8,onChange:p}=e,o=n==="textarea"?new hY.TextA
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function mA(){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 En(e,I){var l=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!l){if(Array.isArray(e)||(l=Kh(e))||I&&e&&typeof e.length=="number"){l&&(e=l);var G=0,c=function(){};return{s:c,n:function(){return G>=e.length?{done:!0}:{done:!1,value:e[G++]}},e:function(Z){throw Z},f:c}}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 t=!0,b=!1,d;return{s:function(){l=l.call(e)},n:function(){var Z=l.next();return t=Z.done,Z},e:function(Z){b=!0,d=Z},f:function(){try{!t&&l.return!=null&&l.return()}finally{if(b)throw d}}}}var aA="finalize",nA="consider";function iZ(e,I,l){e.dispatchEvent(new CustomEvent(aA,{detail:{items:I,info:l}}))}function ht(e,I,l){e.dispatchEvent(new CustomEvent(nA,{detail:{items:I,info:l}}))}var HY="draggedEntered",kn="draggedLeft",vY="draggedOverIndex",Uh="draggedLeftDocument",RY={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function WA(e,I,l){e.dispatchEvent(new CustomEvent(HY,{detail:{indexObj:I,draggedEl:l}}))}function NA(e,I,l){e.dispatchEvent(new CustomEvent(kn,{detail:{draggedEl:I,type:RY.LEFT_FOR_ANOTHER,theOtherDz:l}}))}function YA(e,I){e.dispatchEvent(new CustomEvent(kn,{detail:{draggedEl:I,type:RY.OUTSIDE_OF_ANY}}))}function sA(e,I,l){e.dispatchEvent(new CustomEvent(vY,{detail:{indexObj:I,draggedEl:l}}))}function uA(e){window.dispatchEvent(new CustomEvent(Uh,{detail:{draggedEl:e}}))}var gG={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:HY,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:vY,DRAGGED_LEFT:kn,DRAGGED_LEFT_ALL:"draggedLeftAll",DROPPED_INTO_ZONE:"droppedIntoZone",DROPPED_INTO_ANOTHER:"droppedIntoAnother",DROPPED_OUTSIDE_OF_ANY:"droppedOutsideOfAny",DRAG_STOPPED:"dragStopped"},oG={POINTER:"pointer",KEYBOARD:"keyboard"},yY="isDndShadowItem",JY="data-is-dnd-shadow-item-internal",CA="data-is-dnd-shadow-item-hint",Fb="id:dnd-shadow-placeholder-0000",iA="dnd-action-dragged-el",bG="id",vh=0;function $R(){vh++}function Ir(){if(vh===0)throw new Error("Bug! trying to decrement when there are no dropzones");vh--}var xh=typeof window>"u",HI=function(){};function yh(e){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,l,G=I?oA(e):e.getBoundingClientRect(),c=getComputedStyle(e),t=c.transform;if(t){var b,d,Z,m;if(t.startsWith("matrix3d("))l=t.slice(9,-1).split(/, /),b=+l[0],d=+l[5],Z=+l[12],m=+l[13];else if(t.startsWith("matrix("))l=t.slice(7,-1).split(/, /),b=+l[0],d=+l[3],Z=+l[4],m=+l[5];else return G;var a=c.transformOrigin,n=G.x-Z-(1-b)*parseFloat(a),W=G.y-m-(1-d)*parseFloat(a.slice(a.indexOf(" ")+1)),N=b?G.width/b:e.offsetWidth,Y=d?G.height/d:e.offsetHeight;return{x:n,y:W,width:N,height:Y,top:W,right:n+N,bottom:W+Y,left:n}}else return G}function lr(e){var I=yh(e);return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}function Gr(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 er(e){return{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}}function hA(e,I){return Math.sqrt(Math.pow(e.x-I.x,2)+Math.pow(e.y-I.y,2))}function AY(e,I){return e.y<=I.bottom&&e.y>=I.top&&e.x>=I.left&&e.x<=I.right}function yn(e){return er(Gr(e))}function zR(e,I){var l=yn(e),G=lr(I);return AY(l,G)}function pA(e,I){var l=yn(e),G=yn(I);return hA(l,G)}function VA(e){var I=Gr(e);return I.right<0||I.left>document.documentElement.scrollWidth||I.bottom<0||I.top>document.documentElement.scrollHeight}function oA(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 c=G.getBoundingClientRect(),t=window.getComputedStyle(G).overflowY,b=window.getComputedStyle(G).overflowX,d=t==="scroll"||t==="auto",Z=b==="scroll"||b==="auto";d&&(l.top=Math.max(l.top,c.top),l.bottom=Math.min(l.bottom,c.bottom)),Z&&(l.left=Math.max(l.left,c.left),l.right=Math.min(l.right,c.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 sZ;function zh(){HI(function(){return"resetting indexes cache"}),sZ=new Map}zh();function XA(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 vr(e,I,l){if(e.type==="Multi")try{return await new Is(I,e).waitForClose}catch{return}let G=jE(e,I,l);if(!G)throw new Error("Invalid choice type");return await G.waitForClose}function yr(e){return{...e,command:!e.command}}var Gs=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 Jr(e,I,l){if(!I||!l)return e;let G=I0(e,I),c=I0(e,l);if(!G||!c||c.type!=="Multi"||G.type==="Multi"&&(G.id===c.id||fE(G).has(c.id)))return e;let{updated:t,removed:b}=Ar(e,I);return b?Er(t,l,b)??e:e}function I0(e,I){for(let l of e){if(l.id===I)return l;if(l.type==="Multi"){let G=I0(l.choices,I);if(G)return G}}}function fE(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 Ar(e,I){let l;return{updated:e.map(c=>{if(c.id===I){l=c;return}if(c.type!=="Multi")return c;let t=Ar(c.choices,I);return t.removed&&(l=t.removed),t.removed?{...c,choices:t.updated}:c}).filter(Boolean),removed:l}}function Er(e,I,l){let G=!1,c=e.map(t=>{if(t.id===I&&t.type==="Multi"){G=!0;let d=t;return{...d,choices:[...d.choices,l]}}if(t.type!=="Multi")return t;let b=Er(t.choices,I,l);return b?(G=!0,{...t,choices:b}):t});return G?c:void 0}var sc=require("obsidian");var Ql=require("obsidian");var kr=require("obsidian");var es=null,SE=24*60*60*1e3;async function Or(){if(es&&Date.now()-es.fetchedAt<SE)return es.data;if(P.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let I=await(await(0,kr.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;return es={data:I,fetchedAt:Date.now()},I}function e0(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 Kr(e){return e.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}function c0(e,I){let l=new Set(e.map(c=>c.name)),G=I.filter(c=>!l.has(c.name));return e.concat(G)}var zr=require("obsidian");var TE=128e3;async function cs(e,I){let l=e.modelSource??"providerApi";if(l==="modelsDev")return Ur(e);if(l==="providerApi")return xr(e,I);try{return await xr(e,I)}catch(G){if(!e0(e.endpoint))throw G;return Ur(e,G)}}async function Ur(e,I){try{let l=await Or(),G=e0(e.endpoint);if(!G||!(G in l))throw new Error(`models.dev does not list a provider that matches ${e.endpoint}.`);let c=Object.values(l[G].models);return Kr(c)}catch(l){throw I?new Error(`Provider API failed (${I.message}). Fallback to models.dev also failed: ${l.message}`):l}}async function xr(e,I){let{disableOnlineFeatures:l}=P.getState();if(l)throw new Error("Online features are disabled \u2014 enable them to browse provider models.");if(!e.endpoint)throw new Error("Provider is missing an endpoi
`),d=mI(b),h(I,"class","warning svelte-iqd8ho")},m(Z,m){tI(Z,I,m),i(I,l),i(I,G),i(I,c),i(c,t),i(c,d)},p(Z,m){m[0]&256&&b!==(b=Z[8].missingChoiceIds.join(", ")+"")&&QI(d,b)},d(Z){Z&&eI(I)}}}function LL(e){let I,l,G,c,t=e[4].missingChoices.length>0&&FL(e),b=e[4].missingAssets.length>0&&wL(e);return{c(){I=F("section"),l=F("h4"),l.textContent="Warnings",G=M(),t&&t.c(),c=M(),b&&b.c(),h(I,"class","warning svelte-iqd8ho")},m(d,Z){tI(d,I,Z),i(I,l),i(I,G),t&&t.m(I,null),i(I,c),b&&b.m(I,null)},p(d,Z){d[4].missingChoices.length>0?t?t.p(d,Z):(t=FL(d),t.c(),t.m(I,c)):t&&(t.d(1),t=null),d[4].missingAssets.length>0?b?b.p(d,Z):(b=wL(d),b.c(),b.m(I,null)):b&&(b.d(1),b=null)},d(d){d&&eI(I),t&&t.d(),b&&b.d()}}}function FL(e){let I,l,G=e[4].missingChoices.map(e[23]).join(", ")+"",c;return{c(){I=F("p"),l=mI(`Missing choices:
`),c=mI(G)},m(t,b){tI(t,I,b),i(I,l),i(I,c)},p(t,b){b[0]&144&&G!==(G=t[4].missingChoices.map(t[23]).join(", ")+"")&&QI(c,G)},d(t){t&&eI(I)}}}function wL(e){let I,l,G,c,t=al(e[4].missingAssets),b=[];for(let d=0;d<t.length;d+=1)b[d]=gL(oL(e,t,d));return{c(){I=F("div"),l=F("p"),l.textContent="Missing assets:",G=M(),c=F("ul");for(let d=0;d<b.length;d+=1)b[d].c();h(c,"class","svelte-iqd8ho")},m(d,Z){tI(d,I,Z),i(I,l),i(I,G),i(I,c);for(let m=0;m<b.length;m+=1)b[m]&&b[m].m(c,null)},p(d,Z){if(Z[0]&528){t=al(d[4].missingAssets);let m;for(m=0;m<t.length;m+=1){let a=oL(d,t,m);b[m]?b[m].p(a,Z):(b[m]=gL(a),b[m].c(),b[m].m(c,null))}for(;m<b.length;m+=1)b[m].d(1);b.length=t.length}},d(d){d&&eI(I),hc(b,d)}}}function gL(e){let I,l=e[28].path+"",G,c,t,b,d=e[9][e[28].kind]+"",Z,m;return{c(){I=F("li"),G=mI(l),c=M(),t=F("span"),b=mI("("),Z=mI(d),m=mI(")"),h(t,"class","assetKind svelte-iqd8ho")},m(a,n){tI(a,I,n),i(I,G),i(I,c),i(I,t),i(t,b),i(t,Z),i(t,m)},p(a,n){n[0]&16&&l!==(l=a[28].path+"")&&QI(G,l),n[0]&16&&d!==(d=a[9][a[28].kind]+"")&&QI(Z,d)},d(a){a&&eI(I)}}}function Bk(e){let I;return{c(){I=mI("Copy JSON")},m(l,G){tI(l,I,G)},d(l){l&&eI(I)}}}function Dk(e){let I;return{c(){I=mI("Copying\u2026")},m(l,G){tI(l,I,G)},d(l){l&&eI(I)}}}function Mk(e){let I;return{c(){I=mI("Save to file")},m(l,G){tI(l,I,G)},d(l){l&&eI(I)}}}function jk(e){let I;return{c(){I=mI("Saving\u2026")},m(l,G){tI(l,I,G)},d(l){l&&eI(I)}}}function fk(e){let I,l,G,c,t,b,d,Z,m,a,n,W,N,Y,u,C,p,o,R,s,Q=e[8].rootCount+"",r,V,w,H,O,f,k=e[8].totalChoices+"",A,E,L,y,v,x,D=e[8].dependencyCount+"",$,aI,nI,VI,rI,CI,WI=e[8].userScripts+e[8].conditionalScripts+"",LI,$I,sl,wl,Cl,Qe,zG=e[8].templateFiles+e[8].captureTemplates+"",BG,nG,WG,S,EI,KI,MI,Ie,NG,DG,Uc,ic,le,xc,ot,zc,Re,$n,re,Xt,HZ,Qt,Le,IW,X,J,U;function j(Dl,ul){return Dl[6].length===0?zk:xk}let II=j(e,[-1,-1]),lI=II(e),_=e[8].missingChoiceIds.length>0&&rL(e),NI=e[4]&&LL(e);function Il(Dl,ul){return Dl[5]==="copy"?Dk:Bk}let gl=Il(e,[-1,-1]),cl=gl(e);function Ge(Dl,ul){return Dl[5]==="save"?jk:Mk}let zl=Ge(e,[-1,-1]),Bl=zl(e);return{c(){I=F("div"),l=F("header"),l.innerHTML='<h2>Export QuickAdd Package</h2> <p class="svelte-iqd8ho">Select choices to bundle. Dependencies are added automatically.</p>',G=M(),c=F("section"),t=F("input"),d=M(),Z=F("div"),m=F("button"),m.textContent="Select visible",a=M(),n=F("button"),n.textContent="Clear selection",W=M(),N=F("section"),lI.c(),Y=M(),u=F("section"),C=F("h3"),C.textContent="Package summary",p=M(),o=F("div"),R=F("div"),s=F("strong"),r=mI(Q),V=M(),w=F("span"),w.textContent="Selected choices",H=M(),O=F("div"),f=F("strong"),A=mI(k),E=M(),L=F("span"),L.textContent="Total packaged",y=M(),v=F("div"),x=F("strong"),$=mI(D),aI=M(),nI=F("span"),nI.textContent="Auto-included",VI=M(),rI=F("div"),CI=F("strong"),LI=mI(WI),$I=M(),sl=F("span"),sl.textContent="Scripts embedded",wl=M(),Cl=F("div"),Qe=F("strong"),BG=mI(zG),nG=M(),WG=F("span"),WG.textContent="Templates embedded",S=M(),_&&_.c(),EI=M(),NI&&NI.c(),KI=M(),MI=F("section"),Ie=F("div"),NG=F("button"),cl.c(),Uc=M(),ic=F("div"),le=F("label"),xc=F("span"),xc.textContent="Save to file",ot=M(),zc=F("div"),Re=F("input"),$n=M(),re=F("button"),Bl.c(),HZ=M(),Qt=F("section"),Le=F("button"),IW=mI("Cancel"),h(l,"class","svelte-iqd8ho"),h(t,"type","text"),h(t,"placeholder","Filter choices"),h(t,"autocapitalize","off"),h(t,"autocorrect","off"),h(t,"spellcheck",b=!1),h(t,"class","svelte-iqd8ho"),h(m,"type","button"),h(m,"class","svelte-iqd8ho"),h(n,"type","button"),h(n,"class","svelte-iqd8ho"),h(Z,"class","controlButtons svelte-iqd8ho"),h(c,"class","controls svelte-iqd8ho"),h(N,"class","choiceList svelte-iqd8ho"),h(C,"class","svelte-iqd8ho"),h(s,"class","svelte-iqd8ho"),h(R,"class","svelte-iqd8ho"),h(f,"class","svelte-iqd8ho"),h(O,"class","svelte-iqd8ho"),h(x,"class","svelte-iqd8ho"),h(v,"class","svelte-iqd8ho"),h(CI,"class","svelte-iqd8ho"),h(rI,"class","svelte-iqd8ho"),h(Qe,"class","svelte-iqd8ho"),h(Cl,"class","svelte-iqd8ho"),h(o,"class","summaryGrid svelte-iqd8ho"),h(u,"class","summary svelte-iqd8ho"),h(NG,"type","button"),h(NG,"class","secondary svelte-iq
tm = tomorrow
yd = yesterday`).setValue(qs(P.getState().dateAliases)).onChange(b=>{P.setState({dateAliases:P0(b)})}),t.inputEl.style.width="100%",t.inputEl.style.minHeight="6rem",t.inputEl.style.flex="1 1 280px",t.inputEl.style.maxWidth="100%",t.inputEl.style.boxSizing="border-box"}),G.addButton(t=>{t.setButtonText("Reset to defaults").onClick(()=>{P.setState({dateAliases:Ob}),c&&c.setValue(qs(Ob))}),t.buttonEl.style.alignSelf="flex-start",t.buttonEl.style.whiteSpace="nowrap"})})}addDisableOnlineFeaturesSetting(l){l.addSetting(G=>{G.setName("Disable AI & Online features").setDesc("This prevents the plugin from making requests to external providers like OpenAI. You can still use User Scripts to execute arbitrary code, including contacting external providers. However, this setting disables plugin features like the AI Assistant from doing so. You need to disable this setting to use the AI Assistant.").addToggle(c=>c.setValue(P.getState().disableOnlineFeatures).onChange(t=>{P.setState({disableOnlineFeatures:t}),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(c=>{c.setValue(P.getState().enableRibbonIcon).onChange(t=>{P.setState({enableRibbonIcon:t}),this.display()})})})}};var LZ=class{formatOutputString(I){return`QuickAdd: (${I.level}) ${I.message}`}getQuickAddError(I,l,G,c){return{message:I,level:l,time:Date.now(),stack:G,originalError:c}}};var fn=class extends LZ{constructor(){super(...arguments);this.ErrorLog=[]}logError(l,G,c){let t=this.getQuickAddError(l,"ERROR",G,c);this.addMessageToErrorLog(t);let b=c||new Error(l);console.error(this.formatOutputString(t),b)}logWarning(l,G,c){let t=this.getQuickAddError(l,"WARNING",G,c);this.addMessageToErrorLog(t);let b=c||new Error(l);console.warn(this.formatOutputString(t),b)}logMessage(l,G,c){let t=this.getQuickAddError(l,"LOG",G,c);this.addMessageToErrorLog(t),c?console.log(this.formatOutputString(t),c):console.log(this.formatOutputString(t))}addMessageToErrorLog(l){this.ErrorLog.push(l),this.ErrorLog.length>SC&&(this.ErrorLog=this.ErrorLog.slice(-SC))}clearErrorLog(){this.ErrorLog=[]}};var V0=require("obsidian");var Vs=class extends LZ{constructor(l){super();this.plugin=l}logError(l,G,c){let t=this.getQuickAddError(l,"ERROR",G,c);new V0.Notice(this.formatOutputString(t),15e3)}logWarning(l,G,c){let t=this.getQuickAddError(l,"WARNING",G,c);new V0.Notice(this.formatOutputString(t))}logMessage(l,G,c){}};var os=class{constructor(I,l,G,c){this.app=I;this.plugin=l;this.choices=G;this.choiceExecutor=c}async run(){let I=Ue(this.choices).filter(l=>l.type==="Macro"&&l.runOnStartup);for(let l of I)await new dc(this.app,this.plugin,l,this.choiceExecutor,new Map).run()}};var o0=require("obsidian");var Xs=class extends aZ{constructor(I,l,G,c){super(I,l,c),this.choiceExecutor=c,this.choice=G}async run(){try{SG(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 I=lt(this.choice.appendLink);this.setLinkToCurrentFileBehavior(I.enabled&&!I.requireActiveFile?"optional":"required");let l="";if(this.choice.folder.enabled)l=await this.getFolderPath();else{let Z=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");l=Z===this.app.vault.getRoot()?"":Z.path}let G=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:gt,c=await this.formatter.formatFileName(G,this.choice.name),t=this.normalizeTemplateFilePath(l,c,this.choice.templatePath);this.choice.fileExistsMode===yt&&(t=await this.incrementFileName(t));let b,d=!1;if(await this.app.vault.adapter.exists(t)){let Z=this.findExistingFile(t);if(!(Z instanceof o0.TFile)||Z.extension!=="md"&&Z.extension!=="canvas"){K.logError(`'${t}' already exists but could not be resolved as a markdown or canvas file.`);return}let m=this.choice.fileExistsMode;if(!this.choice.setFileExistsBehavior)try{m=await CG.Suggest(this.app,[...cu],[...cu])}catch(a){throw
2026-01-05 19:25:56 +08:00
`)}}).join(`
2026-01-31 08:25:19 +08:00
`)}}var lF=e=>e.join(""),sO=e=>e.split(/\b/),uO=IF("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",lF),CO={splitFunction:sO,joinFunction:lF,conflictFunction:uO};function F0(e,I,l,G={}){G=Object.assign({},CO,G);let[c,t,b]=[e,I,l].map(m=>G.splitFunction.call(G,m)),d=qn.merge(c,t,b);return Pn.collateMerge(d,G.joinFunction,G.conflictFunction)}var GF=F0;var w0=require("obsidian");function eF(e,I){return e.line===I.line}function iO(e){let I=[];return e.forEach((l,G)=>{let c=l.match(/^(#+)[\s]+(.*)$/);c&&I.push({level:c[1].length,text:c[2],line:G})}),I}function Fs(e,I,l=!1){let G=iO(e),c=G.find(m=>m.line===I),t=!!c;if(!t&&l)throw new Error(`Target line ${I} is not a heading, but we are trying to find the end of its section.`);if(!t&&!l){let m=cF(e,I,a=>a.trim()==="");return m!==null&&m>I?m-1:I}let b=e.length-1,d=hO(c,G,e,l),Z=oO(e,d,m=>m.trim()!=="");if(Z!==null){if(Z<I)return I;let m=e[Z+1].trim()==="";return Z+1===b&&!m?d:Z===0?Z+1:Z}return d}function hO(e,I,l,G){let c=I.findIndex(a=>eF(a,e)),t=c===I.length-1,b=l.length-1;if(t)return b;let[d,Z]=pO(e,I);if(Z&&d===I.length)return b;if(Z&&G)return I[d].line-1;if(Z&&!G)return I[c+1].line;if(!G&&!Z){let a=VO(e.line,I);return a===null?b:a}return b}function pO(e,I){let l=I.findIndex(c=>eF(c,e)),G=cF(I,l,c=>c.level<=e.level);return G===null?[-1,!1]:[G,!0]}function VO(e,I){let l=I.findIndex(G=>G.line>e);return l===-1?null:l}function oO(e,I,l){for(let G=I-1;G>=0;G--)if(l(e[G]))return G;return null}function cF(e,I,l){for(let G=I+1;G<e.length;G++)if(l(e[G]))return G;return null}var ws=class extends Ke{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,c,t){if(this.choice=G,this.file=t,this.fileContent=c,!G||!t||c===null)return l;let b=G.insertAfter.enabled||G.prepend||!G.captureToActiveFile||G.activeFileWritePosition==="top";return await this.formatFileContent(l,b)}async formatContent(l,G){return this.choice=G,G?await this.formatFileContent(l):l}async formatFileContent(l,G=!0){let c=await super.formatFileContent(l);if(c=this.replaceLinebreakInString(c),G&&this.file&&!this.templaterProcessed){let d=await pd(this.app,c,this.file);d&&(c=d),this.templaterProcessed=!0}if(c.trim()==="")return this.fileContent;if(this.choice.prepend){let d=!this.choice.task;return`${this.fileContent}${d?`
`:""}${c}`}if(this.choice.insertAfter.enabled)return await this.insertAfterHandler(c);let b=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):null;return b==null||b<0?`${c}${this.fileContent}`:this.insertTextAfterPositionInBody(c,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 c=this.normalizeTarget(G),t=-1;for(let b=0;b<l.length;b++){let d=l[b].trimStart();if(d===c)return b;if(d.startsWith(c)){let m=d.slice(c.length);if(/^\s*$/.test(m))return b;t===-1&&(t=b);continue}let Z=d.indexOf(c);if(Z!==-1){let m=d.slice(Z+c.length);if(/^\s*$/.test(m))return b;t===-1&&(t=b)}}return t}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,c,t){if(G<0)return G;let b=l[G]??"";if(!this.shouldSkipBlankLinesAfterMatch(t,b))return G;let Z=c.endsWith(`
`)?Math.max(l.length-1,0):l.length,m=G;for(let a=G+1;a<Z;a++){if(l[a].trim().length===0){m=a;continue}break}return m}async insertAfterHandler(l){let G=await this.formatLocationString(this.choice.insertAfter.after);if(this.choice.insertAfter?.inline)return await this.insertAfterInlineHandler(l,G);let c=Rh(this.fileContent),t=this.findInsertAfterIndex(c,G);if(t===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(l);qI(new Error("Unable to find insert after line in file"),"Insert After Error")}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");t=Fs(c,t,!!this.choice.insertAfter.considerSubsections)??c.length-1}else{let d=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";t=this.findInsertAfterPositionWithBlankLines(c,t,this.fileContent,d)}return this.insertTextAfterPositionInBody(l,this.fileContent,t)}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 qI(new Error("Inline insert after target must be a single line."),"Insert After Inline Error"),this.fileContent;let c=this.fileContent.indexOf(G);if(c===-1)return this.choice.insertAfter?.createIfNotFound?await this.createInlineInsertAfterIfNotFound(l,G):(qI(new Error("Unable to find insert after text in file."),"Insert After Inline Error"),this.fileContent);let t=c+G.length;if(this.choice.insertAfter?.replaceExisting){let b=this.getInlineEndOfLine(t);return this.fileContent.slice(0,t)+l+this.fileContent.slice(b)}return this.fileContent.slice(0,t)+l+this.fileContent.slice(t)}async createInsertAfterIfNotFound(l){let c=`${this.replaceLinebreakInString(await this.formatLocationString(this.choice.insertAfter.after))}
${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Kb){let t=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(c,this.fileContent,t)}if(this.choice.insertAfter?.createIfNotFoundLocation===AZ)return`${this.fileContent}
${c}`;if(this.choice.insertAfter?.createIfNotFoundLocation===EZ)try{let t=this.app.workspace.getActiveViewOfType(w0.MarkdownView);if(!t)throw new Error("No active view.");let d=t.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let m=Rh(this.fileContent);d=Fs(m,d,!!this.choice.insertAfter.considerSubsections)??m.length-1}return this.insertTextAfterPositionInBody(c,this.fileContent,d)}catch(t){qI(t,`Unable to insert line '${this.choice.insertAfter.after}' at cursor position`)}}async createInlineInsertAfterIfNotFound(l,G){let c=`${G}${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Kb){let t=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(c,this.fileContent,t)}if(this.choice.insertAfter?.createIfNotFoundLocation===AZ)return`${this.fileContent}
${c}`;if(this.choice.insertAfter?.createIfNotFoundLocation===EZ)try{let t=this.app.workspace.getActiveViewOfType(w0.MarkdownView);if(!t)throw new Error("No active view.");let d=t.editor.getCursor().line;return this.insertTextAfterPositionInBody(c,this.fileContent,d)}catch(t){qI(t,`Unable to insert line '${this.choice.insertAfter.after}' at cursor position`)}return K.logWarning(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`),this.fileContent}getFrontmatterEndPosition(l,G){let c=this.app.metadataCache.getFileCache(l);if(c?.frontmatterPosition)return c.frontmatterPosition.end.line;if(G){let t=this.inferFrontmatterEndLineFromContent(G);if(t!==null)return t}return K.logMessage("could not get frontmatter. Maybe there isn't any."),-1}inferFrontmatterEndLineFromContent(l){let G=bN(l);if(!G)return null;let c=l.slice(0,G[1]),t=c.split(/\r?\n/);return t.length===0?null:c.endsWith(`
`)?t.length-2:t.length-1}insertTextAfterPositionInBody(l,G,c){if(c===-1){let Z=!this.choice.task;return`${l}${Z?`
`:""}${G}`}let t=G.split(`
`),b=t.slice(0,c+1).join(`
`),d=t.slice(c+1).join(`
`);return`${b}
${l}${d}`}};function tF(e){return e.captureToActiveFile&&e.newLineCapture?.enabled?e.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":e.captureToActiveFile&&!e.prepend&&!e.insertAfter.enabled?e.activeFileWritePosition==="top"?"activeFileTop":"currentLine":e.insertAfter.enabled?"insertAfter":e.prepend?"prepend":"append"}var bF=4e3,gs=class extends $d{constructor(l,G,c,t){super(l);this.choiceExecutor=t;this.capturePropertyVars=new Map;this.choice=c,this.plugin=G,this.formatter=new ws(l,G,t)}showSuccessNotice(l,{wasNewFile:G,action:c}){let t=`'${l.basename}'`;if(G){new g0.Notice(`Created and captured to ${t}`,bF);return}let b="";switch(c){case"currentLine":b=`Captured to current line in ${t}`;break;case"prepend":case"activeFileTop":b=`Captured to top of ${t}`;break;case"append":b=`Captured to ${t}`;break;case"insertAfter":{let d=this.choice.insertAfter.after;b=d?`Captured to ${t} under '${d}'`:`Captured to ${t}`;break}}new g0.Notice(b,bF)}async run(){try{this.capturePropertyVars.clear();let l=lt(this.choice.appendLink);this.formatter.setLinkToCurrentFileBehavior(l.enabled&&!l.requireActiveFile?"optional":"required");let G=this.choice.useSelectionAsCaptureValue,c=this.plugin.settings.useSelectionAsCaptureValue??!0,t=typeof G=="boolean"?G:c;this.formatter.setUseSelectionAsCaptureValue(t);let b=await this.getFormattedPathToCaptureTo(this.choice.captureToActiveFile),d=this.getCaptureContent(),Z,m=await this.fileExists(b);if(m)Z=this.onFileExists.bind(this);else if(this.choice?.createFileIfItDoesntExist?.enabled)Z=(u,C,p)=>this.onCreateFileIfItDoesntExist(u,C,l);else{K.logWarning(`The file ${b} does not exist and "Create file if it doesn't exist" is disabled.`);return}let{file:a,newFileContent:n,captureContent:W}=await Z(b,d),N=tF(this.choice);if(N==="currentLine"||N==="newLineAbove"||N==="newLineBelow"){let u=await pd(this.app,W,a);switch(N){case"currentLine":Wo(u,this.app);break;case"newLineAbove":Yo(u,this.app);break;case"newLineBelow":so(u,this.app);break}}else await this.app.vault.modify(a,n),this.choice.templater?.afterCapture==="wholeFile"&&await hd(this.app,a),await this.applyCapturePropertyVars(a);if(this.plugin.settings.showCaptureNotification&&this.showSuccessNotice(a,{wasNewFile:!m,action:N}),l.enabled&&GN(this.app,a,l),this.choice.openFile&&a){let u=KG(this.choice.fileOpening),C=u.focus??!0;eN(this.app,a,C)||await Vd(this.app,a,u),await lN(this.app,a)}}catch(l){if(Yt(l,{logPrefix:"Capture execution aborted",noticePrefix:"Capture execution aborted",defaultReason:"Capture aborted"})){this.choiceExecutor.signalAbort?.(l);return}qI(l,`Error running capture choice "${this.choice.name}"`)}}getCaptureContent(){let l;return this.choice.format.enabled?l=this.choice.format.format:l=gt,this.choice.task&&(l=`- [ ] ${l}
`),l}async getFormattedPathToCaptureTo(l){let G=this.choiceExecutor?.variables?.get(UZ);if(!l&&G&&typeof G=="string"&&G.length>0)return G;if(l){let a=this.app.workspace.getActiveFile();return SG(a,"Cannot capture to active file - no active file."),a.path}let c=this.choice.captureTo,t=await this.formatFilePath(c),b=t.replace(/^\/$|\/\.md$|^\.md$/,""),d=b==="",Z=d||cN(this.app,b),m=t.startsWith("#");if(Z)return this.selectFileInFolder(b,d);if(m){let a=t.replace(/\.md$/,"");return this.selectFileWithTag(a)}return t}async selectFileInFolder(l,G){let c=l.endsWith("/")||G?l:`${l}/`,t=Gt(this.app,c);SG(t.length>0,`Folder ${c} is empty.`);let b=t.map(m=>m.path),d;try{d=await ZG.Suggest(this.app,b.map(m=>m.replace(c,"")),b)}catch(m){throw il(m)?new SI("Input cancelled by user"):m}SG(!!d&&d.length>0,"No file selected for capture.");let Z=d.startsWith(`${c}`)?d:`${c}/${d}`;return await this.formatFilePath(Z)}async selectFileWithTag(l){let G=l.startsWith("#")?l:`#${l}`,c=tN(this.app,G);SG(c.length>0,`No files with tag ${l}.`);let t=c.map(d=>d.path),b;try{b=await ZG.Suggest(this.app,t,t)}catch(d){throw il(d)?new SI("Input cancelled by user"):d}return SG(!!b&&b.length>0,"No file selected for capture."),await this.formatFilePath(b)}async onFileExists(l,G){let c=this.getFileByPath(l);if(!c)throw new Error("File not found");this.formatter.setTitle(c.basename),this.formatter.setDestinationFile(c);let t=await this.formatter.formatContentOnly(G);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let b=await this.app.vault.read(c),d=await this.formatter.formatContentWithFile(t,this.choice,b,c);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let Z=await this.app.vault.read(c),m=d;if(Z!==b){let a=GF(Z,b,d);SG(!a.isSuccess,()=>`The file ${l} has been modified since the last read.
2026-01-05 19:25:56 +08:00
QuickAdd could not merge the versions two without conflicts, and will not modify the file.
2026-01-31 08:25:19 +08:00
This is in order to prevent data loss.`),m=a.joinedResults()}return{file:c,newFileContent:m,captureContent:t}}async onCreateFileIfItDoesntExist(l,G,c){let t=l.split("/").pop()?.replace(/\.md$/,"")||"";this.formatter.setTitle(t),this.formatter.setDestinationSourcePath(l);let b=await this.formatter.formatContentOnly(G);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let d="";if(this.choice.createFileIfItDoesntExist.createWithTemplate){let n=new st(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);c?.enabled&&!c.requireActiveFile&&n.setLinkToCurrentFileBehavior("optional"),d=await n.run();let W=n.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 Z=await this.createFileWithInput(l,d,{suppressTemplaterOnCreate:this.choice.createFileIfItDoesntExist.createWithTemplate});this.choice.createFileIfItDoesntExist.createWithTemplate&&this.templatePropertyVars&&this.shouldPostProcessFrontMatter(Z,this.templatePropertyVars)&&await this.postProcessFrontMatter(Z,this.templatePropertyVars),this.choice.createFileIfItDoesntExist.createWithTemplate&&d?await hd(this.app,Z):IN(this.app)&&await ao(this.app,Z);let m=await this.app.vault.read(Z),a=await this.formatter.formatContentWithFile(b,this.choice,m,Z);return this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),{file:Z,newFileContent:a,captureContent:b}}async formatFilePath(l){let G=await this.formatter.formatFileName(l,this.choice.name);return this.normalizeMarkdownFilePath("",G)}mergeCapturePropertyVars(l){if(!(!l||l.size===0)){for(let[G,c]of l)this.capturePropertyVars.set(G,c);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 Hs=require("obsidian");var H0="\u2190 Back",Vt=class e extends Hs.FuzzySuggestModal{constructor(l,G,c){super(l.app);this.plugin=l;this.choices=G;this.choiceExecutor=new Kc(this.app,this.plugin);this.placeholderStack=[];c?.choiceExecutor&&(this.choiceExecutor=c.choiceExecutor),this.placeholderStack=c?.placeholderStack??[],this.currentPlaceholder=c?.placeholder?.trim()||void 0,this.currentPlaceholder&&this.setPlaceholder(this.currentPlaceholder)}static Open(l,G,c){new e(l,G,c).open()}renderSuggestion(l,G){G.empty(),Hs.MarkdownRenderer.renderMarkdown(l.item.name,G,"",this.plugin),G.classList.add("quickadd-choice-suggestion"),l.item.name===H0&&G.classList.add("quickadd-choice-suggestion-back")}getItemText(l){return l.name}getItems(){return this.choices}async onChooseItem(l,G){l.type==="Multi"?this.onChooseMultiType(l):await this.choiceExecutor.execute(l)}onChooseMultiType(l){let G=[...l.choices],c=l.name===H0;c||G.push(new QZ(H0).addChoices(this.choices));let t=c?this.placeholderStack[this.placeholderStack.length-1]:l.placeholder?.trim()||l.name,b=c?this.placeholderStack.slice(0,-1):[...this.placeholderStack,this.currentPlaceholder];e.Open(this.plugin,G,{choiceExecutor:this.choiceExecutor,placeholder:t,placeholderStack:b})}};var vs=require("obsidian");var _n=class extends Pe{constructor(l,G,c){super(l);this.app=l;this.plugin=G;this.choiceExecutor=c;this.requirements=new Map;this.templatesToScan=new Set;this.dateParser=ge,c&&(this.variables=new Map(c.variables))}async scanString(l){let G=await this.replaceGlobalVarInString(l);this.scanVariableTokens(G),await this.format(G)}async format(l){let G=l;G=await this.replaceGlobalVarInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=await this.replaceValueInString(G),G=await this.repl
2026-01-05 19:25:56 +08:00
${c}
2026-01-31 08:25:19 +08:00
QuickAdd will now revert to backup.`),e.settings=G}}e.saveSettings()}var pF=UO;var gZ=require("obsidian");async function xO(e,I,l){let G=await fetch(`https://api.github.com/repos/${e}/${I}/releases`),c=await G.json();if(!G.ok&&"message"in c||!Array.isArray(c))throw new Error(`Failed to fetch releases: ${c.message??"Unknown error"}`);let t=c.findIndex(b=>b.tag_name===l);if(t===-1)throw new Error(`Could not find release with tag ${l}`);return c.slice(0,t).filter(b=>!b.draft&&!b.prerelease)}function zO(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 Ks=class extends gZ.Modal{constructor(I,l){super(I),this.previousVersion=l,this.releaseNotesPromise=xO("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.",c='<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>',t=I.createDiv("quickadd-update-modal"),b=this.releases.map(a=>a.body).join(`
2026-01-05 19:25:56 +08:00
---
2026-01-31 08:25:19 +08:00
`),d=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,m=`${l}
${G}
2026-01-05 19:25:56 +08:00
${c}
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.
${d}
---
2026-01-31 08:25:19 +08:00
${zO(b)}`;gZ.MarkdownRenderer.renderMarkdown(m,t,this.app.vault.getRoot().path,new gZ.Component)}};var xl=require("obsidian");var Us=class extends xl.Modal{constructor(l,G){super(l);this.showAdvancedSettings=!1;this.settings=G,this.waitForClose=new Promise((c,t)=>{this.rejectPromise=t,this.resolvePromise=c}),this.open(),this.display()}get systemPromptTokenLength(){let l=Je(this.settings.model);return l?TG(this.settings.systemPrompt,l):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();let l=this.contentEl.createEl("h2",{text:`${this.settings.name} Settings`});l.style.textAlign="center",l.style.cursor="pointer",l.style.userSelect="none",l.addEventListener("click",async()=>{try{let G=await pl.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 xl.Setting(l).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(G=>{let c=Gc();for(let t of c)G.addOption(t,t);G.addOption("Ask me","Ask me"),G.setValue(this.settings.model),G.onChange(t=>{this.settings.model=t,this.reload()})})}addOutputVariableNameSetting(l){new xl.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(c=>{this.settings.outputVariableName=c})})}addSystemPromptSetting(l){new xl.Setting(l).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let G=this.contentEl.createEl("div"),c=G.createEl("span");c.style.color="var(--text-muted-color)";let t=G.createEl("div",{text:"Exact for OpenAI models; estimates for others."});t.style.color="var(--text-muted-color)",t.style.fontSize="var(--font-ui-smaller)",G.appendChild(c),G.appendChild(t);let b=new xl.TextAreaComponent(l);b.setValue(this.settings.systemPrompt).onChange(async a=>{this.settings.systemPrompt=a,Z.innerText=await d.format(a),m()}),new eG(this.app,b.inputEl,PI.instance);let d=new FG(this.app,PI.instance);b.inputEl.style.width="100%",b.inputEl.style.height="100px",b.inputEl.style.minHeight="100px",b.inputEl.style.marginBottom="1em";let Z=this.contentEl.createEl("span"),m=(0,xl.debounce)(()=>{c.innerText=`Token count: ${this.systemPromptTokenLength}`},50);m(),(async()=>Z.innerText=await d.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(l){new xl.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(c=>{this.showAdvancedSettings=c,this.reload()})})}addTemperatureSetting(l){new xl.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(c=>{this.settings.modelParameters.temperature=c})})}addTopPSetting(l){new xl.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,
2026-01-05 19:25:56 +08:00
/* nosourcemap */