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

114 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-02-24 07:55:02 +08:00
var JF=Object.create;var yZ=Object.defineProperty;var AF=Object.getOwnPropertyDescriptor;var EF=Object.getOwnPropertyNames;var kF=Object.getPrototypeOf,OF=Object.prototype.hasOwnProperty;var KF=(e,I,l)=>I in e?yZ(e,I,{enumerable:!0,configurable:!0,writable:!0,value:l}):e[I]=l;var cW=(e,I)=>()=>(I||e((I={exports:{}}).exports,I),I.exports),HG=(e,I)=>{for(var l in I)yZ(e,l,{get:I[l],enumerable:!0})},f0=(e,I,l,G)=>{if(I&&typeof I=="object"||typeof I=="function")for(let c of EF(I))!OF.call(e,c)&&c!==l&&yZ(e,c,{get:()=>I[c],enumerable:!(G=AF(I,c))||G.enumerable});return e};var UI=(e,I,l)=>(l=e!=null?JF(kF(e)):{},f0(I||!e||!e.__esModule?yZ(l,"default",{value:e,enumerable:!0}):l,e)),UF=e=>f0(yZ({},"__esModule",{value:!0}),e);var GI=(e,I,l)=>KF(e,typeof I!="symbol"?I+"":I,l);var Op=cW((Nu,Yu)=>{(function(e,I){typeof Nu=="object"&&typeof Yu<"u"?Yu.exports=I():typeof define=="function"&&define.amd?define(I):(e=typeof globalThis<"u"?globalThis:e||self).dayjs_plugin_quarterOfYear=I()})(Nu,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=cW((su,uu)=>{(function(e,I){typeof su=="object"&&typeof uu<"u"?uu.exports=I():typeof define=="function"&&define.amd?define(I):(e=typeof globalThis<"u"?globalThis:e||self).dayjs=I()})(su,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+)?$/,C=/\[([^\]]+)]|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,u={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 O=["th","st","nd","rd"],K=k%100;return"["+k+(O[(K-20)%10]||O[K]||O[0])+"]"}},V=function(k,O,K){var J=String(k);return!J||J.length>=O?k:""+Array(O+1-J.length).join(K)+k},o={s:V,z:function(k){var O=-k.utcOffset(),K=Math.abs(O),J=Math.floor(K/60),v=K%60;return(O<=0?"+":"-")+V(J,2,"0")+":"+V(v,2,"0")},m:function k(O,K){if(O.date()<K.date())return-k(K,O);var J=12*(K.year()-O.year())+(K.month()-O.month()),v=O.clone().add(J,m),H=K-v<0,A=O.clone().add(J+(H?-1:1),m);return+(-(J+(K-v)/(H?v-A:A-v))||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]=u;var Q="$isDayjsObject",L=function(k){return k instanceof E||!(!k||!k[Q])},h=function k(O,K,J){var v;if(!O)return R;if(typeof O=="string"){var H=O.toLowerCase();s[H]&&(v=H),K&&(s[H]=K,v=H);var A=O.split("-");if(!v&&A.length>1)return k(A[0])}else{var B=O.name;s[B]=O,v=B}return!J&&v&&(R=v),v||!J&&R},w=function(k,O){if(L(k))return k.clone();var K=typeof O=="object"?O:{};return K.date=k,K.args=arguments,new E(K)},F=o;F.l=h,F.i=L,F.w=function(k,O){return w(k,{locale:O.$L,utc:O.$u,x:O.$x,$offset:O.$offset})};var E=function(){function k(K){this.$L=h(K.locale,null,!0),this.parse(K),this.$x=this.$x||K.x||{},this[Q]=!0}var O=k.prototype;return O.parse=function(K){this.$d=function(J){var v=J.date,H=J.utc;if(v===null)return new Date(NaN);if(F.u(v))return new Date;if(v instanceof Date)return new Date(v);if(typeof v=="string"&&!/Z$/i.test(v)){var A=v.match(Y);if(A){var B=A[2]-1||0,q=(A[7]||"0").substring(0,3);return H?new Date(Date.UTC(A[1],B,A[3]||1,A[4]||0,A[5]||0,A[6]||0,q)):new Date(A[1],B,A[3]||1,A[4]||0,A[5]||0,A[6]||0,q)}}return new Date(v)}(K),this.init()},O.init=f
`||X.charAt($)==="\r"&&X.charAt($+1)!==`
`)&&(II++,lI===0&&(lI=$+1)),$--}var NI=j+II,Il=y-lI;return U[y]={line:NI,lineStart:lI},{offset:y,line:NI+1,column:Il+1}}function k(X){if(!s(X))throw new Error("not a parser: "+X)}function O(X,y){return typeof X=="string"?X.charAt(y):X[y]}function K(X){if(typeof X!="number")throw new Error("not a number: "+X)}function J(X){if(typeof X!="function")throw new Error("not a function: "+X)}function v(X){if(typeof X!="string")throw new Error("not a string: "+X)}var H=2,A=3,B=8,q=5*B,aI=4*B,nI=" ";function VI(X,y){return new Array(y+1).join(X)}function rI(X,y,U){var j=y-X.length;return j<=0?X:VI(U,j)+X}function CI(X,y,U,j){return{from:X-y>0?X-y:0,to:X+U>j?j:X+U}}function WI(X,y){var U,j,II,lI,$,NI=y.index,Il=NI.offset,Hl=1;if(Il===X.length)return"Got the end of the input";if(L(X)){var cl=Il-Il%B,Ge=Il-cl,Bl=CI(cl,q,aI+B,X.length),Dl=m(function(kl){return m(function(vb){return rI(vb.toString(16),2,"0")},kl)},function(kl,vb){var yb=kl.length,Rt=[],Jb=0;if(yb<=vb)return[kl.slice()];for(var Ab=0;Ab<yb;Ab++)Rt[Jb]||Rt.push([]),Rt[Jb].push(kl[Ab]),(Ab+1)%vb==0&&Jb++;return Rt}(X.slice(Bl.from,Bl.to).toJSON().data,B));lI=function(kl){return kl.from===0&&kl.to===1?{from:kl.from,to:kl.to}:{from:kl.from/B,to:Math.floor(kl.to/B)}}(Bl),j=cl/B,U=3*Ge,Ge>=4&&(U+=1),Hl=2,II=m(function(kl){return kl.length<=4?kl.join(" "):kl.slice(0,4).join(" ")+" "+kl.slice(4).join(" ")},Dl),($=(8*(lI.to>0?lI.to-1:lI.to)).toString(16).length)<2&&($=2)}else{var Ml=X.split(/\r\n|[\n\r\u2028\u2029]/);U=NI.column-1,j=NI.line-1,lI=CI(j,H,A,Ml.length),II=Ml.slice(lI.from,lI.to),$=lI.to.toString().length}var ul=j-lI.from;return L(X)&&($=(8*(lI.to>0?lI.to-1:lI.to)).toString(16).length)<2&&($=2),Z(function(kl,vb,yb){var Rt,Jb=yb===ul,Ab=Jb?"> ":nI;return Rt=L(X)?rI((8*(lI.from+yb)).toString(16),$,"0"):rI((lI.from+yb+1).toString(),$," "),[].concat(kl,[Ab+Rt+" | "+vb],Jb?[nI+VI(" ",$)+" | "+rI("",U," ")+VI("^",Hl)]:[])},[],II).join(`
`)}function LI(X,y){return[`
2026-01-31 08:25:19 +08:00
`,"-- PARSING FAILED "+VI("-",50),`
2026-01-05 19:25:56 +08:00
2026-02-24 07:55:02 +08:00
`,WI(X,y),`
2026-01-05 19:25:56 +08:00
2026-02-24 07:55:02 +08:00
`,(U=y.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(", ")),`
2026-02-24 07:55:02 +08:00
`].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),y=X.length,U=0;U<y;U+=1)k(X[U]);return t(function(j,II){for(var lI,$=new Array(y),NI=0;NI<y;NI+=1){if(!(lI=F(X[NI]._(j,II),lI)).status)return lI;$[NI]=lI.value,II=lI.index}return F(h(II,$),lI)})}function gl(){var X=[].slice.call(arguments);if(X.length===0)throw new Error("seqMap needs at least one argument");var y=X.pop();return J(y),sl.apply(null,X).map(function(U){return y.apply(null,U)})}function Cl(){var X=[].slice.call(arguments),y=X.length;if(y===0)return f("zero alternates");for(var U=0;U<y;U+=1)k(X[U]);return t(function(j,II){for(var lI,$=0;$<X.length;$+=1)if((lI=F(X[$]._(j,II),lI)).status)return lI;return lI})}function Qe(X,y){return zG(X,y).or(WG([]))}function zG(X,y){return k(X),k(y),gl(X,y.then(X).many(),function(U,j){return[U].concat(j)})}function BG(X){v(X);var y="'"+X+"'";return t(function(U,j){var II=j+X.length,lI=U.slice(j,II);return lI===X?h(II,lI):w(j,y)})}function nG(X,y){(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?K(y):y=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<=y&&y<=$.length){var NI=$[0],Il=$[y];return h(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(y,U){return h(U,X)})}function f(X){return t(function(y,U){return w(U,X)})}function EI(X){if(s(X))return t(function(y,U){var j=X._(y,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(y,U){var j=X._(y,U),II=y.slice(U,j.index);return j.status?w(U,'not "'+II+'"'):h(U,null)})}function jI(X){return J(X),t(function(y,U){var j=O(y,U);return U<y.length&&X(j)?h(U+1,j):w(U,"a character/byte matching "+X)})}function Ie(X,y){arguments.length<2&&(y=X,X=void 0);var U=t(function(j,II){return U._=y()._,U._(j,II)});return X?U.desc(X):U}function NG(){return f("fantasy-land/empty")}b.parse=function(X){if(typeof X!="string"&&!L(X))throw new Error(".parse must be called with a string or Buffer as its argument");var y,U=this.skip(le)._(X,0);return y=U.status?{status:!0,value:U.value}:{status:!1,index:T(X,U.furthest),expected:U.expected},delete E[X],y},b.tryParse=function(X){var y=this.parse(X);if(y.status)return y.value;var U=LI(X,y),j=new Error(U);throw j.type="ParsimmonError",j.result=y,j},b.assert=function(X,y){return this.chain(function(U){return X(U)?WG(U):f(y)})},b.or=function(X){return Cl(this,X)},b.trim=function(X){return this.wrap(X,X)},b.wrap=function(X,y){return gl(X,this,y,function(U,j){return j})},b.thru=function(X){return X(this)},b.then=function(X){return k(X),sl(this,X).map(function(y){return y[1]})},b.many=function(){var X=this;return t(function(y,U){for(var j=[],II=void 0;;){if(!(II=F(X._(y,U),II)).status)return F(h(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 v(X),this.map(function(y){if(function(II){if(!Q(II))throw new Error("not an array: "+II)}(y),y.length){v(y[0]);for(var U=y[0],j=1;j<y.length;j++)v(y[j]),U+=X+y[j];return U}return""})},b.tie=function(){return this.tieWith("")},b.times=function(X,y){var U=this;return arguments.length<2&&(y=X),K(X),K(y),t(function(j,II){for(var lI=[],$=void 0,NI=void 0,Il=0;Il<X;Il+=1){if(NI=F($=U._(j,II),NI),!$.status)return NI;II=$.index,lI.push($.value)}for(;Il<y&&(NI=F($=U._(j,II),NI),$.status);Il+=1)II=$.index,lI.push($.value);return F(h(II,lI),NI)})},b.result=function(X){return thi
2026-01-31 08:25:19 +08:00
`),Qt=BG(`\r
2026-02-24 07:55:02 +08:00
`),Le=Cl(Qt,vZ,Xt).desc("newline"),eW=Cl(Le,le);t.all=hc,t.alt=Cl,t.any=Uc,t.cr=Xt,t.createLanguage=function(X){var y={};for(var U in X)({}).hasOwnProperty.call(X,U)&&function(j){y[j]=Ie(function(){return X[j](y)})}(U);return y},t.crlf=Qt,t.custom=function(X){return t(X(h,w))},t.digit=xc,t.digits=ot,t.empty=NG,t.end=eW,t.eof=le,t.fail=f,t.formatError=LI,t.index=DG,t.isParser=s,t.lazy=Ie,t.letter=zc,t.letters=Re,t.lf=vZ,t.lookahead=EI,t.makeFailure=w,t.makeSuccess=h,t.newline=Le,t.noneOf=function(X){return jI(function(y){return X.indexOf(y)<0}).desc("none of '"+X+"'")},t.notFollowedBy=KI,t.of=WG,t.oneOf=function(X){for(var y=X.split(""),U=0;U<y.length;U++)y[U]="'"+y[U]+"'";return jI(function(j){return X.indexOf(j)>=0}).desc(y)},t.optWhitespace=GW,t.Parser=t,t.range=function(X,y){return jI(function(U){return X<=U&&U<=y}).desc(X+"-"+y)},t.regex=nG,t.regexp=nG,t.sepBy=Qe,t.sepBy1=zG,t.seq=sl,t.seqMap=gl,t.seqObj=function(){for(var X,y={},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(y,NI))throw new Error("seqObj: duplicate key "+NI);y[NI]=!0,U++;continue}throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(U===0)throw new Error("seqObj expects at least one named parser, found zero");return t(function(Il,Hl){for(var cl,Ge={},Bl=0;Bl<II;Bl+=1){var Dl,Ml;if(Q(j[Bl])?(Dl=j[Bl][0],Ml=j[Bl][1]):(Dl=null,Ml=j[Bl]),!(cl=F(Ml._(Il,Hl),cl)).status)return cl;Dl&&(Ge[Dl]=cl.value),Hl=cl.index}return F(h(Hl,Ge),cl)})},t.string=BG,t.succeed=WG,t.takeWhile=function(X){return J(X),t(function(y,U){for(var j=U;j<y.length&&X(O(y,j));)j++;return h(j,y.slice(U,j))})},t.test=jI,t.whitespace=re,t["fantasy-land/empty"]=NG,t["fantasy-land/of"]=WG,t.Binary={bitSeq:N,bitSeqObj:function(X){W();var y={},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(v($[0]),K($[1]),Object.prototype.hasOwnProperty.call(y,$[0]))throw new Error("duplicate key in bitSeqObj: "+$[0]);return y[$[0]]=!0,U++,$}return K(lI),[null,lI]},X);if(U<1)throw new Error("bitSeqObj expects at least one named pair, got ["+X.join(", ")+"]");var II=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(),K(X),X>255)throw new Error("Value specified to byte constructor ("+X+"=0x"+X.toString(16)+") is larger in value than a single byte.");var y=(X>15?"0x":"0x0")+X.toString(16);return t(function(U,j){var II=O(U,j);return II===X?h(j+1,II):w(j,y)})},buffer:function(X){return Y("buffer",X).map(function(y){return Buffer.from(y)})},encodedString:function(X,y){return Y("string",y).map(function(U){return U.toString(X)})},uintBE:u,uint8BE:u(1),uint16BE:u(2),uint32BE:u(4),uintLE:V,uint8LE:V(1),uint16LE:V(2),uint32LE:V(4),intBE: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}])})})(dY,dY.exports);var g=dY.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,KJ(ke.field).map(([I,l])=>mY.named(UJ(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 XQ(()=>({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 XQ(()=>({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(eh),e.fromClause.trim(eh).atMost(1),e.clause.trim(eh).many(),(I,l,G)=>({header:I,source:l.length==0?tc.folder(""):l[0],operations:G,settings:gh}))}),eh=g.alt(g.whitespace,XR.comment).many().map(e=>e.join("")),xJ=e=>e?e.plugins.plugins.dataview?.api:window.DataviewAPI,zJ=e=>e.plugins.enabledPlugins.has("dataview");bc.DATE_SHORTHANDS=oh;bc.DURATION_TYPES=Vh;bc.EXPRESSION=ke;bc.KEYWORDS=Xh;bc.QUERY_LANGUAGE=XR;bc.getAPI=xJ;bc.isPluginEnabled=zJ;bc.parseField=OJ});var t3={};HG(t3,{default:()=>PI});module.exports=UF(t3);var yF=require("obsidian");var oe=require("obsidian");function TI(){}function Ts(e){return e()}function tW(){return Object.create(null)}function XI(e){e.forEach(Ts)}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 S0(e){return Object.keys(e).length===0}function qs(e){return e??""}function rt(e){return e&&yI(e.destroy)?e.destroy:TI}var JZ=typeof window<"u"?window:typeof globalThis<"u"?globalThis:global;var bW=class e{constructor(I){GI(this,"_listeners","WeakMap"in JZ?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)}))}};bW.entries="WeakMap"in JZ?new WeakMap:void 0;var T0=!1;function q0(){T0=!0}function P0(){T0=!1}function i(e,I){e.appendChild(I)}function tl(e,I,l){let G=_0(e);if(!G.getElementById(I)){let c=r("style");c.id=I,c.textContent=l,BF(G,c)}}function _0(e){if(!e)return document;let I=e.getRootNode?e.getRootNode():e.ownerDocument;return I&&I.host?I:e.ownerDocument}function BF(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 pc(e,I){for(let l=0;l<e.length;l+=1)
`)}function EZ(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 EZ(e).map(([I,l])=>`${I}=${l}`).join(", ")}var YW={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:Kb,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:WW},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=dp((c,t)=>({...Gl(YW)})),{getState:I,setState:l,subscribe:G}=e;return{getState:I,setState:l,subscribe:G}})();var ll=require("obsidian");var gt="{{value}}",tu="{{date}}",mp="{{time}}",bu="{{name}}",cw="{{value:<variable name>}}",tw="{{value:<variable name>|<default value>}}",bw="{{value:<variable name>|default:<value>}}",dw="{{value:<variable name>|label:<helper text>}}",Zw="{{value|case:kebab}}",mw="{{value:<variable name>|case:kebab}}",aw="{{field:<field name>}}",ap="{{mvalue}}",np="{{linkcurrent}}",Wp="{{filenamecurrent}}",Np="{{title}}",Yp="{{selected}}",sp="{{clipboard}}",nw="{{random:<length>}}",Ww="{{global_var:<name>}}";var up=[tu,"{{date:<dateformat>}}","{{vdate:<variable name>, <date format>}}","{{vdate:<variable name>, <date format>|<default value>}}",Ww,gt,bu,Zw,mw,cw,tw,bw,dw,aw,nw];var du=new RegExp(/^-?[0-9]*$/),Ub="top",kZ="bottom",OZ="cursor",sW=new RegExp(/{{DATE(\+-?[0-9]+)?}}/i),xb=new RegExp(/{{DATE:([^}\n\r+]*)(\+-?[0-9]+)?}}/i
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-02-24 07:55:02 +08:00
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,iu.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=Bp(I.getDateWithAdjustedTimezone(),l),c=new e(I);return c.addTag("result/relativeDate"),l.hour||l.minute||l.second?(c.addTag("result/relativeDateAndTime"),Up(c,G),Kp(c,G),c.assign("timezoneOffset",I.getTimezoneOffset())):(xp(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 _(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 sw(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`(?:${sw(e).sort((l,G)=>G.length-l.length).join("|").replace(/\./g,"\\.")})`}var Mp=UI(BI(),1);function vG(e){return e<100&&(e>50?e=e+1900:e=e+2e3),e}function SI(e,I,l){let G=(0,Mp.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 oW={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},Vu={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={...Vu,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},hu={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},pu={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
2026-01-31 08:25:19 +08:00
`,{line:b,ch:0}),c.setCursor({line:b,ch:e.length});else{let d=c.getLine(b);c.replaceRange(`
2026-02-24 07:55:02 +08:00
`+e,{line:b,ch:d.length}),c.setCursor({line:b+1,ch:e.length})}}catch{x.logError(`unable to insert '${e}' on new line ${I}.`)}}function Ro(e,I){Qo(e,"above",I)}function ro(e,I){Qo(e,"below",I)}function g4(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);x.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},C=W.length===0?"":`
`;b.replaceRange(C+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 v4(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 cN(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)?v4(b):b;return g4(e,Z,l.placement,{requireActiveView:!1}),!0}function y4(e,I){return e.commands.findCommand(I)}function Lo(e,I){y4(e,I)&&(delete e.commands.commands[I],delete e.commands.editorCommands[I])}function eb(e){return e.vault.getAllLoadedFiles().filter(I=>I instanceof ne.TFolder).map(I=>I.path)}function In(e){let I=e.split("::").map(l=>l.trim()).filter(Boolean);return{basename:I[0],memberAccess:I.slice(1)}}async function od(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 tN(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 Fc(e,I){let l=I.vault.getAbstractFileByPath(e.path);if(!l){x.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}=In(e.name);if(a&&a.length>0){let n;for(;n=a.shift();)m=m[n]}return m}}function Fo(e,I){let l=Gl(e);for(let G of I)delete l[G];return l}function bN(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 J4(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 A4(e,I){let l=e.metadataCache.getFileCache(I);if(!l)return[];let G=[];return l.frontmatter&&G.push(...J4(l)),l.tags&&Array.isArray(l.tags)&&G.push(...l.tags.map(c=>c.tag.replace(/^\#/,""))),G}function dN(e,I){let l=I.replace(/^\#/,"");return e.vault.getMarkdownFiles().filter(G=>A4(e,G).includes(l))}function ZN(e){let l=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(e);return l?[0,l[0].length]:null}function wo(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(`
2026-01-31 08:25:19 +08:00
`,I-1)+1,b=e.indexOf(`
2026-02-24 07:55:02 +08:00
`,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 go={"[":"]","(":")","{":"}","<":">"};function E4(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 go){c.push(go[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 k4(e){return e.includes(`
2026-01-31 08:25:19 +08:00
`)?e.replace(/\r?\n/g,`
`):e.includes("\\n")?e.replace(/\\n/g,`
2026-02-24 07:55:02 +08:00
`):e}function O4(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 K4(e){if(!e)return!1;let I=e.toLowerCase();return I==="list"||I==="tags"||I==="multitext"}function Ho(e,I){let l=e.trim();if(!l)return;let G=k4(l),c=I?.propertyType??O4(I?.app,I?.propertyKey),t=K4(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=E4(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=ZN(l),m=wo(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,C=null;if(m.isKeyValuePosition?C=[N]:Y.test(n)&&(C=this.findListParentPath(l,m.lineStart,m.baseIndent??"")),!C||C.length===0)return;let u=C[C.length-1],V=t;if(typeof t=="string"){let s=Ho(t,this.buildParseOptions(u));s!==void 0&&(V=s)}if(!(typeof V!="string"&&(Array.isArray(V)||typeof V=="object"&&V!==null||typeof V=="number"||typeof V=="boolean"||V===null)))return;let R=C.join(vo);this.map.set(R,V)}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 yo=/[\u0000-\u001F]/u,Jo=/[\\/:*?"<>|]/u,Ao=/[. ]$/u,U4=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 mN(e){return U4.has(e.toUpperCase())}function x4(e){if(!e)return null;let I=e.trim().toLowerCase();switch(I){case"kebab":case"snake":case"camel":case"pascal":case"title":case"lower":case"upper":case"slug":return I;default:return null}}function di(e){if(!e)return e;let I=e.toLowerCase();return I.slice(0,1).toUpperCase()+I.slice(1)}function Zi(e){return/\p{L}/u.test(e)?/\p{Lu}/u.test(e)&&!/\p{Ll}/u.test(e):!1}function aN(e){return/\p{Lu}/u.test(e)&&/\p{Ll}/u.test(e)}function z4(e){return/^\p{Ll}/u.test(e)&&aN(e)}function B4(e){if(!e)return[];{let l=e.match(/^([\p{Ll}][\p{Lu}]{2,})([\p{N}]+)?$/u);if(l){let G=[l[1]];return l[2]&&G.push(l[2]),G}}if(/^[\p{Ll}][\p{Lu}][\p{Ll}]+(?:[\p{Lu}][\p{Ll}]+)*$/u.test(e))return[e];let I=e;return I=I.replace(/([\p{Lu}]+)([\p{Lu}][\p{Ll}])/gu,"$1 $2"),I=I.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu,"$1 $2"),I=I.replace(/([\p{L}])([\p{N}])/gu,"$1 $2"),I=I.replace(/([\p{N}])([\p{L}])/gu,"$1 $2"),I.trim().split(/\s+/u).map(l=>l.trim()).filter(Boolean)}function D4(e){return e.split(/[^\p{L}\p{N}\p{M}]+/gu).filter(Boolean).flatMap(B4).filter(Boolean)}function nN(e,I){let l=x4(I);if(!l)return e;if(l==="lower")return e.toLowerCase();if(l==="upper")return e.toUpperCase();let G=D4(e);if(G.length===0)return"";switch(l){case"kebab":return G.map(c=>c.toLowerCase()).join("-");case"snake":return G.map(c=>c.toLowerCase()).join("_");case"camel":{let[c,...t]=G,b=c?z4(c)?c:c.toLowerCase():"",d=t.map(Z=>Zi(Z)||aN(Z)?Z:di(Z));return[b,...d].join("")}case"pascal":return G.map(c=>Zi(c)||aN(c)?c:di(c)).join("");case"title":return G.map(c=>Zi(c)||aN(c)?c:di(c)).join(" ");case"slug":{let c=G.map(t=>t.toLowerCase()).join("-");return mN(c)?`${c}-`:c}default:return e}}function ln(e){return e.split("|")}function Eo(e){return e.startsWith("|")?e.slice(1):e}function Gn(e){let I=e.indexOf(":");if(I===-1)return null;let l=e.slice(0,I).trim().toLowerCase();if(!l)return null;let G=e.slice(I+1).trim();return{key:l,value:G}}var ko="",Oo=new Set(["label","default","custom","type","case"]);function M4(e,I,l){return l&&I?`${e}${ko}${I}`:e}function en(e){let I=e.indexOf(ko);return I===-1?e:e.slice(0,I)}function j4(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 WN(e,I){if(!I)return null;let l=[I],G=en(I);G!==I&&l.push(G);for(let c of l){if(e.has(c)&&e.get(c)!==void 0)return c;let t=j4(e,c);if(t)return t}return null}function f4(e){if(!e)return!0;let I=e.trim().toLowerCase();return!["false","no","0","off"].includes(I)}function S4(e){let I=e.trim();if(!I)return!1;let l=Gn(I);return l?Oo.has(l.key):!1}function Ko(e,I){if(e.length===0)return{defaultValue:"",allowCustomInput:!1,usesOptions:!1};let l=e.some(S4),G=I&&e.some(a=>a.trim().toLowerCase()==="custom");if(!(l||G))return{defaultValue:e.join("|").trim(),allowCustomInput:!1,usesOptions:!1};let t,b,d="",Z=!1,m;for(let a of e){let n=a.trim();if(!n)continue;if(I&&n.toLowerCase()==="custom"){Z=!0;continue}let W=Gn(n);if(!W)continue;let{key:N,value:Y}=W;if(Oo.has(N))switch(N){case"label":Y&&(t=Y);break;case"case":Y&&(b=Y);break;case"default":d=Y;br
`,G++):t=="\\"?(l+="\\",G++):l+="\\":l+=c}return l}replaceRandomInString(I){let l=I;for(;nu.test(l);){let G=nu.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(;Zu.test(l);)l=this.replacer(l,Zu,G);return l}};YN.FIELD_VARIABLE_PREFIX="FIELD:";var _e=YN;var T4={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"},q4={clipboard:"clipboard_content",date:"formatted_date",time:"current_time",random:"random_value",uuid:"unique_id"},P4=[{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 sN(e){let I=e.toLowerCase(),l=T4[I];return l||`${e}_example`}function uN(e){return q4[e.toLowerCase()]||`${e}_output`}function CN(e){for(let{pattern:I,example:l}of P4)if(I.test(e))return l;return`${e}_value`}function iN(e){return e.length>0?`${e[0]} (${e.length} options)`:"suggestion_list"}function hN(e){return e?.path?e.basename:"current_file"}function pN(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 Xd=class extends _e{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>
2026-02-24 07:55:02 +08:00
`,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 Bi.TFile))return null;let c=document.createElement("div");return c.className="qa-file-tooltip",c.innerHTML=`
2026-01-31 08:25:19 +08:00
<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-02-24 07:55:02 +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 Bi.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 vd=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=hp.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}`;FN(G,c,t,b,{fromCompletion:!0}),this.close()}};var yd=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 Jd=class{constructor(I,l){this.store=yd.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=vX.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]),C=this.rankMap.get(Y.join(","));if(C!=null){t.push(C);continue}t.push(...ry(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)}},xN=ji;Qy(xN,"specialTokenRegex",e=>new RegExp(e.map(I=>Ly(I)).join("|"),"g"));function fi(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-02-24 07:55:02 +08:00
${I}`:""}`;function DN(e){if(e){let I=new KX.Notice(OX("starting",""),1e6);return{setMessage:(l,G)=>{I.setMessage(OX(l,G))},hide:()=>I.hide()}}return{setMessage:(I,l)=>{x.logMessage(`(${I}) ${l}`)},hide:()=>{}}}var UX={cl100k_base:yX,o200k_base:JX},xX=new Map;function Jy(e){let I=e in UX?e:"cl100k_base",l=xX.get(I);if(l)return l;let G=new xN(UX[I]);return xX.set(I,G),G}var TG=(e,I)=>{let l="cl100k_base";try{l=fi(I.name)}catch{l="cl100k_base"}return(l==="p50k_base"||l==="p50k_edit"||l==="r50k_base"||l==="gpt2")&&(l="cl100k_base"),Jy(l).encode(e).length};async function Ay(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 Ey(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 zX.TFile,`${c} is not a file`);let b=await e.vault.cachedRead(t);return[G.basename,b]}async function BX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=DN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,promptTemplate:d,systemPrompt:Z,promptTemplateFolder:m}=I,a=Gt(e,m),[n,W]=await Ey(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 u=BN(e,c,t,Z,I.modelOptions)(N),o=(await Ti(u,100,Q=>{G.setMessage(Y[0],`${Y[1]} (${(Q/1e3).toFixed(2)}s)`)},Q=>{G.setMessage("finished",`Took ${(Q/1e3).toFixed(2)}s.`)})).content,R=("> "+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 MI("Input cancelled by user"):c}}async function Ti(e,I,l,G){let c=Date.now();return await Ay(()=>l(Date.now()-c),e,I),G(Date.now()-c),await e}async function DX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=DN(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=BN(e,c,t,d,m)(a),C=(await Ti(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,u=("> "+C).replace(/\n/g,`
> `),V={[b]:C,[`${b}-quoted`]:u};return setTimeout(()=>G.hide(),5e3),V}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),c}}var Si=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 MX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=DN(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:" "}),C=TG(Y,t),u=kX(t.name)/2-N,V=I.shouldMerge??!0,o=[],R=u-C;if(V){let O=[],K="",J=0;for(let v of W){let H=TG(v,t)+1;if(H>R)throw new Error(`The chunk "${v.slice(0,25)}..." is too large to fit in a single prompt.`);J+H<R?(K+=v,J+=H):(O.push(K),K=v,J=H)}K!==""&&O.push(K);for(let v of O){let H=await l(Z,{chunk:v});o.push(H)}}else for(let O of W){let K=TG(O,t);if(K>u)throw new Error(`Chunk size (${K}) is larger than the maximum chunk size (${u}). Please check your chunk separator.`);let J=await l(Z,{chunk:O});o.push(J)}let s=BN(e,c,t,d,a),Q=["prompting",`${o.length} prompts being sent.`];G.setMessage(Q[0],Q[1]);let L=new Si(5,1e3*30),h=Promise.all(o.map(O=>L.add(()=>s(O)))),E=(await Ti(h,100,O=>{G.setMessage(Q[0],`${Q[1]} (${(O/1e3).toFixed(2)}s)`)},O=>{G.setMessage("finished",`Took ${(O/1e3).toFixed(2)}s.`)})).map(O=>O.content).join(I.resultJoiner),T=("> "+E).replace(/\n/g,`
> `),k={[b]:E,[`${b}-quoted`]:T};return setTimeout(()=>G.hide(),5e3),k}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),c}}var ky="quickadd-ai";function Oy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Ky(e){let I=e.name?.trim()||"provider";return`${ky}-${Oy(I)}`}async function Jc(e,I){let l=I.apiKeyRef?.trim();if(l&&e?.secretStorage?.getSecret)try{let G=await Promise.resolve(e.secretStorage.getSecret(l));if(G)return G}catch(G){x.logWarning(`Failed to read SecretStorage entry "${l}": ${G.message??G}`)}return I.apiKey??""}async function jX(e,I,l){let G=l?.trim();if(!G||!e?.secretStorage?.getSecret||!e.secretStorage?.setSecret)return null;let c=Ky(I),t=c,b=1;for(;;){let d=null;try{d=await Promise.resolve(e.secretStorage.getSecret(t))}catch(Z){x.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 x.logWarning(`Failed to write SecretStorage entry "${t}": ${d.message??d}`),null}}var kd=require("obsidian"),Nn=class e extends kd.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 kd.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 kd.ButtonComponent(l).setButtonText("Submit").setCta().onClick(c=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};var MN=require("obsidian"),Yn=class e extends MN.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 MN.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 Od=require("obsidian");var dt=class e extends Od.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 Jd({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 Hd(l,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new vd(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 V?(d?.shouldAssignVariables&&Object.entries(V).forEach(([o,R])=>{G.variables.set(o,R)}),V):(qI(new Error("AI Assistant returned null"),"Chunked AI Prompt error"),{})},getModels:()=>ec(),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(yh.MarkdownView);return c?c.editor.getSelection()??"":""},getSelectedText:()=>{let c=I.workspace.getActiveViewOfType(yh.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)=>Lc({format:c,offset:t}),tomorrow:c=>Lc({format:c,offset:1}),yesterday:c=>Lc({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=iY.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);Pd.getFieldValues(W,c).forEach(Y=>Z.add(Y))}}return Array.from(Z).sort()},clearCache:c=>{dc.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 Yb.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 Yn.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 Nn.Open(I,l,G)}catch(c){Wt(c);return}}};function Wt(e){if(e instanceof MI)throw e;if(il(e))throw new MI("Input cancelled by user")}var IZ=class extends Qd{};var mG=[];for(let e=0;e<256;++e)mG.push((e+256).toString(16).slice(1));function LR(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 Jh,TJ=new Uint8Array(16);function Ah(){if(!Jh){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Jh=crypto.getRandomValues.bind(crypto)}return Jh(TJ)}var qJ=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Eh={randomUUID:qJ};function PJ(e,I,l){if(Eh.randomUUID&&!I&&!e)return Eh.randomUUID();e=e||{};let G=e.random??e.rng?.()??Ah();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 LR(G)}var iG=PJ;var lG=class{constructor(I,l){this.name=I,this.type=l,this.id=iG()}};var FR=require("obsidian");var Ll=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 xR=require("obsidian");function dZ(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 _J=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],HR=new Set(["true","1","yes","on"]),vR=new Set(["false","0","no","off"]);function Nt(e){return _J.includes(e)}function yR(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 JR(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 HR.has(l)?!0:vR.has(l)?!1:!!I}case"string":default:return I}}function Oh(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(HR.has(l))return!0;if(vR.has(l))return!1}return!!e;case"string":default:return e==null?"":String(e)}}function $J(e){if(!Nt(e.operator))return"";let I=e.expectedValue??"";return I.length===0?"(empty)":e.valueType==="string"?`"${I}"`:I}function IA(e){let I=e.variableName?`$${e.variableName}`:"(missing variable)",l=GA(e.operator),G=Nt(e.operator)?` ${$J(e)}`:"";return`${I} ${l}${G}`.trim()}function lA(e){let I=e.exportName?`::${e.exportName}`:"";return`script ${e.scriptPath}${I}`}function ZZ(e){return e.mode==="variable"?IA(e):lA(e)}function GA(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 ER(e,I){return e.mode==="script"?await I.evaluateScriptCondition(e):eA(e,I.variables)}function eA(e,I){let l=e.variableName?.trim();if(!l)return x.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(l in I))return x.logWarning(`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=JR(e);return c===void 0?(x.logWarning(`Conditional command: Operator '${e.operator}' requires a comparison value.`),!1):e.operator==="contains"?AR(G,c,e):e.operator==="notContains"?!AR(G,c,e):cA(G,c,e)}return!1}function AR(e,I,l){return e==null?!1:typeof I=="string"&&I.length===0?(x.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1):Array.isArray(e)?e.map(G=>Oh(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 cA(e,I,l){let G=Oh(e,l.valueType);switch(l.operator){case"equals":return G===I;case"notEquals":return G!==I;case"lessThan":return hY(G,I,(c,t)=>c<t);case"lessThanOrEqual":return hY(G,I,(c,t)=>c<=t);case"greaterThan":return hY(G,I,(c,t)=>c>t);case"greaterThanOrEqual":return hY(G,I,(c,t)=>c>=t);default:return!1}}function hY(e,I,l){let G=Number(e),c=Number(I);return Number.isNaN(G)||Number.isNaN(c)?(x.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):l(G,c)}var kR=require("obsidian");function Yt(e,{logPrefix:I,noticePrefix:l=I,defaultReason:G}){if(!(e instanceof MI))return!1;let c=typeof e.message=="string"&&e.message.trim().length>0?e.message:G;return x.logMessage(`${I}: ${c}`),(!(typeof e.message=="string"&&e.message.toLowerCase().includes("cancelled by user"))||P.getState().showInputCancellationNotification)&&new kR.Notice(`${l}: ${c}`
2026-01-31 08:25:19 +08:00
${AI}
2026-02-24 07:55:02 +08:00
\\end{${e}}${AI}`}var zR=[...dA,...ZA.map(mA)];var BR=require("obsidian");var aA=new RegExp(/\\([a-z{}A-Z0-9]*)$/),oY=class extends IG{constructor(l){super(PI.instance.app,l);this.inputEl=l;this.lastInput="";this.symbols=Object.assign([],zR),this.elementsRendered=this.symbols.reduce((G,c)=>{try{G[c.toString()]=(0,BR.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=aA.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 XY=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 oY(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 _e{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-02-24 07:55:02 +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 MI("Input cancelled by user"):G}}generateCacheKey(l){return YY(l)}async getMacroValue(l,G){let c=new VY(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(DR.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(;xZ.test(G);){let t=xZ.exec(G)?.at(1)?.trim();if(t){let b=new pY(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,xZ,d):this.replacer(G,xZ,"")}}return G}async collectValuesManually(l,G){return await sY(this.app,l,G)}};var aZ=require("obsidian");var MR=require("obsidian");function jR(e){return((0,MR.normalizePath)(e).split("/").pop()??"").replace(/\.(md|canvas)$/i,"")}var mc=class extends Error{constructor(I){super(I),this.name="InvalidFolderPathError"}};function Kh(e){return e instanceof MI||!!e&&typeof e=="object"&&"name"in e&&e.name==="MacroAbortError"}var nZ=class extends Qd{constructor(l,G,c){super(l);this.plugin=G;this.templater=bi(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 MI("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 mc){new aZ.Notice(t.message);continue}throw t}return await this.ensureFolderExists(c),c}}async ensureFolderExists(l){l.isEmpty||l.exists||await this.createFolder(l.resolved)}async handleSingleSelection(l){let G=l.items[0]??"",c=await this.resolveSelection(G,l);if(c.isEmpty)return"";if(!c.isAllowed)throw this.showFolderNotAllowedNotice(l.allowedRoots),new MI("Selected folder not allowed.");if(c.re
2026-01-31 08:25:19 +08:00
${Z}`:`${Z}
2026-02-24 07:55:02 +08:00
${d}`;return await this.app.vault.modify(l,m),l}catch(t){if(Kh(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 aZ.TFile))throw new Error(`Template file not found at path "${G}".`);return await this.app.vault.cachedRead(c)}};var st=class extends nZ{constructor(l,G,c,t){super(l,G,t);this.templatePath=c}async run(){let l=await this.getTemplateContent(this.templatePath);return l||x.logError(`Template ${this.templatePath} not found.`),l=await this.formatter.formatFileContent(l),l}getAndClearTemplatePropertyVars(){return this.formatter.getAndClearTemplatePropertyVars()}};var FG=class extends _e{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=en(l);return sN(c)}getCurrentFileLink(){return this.app?hN(this.app.workspace.getActiveFile()):null}getCurrentFileName(){return this.app?pN(this.app.workspace.getActiveFile()):"current_filename"}suggestForValue(l,G=!1,c){return iN(l)}getMacroValue(l,G){return uN(l)}promptForMathValue(){return Promise.resolve("calculation_result")}promptForVariable(l,G){return Promise.resolve(CN(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 QY=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=vc(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){if(!l)return;let c=Ri(l),t=Ri(this.getCurrentQuery());l.toLowerCase().endsWith(".md")&&t.toLowerCase().startsWith(`${c.toLowerCase()}.`)&&(t=c),this.renderMatch(G,c,t)}getCurrentQuery(){return this.inputEl.value}};function Rb(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="t
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function RA(){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 Kn(e,I){var l=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!l){if(Array.isArray(e)||(l=Ph(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 rA="finalize",LA="consider";function hZ(e,I,l){e.dispatchEvent(new CustomEvent(rA,{detail:{items:I,info:l}}))}function ht(e,I,l){e.dispatchEvent(new CustomEvent(LA,{detail:{items:I,info:l}}))}var kY="draggedEntered",Un="draggedLeft",OY="draggedOverIndex",_h="draggedLeftDocument",HY={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function FA(e,I,l){e.dispatchEvent(new CustomEvent(kY,{detail:{indexObj:I,draggedEl:l}}))}function wA(e,I,l){e.dispatchEvent(new CustomEvent(Un,{detail:{draggedEl:I,type:HY.LEFT_FOR_ANOTHER,theOtherDz:l}}))}function gA(e,I){e.dispatchEvent(new CustomEvent(Un,{detail:{draggedEl:I,type:HY.OUTSIDE_OF_ANY}}))}function HA(e,I,l){e.dispatchEvent(new CustomEvent(OY,{detail:{indexObj:I,draggedEl:l}}))}function vA(e){window.dispatchEvent(new CustomEvent(_h,{detail:{draggedEl:e}}))}var gG={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:kY,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:OY,DRAGGED_LEFT:Un,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"},KY="isDndShadowItem",UY="data-is-dnd-shadow-item-internal",yA="data-is-dnd-shadow-item-hint",wb="id:dnd-shadow-placeholder-0000",JA="dnd-action-dragged-el",bG="id",Dh=0;function mr(){Dh++}function ar(){if(Dh===0)throw new Error("Bug! trying to decrement when there are no dropzones");Dh--}var $h=typeof window>"u",HI=function(){};function Mh(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 nr(e){var I=Mh(e);return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}function Wr(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 Nr(e){return{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}}function AA(e,I){return Math.sqrt(Math.pow(e.x-I.x,2)+Math.pow(e.y-I.y,2))}function xY(e,I){return e.y<=I.bottom&&e.y>=I.top&&e.x>=I.left&&e.x<=I.right}function En(e){return Nr(Wr(e))}function _R(e,I){var l=En(e),G=nr(I);return xY(l,G)}function EA(e,I){var l=En(e),G=En(I);return AA(l,G)}function kA(e){var I=Wr(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 uZ;function I0(){HI(function(){return"resetting indexes cache"}),uZ=new Map}I0();function KA(e){var I=Array.from(e.children).f
2026-01-31 08:25:19 +08:00
${l?"Deleting this choice will delete all ("+e.choices.length+") choices inside it!":""}
${G?"Deleting this choice will delete its macro commands!":""}
2026-02-24 07:55:02 +08:00
`)}async function zr(e,I,l){if(e.type==="Multi")try{return await new bs(I,e).waitForClose}catch{return}let G=Zk(e,I,l);if(!G)throw new Error("Invalid choice type");return await G.waitForClose}function Br(e){return{...e,command:!e.command}}var Zs=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 Dr(e,I,l){if(!I||!l)return e;let G=W0(e,I),c=W0(e,l);if(!G||!c||c.type!=="Multi"||G.type==="Multi"&&(G.id===c.id||mk(G).has(c.id)))return e;let{updated:t,removed:b}=Mr(e,I);return b?jr(t,l,b)??e:e}function W0(e,I){for(let l of e){if(l.id===I)return l;if(l.type==="Multi"){let G=W0(l.choices,I);if(G)return G}}}function mk(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 Mr(e,I){let l;return{updated:e.map(c=>{if(c.id===I){l=c;return}if(c.type!=="Multi")return c;let t=Mr(c.choices,I);return t.removed&&(l=t.removed),t.removed?{...c,choices:t.updated}:c}).filter(Boolean),removed:l}}function jr(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=jr(t.choices,I,l);return b?(G=!0,{...t,choices:b}):t});return G?c:void 0}var uc=require("obsidian");var Ql=require("obsidian");var fr=require("obsidian");var ms=null,ak=24*60*60*1e3;async function Sr(){if(ms&&Date.now()-ms.fetchedAt<ak)return ms.data;if(P.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let I=await(await(0,fr.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;return ms={data:I,fetchedAt:Date.now()},I}function s0(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 Tr(e){return e.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}function u0(e,I){let l=new Set(e.map(c=>c.name)),G=I.filter(c=>!l.has(c.name));return e.concat(G)}var _r=require("obsidian");var nk=128e3;async function as(e,I){let l=e.modelSource??"providerApi";if(l==="modelsDev")return qr(e);if(l==="providerApi")return Pr(e,I);try{return await Pr(e,I)}catch(G){if(!s0(e.endpoint))throw G;return qr(e,G)}}async function qr(e,I){try{let l=await Sr(),G=s0(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 Tr(c)}catch(l){throw I?new Error(`Provider API failed (${I.message}). Fallback to models.dev also failed: ${l.message}`):l}}async function Pr(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),p(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 kL(e){let I,l,G,c,t=e[4].missingChoices.length>0&&OL(e),b=e[4].missingAssets.length>0&&KL(e);return{c(){I=r("section"),l=r("h4"),l.textContent="Warnings",G=M(),t&&t.c(),c=M(),b&&b.c(),p(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=OL(d),t.c(),t.m(I,c)):t&&(t.d(1),t=null),d[4].missingAssets.length>0?b?b.p(d,Z):(b=KL(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 OL(e){let I,l,G=e[4].missingChoices.map(e[23]).join(", ")+"",c;return{c(){I=r("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 KL(e){let I,l,G,c,t=al(e[4].missingAssets),b=[];for(let d=0;d<t.length;d+=1)b[d]=UL(vL(e,t,d));return{c(){I=r("div"),l=r("p"),l.textContent="Missing assets:",G=M(),c=r("ul");for(let d=0;d<b.length;d+=1)b[d].c();p(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=vL(d,t,m);b[m]?b[m].p(a,Z):(b[m]=UL(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),pc(b,d)}}}function UL(e){let I,l=e[28].path+"",G,c,t,b,d=e[9][e[28].kind]+"",Z,m;return{c(){I=r("li"),G=mI(l),c=M(),t=r("span"),b=mI("("),Z=mI(d),m=mI(")"),p(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 tO(e){let I;return{c(){I=mI("Copy JSON")},m(l,G){tI(l,I,G)},d(l){l&&eI(I)}}}function bO(e){let I;return{c(){I=mI("Copying\u2026")},m(l,G){tI(l,I,G)},d(l){l&&eI(I)}}}function dO(e){let I;return{c(){I=mI("Save to file")},m(l,G){tI(l,I,G)},d(l){l&&eI(I)}}}function ZO(e){let I;return{c(){I=mI("Saving\u2026")},m(l,G){tI(l,I,G)},d(l){l&&eI(I)}}}function mO(e){let I,l,G,c,t,b,d,Z,m,a,n,W,N,Y,C,u,V,o,R,s,Q=e[8].rootCount+"",L,h,w,F,E,T,k=e[8].totalChoices+"",O,K,J,v,H,A,B=e[8].dependencyCount+"",q,aI,nI,VI,rI,CI,WI=e[8].userScripts+e[8].conditionalScripts+"",LI,$I,sl,gl,Cl,Qe,zG=e[8].templateFiles+e[8].captureTemplates+"",BG,nG,WG,f,EI,KI,jI,Ie,NG,DG,Uc,hc,le,xc,ot,zc,Re,GW,re,Xt,vZ,Qt,Le,eW,X,y,U;function j(Ml,ul){return Ml[6].length===0?cO:eO}let II=j(e,[-1,-1]),lI=II(e),$=e[8].missingChoiceIds.length>0&&EL(e),NI=e[4]&&kL(e);function Il(Ml,ul){return Ml[5]==="copy"?bO:tO}let Hl=Il(e,[-1,-1]),cl=Hl(e);function Ge(Ml,ul){return Ml[5]==="save"?ZO:dO}let Bl=Ge(e,[-1,-1]),Dl=Bl(e);return{c(){I=r("div"),l=r("header"),l.innerHTML='<h2>Export QuickAdd Package</h2> <p class="svelte-iqd8ho">Select choices to bundle. Dependencies are added automatically.</p>',G=M(),c=r("section"),t=r("input"),d=M(),Z=r("div"),m=r("button"),m.textContent="Select visible",a=M(),n=r("button"),n.textContent="Clear selection",W=M(),N=r("section"),lI.c(),Y=M(),C=r("section"),u=r("h3"),u.textContent="Package summary",V=M(),o=r("div"),R=r("div"),s=r("strong"),L=mI(Q),h=M(),w=r("span"),w.textContent="Selected choices",F=M(),E=r("div"),T=r("strong"),O=mI(k),K=M(),J=r("span"),J.textContent="Total packaged",v=M(),H=r("div"),A=r("strong"),q=mI(B),aI=M(),nI=r("span"),nI.textContent="Auto-included",VI=M(),rI=r("div"),CI=r("strong"),LI=mI(WI),$I=M(),sl=r("span"),sl.textContent="Scripts embedded",gl=M(),Cl=r("div"),Qe=r("strong"),BG=mI(zG),nG=M(),WG=r("span"),WG.textContent="Templates embedded",f=M(),$&&$.c(),EI=M(),NI&&NI.c(),KI=M(),jI=r("section"),Ie=r("div"),NG=r("button"),cl.c(),Uc=M(),hc=r("div"),le=r("label"),xc=r("span"),xc.textContent="Save to file",ot=M(),zc=r("div"),Re=r("input"),GW=M(),re=r("button"),Dl.c(),vZ=M(),Qt=r("section"),Le=r("button"),eW=mI("Cancel"),p(l,"class","svelte-iqd8ho"),p(t,"type","text"),p(t,"placeholder","Filter choices"),p(t,"autocapitalize","off"),p(t,"autocorrect","off"),p(t,"spellcheck",b=!1),p(t,"class","svelte-iqd8ho"),p(m,"type","button"),p(m,"class","svelte-iqd8ho"),p(n,"type","button"),p(n,"class","svelte-iqd8ho"),p(Z,"class","controlButtons svelte-iqd8ho"),p(c,"class","controls svelte-iqd8ho"),p(N,"class","choiceList svelte-iqd8ho"),p(u,"class","svelte-iqd8ho"),p(s,"class","svelte-iqd8ho"),p(R,"class","svelte-iqd8ho"),p(T,"class","svelte-iqd8ho"),p(E,"class","svelte-iqd8ho"),p(A,"class","svelte-iqd8ho"),p(H,"class","svelte-iqd8ho"),p(CI,"class","svelte-iqd8ho"),p(rI,"class","svelte-iqd8ho"),p(Qe,"class","svelte-iqd8ho"),p(Cl,"class","svelte-iqd8ho"),p(o,"class","summaryGrid svelte-iqd8ho"),p(C,"class","summary svelte-iqd8ho"),p(NG,"type","button"),p(NG,"class","secondary svelte-iq
2026-01-31 08:25:19 +08:00
tm = tomorrow
2026-02-24 07:55:02 +08:00
yd = yesterday`).setValue(cu(P.getState().dateAliases)).onChange(b=>{P.setState({dateAliases:Zp(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:Kb}),c&&c.setValue(cu(Kb))}),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 FZ=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 qn=class extends FZ{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>Gi&&(this.ErrorLog=this.ErrorLog.slice(-Gi))}clearErrorLog(){this.ErrorLog=[]}};var v0=require("obsidian");var Fs=class extends FZ{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 ws=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 Zc(this.app,this.plugin,l,this.choiceExecutor,new Map).run()}};var y0=require("obsidian");var gs=class extends nZ{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 y0.TFile)||Z.extension!=="md"&&Z.extension!=="canvas"){x.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,[...Wu],[...Wu])}catch(a){throw
2026-01-05 19:25:56 +08:00
`)}}).join(`
2026-02-24 07:55:02 +08:00
`)}}var nF=e=>e.join(""),HO=e=>e.split(/\b/),vO=aF("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",nF),yO={splitFunction:HO,joinFunction:nF,conflictFunction:vO};function K0(e,I,l,G={}){G=Object.assign({},yO,G);let[c,t,b]=[e,I,l].map(m=>G.splitFunction.call(G,m)),d=$n.merge(c,t,b);return IW.collateMerge(d,G.joinFunction,G.conflictFunction)}var WF=K0;var U0=require("obsidian");function NF(e,I){return e.line===I.line}function JO(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 As(e,I,l=!1){let G=JO(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=YF(e,I,a=>a.trim()==="");return m!==null&&m>I?m-1:I}let b=e.length-1,d=AO(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 AO(e,I,l,G){let c=I.findIndex(a=>NF(a,e)),t=c===I.length-1,b=l.length-1;if(t)return b;let[d,Z]=EO(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=kO(e.line,I);return a===null?b:a}return b}function EO(e,I){let l=I.findIndex(c=>NF(c,e)),G=YF(I,l,c=>c.level<=e.level);return G===null?[-1,!1]:[G,!0]}function kO(e,I){let l=I.find(G=>G.line>e);return l?l.line:null}function OO(e,I,l){for(let G=I-1;G>=0;G--)if(l(e[G]))return G;return null}function YF(e,I,l){for(let G=I+1;G<e.length;G++)if(l(e[G]))return G;return null}var Es=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 Vd(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,Z=this.fileContent.length>0&&!this.fileContent.endsWith(`
`)&&!c.startsWith(`
`),m=d||Z?`
`:"";return`${this.fileContent}${m}${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=kh(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=As(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(`
2026-01-31 08:25:19 +08:00
`)||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))}
2026-02-24 07:55:02 +08:00
${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Ub){let t=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(c,this.fileContent,t)}if(this.choice.insertAfter?.createIfNotFoundLocation===kZ)return`${this.fileContent}
${c}`;if(this.choice.insertAfter?.createIfNotFoundLocation===OZ)try{let t=this.app.workspace.getActiveViewOfType(U0.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=kh(this.fileContent);d=As(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===Ub){let t=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(c,this.fileContent,t)}if(this.choice.insertAfter?.createIfNotFoundLocation===kZ)return`${this.fileContent}
${c}`;if(this.choice.insertAfter?.createIfNotFoundLocation===OZ)try{let t=this.app.workspace.getActiveViewOfType(U0.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 x.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 x.logMessage("could not get frontmatter. Maybe there isn't any."),-1}inferFrontmatterEndLineFromContent(l){let G=ZN(l);if(!G)return null;let c=l.slice(0,G[1]),t=c.split(/\r?\n/);return t.length===0?null:c.endsWith(`
2026-01-31 08:25:19 +08:00
`)?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}
2026-02-24 07:55:02 +08:00
${l}${d}`}};var ks=class extends MI{};function sF(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 uF=4e3,Os=class extends IZ{constructor(l,G,c,t){super(l);this.choiceExecutor=t;this.capturePropertyVars=new Map;this.choice=c,this.plugin=G,this.formatter=new Es(l,G,t)}showSuccessNotice(l,{wasNewFile:G,action:c}){let t=`'${l.basename}'`;if(G){new x0.Notice(`Created and captured to ${t}`,uF);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 x0.Notice(b,uF)}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=(C,u,V)=>this.onCreateFileIfItDoesntExist(C,u,l);else throw new ks(`Target file missing: ${b}. Enable "Create file if it doesn't exist" or choose an existing file.`);let{file:a,newFileContent:n,captureContent:W}=await Z(b,d),N=sF(this.choice);if(N==="currentLine"||N==="newLineAbove"||N==="newLineBelow"){let C=await Vd(this.app,W,a);switch(N){case"currentLine":Xo(C,this.app);break;case"newLineAbove":Ro(C,this.app);break;case"newLineBelow":ro(C,this.app);break}}else await this.app.vault.modify(a,n),this.choice.templater?.afterCapture==="wholeFile"&&await pd(this.app,a),await this.applyCapturePropertyVars(a);if(this.plugin.settings.showCaptureNotification&&this.showSuccessNotice(a,{wasNewFile:!m,action:N}),l.enabled&&cN(this.app,a,l),this.choice.openFile&&a){let C=KG(this.choice.fileOpening),u=C.focus??!0;tN(this.app,a,u)||await od(this.app,a,C),await eN(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(zZ);if(!l&&G&&typeof G=="string"&&G.length>0)return G;if(l){let d=this.app.workspace.getActiveFile();return SG(d,"Cannot capture to active file - no active file."),d.path}let c=this.choice.captureTo,t=await this.formatter.formatFileName(c,this.choice.name),b=this.resolveCaptureTarget(t);switch(b.kind){case"vault":return this.selectFileInFolder("",!0);case"tag":return this.selectFileWithTag(b.tag);case"folder":return this.selectFileInFolder(b.folder,!1);case"file":return this.normalizeMarkdownFilePath("",b.path)}}resolveCaptureTarget(l){let G=this.stripLeadingSlash(l.trim());if(G==="")return{kind:"vault"};if(G.startsWith("#"))return{kind:"tag",tag:G.replace(/\.md$/,"")};let c=G.endsWith("/"),t=G.replace(/\/+$/,"");if(c)return{kind:"folder",folder:t};if(G.endsWith(".md"))return{kind:"file",path:G};let b=this.normalizeMarkdownFilePath("",t),Z=!!this.app.vault.getAbstractFileByPath(b);return bN(this.app,t)&&!Z?{kind:"folder",folder:t}:{kind:"file",path:G}}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 MI("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=dN(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 MI("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=WF(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-02-24 07:55:02 +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();x.logMessage(`CaptureChoiceEngine: Collected ${W.size} template property variables`),W.size>0&&x.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 pd(this.app,Z):GN(this.app)&&await Vo(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);x.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}x.logMessage(`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`),await this.postProcessFrontMatter(l,this.capturePropertyVars),this.capturePropertyVars.clear()}}};var Ks=require("obsidian");var z0="\u2190 Back",Vt=class e extends Ks.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(),Ks.MarkdownRenderer.renderMarkdown(l.item.name,G,"",this.plugin),G.classList.add("quickadd-choice-suggestion"),l.item.name===z0&&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===z0;c||G.push(new RZ(z0).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 Us=require("obsidian");var lW=class extends _e{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-02-24 07:55:02 +08:00
QuickAdd will now revert to backup.`),e.settings=G}}e.saveSettings()}var gF=G3;var HZ=require("obsidian");async function e3(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 c3(e,I=1){let l=e.split(`
2026-01-31 08:25:19 +08:00
`);for(let G=0;G<l.length;G++)l[G].startsWith("#")&&(l[G]="#".repeat(I)+l[G]);return l.join(`
2026-02-24 07:55:02 +08:00
`)}var fs=class extends HZ.Modal{constructor(I,l){super(I),this.previousVersion=l,this.releaseNotesPromise=e3("chhoumann","quickadd",l),this.releaseNotesPromise.then(G=>{if(this.releases=G,this.releases.length===0){this.close();return}this.display()}).catch(G=>{x.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}
2026-01-31 08:25:19 +08:00
`,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-02-24 07:55:02 +08:00
${c3(b)}`;HZ.MarkdownRenderer.renderMarkdown(m,t,this.app.vault.getRoot().path,new HZ.Component)}};var zl=require("obsidian");var Ss=class extends zl.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 zl.Setting(l).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(G=>{let c=ec();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 zl.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 zl.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 zl.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,zl.debounce)(()=>{c.innerText=`Token count: ${this.systemPromptTokenLength}`},50);m(),(async()=>Z.innerText=await d.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(l){new zl.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 zl.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 zl.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 */