/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var rY=Object.create;var Yf=Object.defineProperty;var nY=Object.getOwnPropertyDescriptor;var iY=Object.getOwnPropertyNames;var oY=Object.getPrototypeOf,sY=Object.prototype.hasOwnProperty;var vR=r=>{throw TypeError(r)};var aY=(r,t,e)=>t in r?Yf(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var x=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(n){throw e=[n],n}};var cb=(r,t)=>{for(var e in t)Yf(r,e,{get:t[e],enumerable:!0})},yR=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of iY(t))!sY.call(r,i)&&i!==e&&Yf(r,i,{get:()=>t[i],enumerable:!(n=nY(t,i))||n.enumerable});return r};var lY=(r,t,e)=>(e=r!=null?rY(oY(r)):{},yR(t||!r||!r.__esModule?Yf(e,"default",{value:r,enumerable:!0}):e,r)),cY=r=>yR(Yf({},"__esModule",{value:!0}),r);var fe=(r,t,e)=>aY(r,typeof t!="symbol"?t+"":t,e),fk=(r,t,e)=>t.has(r)||vR("Cannot "+e);var L=(r,t,e)=>(fk(r,t,"read from private field"),e?e.call(r):t.get(r)),qe=(r,t,e)=>t.has(r)?vR("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),Oe=(r,t,e,n)=>(fk(r,t,"write to private field"),n?n.call(r,e):t.set(r,e),e),tt=(r,t,e)=>(fk(r,t,"access private method"),e);var oD,sD,aD=x(()=>{oD=r=>{let t,e=new Set,n=(c,d)=>{let u=typeof c=="function"?c(t):c;if(!Object.is(u,t)){let p=t;t=d??(typeof u!="object"||u===null)?u:Object.assign({},t,u),e.forEach(m=>m(t,p))}},i=()=>t,a={setState:n,getState:i,getInitialState:()=>l,subscribe:c=>(e.add(c),()=>e.delete(c))},l=t=r(n,i,a);return a},sD=(r=>r?oD(r):oD)});function Sh(r){if(r.kind)return r.kind;let t=(r.name??"").toLowerCase(),e=cD(r.endpoint),n=i=>e===i||e.endsWith(`.${i}`);return t==="anthropic"||n("api.anthropic.com")?"anthropic":t==="gemini"||n("generativelanguage.googleapis.com")?"gemini":"openai"}function lD(r){let t=Sh(r);return t==="openai"&&cD(r.endpoint)==="api.openai.com"?"openai-responses":t}function cD(r){let t=(r??"").trim();if(!t)return"";for(let e of[t,`https://${t}`])try{return new URL(e).hostname.toLowerCase()}catch{}return""}function $K(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Qb(r,t){let e=$K(r),n=new Set(t.map(o=>o.id).filter(o=>!!o)),i=e;for(let o=2;n.has(i);o++)i=`${e}-${o}`;return i}function Xb(r){let t=!1,e=new Set;for(let n of r){if(n.id&&!e.has(n.id)){e.add(n.id);continue}n.id=Qb(n.id??n.name,r),e.add(n.id),t=!0}return t}function Nl(r,t){return t&&t.name===r?t:void 0}function lp(r){return r.map((t,e)=>({model:t,index:e})).sort((t,e)=>{let n=+!!t.model.deprecated-+!!e.model.deprecated;if(n!==0)return n;let i=t.model.releaseDate??"",o=e.model.releaseDate??"";return i!==o?i?o&&it)}function Jb(r){return Ah[r].map(t=>({...t}))}var Ah,dD,FK,MK,Zb,gi=x(()=>{Ah={openai:[{name:"gpt-6-sol",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-6-luna",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-6-astra",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.6-sol",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.6-luna",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.6-terra",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.5",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.4",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!0},{name:"gpt-5.4-mini",maxTokens:4e5,maxOutputTokens:128e3,supportsTemperature:!0},{name:"gpt-5.4-nano",maxTokens:4e5,maxOutputTokens:128e3,supportsTemperature:!0},{name:"gpt-4.1",maxTokens:1047576,maxOutputTokens:32768,supportsTemperature:!0},{name:"gpt-4.1-mini",maxTokens:1047576,maxOutputTokens:32768,supportsTemperature:!0},{name:"gpt-4o",maxTokens:128e3,maxOutputTokens:16384,supportsTemperature:!0},{name:"gpt-4o-mini",maxTokens:128e3,maxOutputTokens:16384,supportsTemperature:!0},{name:"o3",maxTokens:2e5,maxOutputTokens:1e5,supportsTemperature:!1},{name:"o4-mini",maxTokens:2e5,maxOutputTokens:1e5,supportsTemperature:!1}],google:[{name:"gemini-3.8-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.7-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.6-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.5-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.5-flash-lite",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.1-pro-preview",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.1-flash-lite",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3-flash-preview",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-2.5-pro",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-2.5-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-2.5-flash-lite",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0}],anthropic:[{name:"claude-opus-5-5",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-fable-5-1",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-fable-5",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-sonnet-5",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-opus-4-8",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-opus-4-5",maxTokens:2e5,maxOutputTokens:64e3,supportsTemperature:!0},{name:"claude-haiku-4-5",maxTokens:2e5,maxOutputTokens:64e3,supportsTemperature:!0}]},dD={openai:["gpt-4-32k","gpt-4-1106-preview"],google:["gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"]};FK={id:"openai",name:"OpenAI",endpoint:"https://api.openai.com/v1",kind:"openai",apiKey:"",models:Jb("openai"),autoSyncModels:!0,modelSource:"modelsDev"},MK={id:"gemini",name:"Gemini",endpoint:"https://generativelanguage.googleapis.com",kind:"gemini",apiKey:"",models:Jb("google"),autoSyncModels:!0,modelSource:"modelsDev"},Zb=[FK,MK]});function uD(r,t){return Object.prototype.hasOwnProperty.call(r,t)?r[t]:void 0}function Ih(r,t=cp){let e=r.trim();if(!e)return r;let n=uD(t,e.toLowerCase());if(n)return n;let[i,...o]=e.split(/\s+/),s=uD(t,i.toLowerCase());return s?[s,...o].join(" "):r}function pD(r){let t={},e=r.split(/\r?\n/);for(let n of e){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o===-1)continue;let s=i.slice(0,o).trim().toLowerCase(),a=i.slice(o+1).trim();!s||!a||Object.defineProperty(t,s,{value:a,enumerable:!0,writable:!0,configurable:!0})}return t}function yS(r){return Object.entries(r).filter(([t,e])=>t&&e).map(([t,e])=>`${t} = ${e}`).join(` `)}function Ph(r){let t=Object.entries(r);if(t.length===0)return[];let n=["t","tm","yd"].map(s=>{let a=r[s];return a?[s,a]:null}).filter(s=>s!==null),i=new Set(n.map(([s])=>s)),o=t.filter(([s])=>!i.has(s)).sort((s,a)=>{let l=s[0].length-a[0].length;return l!==0?l:s[0].localeCompare(a[0])});return[...n,...o]}function ew(r){return Ph(r).map(([t,e])=>`${t}=${e}`).join(", ")}var cp,wd=x(()=>{cp={t:"today",tm:"tomorrow",yd:"yesterday",nw:"next week",nm:"next month",ny:"next year",lw:"last week",lm:"last month",ly:"last year"}});var tw,bS=x(()=>{gi();wd();tw={choices:[],inputPrompt:"single-line",persistInputPromptDrafts:!0,useSelectionAsCaptureValue:!0,namePastedImagesAfterNoteTitle:!1,searchNestedChoices:!0,templateFolderLauncherRow:"bottom",devMode:!1,templateFolderPaths:[],announceUpdates:"major",version:"0.0.0",globalVariables:{},onePageInputEnabled:!1,disableOnlineFeatures:!0,enableUriCallbacks:!1,enableRibbonIcon:!1,showCaptureNotification:!0,showInputCancellationNotification:!1,enableTemplatePropertyTypes:!1,dateAliases:cp,showDateCalendar:!0,ai:{defaultModel:"Ask me",defaultSystemPrompt:'As an AI assistant within Obsidian, your primary goal is to help users manage their ideas and knowledge more effectively. Format your responses using Markdown syntax. Please use the [[Obsidian]] link format. You can write aliases for the links by writing [[Obsidian|the alias after the pipe symbol]]. To use mathematical notation, use LaTeX syntax. LaTeX syntax for larger equations should be on separate lines, surrounded with double dollar signs ($$). You can also inline math expressions by wrapping it in $ symbols. For example, use $$w_{ij}^{\\text{new}}:=w_{ij}^{\\text{current}}+\\eta\\cdot\\delta_j\\cdot x_{ij}$$ on a separate line, but you can write "($\\eta$ = learning rate, $\\delta_j$ = error term, $x_{ij}$ = input)" inline.',promptTemplatesFolderPath:"",showAssistant:!0,providers:Zb,confirmToolCalls:"destructive"},migrations:{useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,consolidateFileExistsBehavior:!1,repairTemplateFileExistsBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1,migrateToMultipleTemplateFolders:!1,refreshStaleDefaultModelSeeds:!1,pinAiModelRefs:!1}}});function ke(r){if(typeof structuredClone=="function")try{return structuredClone(r)}catch{}return Vl(r,new Map)}function Vl(r,t){if(r===null||typeof r!="object")return r;if(t.has(r))return t.get(r);if(r instanceof Date){let i=new Date(r.getTime());return t.set(r,i),i}if(Array.isArray(r)){let i=[];t.set(r,i);for(let o of r)i.push(Vl(o,t));return i}if(r instanceof Map){let i=new Map;t.set(r,i);for(let[o,s]of r.entries())i.set(Vl(o,t),Vl(s,t));return i}if(r instanceof Set){let i=new Set;t.set(r,i);for(let o of r.values())i.add(Vl(o,t));return i}if(r instanceof RegExp){let i=new RegExp(r.source,r.flags);return i.lastIndex=r.lastIndex,t.set(r,i),i}if(r instanceof ArrayBuffer){let i=r.slice(0);return t.set(r,i),i}if(ArrayBuffer.isView(r)){if(r instanceof DataView){let a=new DataView(Vl(r.buffer,t),r.byteOffset,r.byteLength);return t.set(r,a),a}let i=r,o=Vl(i.buffer,t),s=new i.constructor(o,i.byteOffset,i.length);return t.set(r,s),s}let e=Object.getPrototypeOf(r),n=Object.create(e);t.set(r,n);for(let[i,o]of Object.entries(r))Object.defineProperty(n,i,{value:Vl(o,t),writable:!0,enumerable:!0,configurable:!0});return n}var tn=x(()=>{});var U,je=x(()=>{aD();bS();tn();U=(()=>{let r=sD((i,o)=>({...ke(tw)})),{getState:t,setState:e,subscribe:n}=r;return{getState:t,replaceState:i=>e(i,!0),setState:e,subscribe:n}})()});var Cd,$h,S,ye=x(()=>{Cd=class Cd{register(t){return Cd.loggers.push(t),this}logError(t){let e=t instanceof Error?t.message:t,n=t instanceof Error?t.stack:void 0,i=t instanceof Error?t:void 0;Cd.loggers.forEach(o=>o.logError(e,n,i))}logWarning(t){let e=t instanceof Error?t.message:t,n=t instanceof Error?t.stack:void 0,i=t instanceof Error?t:void 0;Cd.loggers.forEach(o=>o.logWarning(e,n,i))}logMessage(t){let e=t instanceof Error?t.message:t,n=t instanceof Error?t.stack:void 0,i=t instanceof Error?t:void 0;Cd.loggers.forEach(o=>o.logMessage(e,n,i))}};Cd.loggers=[];$h=Cd,S=new $h});var xr,mD,fD,Vi,xd,Ed,Yo,hD,wS,gD,CS,fo,Td,Bl,dp,rw,Ss,xS,ES,xt,lr,Rn,Fh,nw,As,iw,Mh,ho,Rh,Oh,TS,_S,vD,yD,bD,wD,CD,xD,ED,TD,_D,kD,SD,kS,AD,ID,PD,$D,FD,MD,RD,OD,DD,LD,ND,SS,AS,IS,PS,$S,VD,BD,UD,qD,ow,Dh,Sa,zD,Le=x(()=>{xr="{{value}}",mD="{{name}}",fD=new RegExp(/^-?[0-9]*$/),Vi="top",xd="bottom",Ed="cursor",Yo="ordered",hD=new RegExp(/{{DATE(\+-?[0-9]+)?(?:\|((?:startof|endof):[a-z]+))?(?:\|case:([a-z-]+))?}}/i),wS=new RegExp(/{{DATE:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|[]|\|(?!(?:startof|endof):[a-z])(?!(?:case):[a-z-]+}}))*)(\+-?[0-9]+)?(?:\|((?:startof|endof):[a-z]+))?(?:\|case:([a-z-]+))?}}/i),gD=new RegExp(/{{TIME(?:\|case:([a-z-]+))?}}/i),CS=new RegExp(/{{TIME:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|[]|\|(?!(?:case):[a-z-]+}}))*)(?:\|case:([a-z-]+))?}}/i),fo=new RegExp(/{{(?:NAME|VALUE)(?!:)(?:\|[^\n\r}]*)?}}/i),Td=new RegExp(/{{VALUE:([^\n\r}]*)}}/i),Bl="FIELD:",dp=new RegExp(/{{FIELD:([^\n\r}|{]*)(\|[^\n\r}{]*)?}}/i),rw=new RegExp(/{{FILE:([^\n\r{}]*)}}/i),Ss=new RegExp(/{{VDATE:([^\n\r},|{]*)(?:,([^\n\r}|{]*))?(?:\|([^\n\r}{]*))?}}/i),xS=new RegExp(/{{LINKCURRENT}}/i),ES=new RegExp(/{{LINKSECTION}}/i),xt=new RegExp(/\.md$/i),lr=new RegExp(/\.canvas$/i),Rn=new RegExp(/\.base$/i),Fh=new RegExp(/\.js$/i),nw=new RegExp(/{{MACRO:([^\n\r}]*)}}/i),As=new RegExp(/{{TEMPLATE:([^\n\r}]*\.(?:md|canvas|base))}}/i),iw=new RegExp(/{{GLOBAL_VAR:([^\n\r}]*)}}/i),Mh=new RegExp(/{{MVALUE}}/i),ho=new RegExp(/{{TITLE}}/i),Rh=new RegExp(/{{PROPERTY}}/i),Oh=new RegExp(/{{SELECTED}}/i),TS=new RegExp(/{{CLIPBOARD}}/i),_S=new RegExp(/{{RANDOM:(\d+)}}/i),vD=new RegExp(/\[\[([^\]]*)$/),yD=new RegExp(/#([^ ]*)$/),bD=new RegExp(/{{[D]?[A]?[T]?[E]?[}]?[}]?$/i),wD=new RegExp(/{{[D]?[A]?[T]?[E]?[:]?$|{{DATE:[^\n\r}]*}}$/i),CD=new RegExp(/{{[N]?[A]?[M]?[E]?[}]?[}]?$/i),xD=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[}]?[}]?$/i),ED=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[:]?$|{{VALUE:[^\n\r}]*}}$/i),TD=new RegExp(/{{[V]?[D]?[A]?[T]?[E]?[:]?$|{{VDATE:[^\n\r}]*}}$/i),_D=new RegExp(/{{[L]?[I]?[N]?[K]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),kD=new RegExp(/^\{\{(?:l(?:i(?:n(?:k(?:s(?:e(?:c(?:t(?:i(?:o(?:n(?:\}\}?)?)?)?)?)?)?)?)?)?)?)?)?$/i),SD=new RegExp(/{{[F]?[I]?[L]?[E]?[N]?[A]?[M]?[E]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),kS=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),AD=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[}]?[}]?$/i),ID=new RegExp(/{{[F]?[I]?[L]?[E]?[:]?$/i),PD=new RegExp(/{{[F]?[I]?[E]?[L]?[D]?[:]?$/i),$D=new RegExp(/{{[T]?[E]?[M]?[P]?[L]?[A]?[T]?[E]?[:]?$|{{TEMPLATE:[^\n\r}]*[}]?[}]?$/i),FD=new RegExp(/{{[M]?[A]?[C]?[R]?[O]?[:]?$|{{MACRO:[^\n\r}]*}}$/i),MD=new RegExp(/{{[M]?[V]?[A]?[L]?[U]?[E]?[}]?[}]?/i),RD=new RegExp(/{{[T]?[I]?[T]?[L]?[E]?[}]?[}]?/i),OD=new RegExp(/{{[P]?[R]?[O]?[P]?[E]?[R]?[T]?[Y]?[}]?[}]?$/i),DD=/{{(?:C(?:U(?:R(?:S(?:O(?:R)?)?)?)?)?)?[}]?[}]?$/i,LD=new RegExp(/{{[S]?[E]?[L]?[E]?[C]?[T]?[E]?[D]?[}]?[}]?/i),ND=new RegExp(/{{[C]?[L]?[I]?[P]?[B]?[O]?[A]?[R]?[D]?[}]?[}]?$/i),SS=new RegExp(/{{[D]?[A]?[I]?[L]?[Y]?[}]?[}]?$|{{DAILY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),AS=new RegExp(/{{[W]?[E]?[E]?[K]?[L]?[Y]?[}]?[}]?$|{{WEEKLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),IS=new RegExp(/{{[M]?[O]?[N]?[T]?[H]?[L]?[Y]?[}]?[}]?$|{{MONTHLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),PS=new RegExp(/{{[Q]?[U]?[A]?[R]?[T]?[E]?[R]?[L]?[Y]?[}]?[}]?$|{{QUARTERLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),$S=new RegExp(/{{[Y]?[E]?[A]?[R]?[L]?[Y]?[}]?[}]?$|{{YEARLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),VD=new RegExp(/{{[R]?[A]?[N]?[D]?[O]?[M]?[:]?$|{{RANDOM:[^\n\r}]*}}$/i),BD=new RegExp(/{{[G]?[L]?[O]?[B]?[A]?[L]?[_]?[V]?[A]?[R]?[:]?$|{{GLOBAL_VAR:[^\n\r}]*}}$/i),UD=new RegExp(/{{[T]?[I]?[M]?[E]?[}]?[}]?/i),qD=new RegExp(/{{[T]?[I]?[M]?[E]?[:]?$|{{TIME:[^\n\r}]*}}$/i),ow="__qa.",Dh=`${ow}captureTargetFilePath`,Sa=`${ow}dateOrigin`,zD=new RegExp(/\[\[([^\]]*)\]\]/)});function jD(r){return typeof r=="string"?r:""}function go(r){return jD(r).replace(/^\s+(?=[\\/])/,"").replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"").trimEnd().replace(/\/$/,"").normalize("NFC")}function cr(r){return jD(r).trim().replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"").normalize("NFC")}function Is(r){return((0,RS.normalizePath)(r).split("/").pop()??"").replace(/\.(md|canvas|base)$/i,"")}function ei(r){let t=(0,RS.normalizePath)(r),e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}var RS,Dr=x(()=>{RS=require("obsidian")});function Ps(r){return xt.test(r)||lr.test(r)||Rn.test(r)}function nn(r,t){let e=En(t);if(!e)return null;let n=r.vault.getAbstractFileByPath(e);return n instanceof YD.TFile?n:null}function En(r){let t=cr(r);return t?Ps(t)?t:`${t}.md`:""}function ti(r){if(!Array.isArray(r))return[];let t=new Set,e=[];for(let n of r){if(typeof n!="string")continue;let i=cr(n);!i||t.has(i)||(t.add(i),e.push(i))}return e}function KD(r,t){return t.length===0?!0:t.some(e=>r===e||r.startsWith(`${e}/`))}var YD,Jt=x(()=>{YD=require("obsidian");Le();Dr()});function Aa(r){return/\{\{[^}]*\}\}/.test(r)}var Nh=x(()=>{});function Bi(r){if(r.nodeType===Node.DOCUMENT_NODE)return r;let t=r.ownerDocument;if(!t)throw new Error("Unable to resolve owner document for DOM node.");return t}function Vh(r){let t=Bi(r).defaultView;if(!t)throw new Error("Unable to resolve owner window for DOM node.");return t}function At(r,t){return Bi(r).win.createEl(t)}function _d(r,t){return Bi(r).createTextNode(t)}var Ko=x(()=>{});var sw=x(()=>{});var at,ri=x(()=>{at=class extends Error{constructor(t){super(t||"Macro execution aborted"),this.name="MacroAbortError"}}});function on(){return new et(ql)}var et,ql,rr=x(()=>{ri();et=class extends at{},ql="Input cancelled by user"});function Ia(r,t){if(r instanceof Error){if(!t)return r;let n=new Error(`${t}: ${r.message}`);return n.name=r.name,n.stack=r.stack,n}let e=t?`${t}: ${String(r)}`:String(r);return new Error(e)}function Be(r){return r instanceof et?!0:typeof r=="string"&&DK.has(r)}function LS(r){return typeof r=="object"&&r!==null||typeof r=="function"}function VK(r,t){let e=r;for(let n=0;n{kd(n,r)};return(...n)=>{try{let i=t(...n);typeof i?.then=="function"&&Promise.resolve(i).catch(e)}catch(i){e(i)}}}function ZD(r){let t=r.then(void 0,e=>{throw Be(e)&&t.catch(()=>{}),e});return t}var OS,DK,DS,LK,NK,nt=x(()=>{ye();sw();rr();OS=100;DK=new Set(["no input given.","No input given.","cancelled"]),DS=new WeakMap,LK=1e4,NK=8});function e0(r,t){return BK.test(r[t])}function UK(r){if(!r.includes("![["))return r;let t="",e=0,n=0,i=0;for(;nt&&r.charCodeAt(e-1)===35){for(;e>t&&r.charCodeAt(e-1)===35;)e--;for(;e>t&&e0(r,e-1);)e--}return r.slice(t,e)}function HK(r){if(!r.includes("[[")&&!r.includes("]]"))return r;let t="",e=0,n=0;for(;n{BK=/^\s$/;WK=/[*_`~]/g});function sn(r){return typeof r=="string"?r:r==null?"":String(r)}function r0(r,t){r.scope?.register(["Mod","Shift"],"Enter",()=>(t(),!1)),typeof r.setInstructions=="function"&&r.setInstructions([{command:"\u2191\u2193",purpose:"to navigate"},{command:"\u21B5",purpose:"to choose"},{command:"ctrl/cmd+shift+\u21B5",purpose:"to skip (leave empty)"},{command:"esc",purpose:"to cancel"}]);let e=r.modalEl;if(e&&typeof e.createDiv=="function"){let i=e.createDiv({cls:"qa-suggester-skip-bar"}).createEl("button",{text:"Skip (leave empty)",cls:"qa-suggester-skip-button"});i.type="button",i.setAttribute("aria-label","Skip and leave empty"),i.addEventListener("click",o=>{o.preventDefault(),t()})}}function pp(r){let t=!1;return e=>{t||(t=!0,S.logWarning(Ia(e,r)))}}function zl(r){return sn(r)}function Ht(r){return r.normalize("NFC").toLowerCase()}function aw(r){return r.toLowerCase().endsWith(".md")?r.slice(0,-3):r}function lw(r,t,e,n,i={}){let o=r.value;r.value=o.slice(0,t)+n+o.slice(e),r.setSelectionRange(t+n.length,t+n.length);let s=new Event("input",{bubbles:!0});i.fromCompletion&&(s.fromCompletion=!0),r.dispatchEvent(s)}function n0(r,t,e){if(r.replaceChildren(),!e){r.textContent=t;return}let n="",i=[],o=[],s=0;for(let u of t){let p=u.toLowerCase(),m=s,h=s+u.length;for(let g=0;gu){u>l&&r.append(_d(r,t.slice(l,u)));let m=At(r,"mark");m.className="qa-highlight",m.textContent=t.slice(u,p),r.append(m),l=p}c=d+a.length,d=n.indexOf(a,c)}li&&r.append(_d(r,t.slice(i,a)));let c=At(r,"mark");c.className="qa-highlight",c.textContent=t.slice(a,l),r.append(c),i=l}i{ye();Ko();nt();t0()});function YK(r,t,e){let n=r.closest(".modal")?.querySelector(".qa-prompt-actions");if(!n)return!1;let i=n.getBoundingClientRect(),o=i.height>0&&i.top>=t.bottom,s=t.bottom+Uh+e>i.top;return o&&s}function KK(r,t){let e=r.getBoundingClientRect(),n=r.ownerDocument,i=n.defaultView?.visualViewport??{offsetLeft:0,offsetTop:0,width:n.documentElement.clientWidth,height:n.documentElement.clientHeight},o=Math.max(e.width,Math.min(jK,i.width));t.setCssStyles({maxHeight:"",width:`${o}px`,left:"0px",top:"0px"});let s=t.getBoundingClientRect(),a=parseFloat(getComputedStyle(n.documentElement).getPropertyValue("--keyboard-height"))||0,l=Math.min(i.offsetTop+i.height,n.documentElement.clientHeight-a),c=parseFloat(getComputedStyle(n.body).getPropertyValue("--safe-area-inset-top"))||0,d=r.closest(".modal.mod-settings")?.querySelector(".modal-header"),u=Math.max(i.offsetTop+c,d?.getBoundingClientRect().bottom??0),p=l-e.bottom-Uh,m=e.top-Uh-u,h=s.height<=p,v=s.height<=m?!h||YK(r,e,s.height):!h&&m>p,b=Math.min(s.height,v?m:p),y=v?e.top-Uh-b:e.bottom+Uh,C=Math.max(i.offsetLeft,Math.min(e.left,i.offsetLeft+i.width-o));t.setCssStyles({maxHeight:be.nodeName==="MARK"?Array.from(e.childNodes):[e]).filter(e=>e.nodeType===Node.TEXT_NODE&&!!e.nodeValue?.includes("/"));for(let e of t){let n=(e.nodeValue??"").match(/[^/]*\/|[^/]+$/g)??[];e.replaceWith(...n.flatMap(i=>i.endsWith("/")?[i,At(r,"wbr")]:[i]))}}var cw,GK,Uh,jK,XK,VS,Bh,Er,Ms=x(()=>{cw=require("obsidian");ye();Ko();an();GK=(r,t)=>(r%t+t)%t,Uh=4,jK=300;XK=0,VS=class{constructor(t,e,n,i,o){this.isOpen=!1;this.owner=t,this.containerEl=e,this.optionIdPrefix=i,this.onActiveOptionChange=o,this.clickListener=a=>{let l=this.findSuggestionItem(a.target);l&&this.onSuggestionClick(a,l)},this.mousemoveListener=a=>{let l=this.findSuggestionItem(a.target);l&&this.onSuggestionMouseover(a,l)},e.addEventListener("click",this.clickListener),e.addEventListener("mousemove",this.mousemoveListener);let s={ArrowUp:()=>this.selectedItem-1,ArrowDown:()=>this.selectedItem+1,PageUp:()=>Math.max(0,this.selectedItem-5),PageDown:()=>Math.min(this.suggestions.length-1,this.selectedItem+5)};for(let[a,l]of Object.entries(s))n.register([],a,c=>{if(!c.isComposing&&this.isOpen)return this.setSelectedItem(l(),!0),!1})}findSuggestionItem(t){let e=this.containerEl.ownerDocument.defaultView;if(!e||!(t instanceof e.Element))return null;let n=t.closest(".suggestion-item");return n&&this.containerEl.contains(n)?n:null}onSuggestionClick(t,e){t.preventDefault();let n=this.suggestions.indexOf(e);this.setSelectedItem(n,!1),this.useSelectedItem(t)}onSuggestionMouseover(t,e){let n=this.suggestions.indexOf(e);this.setSelectedItem(n,!1)}setSuggestions(t){this.containerEl.replaceChildren();let e=[];if(t.forEach((n,i)=>{let o=this.containerEl.createDiv({cls:"suggestion-item"});o.setAttribute("role","option"),o.setAttribute("aria-selected","false"),o.setAttribute("id",`${this.optionIdPrefix}-option-${i}`),this.owner.renderSuggestion(n,o),QK(o),e.push(o)}),this.values=t,this.suggestions=e,t.length===0){this.isOpen=!1,this.onActiveOptionChange(null);return}this.setSelectedItem(0,!1),this.isOpen=!0}useSelectedItem(t){let e=this.values[this.selectedItem];e&&this.owner.selectSuggestion(e,t)}setSelectedItem(t,e){if(!this.suggestions?.length)return;let n=GK(t,this.suggestions.length),i=this.suggestions[this.selectedItem],o=this.suggestions[n];i?.classList.remove("is-selected"),o?.classList.add("is-selected"),i?.setAttribute("aria-selected","false"),o?.setAttribute("aria-selected","true"),this.onActiveOptionChange(o?.id??null),this.selectedItem=n,e&&o.scrollIntoView(!1)}close(){this.isOpen=!1,this.onActiveOptionChange(null)}getIsOpen(){return this.isOpen}},Bh=new WeakMap,Er=class{constructor(t,e,n){this.currentRequestId=0;this.isOpen=!1;this.destroyed=!1;this.currentQuery="";this.listQuery=null;this.renderMatch=n0;let i=this.constructor.name,o=Bh.get(e);o||(o=new Map,Bh.set(e,o));let s=o.get(i);s&&s.destroy(),Bh.set(e,o),o.set(i,this),this.app=t,this.inputEl=e,this.scope=new cw.Scope(n),this.suggestEl=this.inputEl.ownerDocument.win.createDiv(),this.suggestEl.classList.add("suggestion-container","qa-text-input-suggest");let a=this.suggestEl.createDiv({cls:"suggestion"});this.listboxId=`qa-suggest-listbox-${++XK}`,a.id=this.listboxId,a.setAttribute("role","listbox"),a.setAttribute("aria-label","Suggestions"),this.suggest=new VS(this,a,this.scope,this.listboxId,l=>this.setActiveDescendant(l)),this.scope.register([],"Escape",this.close.bind(this)),this.scope.register([],"Enter",l=>{if(!(l.isComposing||!this.suggest.getIsOpen()))return this.useSelectedItem(l),!1}),this.debouncedOnInputChanged=(0,cw.debounce)(this.onInputChanged.bind(this),50),this.inputEventListener=l=>this.debouncedOnInputChanged(l),this.focusEventListener=()=>this.debouncedOnInputChanged(),this.inputBlurListener=this.close.bind(this),this.inputEl.addEventListener("input",this.inputEventListener),this.inputEl.addEventListener("focus",this.focusEventListener),this.inputEl.addEventListener("blur",this.inputBlurListener),this.inputEl.setAttribute("role","combobox"),this.inputEl.setAttribute("aria-autocomplete","list"),this.inputEl.setAttribute("aria-expanded","false"),this.inputEl.setAttribute("aria-controls",this.listboxId),this.inputEl.setAttribute("aria-haspopup","listbox"),this.suggestEl.addEventListener("mousedown",l=>{l.preventDefault()}),this.globalClickListener=this.onGlobalClick.bind(this),this.globalWheelListener=this.onGlobalWheel.bind(this),this.globalScrollListener=l=>{this.suggestEl.contains(l.target)||this.reposition()},this.globalResizeListener=this.close.bind(this),this.globalKeyboardListener=this.reposition.bind(this),this.globalBlurListener=this.close.bind(this)}onGlobalClick(t){if(!this.isOpen)return;let e=t.target;!this.suggestEl.contains(e)&&!this.inputEl.contains(e)&&this.close()}onGlobalWheel(t){if(!this.isOpen)return;let e=t.target;this.suggestEl.contains(e)||this.close()}async onInputChanged(t){if(this.destroyed||this.inputEl.closest("[hidden]")||this.inputEl.ownerDocument.activeElement!==this.inputEl)return;let e=!!(t?.fromCompletion&&t.keepOpen);if(t?.fromCompletion&&!e)return;let n=this.inputEl.value,i=++this.currentRequestId;this.currentQuery=n;try{let o=await this.getSuggestions(n);if(i!==this.currentRequestId)return;if(!o?.length){(e||this.isOpen)&&this.close();return}this.suggest.setSuggestions(o),this.listQuery=n,e&&this.isOpen?this.reposition():this.open(this.app.dom.appContainerEl,this.inputEl)}catch(o){S.logError(o),e||this.close()}}async useSelectedItem(t){this.inputEl.value!==this.listQuery&&(this.debouncedOnInputChanged.cancel(),await this.onInputChanged(),this.inputEl.value!==this.listQuery||!this.suggest.getIsOpen())||this.suggest.useSelectedItem(t)}open(t,e){if(this.destroyed||e.closest("[hidden]"))return;let n=!this.isOpen;n&&this.app.keymap.pushScope(this.scope),this.isOpen=!0,this.inputEl.setAttribute("aria-expanded","true"),this.inputEl.setAttribute("aria-controls",this.listboxId);let i=Bi(e);if((Bi(t)===i?t:i.body).appendChild(this.suggestEl),this.reposition(),!n)return;let a=Vh(e);i.addEventListener("pointerdown",this.globalClickListener,!0),i.addEventListener("wheel",this.globalWheelListener,!0),i.addEventListener("scroll",this.globalScrollListener,!0),a.addEventListener("resize",this.globalResizeListener),a.addEventListener("keyboardDidShow",this.globalKeyboardListener),a.addEventListener("blur",this.globalBlurListener)}reposition(){KK(this.inputEl,this.suggestEl)}close(){if(this.currentRequestId++,!this.isOpen)return;this.app.keymap.popScope(this.scope),this.isOpen=!1,this.inputEl.setAttribute("aria-expanded","false"),this.setActiveDescendant(null),this.suggest.close(),this.suggest.setSuggestions([]),this.suggestEl.remove();let t=Bi(this.inputEl),e=Vh(this.inputEl);t.removeEventListener("pointerdown",this.globalClickListener,!0),t.removeEventListener("wheel",this.globalWheelListener,!0),t.removeEventListener("scroll",this.globalScrollListener,!0),e.removeEventListener("resize",this.globalResizeListener),e.removeEventListener("keyboardDidShow",this.globalKeyboardListener),e.removeEventListener("blur",this.globalBlurListener)}destroy(){this.destroyed=!0,this.close(),this.inputEl.removeEventListener("input",this.inputEventListener),this.inputEl.removeEventListener("focus",this.focusEventListener),this.inputEl.removeEventListener("blur",this.inputBlurListener);let t=this.constructor.name,e=Bh.get(this.inputEl);e&&(e.delete(t),e.size===0&&Bh.delete(this.inputEl))}setActiveDescendant(t){if(t){this.inputEl.setAttribute("aria-activedescendant",t);return}this.inputEl.removeAttribute("aria-activedescendant")}getCurrentQuery(){return this.currentQuery}}});function Wt(r){return Array.isArray(r)||r==null?!1:typeof r=="object"?Object.keys(r).length>0:!!r}var qh=x(()=>{});function Vt(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let r=crypto.getRandomValues(new Uint8Array(16));r[6]=r[6]&15|64,r[8]=r[8]&63|128;let t=Array.from(r,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Qo=x(()=>{});function dw(r){return Ee(r)&&r.type==="Multi"}function Ee(r){return typeof r=="object"&&r!==null}function Ne(r){return dw(r)?Array.isArray(r.choices)?r.choices:[]:[]}function $a(r){return dw(r)&&Array.isArray(r.choices)}function mp(r){if(!Array.isArray(r))return!0;let t=e=>e.some(n=>{if(Array.isArray(n))return!0;if(!Ee(n)||n.type!=="Multi")return!1;let i=n.choices;return Array.isArray(i)?t(i):Wt(i)});return t(r)}function mr(r){return Array.isArray(r)?r:[]}function vo(r){return dw(r)?Wt(r.choices):!1}function fp(r){switch(r){case"Template":return"file-text";case"Capture":return"pencil";case"Macro":return"terminal";case"Multi":return"folder";default:return"file-plus"}}function Sd(r){return(typeof r.icon=="string"?r.icon.trim():"")||fp(r.type)}function Zt(r){let t=[],e=n=>{Ee(n)&&(t.push(n),Ne(n).forEach(e))};return mr(r).forEach(e),t}function i0(r){let t=new Map,e=n=>{let i=[];for(let o of n){if(!Ee(o)){i.push(o);continue}let s=o,a=t.get(s.id);if(a){if(JSON.stringify(s)===JSON.stringify(a))continue;s={...s,id:Vt()}}t.set(s.id,s),dw(s)&&Array.isArray(s.choices)&&(s={...s,choices:e(s.choices)}),i.push(s)}return i};return e(r)}function uw(r){let t=r.type==="Capture"?r.format:r.type==="Template"?r.fileNameFormat:void 0;if(!t||typeof t!="object")return;let e=t,n=typeof e.format=="string"?e.format:"";e.enabled===!0&&n.trim()===""&&(e.enabled=!1)}function o0(r){if(!Array.isArray(r))return{choices:[],changed:!1,repaired:[]};let t=new Set,e=[],n=o=>{let s=!1,a=[];for(let l of o){if(Array.isArray(l)){s=!0,a.push(...n(l));continue}if(!Ee(l)){s=!0;continue}let c=l;if($a(c)){let p=c.choices,m=n(p);m!==p&&(c={...c,choices:m},s=!0)}let d=c.id;if(typeof d=="string"&&d!==""&&!t.has(d)){t.add(d),a.push(c);continue}let u={...c,id:Vt()};t.add(u.id),e.push({previousId:d,choice:u}),a.push(u),s=!0}return s?a:o},i=n(r);return{choices:i,changed:i!==r,repaired:e}}function Ad(r,t=[],e=0,n=null){let i=[];for(let o of mr(r)){if(!Ee(o))continue;let s=[...t,o.name];i.push({choice:o,id:o.id,path:s,depth:e,parentId:n}),i.push(...Ad(Ne(o),s,e+1,o.id))}return i}var lt=x(()=>{qh();Qo();qh()});function BS(r,t,e=[]){let n=r(t),i;for(let o of e){let s=r(o);s&&(!n||s.score>n.score)&&(n=s,i=o)}return n?i===void 0?{result:n}:{result:n,alias:i}:null}function Hl(r,t,e,n){let i=r.trim();if(!i)return t.slice(0,n.limit).map(a=>({item:a,matches:[]}));let o=(0,u0.prepareFuzzySearch)(i),s=[];for(let a of t){let l=e(a),c=BS(o,l,n.aliases?.(a));if(!c)continue;let{result:d,alias:u}=c,p=d.matches;if(n.caseSensitive){let m=l.indexOf(i);if(m<0)continue;p=[[m,m+i.length]]}s.push({item:a,matches:p,score:d.score,...u!==void 0?{alias:u}:{}})}return s.sort((a,l)=>l.score-a.score).slice(0,n.limit).map(({score:a,...l})=>l)}var u0,hp=x(()=>{u0=require("obsidian")});function vQ(r,t,e,n={}){let i=n.tab??" ";if(t===e){let u=t+i.length;return{regionStart:t,regionEnd:t,replacement:i,selectionStart:u,selectionEnd:u}}let o=t===0?0:r.lastIndexOf(` `,t-1)+1,a=r.slice(o,e).split(` `),l=a.length-1,c=0,d=a.map((u,p)=>p===l&&u===""?u:(c+=i.length,i+u));return{regionStart:o,regionEnd:e,replacement:d.join(` `),selectionStart:t+i.length,selectionEnd:e+c}}function yQ(r,t){r.setSelectionRange(t.regionStart,t.regionEnd);let e=r.ownerDocument,n=!1;try{n=typeof e.execCommand=="function"&&e.execCommand("insertText",!1,t.replacement)}catch{n=!1}if(!n){let i=r.value;r.value=i.slice(0,t.regionStart)+t.replacement+i.slice(t.regionEnd),r.setSelectionRange(t.selectionStart,t.selectionEnd),r.dispatchEvent(new Event("input",{bubbles:!0}));return}r.setSelectionRange(t.selectionStart,t.selectionEnd)}function zh(r,t={}){let e=t.passThroughUntilUsed??!1,n=!e,i=()=>{n=!e},o=()=>{n=!0},s=l=>{if(l.key!=="Tab"){gQ.has(l.key)||(n=!0);return}if(!n||l.shiftKey||l.ctrlKey||l.metaKey||l.altKey||l.isComposing||l.defaultPrevented)return;l.preventDefault();let c=r.selectionStart??r.value.length,d=r.selectionEnd??c;yQ(r,vQ(r.value,c,d,t))};r.addEventListener("keydown",s),r.addEventListener("focus",i),r.addEventListener("pointerup",o),r.addEventListener("input",o);let a=!1;return()=>{a||(a=!0,r.removeEventListener("keydown",s),r.removeEventListener("focus",i),r.removeEventListener("pointerup",o),r.removeEventListener("input",o))}}function pw(r){return{destroy:zh(r,{passThroughUntilUsed:!0})}}var gQ,Hh=x(()=>{gQ=new Set(["Shift","Control","Alt","Meta"])});function On(r){return r.replace(/\{\{CURSOR\}\}/gi,"")}function gp(r){let t=/\{\{CURSOR\}\}/i.exec(r);return r=On(r),{content:r,cursor:/^[ \t\r\n\f\v]*$/.test(r)?{kind:"none"}:{kind:"offset",value:t?.index??r.length,source:t?"marker":"defaultEnd"}}}function Fa(r,t,e=""){return{content:t+r.content+e,cursor:r.cursor.kind==="none"?r.cursor:{...r.cursor,value:t.length+r.cursor.value}}}function Wl(r,t,e){return{content:t,cursor:r.cursor.kind==="none"||e===null?{kind:"none"}:{...r.cursor,value:e}}}var Ma=x(()=>{});function SQ(r){return TQ.test(r.trim())}function AQ(r){let t=r.replace(_Q,"");return t===r?!1:!kQ.test(t)}function mw(r,t){return xQ.has(r)?AQ(t):SQ(t)}function fw(r){return r==="noteTitle"||r==="captureTarget"||r==="propertyName"||r==="propertyValue"||r==="folder"||r==="templatePath"||r==="lineTarget"||r==="filePath"}function hw(r){return r!=="templatePath"&&r!=="generic"}function gw(r,t){if(r==="generic")return{};let e=EQ[r];return t?{title:e.ask,placeholder:e.hint}:{placeholder:e.partOf}}function IQ(r,t=44){if(r.length<=t)return r;let e=r.split("/");if(e.length===1)return r;let n=e[e.length-1];if(e.length===2){let s=`${p0}/${n}`;return s.length{Le();xQ=new Set(["captureText"]),EQ={noteTitle:{ask:"Note title",hint:"Title for the new note",partOf:"Part of the new note's title"},captureTarget:{ask:"Capture target",hint:"Where to capture to",partOf:"Part of the capture destination"},captureText:{ask:"Text to capture",hint:"Text to add to the note",partOf:"Part of the text added to the note"},propertyName:{ask:"Property",hint:"Property name",partOf:"Part of the property name"},propertyValue:{ask:"Property value",hint:"Value to capture",partOf:"Part of the property value"},noteBody:{ask:"Note content",hint:"Text inserted into the note",partOf:"Part of the text inserted into the note"},folder:{ask:"Folder",hint:"Folder for the new note",partOf:"Part of the folder path"},templatePath:{ask:"Template",hint:"Path to the template file",partOf:"Part of the template path"},lineTarget:{ask:"Line to find",hint:"Existing line to anchor the capture to",partOf:"Part of the line to find"},filePath:{ask:"File to open",hint:"Path to the file to open",partOf:"Part of the file path"}},TQ=new RegExp(`^(?:${fo.source})$`,"i"),_Q=new RegExp(fo.source,"gi"),kQ=/\{\{[^}\n\r]*\}\}/;p0="\u2026"});function Wh(r){let e=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(r);return e?[0,e[0].length]:null}function Gh(r,t,e,n){let[i,o]=n??[Number.NaN,Number.NaN];if(!(n!==null&&t>=i&&t{});function Rs(r,t,e={}){if(!r||!t)return null;let n=r,i=n.metadataTypeManager??n.metadataCache?.app?.metadataTypeManager;if(!i||typeof i.getTypeInfo!="function")return null;if(e.registeredOnly){let a=i.getAllProperties?.();if(!a||typeof a!="object"||!Object.keys(a).some(l=>l.toLowerCase()===t.toLowerCase()))return null}let o=i.getTypeInfo(t),s=o?.expected?.type??o?.inferred?.type;return typeof s=="string"?s:null}function FQ(r){return r!==null&&PQ.has(r.toLowerCase())}function m0(r,t){return $Q.has(t.toLowerCase())||FQ(Rs(r,t))}var PQ,$Q,bp=x(()=>{PQ=new Set(["aliases","list","multitext","tags"]),$Q=new Set(["aliases","cssclasses","tags"])});function MQ(r,t=","){let e=[],n="",i=[],o=null;for(let a=0;a=0&&r[d]==="\\";d--)c++;c%2===0&&(o=null)}continue}if(l==='"'){o=l,n+=l;continue}if(l in f0){i.push(f0[l]),n+=l;continue}if(i.length>0){let c=i[i.length-1];l===c&&i.pop(),n+=l;continue}if(l===t){let c=n.trim();c.length>0&&e.push(c),n="";continue}n+=l}let s=n.trim();return s.length>0&&e.push(s),e}function RQ(r){return r.includes(` `)?r.replace(/\r?\n/g,` `):r.includes("\\n")?r.replace(/\\n/g,` `):r}function OQ(r){if(!r)return!1;let t=r.toLowerCase();return t==="list"||t==="tags"||t==="multitext"}function h0(r,t){let e=r.trim();if(!e)return;let n=RQ(e),i=t?.propertyType??Rs(t?.app,t?.propertyKey),o=OQ(i),a=o||i===null,c=n.split(/\n/).map(d=>d.trim()).filter(d=>d.length>0);if(a&&c.length>0&&c.every(d=>/^-\s+/.test(d)))return c.map(d=>d.replace(/^-[\s]*/,"").trim());if(n.startsWith("[")&&n.endsWith("]")||n.startsWith("{")&&n.endsWith("}")){if(i&&!o&&i!=="list")return;try{return JSON.parse(n)}catch{}}if(n.includes(",")&&a){let d=MQ(n);if(d.length>1)return d}}var f0,g0=x(()=>{bp();f0={"[":"]","(":")","{":"}","<":">"}});function wp(r){if(typeof r=="string"&&r.startsWith("@date:")){let t=r.substring(6),e=new Date(t);if(!Number.isNaN(e.getTime()))return e}return r}function qS(r){return typeof r!="string"&&(Array.isArray(r)||typeof r=="object"&&r!==null||typeof r=="number"||typeof r=="boolean"||r===null)}function v0(r){return Array.isArray(r)||typeof r=="object"&&r!==null}function y0(r){if(qS(r))return Array.isArray(r)?"[]":r===null?"null":typeof r=="object"?"{}":String(r)}var Cp=x(()=>{});var b0,Ui,jh=x(()=>{US();g0();Cp();bp();b0="\0",Ui=class{constructor(t){this.app=t;this.map=new Map;this.propertyTypeCache=new Map}maybeCollect(t){let{input:e,matchStart:n,matchEnd:i,rawValue:o,fallbackKey:s,collectionActive:a,heuristicEnabled:l}=t;if(!a)return;let c=Wh(e),d=Gh(e,n,i,c);if(!d.isInYaml)return;let u=e.slice(d.lineStart,d.lineEnd),p=u.trim(),m=u.match(/^\s*([^:]+):/),h=m?m[1].trim():s,g=/^-\s*['"]?\{\{(?:VALUE|FIELD|FILE):[^}]+\}\}['"]?\s*$/i,v=null;if(d.isKeyValuePosition?v=[h]:g.test(p)&&(v=this.findListParentPath(e,d.lineStart,d.baseIndent??"")),!v||v.length===0)return;let b=v[v.length-1],y=o;if(l&&typeof o=="string"){let w=h0(o,this.buildParseOptions(b));w!==void 0&&(y=w)}if(!qS(y)||Array.isArray(y)&&y.length===0||!l&&!v0(y))return;let C=v.join(b0);return this.map.set(C,y),y}drain(){let t=new Map(this.map);return this.map.clear(),t}merge(t){for(let[e,n]of t)this.map.set(e,n)}buildParseOptions(t){return{propertyKey:t,propertyType:this.resolvePropertyType(t),app:this.app}}findListParentPath(t,e,n){let i=e-1,o=[],s=n.length;for(;i>=0;){let a=t.lastIndexOf(` `,i),l=a===-1?0:a+1,c=t.slice(l,i+1),d=c.trim();if(d.length===0){i=l-2;continue}if(d==="---"||d==="...")break;if(d.startsWith("-")){i=l-2;continue}let u=c.match(/^(\s*)([^:\n]+):/);if(u){let m=(u[1]??"").length;if(m0?o:null}resolvePropertyType(t){if(!this.app)return null;if(this.propertyTypeCache.has(t))return this.propertyTypeCache.get(t)??null;let e=Rs(this.app,t);return this.propertyTypeCache.set(t,e),e}};Ui.PATH_SEPARATOR=b0});function Pd(r){return DQ.has(r.toUpperCase())}function zS(r){if(r.length===0||r==="."||r===".."||r.startsWith(".")||Yh.test(r)||Kh.test(r)||Qh.test(r))return!1;let t=r.split(".")[0]??"";return t.length===0||!Pd(t)}var Yh,Kh,Qh,DQ,Xh=x(()=>{Yh=new RegExp("[\0-]","u"),Kh=/[\\/:*?"<>|]/u,Qh=/[. ]$/u,DQ=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 w0(r){if(!r)return null;let t=r.trim().toLowerCase();switch(t){case"kebab":case"snake":case"camel":case"pascal":case"title":case"lower":case"upper":case"slug":return t;default:return null}}function bw(r){return w0(r)!==null}function HS(r){if(!r)return r;let t=r.toLowerCase();return t.slice(0,1).toUpperCase()+t.slice(1)}function WS(r){return/\p{L}/u.test(r)?/\p{Lu}/u.test(r)&&!/\p{Ll}/u.test(r):!1}function vw(r){return/\p{Lu}/u.test(r)&&/\p{Ll}/u.test(r)}function LQ(r){return/^\p{Ll}/u.test(r)&&vw(r)}function NQ(r){if(!r)return[];{let e=r.match(/^([\p{Ll}][\p{Lu}]{2,})([\p{N}]+)?$/u);if(e){let n=[e[1]];return e[2]&&n.push(e[2]),n}}if(/^[\p{Ll}][\p{Lu}][\p{Ll}]+(?:[\p{Lu}][\p{Ll}]+)*$/u.test(r))return[r];let t=r;return t=t.replace(/([\p{Lu}])([\p{Lu}][\p{Ll}])/gu,"$1 $2"),t=t.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu,"$1 $2"),t=t.replace(/([\p{L}])([\p{N}])/gu,"$1 $2"),t=t.replace(/([\p{N}])([\p{L}])/gu,"$1 $2"),t.trim().split(/\s+/u).map(e=>e.trim()).filter(Boolean)}function VQ(r){return r.split(/[^\p{L}\p{N}\p{M}]+/gu).filter(Boolean).flatMap(NQ).filter(Boolean)}function Jh(r,t){let e=w0(t);if(!e)return r;if(e==="lower")return r.toLowerCase();if(e==="upper")return r.toUpperCase();let n=VQ(r);if(n.length===0)return"";switch(e){case"kebab":return n.map(i=>i.toLowerCase()).join("-");case"snake":return n.map(i=>i.toLowerCase()).join("_");case"camel":{let[i,...o]=n,s=i?LQ(i)?i:i.toLowerCase():"",a=o.map(l=>WS(l)||vw(l)?l:HS(l));return[s,...a].join("")}case"pascal":return n.map(i=>WS(i)||vw(i)?i:HS(i)).join("");case"title":return n.map(i=>WS(i)||vw(i)?i:HS(i)).join(" ");case"slug":{let i=n.map(o=>o.toLowerCase()).join("-");return Pd(i)?`${i}-`:i}default:return r}}var yw,ww=x(()=>{Xh();yw=["kebab","snake","camel","pascal","title","lower","upper","slug"]});function C0(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(BQ,t=>`\\x${t.charCodeAt(0).toString(16).padStart(2,"0")}`)}function Zh(r){return`"${C0(r)}"`}function GS(r,t,e){let n=Gh(r,t,e,Wh(r));return!n.isInYaml||!n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}function $d(r,t,e,n){return GS(r,t,e)?r[t-1]==='"'?C0(n):n.replace(/'/g,"''"):n}function jS(r,t,e){let n=Gh(r,t,e,Wh(r));return!n.isInYaml||n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}var BQ,Cw=x(()=>{US();BQ=new RegExp("[\0-\x7F]","g")});function xw(r,t,e){let n=r.trim().toLowerCase();if(UQ.has(n))return n;e?.(`QuickAdd: Unsupported multi-select format "${r}" in "${t}". Supported formats: auto, inline, spaced, yaml, markdown.`)}function qQ(r,t){let e=r.lastIndexOf(` `,t-1)+1;return r.slice(e,t).match(/^\s*/)?.[0]??""}function x0(r){if(r.format==="inline"||r.format==="spaced")return!1;let t=r.input.lastIndexOf(` `,r.matchStart-1)+1,e=r.input.indexOf(` `,r.matchEnd);return r.input.slice(t,r.matchStart).trim()===""&&r.input.slice(r.matchEnd,e===-1?void 0:e).trim()===""}function zQ(r){return`- ${r.replace(/\r\n?|\n/g,` `)}`}function E0(r){let{input:t,matchStart:e,values:n,format:i}=r,o=n.map(s=>String(s));switch(i){case"auto":return;case"inline":return o.join(",");case"spaced":return o.join(", ");case"yaml":return`[${o.map(Zh).join(", ")}]`;case"markdown":{if(o.length===0)return"";let s=qQ(t,e);return o.map(zQ).join(` ${s}`)}default:return i}}var UQ,Ew=x(()=>{Cw();UQ=new Set(["auto","inline","spaced","yaml","markdown"])});function Tw(r){let t=r.trim();return t&&(/^\[\[.*\]\]$/.test(t)?t:`[[${t}]]`)}var YS=x(()=>{});function bo(r){return r.split("|")}function T0(r){return r.startsWith("|")?r.slice(1):r}function wo(r){let t=r.indexOf(":");if(t===-1)return null;let e=r.slice(0,t).trim().toLowerCase();if(!e)return null;let n=r.slice(t+1).trim();return{key:e,value:n}}function Gl(r){if(!r)return!0;let t=r.trim().toLowerCase();return!["false","no","0","off"].includes(t)}function Xo(r,t){let e=!1;return{remaining:r.filter(i=>i.trim().toLowerCase()===t?(e=!0,!1):!0),found:e}}var jl=x(()=>{});function KS(r){let{remaining:t,found:e}=Xo(r,"optional"),{remaining:n,found:i}=Xo(t,"trim");return{remaining:n,optional:e,trim:i}}function QS(r,t,e,n,i){let o=r.map(u=>{let p=u.trim();return{raw:p,option:wo(p)}}),s=e?WQ:_0,a=o.some(({option:u})=>u?.key==="type"&&["number","slider"].includes(u.value.toLowerCase())),l=u=>s.has(u)||a&&HQ.has(u);if(!o.some(({raw:u,option:p})=>p&&l(p.key)||t&&["custom","multi"].includes(u.toLowerCase())))return{defaultValue:r.join("|").trim(),allowCustomInput:!1,usesOptions:!1};let d={defaultValue:"",allowCustomInput:!1,usesOptions:!0,multiSelect:!1};for(let{raw:u,option:p}of o){if(t&&u.toLowerCase()==="custom"){d.allowCustomInput=!0;continue}if(t&&u.toLowerCase()==="multi"){d.multiSelect=!0;continue}if(!p||!l(p.key))continue;let{key:m,value:h}=p;switch(m){case"label":h&&(d.label=h);break;case"case":h&&(d.caseStyle=h);break;case"default":d.defaultValue=h;break;case"custom":d.allowCustomInput=Gl(h);break;case"type":h&&(d.inputTypeOverride=h);break;case"min":d.minRaw=h;break;case"max":d.maxRaw=h;break;case"step":d.stepRaw=h;break;case"text":d.displayValuesRaw=h;break;case"optional":d.optionalExplicit=Gl(h);break;case"trim":d.trimExplicit=Gl(h);break;case"multi":d.multiSelect=!0,d.multiEmit=h.trim().toLowerCase()==="linklist"?"linklist":"text";break;case"format":d.multiFormat=xw(h,n,i);break;case"name":h?d.name=h:i(`QuickAdd: empty |name: ignored in "${n}"; provide a variable name, e.g. {{VALUE:a,b|name:category}}.`);break;default:break}}return d}var HQ,_0,WQ,k0=x(()=>{jl();Ew();HQ=new Set(["min","max","step"]),_0=new Set(["label","default","custom","type","case","text","optional","trim","multi","format"]),WQ=new Set([..._0,"name"])});var xp,eg,tg=x(()=>{ye();xp=r=>{S.logWarning(r)},eg=()=>{}});function Ep(r){if(r===void 0)return;let t=r.trim();if(!t)return;let e=Number(t);return Number.isFinite(e)?e:void 0}function GQ(r){return r.minRaw!==void 0||r.maxRaw!==void 0||r.stepRaw!==void 0}function S0(r,t,e){let n=Ep(r.minRaw),i=Ep(r.maxRaw),o=Ep(r.stepRaw),s={};for(let[a,l,c]of[["min",r.minRaw,n],["max",r.maxRaw,i]])l!==void 0&&(c===void 0?e(`QuickAdd: Ignoring invalid ${a} in VALUE token "${t}".`):s[a]=c);return s.min!==void 0&&s.max!==void 0&&s.max0?s:void 0}function XS(r,t,e,n){if(e!=="number"&&e!=="slider")return GQ(r)&&n(`QuickAdd: Ignoring numeric range options in "${t}" because type is not number or slider.`),{inputTypeOverride:e};if(e!=="slider"){let c=S0(r,t,n);return{inputTypeOverride:e,numericConfig:c}}let i=Ep(r.minRaw),o=Ep(r.maxRaw),s=r.stepRaw===void 0?1:Ep(r.stepRaw),a=i===void 0||o===void 0?"slider requires finite min and max values":o<=i?"max must be greater than min":s===void 0||s<=0?"step must be greater than 0":void 0;if(a)return n(`QuickAdd: Invalid slider configuration in "${t}" (${a}); falling back to type:number.`),{inputTypeOverride:"number",numericConfig:S0(r,t,eg)};let l={min:i,max:o,step:s};return{inputTypeOverride:e,numericConfig:l,sliderConfig:l}}function A0(r){let t=String(r),e=/e-(\d+)$/i.exec(t);if(e)return Number(e[1]);let n=t.indexOf(".");return n===-1?0:t.length-n-1}function jQ(r,t){return String(Number(r.toFixed(t)))}function Co(r,t){let e=r?.trim()??"";if(!e)return"";let n=Number(e);if(!Number.isFinite(n))return"";let i=t?.min,o=t?.max,s=n;if(i!==void 0&&(s=Math.max(i,s)),o!==void 0&&(s=Math.min(o,s)),t?.step!==void 0&&t.step>0){let a=i??0,l=Math.round((s-a)/t.step);s=a+l*t.step,i!==void 0&&(s=Math.max(i,s)),o!==void 0&&(s=Math.min(o,s));let c=Math.max(A0(a),A0(t.step));return jQ(s,c)}return String(s)}function Tp(r,t){return Co(r,t)||String(t.min)}var JS=x(()=>{tg()});function _w(r){return r!==void 0&&YQ.has(r)}function Fd(r){let t=[],e="",n=!1;for(let i=0;i=r.length||r[s]===","){n=!1,i=s-1;continue}return r.split(",")}e+=o;continue}if(o===","){t.push(e),e="";continue}if(_w(o)&&e.trim()===""){n=!0,e="";continue}e+=o}return n?r.split(","):(t.push(e),t)}function rg(r){let t=r.trim();if(!_w(t[0]))return r;let e=Fd(t);return e.length===1&&e[0]!==t?e[0].trim():r}var YQ,KQ,ZS=x(()=>{YQ=new Set(['"',"\u201C","\u201D"]);KQ=/[^\S\r\n]/});function JQ(r,t,e){return e&&t?`${r}${eA}${t}`:r}function tA(r){let t=r.indexOf(eA);return t===-1?r:r.slice(0,t)}function ZQ(r,t){let e=t.toLowerCase(),n=null;for(let i of r.keys())if(i.toLowerCase()===e&&r.get(i)!==void 0){if(n)return null;n=i}return n}function Yl(r,t){if(!t)return null;let e=[t],n=tA(t);n!==t&&e.push(n);for(let i of e){if(r.has(i)&&r.get(i)!==void 0)return i;let o=ZQ(r,i);if(o)return o}return null}function I0(r,t,e){if(r&&!bw(r)){e(`QuickAdd: Unsupported |case style "${r}" in token "${t}". Supported styles: ${yw.join(", ")}.`);return}return r}function P0(r,{tokenDisplay:t,hasOptions:e,allowCustomInput:n},i){if(!r)return;let o=r.trim().toLowerCase(),s=o==="boolean"?"checkbox":o;if(!QQ.has(s)){i(`QuickAdd: Unsupported VALUE type "${r}" in token "${t}". Supported types: multiline, number, slider, checkbox, text.`);return}if(e||n){i(`QuickAdd: Ignoring type:${s} for option-list VALUE token "${t}".`);return}return s}function Md(r,t){if(!r)return null;let e=t?.warn??xp,n=bo(r),i=(n.shift()??"").trim();if(!i)return null;let o=Fd(i).map(N=>N.trim()).filter(Boolean),s=o.length>1,{remaining:a,optional:l,trim:c}=KS(n),d=`{{VALUE:${r}}}`,u=QS(a,s,!0,d,e),{label:p,caseStyle:m,defaultValue:h,allowCustomInput:g}=u,v=u.multiSelect??!1,b=u.multiEmit??"text",y=u.multiFormat??"auto",C=u.optionalExplicit??l,w=u.trimExplicit??c;if(!u.usesOptions){let N=h;g=s&&N.toLowerCase()==="custom",h=g?"":N}s&&h&&(h=rg(h));let T=P0(u.inputTypeOverride,{tokenDisplay:d,hasOptions:s,allowCustomInput:g},e),P=XS(u,d,T,e),_;if(u.displayValuesRaw!==void 0){if(!s)throw new Error(`QuickAdd: VALUE option "text" is only supported for option-list tokens in "${d}".`);if(_=Fd(u.displayValuesRaw).map(N=>N.trim()).filter(Boolean),_.length!==o.length)throw new Error(`QuickAdd: VALUE token "${d}" must define the same number of text entries and item entries. To include a comma inside one entry, wrap it in double quotes, e.g. "a, b".`);if(new Set(_).size!==_.length)throw new Error(`QuickAdd: VALUE token "${d}" has duplicate text entries. Text entries must be unique.`)}let I=u.name?.trim()||void 0;I&&I.includes(eA)&&(e(`QuickAdd: |name in "${d}" contains a reserved control character and was ignored.`),I=void 0),I&&XQ.has(I.toLowerCase())&&(e(`QuickAdd: |name:${I} is reserved and was ignored in "${d}". Choose a different name.`),I=void 0),I&&!s&&e(`QuickAdd: |name on a single value in "${d}" is redundant \u2014 use {{VALUE:${I}}} directly.`),m=I0(m,d,e),v&&!s&&(e(`QuickAdd: |multi needs an option list (2+ comma-separated values) in "${d}"; ignoring.`),v=!1),v&&m&&(e(`QuickAdd: |case is ignored with |multi in "${d}" \u2014 a list is not case-transformed.`),m=void 0),!v&&u.multiFormat!==void 0&&(e(`QuickAdd: |format: needs |multi in "${d}"; ignoring.`),y="auto"),!s&&!u.usesOptions&&a.some(N=>N.trim().toLowerCase()==="custom")&&(e(`QuickAdd: |custom needs an option list (2+ comma-separated values) in "${d}"; ignoring.`),h.toLowerCase()==="custom"&&(h=""));let D=I||JQ(i,p,s);return{raw:r,variableName:i,aliasName:I,variableKey:D,label:p,caseStyle:m,defaultValue:h,allowCustomInput:g,suggestedValues:o,displayValues:_,hasOptions:s,inputTypeOverride:P.inputTypeOverride,numericConfig:P.numericConfig,sliderConfig:P.sliderConfig,optional:C,trim:w,multiSelect:v,multiEmit:b,multiFormat:y}}function ng(r,t){let e=t?.warn??xp,n=T0(r),i=bo(n).map(g=>g.trim()).filter(Boolean),{remaining:o,optional:s,trim:a}=KS(i);if(o.length===0)return{defaultValue:"",optional:s,trim:a};let l=`{{VALUE${r}}}`,c=QS(o,!1,!1,l,e);if(c.displayValuesRaw!==void 0)throw new Error(`QuickAdd: VALUE option "text" is only supported for option-list tokens in "${l}".`);let{label:d,caseStyle:u,defaultValue:p}=c;c.usesOptions||(p=p.trim()),u=I0(u,l,e);let m=P0(c.inputTypeOverride,{tokenDisplay:l,hasOptions:!1,allowCustomInput:c.allowCustomInput},e),h=XS(c,l,m,e);return{label:d,caseStyle:u,defaultValue:p,inputTypeOverride:h.inputTypeOverride,numericConfig:h.numericConfig,sliderConfig:h.sliderConfig,optional:c.optionalExplicit??s,trim:c.trimExplicit??a}}var eA,QQ,XQ,xo=x(()=>{k0();JS();ZS();JS();ZS();jl();ww();tg();eA="",QQ=new Set(["multiline","number","slider","checkbox","text"]),XQ=new Set(["value","title"])});function Os(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);if(typeof r=="bigint"||typeof r=="symbol")return r.toString();if(r instanceof Error)return r.message;try{return JSON.stringify(r)??Object.prototype.toString.call(r)}catch{return Object.prototype.toString.call(r)}}function Kl(r){return e3.includes(r)}function M0(r){switch(r){case"lessThan":case"lessThanOrEqual":case"greaterThan":case"greaterThanOrEqual":return"number";case"equals":case"notEquals":return"string";case"contains":case"notContains":return"string";default:return"boolean"}}function R0(r){if(!Kl(r.operator)||r.expectedValue===void 0||r.expectedValue===null)return;let t=r.expectedValue.trim();switch(r.valueType){case"number":{let e=Number(t);return Number.isNaN(e)?NaN:e}case"boolean":{let e=t.toLowerCase();return $0.has(e)?!0:F0.has(e)?!1:!!t}default:return t}}function rA(r,t){switch(t){case"number":return typeof r=="number"?r:typeof r=="boolean"?r?1:0:Number(r);case"boolean":if(typeof r=="boolean")return r;if(typeof r=="string"){let e=r.trim().toLowerCase();if($0.has(e))return!0;if(F0.has(e))return!1}return!!r;default:return r==null?"":Os(r)}}function t3(r){if(!Kl(r.operator))return"";let t=r.expectedValue??"";return t.length===0?"(empty)":r.valueType==="string"?`"${t}"`:t}function r3(r){let t=r.variableName?`$${r.variableName}`:"(missing variable)",e=i3(r.operator),n=Kl(r.operator)?` ${t3(r)}`:"";return`${t} ${e}${n}`.trim()}function n3(r){let t=r.exportName?`::${r.exportName}`:"";return`script ${r.scriptPath}${t}`}function Ql(r){return r.mode==="variable"?r3(r):n3(r)}function i3(r){switch(r){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 r}}var e3,$0,F0,Xl=x(()=>{e3=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],$0=new Set(["true","1","yes","on"]),F0=new Set(["false","0","no","off"])});var o3,kw,nA=x(()=>{Le();yp();ye();jh();ww();Cp();Cw();Ew();YS();xo();tg();Xl();o3=new Set(["number","slider","checkbox"]),kw=class{constructor(t){this.app=t;this.variables=new Map;this.promptScope="generic";this.promptScopeSoleValue=!1;this.templatePropertyCollectionDepth=0;this.listPicksAsLines=!1;this.namedSuggesterOptionSigs=new Map;this.namedSuggesterConflictsWarned=new Set;this.warnSink=t=>this.warn(t);this.propertyCollector=new Ui(t)}writesListPicksAsLines(){return this.listPicksAsLines}async preserveSingleTokenValue(t,e){let n=this.singleTokenValue,i=/^(?:\{\{(?:VALUE|NAME)(?::[^{}]+|\|[^{}]+)?\}\}|\{\{(?:FIELD|FILE):[^{}]+\}\}|\{\{PROPERTY\}\}|`{3,}js quickadd[\s\S]*`{3,})$/i.test(t)?{input:t}:void 0;this.singleTokenValue=i;try{let o=await e();return i?.result&&typeof i.result.value!="string"?i.result.value:o}finally{this.singleTokenValue=n}}retainSingleTokenValue(t,e,n,i){return this.singleTokenValue?.input===t&&e===0&&n===t.length?(this.singleTokenValue.result={value:i},!0):!1}propertyTokenValue(t,e){if(e==="text")return Os(t);if(e==="checkbox"){if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1;throw new Error("A checkbox property value must be true or false.")}if(e==="number"||e==="slider"){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t!="string"||!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t.trim())||!Number.isFinite(Number(t)))throw new Error("A number property value must be a finite number.");return Number(t)}return t}warn(t){S.logWarning(t)}reportProblem(t){S.logError(t)}setPromptRunContext(t){this.promptRunContext={...this.promptRunContext,...t}}getPromptRunContext(){return this.promptRunContext}async withPromptScope(t,e,n){let i=this.promptScope,o=this.promptScopeSoleValue;this.promptScope=t,this.promptScopeSoleValue=mw(t,e);try{return await n()}finally{this.promptScope=i,this.promptScopeSoleValue=o}}hasConcreteVariable(t){return this.variables.has(t)?this.variables.get(t)!==void 0:!1}setTitle(t){this.hasConcreteVariable("title")||this.variables.set("title",t)}getAnonymousValue(){return this.value}userText(t){return t}replacer(t,e,n){return t.replace(e,function(){return n})}applyCaseOption(t,e,n){return e?bw(e)?Jh(t,e):(this.warn(`QuickAdd: Unsupported |case style "${e}" in token "${n}". Supported styles: ${yw.join(", ")}.`),t):t}async resolveValue(t){if(this.valuePromptContext=this.getValuePromptContext(t),this.hasConcreteVariable("value")){let e=this.variables.get("value");this.value=Os(e)}return this.value===void 0&&(this.value=await this.promptForValue()),this.value}async replaceValueInString(t){let e=t;if(!fo.test(e))return e;await this.resolveValue(e);let n=new RegExp(fo.source,"gi");return e=e.replace(n,(...i)=>{let o=i[0],s=i[i.length-2],a=i[i.length-1],l=o.slice(2,-2),c=l.indexOf("|");if(c===-1)return this.retainSingleTokenValue(a,s,s+o.length,this.hasConcreteVariable("value")?this.variables.get("value"):this.value),this.userText($d(a,s,s+o.length,this.value));let d=l.slice(c),u=ng(d,{warn:this.warnSink}),p=this.value===""&&u.defaultValue&&!u.optional?u.defaultValue:this.value,m=this.applyValueTextOptions(p,u);if(this.singleTokenValue){let h=this.value===""&&u.defaultValue&&!u.optional?u.defaultValue:this.hasConcreteVariable("value")?this.variables.get("value"):this.value;this.retainSingleTokenValue(a,s,s+o.length,this.propertyTokenValue(this.applyValueTokenOptions(h,u),u.inputTypeOverride))}return u.inputTypeOverride==="text"&&m!==""&&jS(a,s,s+o.length)?this.userText(Zh(m)):this.userText($d(a,s,s+o.length,m))}),e}applyValueTextOptions(t,e){let n=String(t??""),i=e.trim?n.trim():n;return Jh(i,e.caseStyle)}applyValueTokenOptions(t,e){return Array.isArray(t)?e.trim?t.map(n=>typeof n=="string"?n.trim():n):t:typeof t=="string"?this.applyValueTextOptions(t,e):t}getValuePromptContext(t){let e=new RegExp(fo.source,"gi"),n,i;for(;(n=e.exec(t))!==null;){let s=n[0].slice(2,-2),a=s.indexOf("|");if(a===-1)continue;let l=s.slice(a),c=ng(l,{warn:eg});i||(i={}),!i.label&&c.label&&(i.label=c.label),!i.defaultValue&&c.defaultValue&&(i.defaultValue=c.defaultValue),c.inputTypeOverride&&!i.inputTypeOverride&&(i.inputTypeOverride=c.inputTypeOverride),c.numericConfig&&!i.numericConfig&&(i.numericConfig=c.numericConfig),c.sliderConfig&&!i.sliderConfig&&(i.sliderConfig=c.sliderConfig),c.optional&&(i.optional=!0)}return i}getAndClearTemplatePropertyVars(){return this.propertyCollector.drain()}mergeTemplatePropertyVars(t){this.propertyCollector.merge(t)}renderCollectedOrArrayValue(t){if(this.writesListPicksAsLines()&&Array.isArray(t.rawValue)&&x0({...t,format:t.multiFormat})){let i=t.rawValue.map(String);if(!this.retainSingleTokenValue(t.input,t.matchStart,t.matchEnd,t.rawValue)&&i.some(s=>/[\r\n]/.test(s)))throw new Error("A list item that contains a line break can only be written when its token is the whole Capture format.");return i.join(` `)}if((!t.multiFormat||t.multiFormat==="auto")&&this.retainSingleTokenValue(t.input,t.matchStart,t.matchEnd,t.rawValue),Array.isArray(t.rawValue)&&t.multiFormat){let i=E0({input:t.input,matchStart:t.matchStart,values:t.rawValue,format:t.multiFormat});if(i!==void 0)return i}let e=this.propertyCollector.maybeCollect({...t,collectionActive:this.templatePropertyCollectionDepth>0}),n=y0(e);if(n!==void 0)return n;if(Array.isArray(t.rawValue))return $d(t.input,t.matchStart,t.matchEnd,t.rawValue.join(","))}async withTemplatePropertyCollection(t){this.templatePropertyCollectionDepth+=1;try{return await t()}finally{this.templatePropertyCollectionDepth-=1}}warnOnNamedOptionConflict(t){if(!t.aliasName||!t.hasOptions)return;let e=t.variableKey.toLowerCase(),n=JSON.stringify([t.suggestedValues,t.allowCustomInput,t.displayValues??null,t.multiSelect,t.multiEmit]),i=this.namedSuggesterOptionSigs.get(e);if(i===void 0){this.namedSuggesterOptionSigs.set(e,n);return}i!==n&&!this.namedSuggesterConflictsWarned.has(e)&&(this.namedSuggesterConflictsWarned.add(e),this.warn(`QuickAdd: named value "${t.variableKey}" is defined with different option lists; the first definition's value is reused.`))}async ensureValueVariableResolved(t){let{variableName:e,variableKey:n,label:i,defaultValue:o,allowCustomInput:s,suggestedValues:a,displayValues:l,hasOptions:c}=t;this.warnOnNamedOptionConflict(t),await this.resolveIncludingTextDate(n);let d=Yl(this.variables,n);if(d)return d;let u=this.promptScope==="propertyValue"?this.variables.get("propertyKey"):void 0,p=c?i||(typeof u=="string"?u:void 0):void 0;if(c&&t.multiSelect){let h=await this.suggestForValueMulti(a,s,{placeholder:p,variableKey:n,displayValues:l,optional:t.optional});return this.variables.set(n,t.multiEmit==="linklist"?h.map(Tw):h),n}let m="";return c?m=await this.suggestForValue(a,s,{placeholder:p,variableKey:n,displayValues:l,optional:t.optional}):m=await this.promptForVariable(e,{defaultValue:o,label:i,inputTypeOverride:t.inputTypeOverride,numericConfig:t.numericConfig,sliderConfig:t.sliderConfig,variableKey:n,optional:t.optional}),!m&&o&&!t.optional&&(m=o),this.variables.set(n,m),n}async resolveNamedSuggesterDefinitions(t){if(!/\|\s*name\s*:/i.test(t))return;let e=new RegExp(Td.source,"gi"),n=[],i;for(;(i=e.exec(t))!==null;){if(!i[1])continue;let a;try{a=Md(i[1],{warn:eg})}catch{return}a&&n.push({parsed:a,index:i.index})}let o=new Map;for(let{parsed:a,index:l}of n){if(a.hasOptions&&a.aliasName)continue;let c=a.variableKey.toLowerCase();o.has(c)||o.set(c,l)}let s=new Set;for(let{parsed:a,index:l}of n){if(!a.hasOptions||!a.aliasName)continue;let c=a.variableKey.toLowerCase();(o.get(c)??l)>=l||s.has(c)||(s.add(c),await this.ensureValueVariableResolved(a))}}async replaceVariableInString(t){let e=t;await this.resolveNamedSuggesterDefinitions(e);let n=new RegExp(Td.source,"gi"),i=this.isTemplatePropertyTypesEnabled(),o;for(;(o=n.exec(e))!==null;){if(!o[1])throw new Error(`Unable to parse variable. Invalid syntax in: "${e.substring(Math.max(0,o.index-10),Math.min(e.length,o.index+30))}..."`);let s=Md(o[1],{warn:this.warnSink});if(!s)throw new Error(`Unable to parse variable. Invalid syntax in: "${e.substring(Math.max(0,o.index-10),Math.min(e.length,o.index+30))}..."`);let{variableName:a}=s,l=await this.ensureValueVariableResolved(s),c=this.variables.get(l),d=this.applyValueTokenOptions(c,s);this.singleTokenValue&&(!s.multiFormat||s.multiFormat==="auto")&&this.retainSingleTokenValue(e,o.index,o.index+o[0].length,this.propertyTokenValue(d,s.inputTypeOverride));let u=this.renderCollectedOrArrayValue({input:e,matchStart:o.index,matchEnd:o.index+o[0].length,rawValue:this.singleTokenValue?.result?this.singleTokenValue.result.value:d,fallbackKey:a,heuristicEnabled:i&&this.templatePropertyCollectionDepth>0&&s.inputTypeOverride!=="text",multiFormat:s.multiFormat}),p,m=!1;if(u!==void 0)p=u;else{let v=String(this.applyValueTextOptions(this.getValueTokenText(l),s)??"");s.inputTypeOverride==="text"&&v!==""&&jS(e,o.index,o.index+o[0].length)?p=Zh(v):o3.has(s.inputTypeOverride??"")&&GS(e,o.index,o.index+o[0].length)?(m=!0,p=v):p=$d(e,o.index,o.index+o[0].length,v)}p=this.userText(p);let h=m?o.index-1:o.index,g=o.index+o[0].length+(m?1:0);e=e.slice(0,h)+p+e.slice(g),n.lastIndex=h+p.length}return e}async resolveIncludingTextDate(t){}getValueTokenText(t){return this.getVariableValue(t)}suggestForValueMulti(t,e,n){return[]}}});function Sw(r){let t=r.trim().toLowerCase(),e=s3[t];if(!e)throw new Error(`Unknown date unit "${r.trim()}". Valid units: ${a3}.`);return e}function O0(r){let t=wo(r);return t?t.key==="startof"?{boundary:"start",unit:Sw(t.value)}:t.key==="endof"?{boundary:"end",unit:Sw(t.value)}:null:null}function _p(r,t){return t?t.boundary==="start"?r.startOf(t.unit):r.endOf(t.unit):r}var s3,a3,ig=x(()=>{jl();s3={year:"year",years:"year",y:"year",quarter:"quarter",quarters:"quarter",q:"quarter",month:"month",months:"month",week:"week",weeks:"week",w:"week",isoweek:"isoWeek",isoweeks:"isoWeek",day:"day",days:"day",d:"day"},a3="year, quarter, month, week, isoweek, day"});function l3(r){return r===void 0?window.moment():window.moment(r)}function c3(r){let t=l3(r?.now);return r?.origin?window.moment(r.origin).hour(t.hour()).minute(t.minute()).second(t.second()).millisecond(t.millisecond()):t}function Ra(r){let t;return r?.offset!==null&&r?.offset!==void 0&&typeof r.offset=="number"&&(t=window.moment.duration(r.offset,"days")),_p(c3(r).add(t),r?.snap).format(r?.format??"YYYY-MM-DD")}var Aw=x(()=>{ig()});function og(r){if(!r)return{optional:!1,withTime:!1};let{remaining:t,found:e}=Xo(bo(r),"optional"),{remaining:n,found:i}=Xo(t,"time"),{remaining:o,found:s}=Xo(n,"datetime"),a,l=!1,c,d,u,p=[];for(let h of o){let g=wo(h.trim());if(g?.key==="optional"){a=Gl(g.value);continue}if(g?.key==="type"){g.value.trim().toLowerCase()==="datetime"&&(l=!0);continue}if(g?.key==="startof"||g?.key==="endof"){c||(c={boundary:g.key==="startof"?"start":"end",unit:Sw(g.value)});continue}if(g?.key==="case"){d=g.value.trim()||void 0;continue}if(g?.key==="label"){u=g.value||void 0;continue}p.push(h)}return{defaultValue:p.join("|").trim()||void 0,optional:a??e,withTime:i||s||l,snap:c,...d?{caseStyle:d}:{},...u?{label:u}:{}}}function Iw(r){try{return{options:og(r)}}catch(t){return{options:{optional:!1,withTime:!1},error:t instanceof Error?t.message:String(t)}}}var sg=x(()=>{jl();ig()});function D0(r,t,e){return r.replace(t,()=>e)}function ag(r){return r?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"}function iA(r,t,e,n=!1){let i=kp.get(r);i||(i=new Map,kp.set(r,i));let o=r.get(t),s=i.get(t);(n||!s||s.answer!==o)&&i.set(t,{answer:o,dateFormat:e})}function Pw(r,t){let e=kp.get(r)?.get(t);return e&&e.answer===r.get(t)?e.dateFormat:void 0}function lg(r,t){let e=Pw(r,t);if(e!==void 0)return e;let n=t.toLowerCase(),i=[...kp.get(r)?.keys()??[]].filter(o=>o.toLowerCase()===n);return i.length===1?Pw(r,i[0]):void 0}function L0(r){return new Map(kp.get(r))}function cg(r,t){kp.set(r,new Map(t))}function dg(r,t,e,n){if(r===void 0)return null;let i=r,o;if(typeof i=="string"&&i&&!i.startsWith("@date:")){if(n){let s=U.getState().dateAliases,a=n.parseDate(Ih(i,s));a&&(o=`@date:${a.moment.toISOString()}`,i=o)}}else i instanceof Date&&(Number.isNaN(i.getTime())||(o=`@date:${i.toISOString()}`,i=o));if(typeof i=="string"&&i.startsWith("@date:")){let s=i.substring(6);if(n&&window.moment){let a=window.moment(s);if(a?.isValid())return{text:_p(a,e).format(t),...o!==void 0?{normalized:o}:{}}}return{text:"",...o!==void 0?{normalized:o}:{}}}return typeof i=="string"&&i?{text:i}:i!=null?{text:Os(i)}:{text:""}}function N0(r,t){let e=r;for(let n of[hD,wS]){let i=n===wS;for(;n.test(e);){let o=n.exec(e);if(i&&!o)throw B0("date",e,n);let s=o?.[i?2:1]?.replace("+","").trim(),a=s&&fD.test(s)?parseInt(s):void 0,l=o?.[i?3:2],c=t.clocks(),d=Ra({...i?{format:o?.[1]}:{},offset:a,snap:l?O0(l)??void 0:void 0,origin:c?.date,now:c?.now});e=D0(e,n,t.applyCase(d,o?.[i?4:3],o?.[0]??"{{DATE}}"))}}return e}function V0(r,t){let e=r;for(let n of[gD,CS]){let i=n===CS;for(;n.test(e);){let o=n.exec(e);if(!o)throw B0("time",e,n);let s=Ra({format:i?o[1]:"HH:mm",now:t.clocks()?.now});e=D0(e,n,t.applyCase(s,o[i?2:1],o[0]))}}return e}function B0(r,t,e){let n=t.search(e);return new Error(`Unable to parse ${r} format. Invalid syntax in: "${t.substring(Math.max(0,n-10),Math.min(t.length,n+30))}..."`)}async function U0(r,t){let e=new RegExp(Ss.source,"gi"),n="",i=0,o;for(;(o=e.exec(r))!==null;){n+=r.slice(i,o.index),i=o.index+o[0].length;let s=o[1]?.trim();if(!s){n+=o[0];continue}let{defaultValue:a,optional:l,withTime:c,snap:d,caseStyle:u,label:p}=og(o[3]),m=o[2]?.trim()||ag(c),h=t.variables.get(s);if(h===void 0){let v=await t.prompt(s,{type:"VDATE",dateFormat:m,defaultValue:a,optional:l,withTime:c,label:p});if(l&&!v?.trim())t.variables.set(s,"");else if(v?.startsWith("@date:"))t.variables.set(s,v);else{if(!t.dateParser)throw new Error("Date parser is not available");let b=U.getState().dateAliases,y=Ih(v,b),C=t.dateParser.parseDate(y);if(C)t.variables.set(s,`@date:${C.moment.toISOString()}`);else throw new Error(`unable to parse date variable ${v}${l?"":". Tip: add |optional inside the {{VDATE}} token to allow leaving this date empty"}`)}}let g=dg(t.variables.get(s),m,d,t.dateParser);g?.normalized!==void 0&&t.variables.set(s,g.normalized),iA(t.variables,s,m,h===void 0||g?.normalized!==void 0),n+=t.applyCase(g?.text??"",u,o[0])}return n+r.slice(i)}var kp,Rd=x(()=>{Le();Aw();je();wd();ig();sg();Xl();kp=new WeakMap});function pg(r,t=0){let e=r.length,n=t;for(;n=3)return{start:i,end:c,code:r.slice(s,l).trim()};a=c}break}}function yi(r){let t=[],e=pg(r);for(;e;)t.push(e),e=pg(r,e.end);return t}function q0(r,t){let e=Math.max(3,t-ug.length+1);for(let n=e;n0&&r[i-1]==="`";)i--;return i}return t}function oA(r){let t=yi(r),e=r.length,n=t.length>0?t[t.length-1].end:0;for(;n=3&&r.startsWith(ug,o))return!0;n=o}return!1}function $w(r){return yi(r).map(({code:t})=>t).filter(t=>t!=="")}var ug,Oa=x(()=>{ug="js quickadd"});function W0(r,t,e,n){let i=new Map,o=new Set,s={LINKCURRENT:t.links,LINKSECTION:t.links,FILENAMECURRENT:t.fileName,FOLDER:t.folder,FOLDERCURRENT:t.activeFolder,TITLE:t.title},a=r.replace(/{{(?:(LINKCURRENT|LINKSECTION|FILENAMECURRENT|TITLE)|(FOLDERCURRENT|FOLDER)(\|name)?)}}/gi,(c,d,u,p)=>{let m=(d??u??"").toUpperCase();if(!(m in e))return c;let h=m;if(!s[h])return c;i.has(h)||i.set(h,e[h]());let g=i.get(h)??null;return(h==="FOLDERCURRENT"?g===null:(h==="LINKCURRENT"||h==="LINKSECTION"||h==="FILENAMECURRENT")&&!g)&&o.add(h),p&&g!==null?g.slice(g.lastIndexOf("/")+1):g??""}),l="Unable to get the active file's folder. Make sure you have a file open in the editor.";if(o.has("FOLDERCURRENT")&&t.activeFolder==="path")throw new Error(l);if(o.size>0){if(n==="required")throw new Error(o.has("LINKCURRENT")||o.has("LINKSECTION")?"Unable to get current file path. Make sure you have a file open in the editor.":o.has("FILENAMECURRENT")?"Unable to get current file name. Make sure you have a file open in the editor.":l);S.logMessage("Skipping current-file token replacement because no active file is available.")}return a}var z0,H0,sA=x(()=>{ye();z0=/{{(?:LINKCURRENT|LINKSECTION|FILENAMECURRENT|FOLDERCURRENT(?:\|name)?)}}/i,H0=/{{FOLDERCURRENT(?:\|name)?}}/i});function d3(r,t){let e=Math.min(r.length,t.length),n=0;for(;ne||r.length>64||t.length>64)return e+1;let n=[],i=Array.from({length:t.length+1},(s,a)=>a),o=[];for(let s=1;s<=r.length;s++){o=new Array(t.length+1),o[0]=s;let a=o[0];for(let l=1;l<=t.length;l++){let c=r[s-1]===t[l-1]?0:1,d=Math.min(i[l]+1,o[l-1]+1,i[l-1]+c);s>1&&l>1&&r[s-1]===t[l-2]&&r[s-2]===t[l-1]&&(d=Math.min(d,n[l-2]+1)),o[l]=d,de)return e+1;n=i,i=o}return i[t.length]}function j0(r,t,e=3){let n=r.trim().toLowerCase();if(!n)return[];let i=t.map((a,l)=>({candidate:a,index:l})).filter(a=>a.candidate!==n),o=i.map(a=>({...a,distance:G0(n,a.candidate,2)})).filter(a=>a.distance<=1).sort((a,l)=>a.distance-l.distance||a.index-l.index);if(o.length>0)return o.slice(0,e).map(a=>a.candidate);if(n.length>=2){let a=i.map(l=>({...l,shared:d3(n,l.candidate)})).filter(l=>l.shared>=2).sort((l,c)=>c.shared-l.shared||l.index-c.index);if(a.length>0)return a.slice(0,e).map(l=>l.candidate)}return i.map(a=>({...a,distance:G0(n,a.candidate,2)})).filter(a=>a.distance<=2&&a.candidate.length>=10).sort((a,l)=>a.distance-l.distance||a.index-l.index).slice(0,e).map(a=>a.candidate)}var Y0=x(()=>{});function Mw(r,t){return r.length<=t?r:`${r.slice(0,t)}\u2026`}function p3(r){let t=r.map(e=>`"${e}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`}function K0(r,t){let e=Mw(r,32),n=`{{FIELD:${Mw(t,48)}}}`,i=u3.get(r);if(i)return`Unknown FIELD filter "${e}" - ${i}. Ignored in ${n}.`;let o=j0(r,Fw);return o.length>0?`Unknown FIELD filter "${e}" - did you mean ${p3(o)}? Ignored in ${n}.`:`Unknown FIELD filter "${e}" in ${n} was ignored. Supported filters: ${Fw.join(", ")}.`}function m3(r,t){let e=Mw(r,32);return`FIELD filter "${e}" needs a value - write "${e}:value". Ignored in {{FIELD:${Mw(t,48)}}}.`}function f3(r,t,e){(e.warn??xp)(K0(r,t))}var Fw,u3,Dn,Da=x(()=>{tg();jl();Y0();Ew();Fw=["folder","tag","inline","inline-code-blocks","exclude-folder","exclude-tag","exclude-file","default","default-from","default-empty","default-always","case-sensitive","multi","format","label"],u3=new Map([["case-insensitive",'matching is already case-insensitive; use "case-sensitive:true" to match exactly']]);Dn=class{static parse(t,e){let n=bo(t).map(d=>d.trim()),i=n[0],o={},s=!1,a="auto",l=!1,c;for(let d=1;dg.trim().toLowerCase()).filter(g=>g.length>0));break;case"default":o.defaultValue=h;break;case"default-from":o.defaultFrom=h.toLowerCase();break;case"default-empty":o.defaultEmpty=h.toLowerCase()==="true";break;case"default-always":o.defaultAlways=h.toLowerCase()==="true";break;case"case-sensitive":o.caseSensitive=h.toLowerCase()==="true";break;case"exclude-folder":o.excludeFolders??(o.excludeFolders=[]),o.excludeFolders.push(h);break;case"exclude-tag":{o.excludeTags??(o.excludeTags=[]);let g=h.startsWith("#")?h.substring(1):h;o.excludeTags.push(g);break}case"exclude-file":o.excludeFiles??(o.excludeFiles=[]),o.excludeFiles.push(h);break}}return!s&&l&&(e?.warn?.(`QuickAdd: |format: needs |multi in "{{FIELD:${t}}}"; ignoring.`),a="auto"),{fieldName:i,filters:o,...s?{multiSelect:s}:{},...a!=="auto"?{multiFormat:a}:{},...c?{label:c}:{}}}}});function v3(r){return r.split(",").map(t=>t.trim().toLowerCase().replace(/^\./,"")).filter(Boolean)}function y3(r){if(r.length!==0)return r.includes("any")?"any":new Set(r.flatMap(t=>g3.get(t)??[t]))}function aA(r){return r.replace(/^\/+|\/+$/g,"")}function Sp(r,t=e=>e){return JSON.stringify([...r].map(t).sort())}function X0(r,t,e){let n=[`folder=${aA(r)}`];return e&&n.push(`types=${e==="any"?"any":Sp([...e])}`),t.folders?.length&&n.push(`folders=${Sp(t.folders,aA)}`),t.tags?.length&&n.push(`tags=${Sp(t.tags)}`),t.excludeFolders?.length&&n.push(`xfolder=${Sp(t.excludeFolders,aA)}`),t.excludeTags?.length&&n.push(`xtag=${Sp(t.excludeTags)}`),t.excludeFiles?.length&&n.push(`xfile=${Sp(t.excludeFiles)}`),n.join("|")}function b3(r){let{folderPath:t,mode:e,label:n,optional:i,allowCustomInput:o,multiSelect:s,filter:a,extensions:l}=r,c=[X0(t,a,l),`mode=${e}`];return n&&c.push(`label=${n}`),i&&c.push("optional"),o&&c.push("custom"),s&&c.push("multi"),c.join("|")}function Rw(r,t){if(!r)return null;let e=bo(r),n=(e.shift()??"").trim();if(!n)return null;let i=e,o=Xo(i,"optional");i=o.remaining;let s=o.found,a=Xo(i,"custom");i=a.remaining;let l=a.found,c=Xo(i,"multi");i=c.remaining;let d=c.found,u="name",p=[];for(let P of i){let _=P.trim().toLowerCase();if(h3.has(_)){u=_;continue}p.push(P)}let m,h,g=[];for(let P of p){let _=wo(P);if(_){if(_.key==="label"&&_.value)m=_.value;else if(_.key==="name"&&_.value)h=_.value;else if(_.key==="type")for(let I of v3(_.value))g.includes(I)||g.push(I)}}let v=y3(g),b=Dn.parse(r,{warn:t?.warn}),y=d||(b.multiSelect??!1),C=b.multiFormat??"auto",w={folder:n,tags:b.filters.tags,excludeFolders:b.filters.excludeFolders,excludeTags:b.filters.excludeTags,excludeFiles:b.filters.excludeFiles},T=h?`${mg}name=${h}|${X0(n,w,v)}${y?"|multi":""}`:`${mg}${b3({folderPath:n,mode:u,label:m,optional:s,allowCustomInput:l,multiSelect:y,filter:w,extensions:v})}`;return{raw:r,folderPath:n,mode:u,label:m,aliasName:h,optional:s,allowCustomInput:l,filter:w,multiSelect:y,multiFormat:C,types:g,extensions:v,variableKey:T}}function J0(r,t){if(!r)return r;for(let e of t)if(r===e)return r;return`${Jo}${r}`}function Od(r){return typeof r!="string"||r===""?{kind:"empty"}:r.startsWith(Jo)?{kind:"custom",text:r.slice(Jo.length)}:r.startsWith(Jl)?{kind:"file",path:r.slice(Jl.length)}:{kind:"raw",value:r}}function Ap(r){return(r.split("/").pop()??r).replace(/\.(md|canvas|base)$/i,"")}function Ip(r){return(r.split("/").pop()??r).replace(/\.md$/i,"")}function Z0(r){return typeof r=="string"&&r.trim().length>0?r.trim():void 0}function w3(r){if(!r)return;let t=Object.entries(r).find(([e])=>e.toLowerCase()==="title");return t?Z0(t[1]):void 0}function C3(r){let t=r?.headings?.find(e=>e.level===1);return Z0(t?.heading)}function E3(r,t){let e=w3(t?.frontmatter);return e||(Object.values(x3).some(i=>i.test(r))?C3(t)??r:r)}function T3(r){let t=r.parent?.path;return t&&t!=="/"?t:r.path.includes("/")?r.path.slice(0,r.path.lastIndexOf("/")):"vault root"}function _3(r){return r.extension&&r.extension!=="md"?r.name:r.basename||Ip(r.path)}function Dd(r,t,e){let n=e.trim().toLowerCase(),i=t.findIndex(o=>o.some(s=>s.toLowerCase()===n));return i>=0?r[i]:void 0}function Ds(r,t){let e=r.map(i=>{let o=t?.(i)??null,s=_3(i),a=E3(s,o),l=a===s?s:`${a} (${s})`,c=(0,Q0.parseFrontMatterAliases)(o?.frontmatter)??[];return{file:i,primary:a,label:l,aliases:c}}),n=new Map;for(let{label:i}of e)n.set(i,(n.get(i)??0)+1);return e.map(({file:i,primary:o,label:s,aliases:a})=>{let l=(n.get(s)??0)<=1?s:`${s} - ${T3(i)}`;return{primary:o,secondary:i.path,label:l,aliases:a}})}var Q0,mg,Jl,Jo,h3,g3,x3,Ln=x(()=>{Q0=require("obsidian");Da();jl();mg="FILE:",Jl="@file:",Jo="@filecustom:",h3=new Set(["name","link","path"]),g3=new Map([["note",["md"]],["image",["avif","bmp","gif","jpeg","jpg","png","svg","webp"]],["audio",["3gp","flac","m4a","mp3","ogg","wav","webm"]],["video",["mkv","mov","mp4","ogv","webm"]],["pdf",["pdf"]]]);x3={timestamp:/^\d{12,}$/,compactUuid:/^[0-9a-f]{32}$/i,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ulid:/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i}});function tL(r,t,e){return Array.isArray(r)?r.map(n=>eL(n,t,e)):eL(r,t,e)}function eL(r,t,e){if(t==="link")return e(r);let n=Od(r);switch(n.kind){case"empty":return"";case"file":return t==="path"?n.path:Ip(n.path);case"custom":case"raw":return n.kind==="custom"?n.text:n.value}}var rL=x(()=>{Ln()});function Ow(r){return new Promise(t=>window.setTimeout(t,r))}function Zl(r){return r.split(` `)}var Pp=x(()=>{});var Dw,fg,Eo,lA=x(()=>{Dw=class{isResolved(){return!this.hasConflicts}isConflicted(){return this.hasConflicts}},fg=class r extends Dw{constructor(t,e,n){super(),this.left=t,this.base=e,this.right=n,this.hasConflicts=!0}static create(t){return new r(t.left,t.base,t.right)}apply(t){return r.create({left:t(this.left),base:t(this.base),right:t(this.right)})}},Eo=class r extends Dw{constructor(t){super(),this.hasConflicts=!1,this.result=t}combine(t){this.result=this.result.concat(t.result)}apply(t){return new r(t(this.result))}}});var La,cA,$p,dA,uA,Ls,hg,Lw,Nw=x(()=>{La=class r{constructor(t,e){this.left=t,this.right=e}static executeDiff(t,e){if(!t.push)throw new Error("Argument is not an array");let n=r.diff(t,e);return new dA(t,e,n).convertToTypedOutput()}static diff(t,e){return new r(t,e).performDiff()}performDiff(){let t=this.identifyUniquePositions();t.sort((o,s)=>s[0]-o[0]);let[e,n]=this.findNextChange(),i=new Lw(e,n,[]);return t.forEach(o=>{i=this.getDifferences(i,o)}),i.changeRanges}getDifferences(t,e){let[n,i]=[t.leftChangePos,t.rightChangePos],[o,s]=e;if(on||e>i)return[t,n,e,i];{let o=this.left.slice(t,n+1).reverse()||[],s=this.right.slice(e,i+1).reverse()||[],a=this.mismatchOffset(o,s);return[t,n-a,e,i-a]}}mismatchOffset(t,e){let n=Math.max(t.length,e.length);for(let i=0;ii.has(a)))].map(a=>[t.get(a),e.get(a)]);return s.unshift([this.left.length,this.right.length]),s}findUnique(t){let e=new Map;t.forEach((i,o)=>{e.set(i,new cA(o,!e.has(i)))});let n=new Map;for(let[i,o]of e.entries())o.unique&&n.set(i,o.pos);return n}appendChangeRange(t,e,n,i,o){return e<=n&&i<=o?t.push(new hg(Ls.change,e+1,n+1,i+1,o+1)):e<=n?t.push(new hg(Ls.remove,e+1,n+1,i+1,i)):i<=o&&t.push(new hg(Ls.add,e+1,e,i+1,o+1)),t}},cA=class{constructor(t,e){this.pos=t,this.unique=e}},$p=class{constructor(t,e){this.text=t,this.low=e}},dA=class{constructor(t,e,n){this.oldTextArray=t,this.newTextArray=e,this.chunks=n,this.oldText=[],this.newText=[]}convertToTypedOutput(){let t=new uA(0,0);return this.chunks.forEach(e=>{let[n,i]=this.setTextNodeIndexes(e,t.oldIndex,t.newIndex),[o,s]=this.appendChanges(e,t.oldIndex+n,t.newIndex+i);t.oldIndex=o,t.newIndex=s}),this.setTheRemainingTextNodeIndexes(t.oldIndex,t.newIndex),{oldText:this.oldText,newText:this.newText}}setTextNodeIndexes(t,e,n){let i=0;for(;e+i{Nw();Vw=class r{constructor(t,e,n,i,o){this.code=t,this.baseLo=e,this.baseHi=n,this.sideLo=i,this.sideHi=o}static fromChangeRange(t){return new r(t.action,t.leftLo,t.leftHi,t.rightLo,t.rightHi)}},Fp=class r{constructor(t,e,n){this.left=t,this.base=e,this.right=n}static executeDiff(t,e,n){return new r(t,e,n).getDifferences()}getDifferences(){let t=La.diff(this.base,this.left).map(n=>Vw.fromChangeRange(n)),e=La.diff(this.base,this.right).map(n=>Vw.fromChangeRange(n));return this.collapseDifferences(new Bw(t,e))}collapseDifferences(t,e=[]){if(t.isFinished())return e;{let n=new Bw,i=t.chooseSide(),o=t.dequeue();return n.enqueue(i,o),t.switchSides(),this.buildResultQueue(t,o.baseHi,n),e.push(this.determineDifference(n,i,t.switchSides())),this.collapseDifferences(t,e)}}buildResultQueue(t,e,n){if(this.queueIsFinished(t.peek(),e))return n;{let i=t.dequeue();return n.enqueue(t.currentSide,i),ee+1}determineDifference(t,e,n){let i=t.get(e)[0].baseLo,o=t.get(n),s=o[o.length-1].baseHi,[a,l]=this.diffableEndpoints(t.get(Nr.left),i,s),[c,d]=this.diffableEndpoints(t.get(Nr.right),i,s),u=this.left.slice(a-1,l),p=this.right.slice(c-1,d),m=this.decideAction(t,u,p);return new pA(m,a,l,c,d,i,s)}diffableEndpoints(t,e,n){if(t.length){let i=t[0],o=t[t.length-1],s=i.sideLo-i.baseLo+e,a=o.sideHi-o.baseHi+n;return[s,a]}else return[e,n]}decideAction(t,e,n){return t.isEmpty(Nr.left)?Na.chooseRight:t.isEmpty(Nr.right)?Na.chooseLeft:e.every((i,o)=>n[o]===i)?Na.noConflictFound:Na.possibleConflict}},pA=class{constructor(t,e,n,i,o,s,a){this.changeType=t,this.leftLo=e,this.leftHi=n,this.rightLo=i,this.rightHi=o,this.baseLo=s,this.baseHi=a}};(function(r){r.chooseRight="choose_right",r.chooseLeft="choose_left",r.possibleConflict="possible_conflict",r.noConflictFound="no_conflict_found"})(Na||(Na={}));(function(r){r.left="left",r.right="right"})(Nr||(Nr={}));Bw=class{constructor(t=[],e=[]){this.diffs={left:t,right:e}}dequeue(t=this.currentSide){return this.diffs[t].shift()}peek(t=this.currentSide){return this.diffs[t]}isFinished(){return this.isEmpty(Nr.left)&&this.isEmpty(Nr.right)}enqueue(t=this.currentSide,e){return this.diffs[t].push(e)}get(t=this.currentSide){return this.diffs[t]}isEmpty(t=this.currentSide){return this.diffs[t].length===0}switchSides(t=this.currentSide){return this.currentSide=t===Nr.left?Nr.right:Nr.left}chooseSide(){return this.isEmpty(Nr.left)?this.currentSide=Nr.right:this.isEmpty(Nr.right)?this.currentSide=Nr.left:this.currentSide=this.get(Nr.left)[0].baseLo<=this.get(Nr.right)[0].baseLo?Nr.left:Nr.right,this.currentSide}}});var gg,fA,nL=x(()=>{lA();mA();Nw();gg=class r{static merge(t,e,n){let i=new r(t,e,n);return i.executeThreeWayMerge(),i.result}constructor(t,e,n){this.result=[],this.text3=new fA(t,n,e)}executeThreeWayMerge(){let t=Fp.executeDiff(this.text3.left,this.text3.base,this.text3.right),e=1;t.forEach(i=>{let o=[];for(let s=e;s{for(let l=i;l<=s.leftLo;l++)this.result.push(new Eo(this.accumulateLines(i,l,n)));let a=this.determineOutcome(s,e,n);i=s.rightHi+1,a&&this.result.push(a)});let o=this.accumulateLines(i,n.length+1,n);o.length&&this.result.push(new Eo(o))}determineOutcome(t,e,n){return t.action===Ls.change?fg.create({left:this.accumulateLines(t.rightLo,t.rightHi,e),right:this.accumulateLines(t.leftLo,t.leftHi,n),base:[]}):t.action===Ls.add?new Eo(this.accumulateLines(t.rightLo,t.rightHi,e)):null}setText(t,e,n){let i=[];for(let o=e;o<=n;o++)i.push(t[o-1]);return i}_conflictRange(t){let e=this.setText(this.text3.right,t.rightLo,t.rightHi),n=this.setText(this.text3.left,t.leftLo,t.leftHi),i=La.diff(e,n);(this._assocRange(i,Ls.change)||this._assocRange(i,Ls.remove))&&t.baseLo<=t.baseHi?this.setConflict(t):this.determineConflict(i,n,e)}interpretChunk(t){if(t.changeType==Na.chooseLeft){let e=this.accumulateLines(t.leftLo,t.leftHi,this.text3.left);e.length&&this.result.push(new Eo(e))}else if(t.changeType!==Na.possibleConflict){let e=this.accumulateLines(t.rightLo,t.rightHi,this.text3.right);e.length&&this.result.push(new Eo(e))}else this._conflictRange(t)}_assocRange(t,e){for(let n=0;n{Ld=class{constructor(t,e,n={}){this.results=t,this.joinFunction=e,this.conflictHandler=n.conflictHandler,this.conflict=n.conflict||!1}isSuccess(){return!this.conflict}isConflict(){return!!this.conflict}joinedResults(){if(this.isConflict())return this.conflictHandler?this.conflictHandler(this.results):this.results;{let[t,e]=[this.results[0],this.results.slice(1)],n=t;return e.forEach(i=>n.combine(i)),n.apply(this.joinFunction).result}}}});var vg,oL=x(()=>{lA();iL();vg=class r{static collateMerge(t,e,n){return t.length?(t=r.combineNonConflicts(t),t.length===1&&t[0].isResolved()?new Ld(t,e):new Ld(t,e,{conflict:!0,conflictHandler:n})):new Ld([new Eo([])],e)}static combineNonConflicts(t){let e=[];return t.forEach(n=>{e.length&&e[e.length-1].isResolved()&&n.isResolved()?e[e.length-1].combine(n):e.push(n)}),e}}});function sL(r,t,e,n){return function(o){return o.map(s=>{if(s.isResolved())return s.apply(n).result;{let a=s.apply(n),{left:l,right:c}=a;return[r,l,t,c,e].join(` `)}}).join(` `)}}var aL=x(()=>{});function hA(r,t,e,n={}){n=Object.assign({},A3,n);let[i,o,s]=[r,t,e].map(c=>n.splitFunction.call(n,c)),a=gg.merge(i,o,s);return vg.collateMerge(a,n.joinFunction,n.conflictFunction)}var lL,k3,S3,A3,cL=x(()=>{nL();oL();aL();lL=r=>r.join(""),k3=r=>r.split(/\b/),S3=sL("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",lL),A3={splitFunction:k3,joinFunction:lL,conflictFunction:S3}});var dL,uL=x(()=>{cL();mA();Nw();dL=hA});function Vr(r,t){if(!r)throw new Error(typeof t=="function"?t():t)}var Nd=x(()=>{});function vA(r,t){let e=i=>i instanceof gA.MarkdownView&&i.file===t&&!!i.editor&&i.getMode()==="source",n=r.workspace.getActiveViewOfType(gA.MarkdownView);return e(n)?n:r.workspace.getLeavesOfType("markdown").map(i=>i.view).find(e)??null}async function pL(r,t){let e=vA(r,t);e&&await yA(e)}async function Bd(r,t){return await pL(r,t),r.vault.read(t)}async function To(r,t,e){let n=vA(r,t);if(n){await yA(n);let i=await r.vault.read(t),{editor:o}=n,s=o.getValue();if(vA(r,t)===n&&s===Vd(i)){let a=Vd(e(s)),l=P3(s,a);return l&&(o.transaction({changes:[{from:o.offsetToPos(l.from),to:o.offsetToPos(l.to),text:l.text}]}),await yA(n).catch(c=>S.logWarning(`Could not save '${t.path}' yet: ${String(c)}`))),a}}return r.vault.process(t,e)}async function mL(r,t,e,n){let i=!1;return{content:await To(r,t,s=>{if(Vd(s)===Vd(e))return n;let a=dL(Vd(s),Vd(e),Vd(n));return Vr(a.isSuccess(),()=>`The file ${t.path} has been modified since the last read. QuickAdd could not merge the two versions without conflicts, and will not modify the file. This is in order to prevent data loss.`),i=!0,a.joinedResults()}),merged:i}}async function Va(r,t,e){await pL(r,t),await r.fileManager.processFrontMatter(t,e)}async function yA(r){await r.save();let t=()=>r.saving===!0;for(let e=0;t();e+=10){if(e>=I3)throw new Error(`Obsidian is still saving '${r.file?.path}'. Try again once it has saved.`);await Ow(10)}}function P3(r,t){if(r===t)return null;let e=Math.min(r.length,t.length),n=0;for(;n{gA=require("obsidian");Pp();uL();Nd();ye();I3=1e4});function Mp(r){return $3.has(r)}function Ba(r){return r==="inFrontmatter"}function Uw(r){return F3.has(r)}function M3(r,t,e){return r==="embed"&&e.type==="activeFile"&&Mp(t)?"embed":"link"}function R3(r,t,e,n){return r==="selection"&&e.type==="activeFile"&&Uw(t)&&n==="link"?"selection":"none"}function O3(r){return r?.type==="specifiedFile"?{type:"specifiedFile",path:typeof r.path=="string"?r.path.trim():""}:{type:"activeFile"}}function D3(r){return typeof r=="object"&&r!==null&&"enabled"in r&&"placement"in r}function Zo(r){if(D3(r)){let t=r.placement??"replaceSelection",e=O3(r.destination),n=M3(r.linkType,t,e);return{enabled:r.enabled,placement:t,requireActiveFile:r.requireActiveFile??!0,linkType:n,displayText:R3(r.displayText,t,e,n),destination:e,frontmatterProperty:r.frontmatterProperty,frontmatterHandling:Ba(t)?r.frontmatterHandling??Ud:r.frontmatterHandling}}return{enabled:r,placement:"replaceSelection",requireActiveFile:!!r,linkType:"link",displayText:"none",destination:{type:"activeFile"}}}var Ud,$3,F3,Ua=x(()=>{Ud="alwaysAppend",$3=new Set(["replaceSelection","afterSelection","endOfLine","newLine"]);F3=new Set(["replaceSelection","afterSelection"])});function bA(r){return r.vault.getConfig?.("useMarkdownLinks")===!0}function L3(r,t){let e=t.replace(/\s+/g,n=>/[\r\n]/.test(n)?" ":n).trim();if(e){if(bA(r))return e.replace(/\\/g,"\\\\").replace(/\[/g,"\\[").replace(/\]/g,"\\]");if(!(e.includes("]]")||e.includes("[[")||e.endsWith("]")))return e}}function N3(r){return`[[${r.path.replace(/\.md$/i,"")}]]`}function qw(r,t,e={}){let n=e.sourcePath??"";if(e.linkType==="embed"&&(!e.placement||Mp(e.placement)))return`![[${r.metadataCache.fileToLinktext(t,n)}]]`;let o=e.alias===void 0?void 0:L3(r,e.alias);return o===void 0?r.fileManager.generateMarkdownLink(t,n):r.fileManager.generateMarkdownLink(t,n,void 0,o)}function wA(r){let t=r.trim().replace(/^\/+/,"");return t?/\.md$/i.test(t)?t:`${t}.md`:""}function bg(r,t){if(t.type!=="specifiedFile")return null;let e=wA(t.path);if(!e)return null;let n=r.vault.getAbstractFileByPath(e);return!(n instanceof yg.TFile)||n.extension!=="md"?null:n}function V3(r,t){return r.length===0?t:r.endsWith(` `)?`${r}${t}`:`${r} ${t}`}async function hL(r,t,e,n){let i=e.destination;if(i?.type!=="specifiedFile")return!1;let o=bg(r,i);if(!o)throw new Error(`Append link target file not found or is not a Markdown file: ${i.path}`);return await CA(r,o,qw(r,t,{sourcePath:o.path,linkType:"link"}),n),!0}async function CA(r,t,e,n){let i;await To(r,t,o=>{let s=V3(o,e);return i={filePath:t.path,before:o,after:s,edits:[{from:o.length,to:o.length,text:s.slice(o.length)}]},s}),i&&n?.(i)}async function B3(r){let t=window.navigator?.clipboard;if(!t?.writeText)return S.logMessage("QuickAdd: Clipboard API is unavailable."),!1;try{return await t.writeText(r),!0}catch(e){return S.logMessage(`QuickAdd: Could not copy link to clipboard: ${e instanceof Error?e.message:String(e)}`),!1}}async function gL(r){let t=N3(r);return await B3(t)?(new yg.Notice(`Copied link to '${r.basename}' to clipboard.`,fL),!0):(new yg.Notice(`Created '${r.basename}', but QuickAdd could not copy its link to the clipboard.`,fL),!1)}var yg,fL,qd=x(()=>{yg=require("obsidian");Ns();ye();Ua();fL=4e3});function Rp(r){return r&&typeof r=="object"?r:void 0}function xA(r){return typeof r=="string"?r.trim():""}function vL(r){return r.replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"")}function yL(r){return`{{${r.toUpperCase()}}}`}function bL(r,t,e){return{source:r,folder:vL(xA(e.folder)),format:xA(e.format)||U3[t],template:vL(xA(e.template))}}function Hw(r,t){let e=Rp(Rp(r?.plugins?.plugins?.["periodic-notes"])?.settings);if(e&&"calendarSets"in e)throw new Error(`${yL(t)} can't read the settings of Periodic Notes 1.0. Use Periodic Notes 0.0.17, or turn it off and use the Daily notes core plugin.`);let n=Rp(e?.[t]);if(n?.enabled===!0)return bL("periodic-notes",t,n);if(t!=="daily")throw new Error(`${yL(t)} needs the Periodic Notes plugin with ${t} notes turned on.`);let i=Rp(r?.internalPlugins?.plugins?.["daily-notes"]);if(i?.enabled===!0)return bL("daily-notes",t,Rp(Rp(i.instance)?.options)??{});throw new Error("{{DAILY}} needs the Daily notes core plugin, or Periodic Notes with daily notes, turned on.")}function wL(r,t){return t.clone().startOf(q3[r])}function CL(r,t,e){let n=wL(t,e).format(r.format).trim().replace(/\.md$/i,"");if(!n)throw new Error(`The ${t} note format "${r.format}" gives an empty file name.`);return r.folder?`${r.folder}/${n}`:n}function xL(r,t,e){let n=r.vault.getAbstractFileByPath(`${t}.md`);if(n instanceof zw.TFile)return r.fileManager.generateMarkdownLink(n,e);if(!bA(r))return`[[${t}]]`;let i=encodeURI(`${t}.md`).replace(/\(/g,"%28").replace(/\)/g,"%29");return`[${(t.split("/").pop()??t).replace(/[\\[\]]/g,"\\$&")}](${i})`}async function EL(r,t,e){let{template:n}=t;if(!n)return null;let i=r.vault.getAbstractFileByPath(n),o=t.source==="periodic-notes"?r.metadataCache.getFirstLinkpathDest(n,""):i instanceof zw.TFile?i:r.vault.getAbstractFileByPath(`${n}.md`);if(!(o instanceof zw.TFile)){let s=t.source==="daily-notes"?"Daily notes":"Periodic Notes";throw new Error(`The ${e} note template "${n}" doesn't exist. Fix it in Settings \u2192 ${s}.`)}return r.vault.cachedRead(o)}function EA(r,t,e,n){return r.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(i,o,s,a,l,c)=>{let d=t.clone().set({hour:e.hour(),minute:e.minute(),second:e.second()});return s&&a&&l&&d.add(parseInt(a,10),l),c?d.format(c.substring(1).trim()):d.format(n)})}function TL(r,t,e,n,i){let{format:o}=t,s=wL(e,n);if(t.source==="daily-notes"){let c=s.format(o).trim();return r.replace(/{{(date|time|title)(?::([^}]*))?}}/gi,(d,u,p)=>{let m=u.toLowerCase();return m==="title"?p===void 0?c:d:i.format(p||(m==="date"?"YYYY-MM-DD":"HH:mm"))})}let a=s.format(o),l=i.format("HH:mm");if(e==="daily")return EA(r.replace(/{{\s*date\s*}}/gi,a).replace(/{{\s*time\s*}}/gi,l).replace(/{{\s*title\s*}}/gi,a),s,i,o).replace(/{{\s*yesterday\s*}}/gi,s.clone().subtract(1,"day").format(o)).replace(/{{\s*tomorrow\s*}}/gi,s.clone().add(1,"d").format(o));if(e==="weekly"){let c=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],d=s.localeData().firstDayOfWeek(),u=[...c.slice(d),...c.slice(0,d)];return EA(r,s,i,o).replace(/{{\s*title\s*}}/gi,a).replace(/{{\s*time\s*}}/gi,l).replace(/{{\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*:(.*?)}}/gi,(p,m,h)=>s.clone().weekday(u.indexOf(m.toLowerCase())).format(h.trim()))}return EA(r,s,i,o).replace(/{{\s*date\s*}}/gi,a).replace(/{{\s*time\s*}}/gi,l).replace(/{{\s*title\s*}}/gi,a)}var zw,TA,U3,q3,_A=x(()=>{zw=require("obsidian");qd();TA=/{{(DAILY|WEEKLY|MONTHLY|QUARTERLY|YEARLY)(\|link)?}}/i,U3={daily:"YYYY-MM-DD",weekly:"gggg-[W]ww",monthly:"YYYY-MM",quarterly:"YYYY-[Q]Q",yearly:"YYYY"},q3={daily:"day",weekly:"week",monthly:"month",quarterly:"quarter",yearly:"year"}});function _L(r){if(!r)return null;let t=r.indexOf("|");if(t===-1){let o=r.trim();return o?{macroName:o}:null}let e=r.slice(0,t).trim();if(!e)return null;let n=r.slice(t+1).trim();if(!n)return{macroName:e};if(!n.toLowerCase().startsWith("label:"))return null;let i=n.slice(6).trim();return{macroName:e,label:i||void 0}}var kL=x(()=>{});function AL(r){let t=r.trim();if(!t||/[\r\n\0]/.test(t)||t==="__proto__")throw new Error("Property name must be nonempty and contain no line breaks or unsafe keys.");return t}function IL(r){return Rh.test(r)}function PL(r){if(r==null)return"";if(Array.isArray(r)){if(!r.every(t=>typeof t=="string"))throw new Error("{{PROPERTY}} only expands lists of text.");if(r.some(t=>/[\r\n]/.test(t)))throw new Error("{{PROPERTY}} cannot expand a list item that contains a line break. Return a rewritten array from an inline script instead.");return r.join(` `)}if(typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return String(r);throw new Error("{{PROPERTY}} only expands text, finite numbers, checkboxes, and lists of text.")}function FL(r){return $L.map(t=>({key:t,present:r.has(t),value:r.get(t)}))}function ML(r,t){for(let e of t)e.present?r.set(e.key,e.value):r.delete(e.key)}function RL(r,t,e){for(let i of $L)if(!(!r.has(i)||r.get(i)===void 0))throw new Error(`Property Capture cannot seed '${i}' because that variable is already set. Rename your {{VALUE:${i}}} prompt (or other writer of this key) so it does not collide with the property snapshot.`);let n;e!=null&&(n=z3(e,t)),r.set("propertyKey",t),r.set("propertyValue",n),r.set("list",Array.isArray(n)?[...n]:[])}function z3(r,t){if(typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;if(Array.isArray(r)&&r.every(e=>typeof e=="string"))return[...r];throw new Error(`Property '${t}' supports text, finite numbers, checkboxes, and lists of text only.`)}function wg(r,t){if(Object.prototype.hasOwnProperty.call(r,t))return t;let e=Object.keys(r).filter(n=>n.trim().toLowerCase()===t.trim().toLowerCase());if(e.length>1)throw new Error(`Property '${t}' matches multiple properties in the target note.`);return e[0]??t}function OL(r){return r.split(/\r?\n/).map(t=>t.trim()).filter(t=>t!=="")}function DL(r){return typeof r=="string"?OL(r).length===0:Array.isArray(r)&&r.length===0}function SL(r,t){if(typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;if(Array.isArray(r)&&r.every(e=>typeof e=="string"))return[...r];throw new Error(`Property '${t}' supports text, finite numbers, checkboxes, and lists of text only.`)}function LL(r,t){if(r===null&&["tags","aliases","cssclasses"].includes(t.toLowerCase()))return"list";if(r===null)return null;switch(r.toLowerCase()){case"text":return"text";case"number":return"number";case"checkbox":case"boolean":return"checkbox";case"list":case"multitext":case"tags":case"aliases":return"list";case"date":return"date";case"datetime":return"datetime";default:throw new Error(`Property '${t}' has unsupported type '${r}'.`)}}function NL(r){if(r.action==="addToList")return!0;let t=LL(r.registeredType,r.key);return t==="list"||t===null&&Array.isArray(r.existing)}function Ww(r){return Array.isArray(r)?"list":typeof r=="boolean"?"checkbox":typeof r=="number"?"number":"text"}function H3(r,t,e){let n=Ww(r);if(t==="date"||t==="datetime"){if(typeof r=="string"&&(r===""||(t==="date"?/^\d{4}-\d{2}-\d{2}$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})?$/).test(r)&&Number.isFinite(Date.parse(r))&&new Date(r.slice(0,10)).toISOString().slice(0,10)===r.slice(0,10)))return}else if(n===t)return;throw new Error(`Property '${e}' requires ${t}; the capture is ${n}. Use a matching typed VALUE token or value.`)}function VL(r){let{frontmatter:t,config:e}=r,n=wg(t,r.key),i=Object.prototype.hasOwnProperty.call(t,n);if(!i&&!e.createIfMissing)throw new Error(`Property '${n}' is missing. Enable 'Create property if missing' to add it.`);let o=i?t[n]:void 0,s=SL(r.value,n),a=o==null?null:SL(o,n),l=LL(r.registeredType,n)??(a===null?null:Ww(a)),c=typeof s=="string"?OL(s):null;if(e.action==="addToList"){if(a!==null&&!Array.isArray(a))throw new Error(`Property '${n}' is ${Ww(a)}. 'Add to list' requires a list.`);if(l!==null&&l!=="list")throw new Error(`Property '${n}' is ${l}. 'Add to list' requires a list.`);let u=c??s;if(!Array.isArray(u))throw new Error(`Property '${n}' requires text or a list of text to add.`);return u.length===0?a??[]:r.compose?[...new Set(u)]:[...new Set([...a??[],...u])]}if(l==="list"&&a!==null&&!Array.isArray(a))throw new Error(`Property '${n}' contains ${Ww(a)}. Set a list only after correcting the existing property to a list.`);if(l===null&&c!==null&&c.length>1)throw new Error(`Property '${n}' has no type yet, so ${c.length} lines could be one text value or a list. Use 'Add to list' to write them as list items, or set the property's type in Obsidian first - Text keeps the lines as one value.`);let d=l==="list"?c??s:s;return l!==null&&H3(d,l,n),Array.isArray(d)?[...new Set(d)]:d}function BL(r){let t=(0,zd.getFrontMatterInfo)(r);if(!t.exists||!t.frontmatter.trim())return{};let e=(0,zd.parseYaml)(t.frontmatter);if(e===null)return{};if(!e||typeof e!="object"||Array.isArray(e))throw new Error("The capture target's frontmatter must be a property mapping.");return Object.fromEntries(Object.entries(e))}function UL(r,t){let e=(0,zd.getFrontMatterInfo)(r),n=e.exists?r.slice(e.contentStart):r;return`--- ${(0,zd.stringifyYaml)(t)}--- ${n}`}var zd,$L,kA=x(()=>{zd=require("obsidian");Le();$L=["propertyKey","propertyValue","list"]});var qL,Gw,ec,Op=x(()=>{nA();Rd();Rd();Oa();sA();qL=require("obsidian");Le();Ln();rL();_A();ye();Cw();Da();kL();kA();nA();Oa();Gw=10,ec=class extends kw{constructor(){super(...arguments);this.linkToCurrentFileBehavior="required";this.targetFolderPath=null;this.periodicNoteTarget=null;this.propertyTokenExpanded=!1}runClocks(){return this.clocks}setTemplateInclusionState(e){this.templateInclusion=e}replaceDateInString(e){let n=N0(e,{clocks:()=>this.runClocks(),applyCase:(i,o,s)=>this.applyCaseOption(i,o,s)});return TA.test(n)?this.replacePeriodicNotesInString(n):n}outermostIncluder(){return this.templateInclusion?.includer?.outermostIncluder()??this}replacePeriodicNotesInString(e){let n=this.runClocks(),i=window.moment(n?.date??n?.now),o=new RegExp(TA.source,"gi");return e.replace(o,(s,a,l)=>{let c=a.toLowerCase(),d=CL(Hw(this.app,c),c,i);return l&&this.app?xL(this.app,d,this.getLinkSourcePath()??""):(this.promptScope==="captureTarget"&&(this.outermostIncluder().periodicNoteTarget={path:d,period:c}),d)})}replaceTimeInString(e){return V0(e,{clocks:()=>this.runClocks(),applyCase:(n,i,o)=>this.applyCaseOption(n,i,o)})}async replaceSelectedInString(e){if(!Oh.test(e))return e;let n=await this.getSelectedText(),i=new RegExp(Oh.source,"gi"),o=this.userText(n);return e.replace(i,()=>o)}async replaceClipboardInString(e){if(!TS.test(e))return e;let n=await this.getClipboardContent(),i=new RegExp(TS.source,"gi"),o=this.userText(n);return e.replace(i,()=>o)}async replaceLinkToCurrentFileInString(e){if(!xS.test(e))return e;let n=this.getCurrentFileLink();if(!n){if(this.linkToCurrentFileBehavior==="required")throw new Error("Unable to get current file path. Make sure you have a file open in the editor.");S.logMessage("Skipping {{LINKCURRENT}} replacement because no active file is available.")}let i=new RegExp(xS.source,"gi");return e.replace(i,()=>n??"")}replaceLinkToCurrentSectionInString(e){if(!ES.test(e))return e;let n=this.getCurrentFileLinkToSection();if(!n){if(this.linkToCurrentFileBehavior==="required")throw new Error("Unable to get current file path. Make sure you have a file open in the editor.");S.logMessage("Skipping {{LINKSECTION}} replacement because no active file is available.")}let i=new RegExp(ES.source,"gi");return e.replace(i,()=>n??"")}replaceCurrentFileLinksInString(e){return this.replaceCurrentFileTokensInString(e,{links:!0})}replaceCurrentFileTokensInString(e,n){return W0(e,n,{LINKCURRENT:()=>this.getCurrentFileLink(),LINKSECTION:()=>this.getCurrentFileLinkToSection(),FILENAMECURRENT:()=>this.getCurrentFileName(),FOLDER:()=>this.targetFolderPath??"",FOLDERCURRENT:()=>this.getCurrentFolderPath(),TITLE:()=>this.getVariableValue("title")},this.linkToCurrentFileBehavior)}async replaceCurrentFileNameInString(e){return this.replaceCurrentFileTokensInString(e,{fileName:!0})}setLinkToCurrentFileBehavior(e){this.linkToCurrentFileBehavior=e}setTargetFolderPath(e){if(e==null){this.targetFolderPath=null;return}let n=e.trim();this.targetFolderPath=n==="/"?"":n.replace(/^\/+/,"").replace(/\/+$/,"")}replaceTargetFolderInString(e){return this.replaceCurrentFileTokensInString(e,{folder:!0})}getCurrentFileLinkToSection(){return null}getCurrentFolderPath(){return null}async replaceFieldVarInString(e){let n=new RegExp(dp.source,"gi"),i="",o=0,s;for(;(s=n.exec(e))!==null;){i+=e.slice(o,s.index);let a=s[1]+(s[2]||"");if(a){let l=this.getFieldVariableKey(a),c=Dn.parse(a,{warnUnknown:!0,warn:this.warnSink});this.hasConcreteVariable(l)||this.variables.set(l,await this.suggestForField(a,c));let d=this.hasConcreteVariable(l)?this.variables.get(l):this.getVariableValue(l);(!c.multiFormat||c.multiFormat==="auto")&&this.retainSingleTokenValue(e,s.index,s.index+s[0].length,d);let u;Array.isArray(d)?u=this.renderCollectedOrArrayValue({input:e,matchStart:s.index,matchEnd:s.index+s[0].length,rawValue:d,fallbackKey:c.fieldName,heuristicEnabled:!1,multiFormat:c.multiFormat??"auto"})??d.join(","):u=$d(e,s.index,s.index+s[0].length,String(d??"")),i+=this.userText(u)}else i+=s[0];o=n.lastIndex}return i+e.slice(o)}getFieldVariableKey(e){return`${Bl}${e}`}async replaceFileInString(e){let n=new RegExp(rw.source,"gi"),i="",o=0,s;for(;(s=n.exec(e))!==null;){i+=e.slice(o,s.index);let a=Rw(s[1]??"",{warn:this.warnSink});if(!a){i+=s[0],o=n.lastIndex;continue}let l=a.variableKey;this.hasConcreteVariable(l)||this.variables.set(l,await this.suggestForFile(a));let c=tL(this.variables.get(l),a.mode,d=>this.getFileLinkForStoredValue(d));if(Array.isArray(c)){let d=this.renderCollectedOrArrayValue({input:e,matchStart:s.index,matchEnd:s.index+s[0].length,rawValue:c,fallbackKey:a.aliasName??a.folderPath,heuristicEnabled:!1,multiFormat:a.multiFormat});i+=this.userText(d??c.join(","))}else i+=this.userText(c);o=n.lastIndex}return i+e.slice(o)}getFileLinkForStoredValue(e){let n=Od(e);if(n.kind==="empty")return"";if(n.kind!=="file"){let s=n.kind==="custom"?n.text:n.value;return s?`[[${s}]]`:""}let i=n.path;if(!i)return"";let o=this.app?.vault.getAbstractFileByPath(i);return o instanceof qL.TFile?this.app?.fileManager.generateMarkdownLink(o,this.getLinkSourcePath()??"")??`[[${Ip(i)}]]`:`[[${Ip(i)}]]`}getLinkSourcePath(){return null}async replaceMathValueInString(e){let n=new RegExp(Mh.source,"gi"),i=this.variables.get("mvalue"),o=typeof i=="string"&&i.trim()?i:null,s="",a=0,l;for(;(l=n.exec(e))!==null;)s+=e.slice(a,l.index),s+=this.userText(o??await this.promptForMathValue()),a=l.index+l[0].length;return s+=e.slice(a),s}async replaceMacrosInString(e){let n=new RegExp(nw.source,"gi"),i="",o=0,s;for(;(s=n.exec(e))!==null;){i+=e.slice(o,s.index),o=s.index+s[0].length;let a=s[1]?_L(s[1]):null;if(!a)continue;let l=await this.getMacroValue(a.macroName,a.label?{label:a.label}:void 0);i+=l?l.toString():""}return i+=e.slice(o),i}async replaceDateVariableInString(e){return U0(e,{variables:this.variables,dateParser:this.dateParser,prompt:(n,i)=>this.promptForVariable(n,i),applyCase:(n,i,o)=>this.applyCaseOption(n,i,o)})}getValueTokenText(e){let n=this.variables.get(e);if(typeof n=="string"&&n.startsWith("@date:")&&window.moment?.(n.slice(6)).isValid()){let i=Pw(this.variables,e)??ag(!1);return dg(n,i,void 0,this.dateParser)?.text??""}return super.getValueTokenText(e)}async replaceTemplateInString(e){let n=e;for(;As.test(n);){let i=As.exec(n);if(!i||!i[1])continue;let o=i[1];if(this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0}),this.templateInclusion.visited.has(o)){let a=`[QuickAdd: template inclusion cycle detected at "${o}"]`;this.reportProblem(a),n=this.replacer(n,As,a);continue}if(this.templateInclusion.depth>=Gw){let a=`[QuickAdd: max template inclusion depth (${Gw}) exceeded at "${o}"]`;this.reportProblem(a),n=this.replacer(n,As,a);continue}this.templateInclusion.visited.add(o);let s;try{s=await this.getTemplateContent(o)}finally{this.templateInclusion.visited.delete(o)}n=this.replacer(n,As,s)}return n}replaceLinebreakInString(e){let n="";for(let i=0;i=p)break;if(ph.start){u=!0;break}}}if(d!==-1&&!u){i+=e.slice(o,d+2),o=d+2;continue}}let l=e[o],c=e[o+1];l==="\\"?c==="n"?(i+=` `,o+=2):c==="\\"?(i+="\\",o+=2):(i+="\\",o+=1):(i+=l,o+=1)}return i}replaceRandomInString(e){let n=e;for(;_S.test(n);){let i=_S.exec(n);if(!i||!i[1])continue;let o=parseInt(i[1]);if(o<=0||o>100)throw new Error(`Random string length must be between 1 and 100. Got: ${o}`);let s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a="";for(let l=0;li)}}});function HL(r){return r<=31||r===127||r===8232||r===8233}function j3(r){let t="",e=0;for(;e0&&t.includes(r[e-1]);)e--;return r.slice(0,e)}function Hd(r){return Y3.filter(t=>r.includes(t))}function jL(r){return`A file or folder name cannot contain ${QL(r)}, so this choice would fail at run time. ${KL}`}function YL(r,t){return`Cannot create "${t}": a file or folder name cannot contain ${QL(r)}. ${KL}`}function QL(r){return r.map(t=>`"${t}"`).join(", ")}function Br(r,t="File path"){let{path:e,problems:n}=JL(r,t);if(n.length>0)throw new Error(n[0]);return e}function XL(r,t="File path"){return JL(r,t)}function JL(r,t){let e=[],n=r.replace(/\\/g,"/").split("/");return{path:n.map((o,s)=>o.length===0&&s!==0&&s!==n.length-1?(e.push(`${t} contains an empty path segment after formatting.`),o):K3(o,t,e)).join("/"),problems:e}}function K3(r,t,e){if(r.length===0)return r;let n=W3.test(r),i=G3.test(r),o=j3(r);n&&(o=o.replace(/^ /u,"")),i&&(o=o.replace(/ $/u,""));let s=WL(o," ");return s==="."||s===".."?(e.push(`${t} cannot contain "." or ".." path segments.`),s):(o=WL(o,". "),o||e.push(`${t} contains an empty path segment after formatting.`),o)}var GL,W3,G3,Y3,KL,es=x(()=>{GL="\0-\x7F\u2028\u2029",W3=new RegExp(`^ *[${GL}]`,"u"),G3=new RegExp(`[${GL}] *$`,"u");Y3=[":"];KL="Check your own text and tokens like {{TIME}}, which is HH:mm."});function Np(r){if(r==null||typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")return"";let t=String(r).trim();return t.startsWith("#")?t.substring(1).trim():t}function xg(r){return r==null?[]:(Array.isArray(r)?r:typeof r=="string"?r.split(/,|\s+/):[r]).map(Np).filter(Boolean)}var IA=x(()=>{});var Vs,jw=x(()=>{IA();Vs=class{static filterFiles(t,e,n){let i=this.applyInclusionFilters(t,e,n);return this.applyExclusionFilters(i,e,n)}static applyInclusionFilters(t,e,n){let i=t,o=this.getIncludeFolders(e);return o.length>0&&(i=i.filter(s=>o.some(a=>this.matchesFolder(s,a)))),e.tags&&e.tags.length>0&&(i=i.filter(s=>this.matchesTags(s,e.tags??[],n,"all"))),i}static applyExclusionFilters(t,e,n){return t.filter(i=>!(e.excludeFolders?.length&&e.excludeFolders.some(o=>this.matchesFolder(i,o)))&&!(e.excludeTags?.length&&this.matchesTags(i,e.excludeTags,n,"any"))&&!(e.excludeFiles?.length&&e.excludeFiles.some(o=>this.matchesFile(i,o))))}static getIncludeFolders(t){let e=t.folders?.length?t.folders:t.folder?[t.folder]:[];return[...new Set(e.map(n=>this.normalizePath(n)).filter(Boolean))]}static matchesFolder(t,e){let n=this.normalizePath(e),i=this.normalizePath(t.path);return i.startsWith(n+"/")||i.substring(0,i.lastIndexOf("/"))===n}static matchesTags(t,e,n,i){let o=n(t);if(!o)return!1;let s=this.getAllTags(o),a=e.map(Np).filter(Boolean),l=c=>s.some(d=>d===c||d.startsWith(c+"/"));return i==="all"?a.every(l):a.some(l)}static matchesFile(t,e){return t.name===e||t.path===e}static getAllTags(t){let e=[];return t.frontmatter?.tags&&e.push(...xg(t.frontmatter.tags)),t.frontmatter?.tag&&e.push(...xg(t.frontmatter.tag)),t.tags&&e.push(...t.tags.map(n=>Np(n.tag))),e.filter(Boolean)}static normalizePath(t){return t.replace(/^\/+|\/+$/g,"")}}});function za(r){return r.vault.getAllLoadedFiles().filter(t=>t instanceof PA.TFolder).map(t=>t.path)}function Eg(r,t){let e=r.vault.getAbstractFileByPath(t);return!!e&&e instanceof PA.TFolder}function ts(r,t){let e=t.replace(/\/+$/,"");if(e==="")return r.vault.getMarkdownFiles();let n=`${e}/`;return r.vault.getMarkdownFiles().filter(i=>i.path===e||i.path.startsWith(n))}function Z3(r){return Object.entries(r.frontmatter??{}).filter(([t])=>["tag","tags"].includes(t.toLowerCase())).flatMap(([,t])=>xg(t)).filter(Boolean)}function e4(r,t){let e=r.metadataCache.getFileCache(t);if(!e)return[];let n=[];return e.frontmatter&&n.push(...Z3(e)),e.tags&&Array.isArray(e.tags)&&n.push(...e.tags.map(i=>Np(i.tag))),n}function lN(r,t){let e=t.replace(/^#/,"");return r.vault.getMarkdownFiles().filter(n=>e4(r,n).includes(e))}function Yw(r,t){return Vs.filterFiles(r.vault.getMarkdownFiles(),t,e=>r.metadataCache.getFileCache(e))}function t4(r,t){let e=t.trim().toLowerCase();return r==null?!1:Array.isArray(r)?r.some(n=>n!=null&&typeof n!="object"&&String(n).trim().toLowerCase()===e):typeof r=="object"?!1:String(r).trim().toLowerCase()===e}function Kw(r,t,e,n){let i=t.trim().toLowerCase();if(!i)return[];let o=r.vault.getMarkdownFiles().filter(a=>{let l=r.metadataCache.getFileCache(a)?.frontmatter;if(!l)return!1;let c=Object.entries(l).find(([d])=>d.toLowerCase()===i);return c?e===void 0?!0:t4(c[1],e):!1});return n&&(n.folder||n.tags?.length||n.excludeFolders?.length||n.excludeTags?.length||n.excludeFiles?.length)&&(o=Vs.filterFiles(o,n,a=>r.metadataCache.getFileCache(a))),o}function Vp(r,t){let{extensions:e}=t,n=e?e==="any"?r.vault.getFiles():r.vault.getFiles().filter(i=>e.has(i.extension.toLowerCase())):r.vault.getMarkdownFiles();return Vs.filterFiles(n,t.filter,i=>r.metadataCache.getFileCache(i))}var PA,bi=x(()=>{PA=require("obsidian");jw();IA()});function qi(r){if(!r.includes("\\|"))return r;let t="",e=0;for(let n of yi(r))t+=cN(r.slice(e,n.start)),t+=r.slice(n.start,n.end),e=n.end;return t+cN(r.slice(e))}var r4,cN,Wd=x(()=>{Oa();r4=/{{[^{}\n\r]*}}/g,cN=r=>r.replace(r4,t=>t.split("\\|").join("|"))});function rc(r,t){let e=r,n=new RegExp(iw.source,"gi"),i=0;for(;n.test(e)&&!(++i>5);)e=e.replace(n,(o,s)=>{let a=String(s??"").trim();if(!a)return o;let l=t?.[a];return typeof l=="string"?qi(l):""});return e}var Tg=x(()=>{Le();Wd()});var dt,Lt,zi,Ha=x(()=>{(function(r){r[r.AM=0]="AM",r[r.PM=1]="PM"})(dt||(dt={}));(function(r){r[r.SUNDAY=0]="SUNDAY",r[r.MONDAY=1]="MONDAY",r[r.TUESDAY=2]="TUESDAY",r[r.WEDNESDAY=3]="WEDNESDAY",r[r.THURSDAY=4]="THURSDAY",r[r.FRIDAY=5]="FRIDAY",r[r.SATURDAY=6]="SATURDAY"})(Lt||(Lt={}));(function(r){r[r.JANUARY=1]="JANUARY",r[r.FEBRUARY=2]="FEBRUARY",r[r.MARCH=3]="MARCH",r[r.APRIL=4]="APRIL",r[r.MAY=5]="MAY",r[r.JUNE=6]="JUNE",r[r.JULY=7]="JULY",r[r.AUGUST=8]="AUGUST",r[r.SEPTEMBER=9]="SEPTEMBER",r[r.OCTOBER=10]="OCTOBER",r[r.NOVEMBER=11]="NOVEMBER",r[r.DECEMBER=12]="DECEMBER"})(zi||(zi={}))});function rs(r,t){r.assign("day",t.getDate()),r.assign("month",t.getMonth()+1),r.assign("year",t.getFullYear())}function Qw(r,t){r.assign("hour",t.getHours()),r.assign("minute",t.getMinutes()),r.assign("second",t.getSeconds()),r.assign("millisecond",t.getMilliseconds()),r.assign("meridiem",t.getHours()<12?dt.AM:dt.PM)}function Wa(r,t){r.imply("day",t.getDate()),r.imply("month",t.getMonth()+1),r.imply("year",t.getFullYear())}function _g(r,t){r.imply("hour",t.getHours()),r.imply("minute",t.getMinutes()),r.imply("second",t.getSeconds()),r.imply("millisecond",t.getMilliseconds()),r.imply("meridiem",t.getHours()<12?dt.AM:dt.PM)}var Gd=x(()=>{Ha()});function nc(r,t,e,n,i=0){let o=0,s=0;for(;sn.dstStart(t.getFullYear())&&!(t>n.dstEnd(t.getFullYear()))?n.timezoneOffsetDuringDst:n.timezoneOffsetNonDst}var i4,$A=x(()=>{Ha();i4={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:120,timezoneOffsetNonDst:60,dstStart:r=>dN(r,zi.MARCH,Lt.SUNDAY,2),dstEnd:r=>dN(r,zi.OCTOBER,Lt.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-300,timezoneOffsetNonDst:-360,dstStart:r=>nc(r,zi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>nc(r,zi.NOVEMBER,Lt.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-240,timezoneOffsetNonDst:-300,dstStart:r=>nc(r,zi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>nc(r,zi.NOVEMBER,Lt.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-360,timezoneOffsetNonDst:-420,dstStart:r=>nc(r,zi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>nc(r,zi.NOVEMBER,Lt.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-420,timezoneOffsetNonDst:-480,dstStart:r=>nc(r,zi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>nc(r,zi.NOVEMBER,Lt.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360}});function cn(r,t){let e=new Date(r);if(t.y&&(t.year=t.y,delete t.y),t.mo&&(t.month=t.mo,delete t.mo),t.M&&(t.month=t.M,delete t.M),t.w&&(t.week=t.w,delete t.w),t.d&&(t.day=t.d,delete t.d),t.h&&(t.hour=t.h,delete t.h),t.m&&(t.minute=t.m,delete t.m),t.s&&(t.second=t.s,delete t.s),t.ms&&(t.millisecond=t.ms,delete t.ms),"year"in t){let n=Math.floor(t.year);e.setFullYear(e.getFullYear()+n);let i=t.year-n;i>0&&(t.month=t?.month??0,t.month+=i*12)}if("quarter"in t){let n=Math.floor(t.quarter);e.setMonth(e.getMonth()+n*3)}if("month"in t){let n=Math.floor(t.month);e.setMonth(e.getMonth()+n);let i=t.month-n;i>0&&(t.week=t?.week??0,t.week+=i*4)}if("week"in t){let n=Math.floor(t.week);e.setDate(e.getDate()+n*7);let i=t.week-n;i>0&&(t.day=t?.day??0,t.day+=Math.round(i*7))}if("day"in t){let n=Math.floor(t.day);e.setDate(e.getDate()+n);let i=t.day-n;i>0&&(t.hour=t?.hour??0,t.hour+=Math.round(i*24))}if("hour"in t){let n=Math.floor(t.hour);e.setHours(e.getHours()+n);let i=t.hour-n;i>0&&(t.minute=t?.minute??0,t.minute+=Math.round(i*60))}if("minute"in t){let n=Math.floor(t.minute);e.setMinutes(e.getMinutes()+n);let i=t.minute-n;i>0&&(t.second=t?.second??0,t.second+=Math.round(i*60))}if("second"in t){let n=Math.floor(t.second);e.setSeconds(e.getSeconds()+n);let i=t.second-n;i>0&&(t.millisecond=t?.millisecond??0,t.millisecond+=Math.round(i*1e3))}if("millisecond"in t){let n=Math.floor(t.millisecond);e.setMilliseconds(e.getMilliseconds()+n)}return e}function ic(r){let t={};for(let e in r)t[e]=-r[e];return t}var uN,Ga=x(()=>{uN={day:0,second:0,millisecond:0}});var oc,mt,ja,ns=x(()=>{Gd();$A();Ga();oc=class r{constructor(t,e){fe(this,"instant");fe(this,"timezoneOffset");this.instant=t??new Date,this.timezoneOffset=e??null}static fromDate(t){return new r(t)}static fromInput(t,e){if(t instanceof Date)return r.fromDate(t);let n=t?.instant??new Date,i=Xw(t?.timezone,n,e);return new r(n,i)}getDateWithAdjustedTimezone(){let t=new Date(this.instant);return this.timezoneOffset!==null&&t.setMinutes(t.getMinutes()-this.getSystemTimezoneAdjustmentMinute(this.instant)),t}getSystemTimezoneAdjustmentMinute(t,e){t||(t=new Date);let n=-t.getTimezoneOffset(),i=e??this.timezoneOffset??n;return n-i}getTimezoneOffset(){return this.timezoneOffset??-this.instant.getTimezoneOffset()}},mt=class r{constructor(t,e){fe(this,"knownValues");fe(this,"impliedValues");fe(this,"reference");fe(this,"_tags",new Set);if(this.reference=t,this.knownValues={},this.impliedValues={},e)for(let i in e)this.knownValues[i]=e[i];let n=t.getDateWithAdjustedTimezone();this.imply("day",n.getDate()),this.imply("month",n.getMonth()+1),this.imply("year",n.getFullYear()),this.imply("hour",12),this.imply("minute",0),this.imply("second",0),this.imply("millisecond",0)}static createRelativeFromReference(t,e=uN){let n=cn(t.getDateWithAdjustedTimezone(),e),i=new r(t);return i.addTag("result/relativeDate"),"hour"in e||"minute"in e||"second"in e||"millisecond"in e?(i.addTag("result/relativeDateAndTime"),Qw(i,n),rs(i,n),i.assign("timezoneOffset",t.getTimezoneOffset())):(_g(i,n),i.imply("timezoneOffset",t.getTimezoneOffset()),"day"in e?(i.assign("day",n.getDate()),i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear()),i.assign("weekday",n.getDay())):"week"in e?(i.assign("day",n.getDate()),i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear()),i.imply("weekday",n.getDay())):(i.imply("day",n.getDate()),"month"in e?(i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear())):(i.imply("month",n.getMonth()+1),"year"in e?i.assign("year",n.getFullYear()):i.imply("year",n.getFullYear())))),i}get(t){return t in this.knownValues?this.knownValues[t]:t in this.impliedValues?this.impliedValues[t]:null}isCertain(t){return t in this.knownValues}getCertainComponents(){return Object.keys(this.knownValues)}imply(t,e){return t in this.knownValues?this:(this.impliedValues[t]=e,this)}assign(t,e){return this.knownValues[t]=e,delete this.impliedValues[t],this}addDurationAsImplied(t){let e=this.dateWithoutTimezoneAdjustment(),n=cn(e,t);return("day"in t||"week"in t||"month"in t||"year"in t)&&(this.delete(["day","weekday","month","year"]),this.imply("day",n.getDate()),this.imply("weekday",n.getDay()),this.imply("month",n.getMonth()+1),this.imply("year",n.getFullYear())),("second"in t||"minute"in t||"hour"in t)&&(this.delete(["second","minute","hour"]),this.imply("second",n.getSeconds()),this.imply("minute",n.getMinutes()),this.imply("hour",n.getHours())),this}delete(t){typeof t=="string"&&(t=[t]);for(let e of t)delete this.knownValues[e],delete this.impliedValues[e]}clone(){let t=new r(this.reference);t.knownValues={},t.impliedValues={};for(let e in this.knownValues)t.knownValues[e]=this.knownValues[e];for(let e in this.impliedValues)t.impliedValues[e]=this.impliedValues[e];return t}isOnlyDate(){return!this.isCertain("hour")&&!this.isCertain("minute")&&!this.isCertain("second")}isOnlyTime(){return!this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")&&!this.isCertain("year")}isOnlyWeekdayComponent(){return this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")}isDateWithUnknownYear(){return this.isCertain("month")&&!this.isCertain("year")}isValidDate(){let t=new Date(Date.UTC(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond")));return t.setUTCFullYear(this.get("year")),!(t.getUTCFullYear()!==this.get("year")||t.getUTCMonth()!==this.get("month")-1||t.getUTCDate()!==this.get("day")||this.get("hour")!=null&&t.getUTCHours()!=this.get("hour")||this.get("minute")!=null&&t.getUTCMinutes()!=this.get("minute"))}toString(){return`[ParsingComponents { tags: ${JSON.stringify(Array.from(this._tags).sort())}, knownValues: ${JSON.stringify(this.knownValues)}, impliedValues: ${JSON.stringify(this.impliedValues)}}, reference: ${JSON.stringify(this.reference)}]`}date(){let t=this.get("timezoneOffset")??this.reference.timezoneOffset;if(t==null)return this.dateWithoutTimezoneAdjustment();let e=new Date(Date.UTC(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond")));return e.setUTCFullYear(this.get("year")),new Date(e.getTime()-t*6e4)}addTag(t){return this._tags.add(t),this}addTags(t){for(let e of t)this._tags.add(e);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let t=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 t.setFullYear(this.get("year")),t}},ja=class r{constructor(t,e,n,i,o){fe(this,"refDate");fe(this,"index");fe(this,"text");fe(this,"reference");fe(this,"start");fe(this,"end");this.reference=t,this.refDate=t.instant,this.index=e,this.text=n,this.start=i||new mt(t),this.end=o}clone(){let t=new r(this.reference,this.index,this.text);return t.start=this.start?this.start.clone():null,t.end=this.end?this.end.clone():null,t}date(){return this.start.date()}addTag(t){return this.start.addTag(t),this.end&&this.end.addTag(t),this}addTags(t){return this.start.addTags(t),this.end&&this.end.addTags(t),this}tags(){let t=new Set(this.start.tags());if(this.end)for(let e of this.end.tags())t.add(e);return t}toString(){let t=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(t)} ...}]`}}});function FA(r,t,e="\\s{0,5},?\\s{0,5}"){let n=t.replace(/\((?!\?)/g,"(?:");return`${r}${n}(?:${e}${n}){0,10}`}function o4(r){let t;return r instanceof Array?t=[...r]:r instanceof Map?t=Array.from(r.keys()):t=Object.keys(r),t}function Ur(r){return`(?:${o4(r).sort((e,n)=>n.length-e.length).join("|").replace(/\./g,"\\.")})`}var Ya=x(()=>{});function Jw(r){return r<100&&(r>50?r=r+1900:r=r+2e3),r}function sc(r,t,e){let n=new Date(r);n.setMonth(e-1),n.setDate(t);let i=cn(n,{year:1}),o=cn(n,{year:-1});return Math.abs(i.getTime()-r.getTime()){Ga()});function s4(r){let t=r.toLowerCase();return MA[t]!==void 0?MA[t]:t==="a"||t==="an"||t=="the"?1:t.match(/few/)?3:t.match(/half/)?.5:t.match(/couple/)?2:t.match(/several/)?7:parseFloat(t)}function zp(r){let t=r.toLowerCase();return RA[t]!==void 0?RA[t]:(t=t.replace(/(?:st|nd|rd|th)$/i,""),parseInt(t))}function Bs(r){if(/BE/i.test(r))return r=r.replace(/BE/i,""),parseInt(r)-543;if(/BCE?/i.test(r))return r=r.replace(/BCE?/i,""),-parseInt(r);if(/(AD|CE)/i.test(r))return r=r.replace(/(AD|CE)/i,""),parseInt(r);let t=parseInt(r);return Jw(t)}function _o(r){let t={},e=r,n=pN.exec(e);for(;n;)l4(t,n),e=e.substring(n[0].length).trim(),n=pN.exec(e);return Object.keys(t).length==0?null:t}function l4(r,t){if(t[0].match(/^[a-zA-Z]+$/))return;let e=s4(t[1]),n=kg[t[2].toLowerCase()];r[n]=e}var Zw,OA,ii,MA,RA,mN,kg,fN,qp,ac,hN,pN,a4,gN,Ka,lc,fr=x(()=>{Ya();Up();Zw={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},OA={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},ii={...OA,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},MA={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},RA={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},mN={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"day",days:"day",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},kg={s:"second",sec:"second",second:"second",seconds:"second",m:"minute",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",hour:"hour",hours:"hour",d:"day",day:"day",days:"day",w:"week",week:"week",weeks:"week",mo:"month",mon:"month",mos:"month",month:"month",months:"month",qtr:"quarter",quarter:"quarter",quarters:"quarter",y:"year",yr:"year",year:"year",years:"year",...mN},fN=`(?:${Ur(MA)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;qp=`(?:${Ur(RA)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;ac="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-9][0-9]{3}|[0-9]{2}(?!\\w|:\\d|\\s+(?:am|pm|o\\s*clock|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)))";hN=`(${fN})\\s{0,3}(${Ur(kg)})`,pN=new RegExp(hN,"i"),a4=`(${fN})\\s{0,3}(${Ur(mN)})`,gN="\\s{0,5},?(?:\\s*and)?\\s{0,5}",Ka=FA("(?:(?:about|around)\\s{0,3})?",hN,gN),lc=FA("(?:(?:about|around)\\s{0,3})?",a4,gN)});var yt,Nn=x(()=>{yt=class{constructor(){fe(this,"cachedInnerPattern",null);fe(this,"cachedPattern",null)}innerPatternHasChange(t,e){return this.innerPattern(t)!==e}patternLeftBoundary(){return"(\\W|^)"}pattern(t){return this.cachedInnerPattern&&!this.innerPatternHasChange(t,this.cachedInnerPattern)?this.cachedPattern:(this.cachedInnerPattern=this.innerPattern(t),this.cachedPattern=new RegExp(`${this.patternLeftBoundary()}${this.cachedInnerPattern.source}`,this.cachedInnerPattern.flags),this.cachedPattern)}extract(t,e){let n=e[1]??"";e.index=e.index+n.length,e[0]=e[0].substring(n.length);for(let i=2;i{fr();ns();Nn();c4=new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Ka})(?=\\W|$)`,"i"),d4=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Ka})(?=\\W|$)`,"i"),u4=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${lc})(?=\\W|$)`,"i"),Sg=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(e){return this.strictMode?u4:e.option.forwardDate?c4:d4}innerExtract(e,n){if(n[0].match(/^for\s*the\s*\w+/))return null;let i=_o(n[1]);return i?mt.createRelativeFromReference(e.reference,i):null}}});var p4,yN,bN,m4,wN,Ag,CN=x(()=>{Up();fr();fr();fr();Ya();Nn();p4=new RegExp(`(?:on\\s{0,3})?(${qp})(?:\\s{0,3}(?:to|\\-|\\\u2013|until|through|till)\\s{0,3}(${qp}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${Ur(ii)})(?:(?:-|/|,?\\s{0,3})(${ac}(?!\\w)))?(?=\\W|$)`,"i"),yN=1,bN=2,m4=3,wN=4,Ag=class extends yt{innerPattern(){return p4}innerExtract(t,e){let n=t.createParsingResult(e.index,e[0]),i=ii[e[m4].toLowerCase()],o=zp(e[yN]);if(o>31)return e.index=e.index+e[yN].length,null;if(n.start.assign("month",i),n.start.assign("day",o),e[wN]){let s=Bs(e[wN]);n.start.assign("year",s)}else{let s=sc(t.refDate,o,i);n.start.imply("year",s)}if(e[bN]){let s=zp(e[bN]);n.end=n.start.clone(),n.end.assign("day",s)}return n}}});var f4,h4,xN,DA,LA,Ig,EN=x(()=>{Up();fr();fr();fr();Ya();Nn();f4=new RegExp(`(${Ur(ii)})(?:-|/|\\s*,?\\s*)(${qp})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${qp})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${ac}))?(?=\\W|$)(?!\\:\\d)`,"i"),h4=1,xN=2,DA=3,LA=4,Ig=class extends yt{constructor(e){super();fe(this,"shouldSkipYearLikeDate");this.shouldSkipYearLikeDate=e}innerPattern(){return f4}innerExtract(e,n){let i=ii[n[h4].toLowerCase()],o=zp(n[xN]);if(o>31||this.shouldSkipYearLikeDate&&!n[DA]&&!n[LA]&&n[xN].match(/^\d{2}$/))return null;let s=e.createParsingComponents({day:o,month:i}).addTag("parser/ENMonthNameMiddleEndianParser");if(n[LA]){let c=Bs(n[LA]);s.assign("year",c)}else{let c=sc(e.refDate,o,i);s.imply("year",c)}if(!n[DA])return s;let a=zp(n[DA]),l=e.createParsingResult(n.index,n[0]);return l.start=s,l.end=s.clone(),l.end.assign("day",a),l}}});var g4,v4,y4,TN,Pg,_N=x(()=>{fr();Up();Ya();fr();Nn();g4=new RegExp(`((?:in)\\s*)?(${Ur(ii)})\\s*(?:(?:,|-|of)?\\s*(${ac})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),v4=1,y4=2,TN=3,Pg=class extends yt{innerPattern(){return g4}innerExtract(t,e){let n=e[y4].toLowerCase();if(e[0].length<=3&&!OA[n])return null;let i=t.createParsingResult(e.index+(e[v4]||"").length,e.index+e[0].length);i.start.imply("day",1),i.start.addTag("parser/ENMonthNameParser");let o=ii[n];if(i.start.assign("month",o),e[TN]){let s=Bs(e[TN]);i.start.assign("year",s)}else{let s=sc(t.refDate,1,o);i.start.imply("year",s)}return i}}});var b4,w4,C4,kN,x4,$g,SN=x(()=>{fr();Ya();Nn();b4=new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${Ur(ii)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),w4=1,C4=2,kN=3,x4=4,$g=class extends yt{constructor(e){super();fe(this,"strictMonthDateOrder");this.strictMonthDateOrder=e}innerPattern(){return b4}innerExtract(e,n){let i=parseInt(n[w4]),o=parseInt(n[x4]),s=n[kN]?parseInt(n[kN]):ii[n[C4].toLowerCase()];if(s<1||s>12){if(this.strictMonthDateOrder)return null;o>=1&&o<=12&&([s,o]=[o,s])}return o<1||o>31?null:{day:o,month:s,year:i}}}});var E4,T4,_4,k4,Fg,AN=x(()=>{fr();Ya();fr();Nn();E4="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-9][0-9]{3})",T4=new RegExp(`(${E4})(?:\\s*[-.\\/,]?\\s*|\\s+of\\s+)(${Ur(ii)})(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),_4=1,k4=2,Fg=class extends yt{innerPattern(){return T4}innerExtract(t,e){let n=Bs(e[_4]),i=e[k4].toLowerCase(),o=ii[i],s=t.createParsingResult(e.index,e[0]);return s.start.imply("day",1),s.start.assign("month",o),s.start.assign("year",n),s.start.addTag("parser/ENYearMonthNameParser"),s}}});var S4,A4,I4,Mg,IN=x(()=>{Nn();S4=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),A4=1,I4=2,Mg=class extends yt{innerPattern(){return S4}innerExtract(t,e){let n=parseInt(e[I4]),i=parseInt(e[A4]);return t.createParsingComponents().imply("day",1).assign("month",i).assign("year",n)}}});function P4(r,t,e,n){return new RegExp(`${r}${t}(\\d{1,4})(?:(?:\\.|:|\uFF1A)(\\d{1,2})(?:(?::|\uFF1A)(\\d{2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${e}`,n)}function $4(r,t){return new RegExp(`^(${r})(\\d{1,4})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${t}`,"i")}var NA,jd,eC,tC,Hp,rC,PN=x(()=>{Ha();NA=2,jd=3,eC=4,tC=5,Hp=6,rC=class{constructor(t=!1){fe(this,"strictMode");fe(this,"cachedPrimaryPrefix",null);fe(this,"cachedPrimarySuffix",null);fe(this,"cachedPrimaryTimePattern",null);fe(this,"cachedFollowingPhase",null);fe(this,"cachedFollowingSuffix",null);fe(this,"cachedFollowingTimePatten",null);this.strictMode=t}patternFlags(){return"i"}primaryPatternLeftBoundary(){return"(^|\\s|T|\\b)"}primarySuffix(){return"(?!/)(?=\\W|$)"}followingSuffix(){return"(?!/)(?=\\W|$)"}pattern(t){return this.getPrimaryTimePatternThroughCache()}extract(t,e){let n=this.extractPrimaryTimeComponents(t,e);if(!n)return e[0].match(/^\d{4}/)?(e.index+=4,null):(e.index+=e[0].length,null);let i=e.index+e[1].length,o=e[0].substring(e[1].length),s=t.createParsingResult(i,o,n);e.index+=e[0].length;let a=t.text.substring(e.index),c=this.getFollowingTimePatternThroughCache().exec(a);return o.match(/^\d{3,4}/)&&c&&(c[0].match(/^\s*([+-])\s*\d{2,4}$/)||c[0].match(/^\s*([+-])\s*\d{2}\W\d{2}/))?null:!c||c[0].match(/^\s*([+-])\s*\d{3,4}$/)?this.checkAndReturnWithoutFollowingPattern(s):(s.end=this.extractFollowingTimeComponents(t,c,s),s.end&&(s.text+=c[0]),this.checkAndReturnWithFollowingPattern(s))}extractPrimaryTimeComponents(t,e,n=!1){let i=t.createParsingComponents(),o=0,s=null,a=parseInt(e[NA]);if(a>100){if(e[NA].length==4&&e[jd]==null&&!e[Hp]||this.strictMode||e[jd]!=null)return null;o=a%100,a=Math.floor(a/100)}if(a>24)return null;if(e[jd]!=null){if(e[jd].length==1&&!e[Hp])return null;o=parseInt(e[jd])}if(o>=60)return null;if(a>12&&(s=dt.PM),e[Hp]!=null){if(a>12)return null;let l=e[Hp][0].toLowerCase();l=="a"&&(s=dt.AM,a==12&&(a=0)),l=="p"&&(s=dt.PM,a!=12&&(a+=12))}if(i.assign("hour",a),i.assign("minute",o),s!==null?i.assign("meridiem",s):a<12?i.imply("meridiem",dt.AM):i.imply("meridiem",dt.PM),e[tC]!=null){let l=parseInt(e[tC].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(e[eC]!=null){let l=parseInt(e[eC]);if(l>=60)return null;i.assign("second",l)}return i}extractFollowingTimeComponents(t,e,n){let i=t.createParsingComponents();if(e[tC]!=null){let l=parseInt(e[tC].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(e[eC]!=null){let l=parseInt(e[eC]);if(l>=60)return null;i.assign("second",l)}let o=parseInt(e[NA]),s=0,a=-1;if(e[jd]!=null?s=parseInt(e[jd]):o>100&&(s=o%100,o=Math.floor(o/100)),s>=60||o>24)return null;if(o>=12&&(a=dt.PM),e[Hp]!=null){if(o>12)return null;let l=e[Hp][0].toLowerCase();l=="a"&&(a=dt.AM,o==12&&(o=0,i.isCertain("day")||i.imply("day",i.get("day")+1))),l=="p"&&(a=dt.PM,o!=12&&(o+=12)),n.start.isCertain("meridiem")||(a==dt.AM?(n.start.imply("meridiem",dt.AM),n.start.get("hour")==12&&n.start.assign("hour",0)):(n.start.imply("meridiem",dt.PM),n.start.get("hour")!=12&&n.start.assign("hour",n.start.get("hour")+12)))}return i.assign("hour",o),i.assign("minute",s),a>=0?i.assign("meridiem",a):n.start.isCertain("meridiem")&&n.start.get("hour")>12?n.start.get("hour")-12>o?i.imply("meridiem",dt.AM):o<=12&&(i.assign("hour",o+12),i.assign("meridiem",dt.PM)):o>12?i.imply("meridiem",dt.PM):o<=12&&i.imply("meridiem",dt.AM),i.date().getTime()24)return null}return t}checkAndReturnWithFollowingPattern(t){if(t.text.match(/^\d+-\d+$/))return null;let e=t.text.match(/[^\d:.](\d[\d.]+)\s*-\s*(\d[\d.]+)$/);if(e){if(this.strictMode)return null;let n=e[1],i=e[2];if(i.includes(".")&&!i.match(/\d(\.\d{2})+$/))return null;let o=parseInt(i),s=parseInt(n);if(o>24||s>24)return null}return t}getPrimaryTimePatternThroughCache(){let t=this.primaryPrefix(),e=this.primarySuffix();return this.cachedPrimaryPrefix===t&&this.cachedPrimarySuffix===e?this.cachedPrimaryTimePattern:(this.cachedPrimaryTimePattern=P4(this.primaryPatternLeftBoundary(),t,e,this.patternFlags()),this.cachedPrimaryPrefix=t,this.cachedPrimarySuffix=e,this.cachedPrimaryTimePattern)}getFollowingTimePatternThroughCache(){let t=this.followingPhase(),e=this.followingSuffix();return this.cachedFollowingPhase===t&&this.cachedFollowingSuffix===e?this.cachedFollowingTimePatten:(this.cachedFollowingTimePatten=$4(t,e),this.cachedFollowingPhase=t,this.cachedFollowingSuffix=e,this.cachedFollowingTimePatten)}}});var Rg,$N=x(()=>{Ha();PN();Rg=class extends rC{constructor(t){super(t)}followingPhase(){return"\\s*(?:\\-|\\\u2013|\\~|\\\u301C|to|until|through|till|\\?)\\s*"}primaryPrefix(){return"(?:(?:at|from)\\s*)??"}primarySuffix(){return"(?:\\s*(?:o\\W*clock|at\\s*night|in\\s*the\\s*(?:morning|afternoon)))?(?!/)(?=\\W|$)"}extractPrimaryTimeComponents(t,e){let n=super.extractPrimaryTimeComponents(t,e);if(!n)return n;if(e[0].endsWith("night")){let i=n.get("hour");i>=6&&i<12?(n.assign("hour",n.get("hour")+12),n.assign("meridiem",dt.PM)):i<6&&n.assign("meridiem",dt.AM)}if(e[0].endsWith("afternoon")){n.assign("meridiem",dt.PM);let i=n.get("hour");i>=0&&i<=6&&n.assign("hour",n.get("hour")+12)}return e[0].endsWith("morning")&&(n.assign("meridiem",dt.AM),n.get("hour")<12&&n.assign("hour",n.get("hour"))),n.addTag("parser/ENTimeExpressionParser")}extractFollowingTimeComponents(t,e,n){let i=super.extractFollowingTimeComponents(t,e,n);return i&&i.addTag("parser/ENTimeExpressionParser"),i}}});var F4,M4,Og,FN=x(()=>{fr();ns();Nn();Ga();F4=new RegExp(`(${Ka})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),M4=new RegExp(`(${lc})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),Og=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(){return this.strictMode?M4:F4}innerExtract(e,n){let i=_o(n[1]);return i?mt.createRelativeFromReference(e.reference,ic(i)):null}}});var R4,O4,D4,Dg,MN=x(()=>{fr();ns();Nn();R4=new RegExp(`(${Ka})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`,"i"),O4=new RegExp(`(${lc})\\s{0,5}(later|after|from now)(?=\\W|$)`,"i"),D4=1,Dg=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(){return this.strictMode?O4:R4}innerExtract(e,n){let i=_o(n[D4]);return i?mt.createRelativeFromReference(e.reference,i):null}}});var Wp,ko,cc=x(()=>{Wp=class{refine(t,e){return e.filter(n=>this.isValid(t,n))}},ko=class{refine(t,e){if(e.length<2)return e;let n=[],i=e[0],o=null;for(let s=1;s{console.log(`${this.constructor.name} merged ${l} and ${c} into ${d}`)}),i=d}}return i!=null&&n.push(i),n}}});var Lg,RN=x(()=>{cc();Ga();Lg=class extends ko{shouldMergeResults(t,e,n){return!e.end&&!n.end&&t.match(this.patternBetween())!=null}mergeResults(t,e,n){if(!e.start.isOnlyWeekdayComponent()&&!n.start.isOnlyWeekdayComponent()&&(n.start.getCertainComponents().forEach(o=>{e.start.isCertain(o)||e.start.imply(o,n.start.get(o))}),e.start.getCertainComponents().forEach(o=>{n.start.isCertain(o)||n.start.imply(o,e.start.get(o))})),e.start.date()>n.start.date()){let o=e.start.date(),s=n.start.date();n.start.isOnlyWeekdayComponent()&&cn(s,{day:7})>o?(s=cn(s,{day:7}),n.start.imply("day",s.getDate()),n.start.imply("month",s.getMonth()+1),n.start.imply("year",s.getFullYear())):e.start.isOnlyWeekdayComponent()&&cn(o,{day:-7})o?(s=cn(s,{year:1}),n.start.imply("year",s.getFullYear())):e.start.isDateWithUnknownYear()&&cn(o,{year:-1}){RN();Ng=class extends Lg{patternBetween(){return/^\s*(to|-|–|until|through|till)\s*$/i}}});function VA(r,t){let e=r.clone(),n=r.start,i=t.start;if(e.start=DN(n,i),r.end!=null||t.end!=null){let o=r.end==null?r.start:r.end,s=t.end==null?t.start:t.end,a=DN(o,s);if(r.end==null&&a.date().getTime()i.startsWith("casualReference/")));return t.isCertain("meridiem")?e.assign("meridiem",t.get("meridiem")):t.get("meridiem")!=null&&!n&&e.imply("meridiem",t.get("meridiem")),e.get("meridiem")==dt.PM&&e.get("hour")<12&&(t.isCertain("hour")?e.assign("hour",e.get("hour")+12):e.imply("hour",e.get("hour")+12)),e.addTags(r.tags()),e.addTags(t.tags()),e}var LN=x(()=>{Ha();Gd()});var Vg,NN=x(()=>{cc();LN();Vg=class extends ko{shouldMergeResults(t,e,n){return(e.start.isOnlyDate()&&n.start.isOnlyTime()||n.start.isOnlyDate()&&e.start.isOnlyTime())&&t.match(this.patternBetween())!=null}mergeResults(t,e,n){let i=e.start.isOnlyDate()?VA(e,n):VA(n,e);return i.index=e.index,i.text=e.text+t+n.text,i}}});var Gp,VN=x(()=>{NN();Gp=class extends Vg{patternBetween(){return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|\u2219|:)?\\s*$")}}});var L4,Bg,BN=x(()=>{$A();L4=new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)","i"),Bg=class{constructor(t){fe(this,"timezoneOverrides");this.timezoneOverrides=t}refine(t,e){let n=t.option.timezones??{};return e.forEach(i=>{let o=t.text.substring(i.index+i.text.length),s=L4.exec(o);if(!s)return;let a=s[1].toUpperCase(),l=i.start.date()??i.refDate??new Date,c={...this.timezoneOverrides,...n},d=Xw(a,l,c);if(d==null)return;t.debug(()=>{console.log(`Extracting timezone: '${a}' into: ${d} for: ${i.start}`)});let u=i.start.get("timezoneOffset");u!==null&&d!=u&&(i.start.isCertain("timezoneOffset")||a!=s[1])||i.start.isOnlyDate()&&a!=s[1]||(i.text+=s[0],i.start.isCertain("timezoneOffset")||i.start.assign("timezoneOffset",d),i.end!=null&&!i.end.isCertain("timezoneOffset")&&i.end.assign("timezoneOffset",d))}),e}}});var N4,V4,B4,U4,Ug,UN=x(()=>{N4=new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?","i"),V4=1,B4=2,U4=3,Ug=class{refine(t,e){return e.forEach(function(n){if(n.start.isCertain("timezoneOffset"))return;let i=t.text.substring(n.index+n.text.length),o=N4.exec(i);if(!o)return;t.debug(()=>{console.log(`Extracting timezone: '${o[0]}' into : ${n}`)});let s=parseInt(o[B4]),a=parseInt(o[U4]||"0"),l=s*60+a;l>840||(o[V4]==="-"&&(l=-l),n.end!=null&&n.end.assign("timezoneOffset",l),n.start.assign("timezoneOffset",l),n.text+=o[0])}),e}}});var dc,BA=x(()=>{dc=class{refine(t,e){if(e.length<2)return e;let n=[],i=e[0];for(let o=1;o=i.index+i.text.length){n.push(i),i=s;continue}let a=null,l=null;s.text.length>i.text.length?(a=s,l=i):(a=i,l=s),t.debug(()=>{console.log(`${this.constructor.name} remove ${l} by ${a}`)}),i=a}return i!=null&&n.push(i),n}}});function qN(r,t,e){let n=r.getDateWithAdjustedTimezone(),i=q4(n,t,e),o=new mt(r);return o=o.addDurationAsImplied({day:i}),o.assign("weekday",t),o}function q4(r,t,e){let n=r.getDay();switch(e){case"this":return Yd(r,t);case"last":return zN(r,t);case"next":return n==Lt.SUNDAY?t==Lt.SUNDAY?7:t:n==Lt.SATURDAY?t==Lt.SATURDAY?7:t==Lt.SUNDAY?8:1+t:t=0&&(n-=7),n}var UA=x(()=>{Ha();ns()});var qg,HN=x(()=>{Gd();Gd();Ga();UA();qg=class{refine(t,e){return t.option.forwardDate&&e.forEach(n=>{let i=t.reference.getDateWithAdjustedTimezone();if(n.start.isOnlyTime()&&t.reference.instant>n.start.date()){let o=t.reference.getDateWithAdjustedTimezone(),s=new Date(o);s.setDate(s.getDate()+1),Wa(n.start,s),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} time from the ref date (${o}) to the following day (${s})`)}),n.end&&n.end.isOnlyTime()&&(Wa(n.end,s),n.start.date()>n.end.date()&&(s.setDate(s.getDate()+1),Wa(n.end,s)))}if(n.start.isOnlyWeekdayComponent()&&i>n.start.date()){let o=Yd(i,n.start.get("weekday"))||7,s=cn(i,{day:o});if(Wa(n.start,s),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} weekday (${n.start})`)}),n.end&&n.start.date()>n.end.date()){let a=Yd(i,n.start.get("weekday"))||7,l=cn(i,{day:a});Wa(n.end,l),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} weekday (${n.end})`)})}}if(n.start.isDateWithUnknownYear()&&i>n.start.date())for(let o=0;o<3&&i>n.start.date();o++)n.start.imply("year",n.start.get("year")+1),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} year (${n.start})`)}),n.end&&!n.end.isCertain("year")&&(n.end.imply("year",n.end.get("year")+1),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} month (${n.start})`)}))}),e}}});var zg,WN=x(()=>{cc();zg=class extends Wp{constructor(e){super();fe(this,"strictMode");this.strictMode=e}isValid(e,n){return n.text.replace(" ","").match(/^\d*(\.\d*)?$/)?(e.debug(()=>{console.log(`Removing unlikely result '${n.text}'`)}),!1):n.start.isValidDate()?n.end&&!n.end.isValidDate()?(e.debug(()=>{console.log(`Removing invalid result: ${n} (${n.end})`)}),!1):this.strictMode?this.isStrictModeValid(e,n):!0:(e.debug(()=>{console.log(`Removing invalid result: ${n} (${n.start})`)}),!1)}isStrictModeValid(e,n){return n.start.isOnlyWeekdayComponent()?(e.debug(()=>{console.log(`(Strict) Removing weekday only component: ${n} (${n.end})`)}),!1):!0}}});var H4,W4,G4,j4,GN,Y4,jN,YN,K4,KN,QN,Hg,XN=x(()=>{Nn();H4=new RegExp("([0-9]{4})\\-([0-9]{1,2})\\-([0-9]{1,2})(?:T([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2})(?:\\.(\\d{1,4}))?)?(Z|([+-]\\d{2}):?(\\d{2})?)?)?(?=\\W|$)","i"),W4=1,G4=2,j4=3,GN=4,Y4=5,jN=6,YN=7,K4=8,KN=9,QN=10,Hg=class extends yt{innerPattern(){return H4}innerExtract(t,e){let n=t.createParsingComponents({year:parseInt(e[W4]),month:parseInt(e[G4]),day:parseInt(e[j4])});if(e[GN]!=null&&(n.assign("hour",parseInt(e[GN])),n.assign("minute",parseInt(e[Y4])),e[jN]!=null&&n.assign("second",parseInt(e[jN])),e[YN]!=null&&n.assign("millisecond",parseInt(e[YN])),e[K4]!=null)){let i=0;if(e[KN]){let o=parseInt(e[KN]),s=0;e[QN]!=null&&(s=parseInt(e[QN])),i=o*60,i<0?i-=s:i+=s}n.assign("timezoneOffset",i)}return n.addTag("parser/ISOFormatParser")}}});var Wg,JN=x(()=>{cc();Wg=class extends ko{mergeResults(t,e,n){let i=n.clone();return i.index=e.index,i.text=e.text+t+i.text,i.start.assign("weekday",e.start.get("weekday")),i.end&&i.end.assign("weekday",e.start.get("weekday")),i}shouldMergeResults(t,e,n){return e.start.isOnlyWeekdayComponent()&&!e.start.isCertain("hour")&&n.start.isCertain("day")&&t.match(/^,?\s*$/)!=null}}});function ZN(r,t=!1){return r.parsers.unshift(new Hg),r.refiners.unshift(new Wg),r.refiners.unshift(new Ug),r.refiners.unshift(new dc),r.refiners.push(new Bg),r.refiners.push(new dc),r.refiners.push(new qg),r.refiners.push(new zg(t)),r}var e1=x(()=>{BN();UN();BA();HN();WN();XN();JN()});function t1(r){let t=r.getDateWithAdjustedTimezone(),e=new mt(r,{});return rs(e,t),Qw(e,t),e.assign("timezoneOffset",r.getTimezoneOffset()),e.addTag("casualReference/now"),e}function r1(r){let t=r.getDateWithAdjustedTimezone(),e=new mt(r,{});return rs(e,t),_g(e,t),e.delete("meridiem"),e.addTag("casualReference/today"),e}function n1(r){return Q4(r,1).addTag("casualReference/yesterday")}function i1(r){return nC(r,1).addTag("casualReference/tomorrow")}function Q4(r,t){return nC(r,-t)}function nC(r,t){let e=r.getDateWithAdjustedTimezone(),n=new mt(r,{}),i=new Date(e.getTime());return i.setDate(i.getDate()+t),rs(n,i),_g(n,i),n.delete("meridiem"),n}function o1(r,t=22){let e=r.getDateWithAdjustedTimezone(),n=new mt(r,{});return rs(n,e),n.imply("hour",t),n.imply("meridiem",dt.PM),n.addTag("casualReference/tonight"),n}function s1(r,t=20){let e=new mt(r,{});return e.imply("meridiem",dt.PM),e.imply("hour",t),e.addTag("casualReference/evening"),e}function a1(r){let t=new mt(r,{});return r.getDateWithAdjustedTimezone().getHours()>2&&t.addDurationAsImplied({day:1}),t.assign("hour",0),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/midnight"),t}function l1(r,t=6){let e=new mt(r,{});return e.imply("meridiem",dt.AM),e.imply("hour",t),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/morning"),e}function c1(r,t=15){let e=new mt(r,{});return e.imply("meridiem",dt.PM),e.imply("hour",t),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/afternoon"),e}function d1(r){let t=new mt(r,{});return t.imply("meridiem",dt.AM),t.assign("hour",12),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/noon"),t}var qA=x(()=>{ns();Gd();Ha()});var X4,Gg,p1=x(()=>{Nn();Gd();qA();X4=/(now|today|tonight|tomorrow|overmorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i,Gg=class extends yt{innerPattern(t){return X4}innerExtract(t,e){let n=t.refDate,i=e[0].toLowerCase(),o=t.createParsingComponents();switch(i){case"now":o=t1(t.reference);break;case"today":o=r1(t.reference);break;case"yesterday":o=n1(t.reference);break;case"tomorrow":case"tmr":case"tmrw":o=i1(t.reference);break;case"tonight":o=o1(t.reference);break;case"overmorrow":o=nC(t.reference,2);break;default:if(i.match(/last\s*night/)){if(n.getHours()>6){let s=new Date(n.getTime());s.setDate(s.getDate()-1),n=s}rs(o,n),o.imply("hour",0)}break}return o.addTag("parser/ENCasualDateParser"),o}}});var J4,jg,m1=x(()=>{Nn();qA();J4=/(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i,jg=class extends yt{innerPattern(){return J4}innerExtract(t,e){let n=null;switch(e[1].toLowerCase()){case"afternoon":n=c1(t.reference);break;case"evening":case"night":n=s1(t.reference);break;case"midnight":n=a1(t.reference);break;case"morning":n=l1(t.reference);break;case"noon":case"midday":n=d1(t.reference);break}return n&&n.addTag("parser/ENCasualTimeParser"),n}}});var Z4,e6,t6,r6,Yg,f1=x(()=>{fr();Ya();Nn();UA();Ha();Z4=new RegExp(`(?:(?:\\,|\\(|\\\uFF08)\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${Ur(Zw)}|weekend|weekday)(?:\\s*(?:\\,|\\)|\\\uFF09))?(?:\\s*(?:of\\s*)?(this|last|past|next)\\s*week)?(?=\\W|$)`,"i"),e6=1,t6=2,r6=3,Yg=class extends yt{innerPattern(){return Z4}innerExtract(t,e){let n=e[e6],i=e[r6],o=n||i;o=o||"",o=o.toLowerCase();let s=null;o=="last"||o=="past"?s="last":o=="next"?s="next":o=="this"&&(s="this");let a=e[t6].toLowerCase(),l;if(Zw[a]!==void 0)l=Zw[a];else if(a=="weekend")l=s=="last"?Lt.SUNDAY:Lt.SATURDAY;else if(a=="weekday"){let c=t.reference.getDateWithAdjustedTimezone().getDay();c==Lt.SUNDAY||c==Lt.SATURDAY?l=s=="last"?Lt.FRIDAY:Lt.MONDAY:(l=c-1,l=s=="last"?l-1:l+1,l=l%5+1)}else return null;return qN(t.reference,l,s)}}});var n6,i6,o6,Kg,h1=x(()=>{fr();ns();Nn();Ya();n6=new RegExp(`(this|last|past|next|after\\s*this)\\s*(${Ur(kg)})(?=\\s*)(?=\\W|$)`,"i"),i6=1,o6=2,Kg=class extends yt{innerPattern(){return n6}innerExtract(t,e){let n=e[i6].toLowerCase(),i=e[o6].toLowerCase(),o=kg[i];if(n=="next"||n.startsWith("after")){let l={};return l[o]=1,mt.createRelativeFromReference(t.reference,l)}if(n=="last"||n=="past"){let l={};return l[o]=-1,mt.createRelativeFromReference(t.reference,l)}let s=t.createParsingComponents(),a=new Date(t.reference.instant.getTime());return i.match(/week/i)?(a.setDate(a.getDate()-a.getDay()),s.imply("day",a.getDate()),s.imply("month",a.getMonth()+1),s.imply("year",a.getFullYear())):i.match(/month/i)?(a.setDate(1),s.imply("day",a.getDate()),s.assign("year",a.getFullYear()),s.assign("month",a.getMonth()+1)):i.match(/year/i)&&(a.setDate(1),a.setMonth(0),s.imply("day",a.getDate()),s.imply("month",a.getMonth()+1),s.assign("year",a.getFullYear())),s}}});var s6,a6,l6,g1,v1,zA,Qg,y1=x(()=>{Up();s6=new RegExp("([^\\d]|^)([0-3]{0,1}[0-9]{1})[\\/\\.\\-]([0-3]{0,1}[0-9]{1})(?:[\\/\\.\\-]([0-9]{4}|[0-9]{2}))?(\\W|$)","i"),a6=1,l6=5,g1=2,v1=3,zA=4,Qg=class{constructor(t){fe(this,"groupNumberMonth");fe(this,"groupNumberDay");this.groupNumberMonth=t?v1:g1,this.groupNumberDay=t?g1:v1}pattern(){return s6}extract(t,e){let n=e.index+e[a6].length,i=e.index+e[0].length-e[l6].length;if(n>0&&t.text.substring(0,n).match("\\d/?$")||i12)&&a>12)if(l>=1&&l<=12&&a<=31)[l,a]=[a,l];else return null;if(l<1||l>31)return null;if(s.start.assign("day",l),s.start.assign("month",a),e[zA]){let c=parseInt(e[zA]),d=Jw(c);s.start.assign("year",d)}else{let c=sc(t.refDate,l,a);s.start.imply("year",c)}return s.addTag("parser/SlashDateFormatParser")}}});var c6,d6,Xg,b1=x(()=>{fr();ns();Nn();Ga();c6=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${Ka})(?=\\W|$)`,"i"),d6=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${lc})(?=\\W|$)`,"i"),Xg=class extends yt{constructor(e=!0){super();fe(this,"allowAbbreviations");this.allowAbbreviations=e}innerPattern(){return this.allowAbbreviations?c6:d6}innerExtract(e,n){let i=n[1].toLowerCase(),o=_o(n[2]);if(!o)return null;switch(i){case"last":case"past":case"-":o=ic(o);break}return mt.createRelativeFromReference(e.reference,o)}}});function u6(r){return r.text.match(/^[+-]/i)!=null}function w1(r){return r.text.match(/^-/i)!=null}var Jg,C1=x(()=>{cc();ns();fr();Ga();Jg=class extends ko{shouldMergeResults(t,e,n){return t.match(/^\s*$/i)?u6(n)||w1(n):!1}mergeResults(t,e,n,i){let o=_o(n.text);w1(n)&&(o=ic(o));let s=mt.createRelativeFromReference(oc.fromDate(e.start.date()),o);return new ja(e.reference,e.index,`${e.text}${t}${n.text}`,s)}}});function x1(r){return r.text.match(/\s+(before|from)$/i)!=null}function p6(r){return r.text.match(/\s+(after|since)$/i)!=null}var Zg,E1=x(()=>{cc();ns();fr();Ga();Zg=class extends ko{patternBetween(){return/^\s*$/i}shouldMergeResults(t,e,n){return!t.match(this.patternBetween())||!x1(e)&&!p6(e)?!1:!!n.start.get("day")&&!!n.start.get("month")&&!!n.start.get("year")}mergeResults(t,e,n){let i=_o(e.text);x1(e)&&(i=ic(i));let o=mt.createRelativeFromReference(oc.fromDate(n.start.date()),i);return new ja(n.reference,e.index,`${e.text}${t}${n.text}`,o)}}});var m6,f6,ev,T1=x(()=>{fr();m6=new RegExp(`^\\s*(${ac})`,"i"),f6=1,ev=class{refine(t,e){return e.forEach(function(n){if(!n.start.isDateWithUnknownYear())return;let i=t.text.substring(n.index+n.text.length),o=m6.exec(i);if(!o||o[0].trim().length<=3)return;t.debug(()=>{console.log(`Extracting year: '${o[0]}' into : ${n}`)});let s=Bs(o[f6]);n.end!=null&&n.end.assign("year",s),n.start.assign("year",s),n.text+=o[0]}),e}}});var tv,_1=x(()=>{cc();tv=class extends Wp{constructor(){super()}isValid(t,e){let n=e.text.trim();return n===t.text.trim()?!0:n.toLowerCase()==="may"&&!t.text.substring(0,e.index).trim().match(/\b(in)$/i)?(t.debug(()=>{console.log(`Removing unlikely result: ${e}`)}),!1):n.toLowerCase().endsWith("the second")?(t.text.substring(e.index+e.text.length).trim().length>0&&t.debug(()=>{console.log(`Removing unlikely result: ${e}`)}),!1):!0}}});var Kd,HA=x(()=>{vN();CN();EN();_N();SN();AN();IN();$N();FN();MN();ON();VN();e1();p1();m1();f1();h1();y1();b1();C1();E1();BA();T1();_1();Kd=class{createCasualConfiguration(t=!1){let e=this.createConfiguration(!1,t);return e.parsers.push(new Gg),e.parsers.push(new jg),e.parsers.push(new Pg),e.parsers.push(new Kg),e.parsers.push(new Xg),e.refiners.push(new tv),e}createConfiguration(t=!0,e=!1){let n=ZN({parsers:[new Qg(e),new Sg(t),new Ag,new Ig(e),new Yg,new Mg,new Rg(t),new Og(t),new Dg(t),new Fg],refiners:[new Gp]},t);return n.parsers.unshift(new $g(t)),n.refiners.unshift(new Zg),n.refiners.unshift(new Jg),n.refiners.unshift(new dc),n.refiners.push(new Gp),n.refiners.push(new ev),n.refiners.push(new Ng),n}}});var jp,WA,k1=x(()=>{ns();HA();jp=class r{constructor(t){fe(this,"parsers");fe(this,"refiners");fe(this,"defaultConfig",new Kd);t=t||this.defaultConfig.createCasualConfiguration(),this.parsers=[...t.parsers],this.refiners=[...t.refiners]}clone(){return new r({parsers:[...this.parsers],refiners:[...this.refiners]})}parseDate(t,e,n){let i=this.parse(t,e,n);return i.length>0?i[0].start.date():null}parse(t,e,n){let i=new WA(t,e,n),o=[];return this.parsers.forEach(s=>{let a=r.executeParser(i,s);o=o.concat(a)}),o.sort((s,a)=>s.index-a.index),this.refiners.forEach(function(s){o=s.refine(i,o)}),o}static executeParser(t,e){let n=[],i=e.pattern(t),o=t.text,s=t.text,a=i.exec(s);for(;a;){let l=a.index+o.length-s.length;a.index=l;let c=e.extract(t,a);if(!c){s=o.substring(a.index+1),a=i.exec(s);continue}let d=null;c instanceof ja?d=c:c instanceof mt?(d=t.createParsingResult(a.index,a[0]),d.start=c):d=t.createParsingResult(a.index,a[0],c);let u=d.index,p=d.text;t.debug(()=>console.log(`${e.constructor.name} extracted (at index=${u}) '${p}'`)),n.push(d),s=o.substring(u+p.length),a=i.exec(s)}return n}},WA=class{constructor(t,e,n){fe(this,"text");fe(this,"option");fe(this,"reference");fe(this,"refDate");this.text=t,this.option=n??{},this.reference=oc.fromInput(e,this.option.timezones),this.refDate=this.reference.instant}createParsingComponents(t){return t instanceof mt?t:new mt(this.reference,t)}createParsingResult(t,e,n,i){let o=typeof e=="string"?e:this.text.substring(t,e),s=n?this.createParsingComponents(n):null,a=i?this.createParsingComponents(i):null;return new ja(this.reference,t,o,s,a)}debug(t){this.option.debug&&(this.option.debug instanceof Function?this.option.debug(t):this.option.debug.debug(t))}}});var GA,S1,h6,TIe,A1=x(()=>{k1();HA();GA=new Kd,S1=new jp(GA.createCasualConfiguration(!1)),h6=new jp(GA.createConfiguration(!0,!1)),TIe=new jp(GA.createCasualConfiguration(!0))});function I1(r,t,e){return v6.parseDate(r,t,e)}var v6,P1=x(()=>{A1();v6=S1});function C6(r){return!b6.test(r)}var b6,w6,jA,So,Qd=x(()=>{P1();b6=/\b(?:last|previous)\b|\bpast\s+(?:few\s+)?(?:\w*day|weekend|week|month|year|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*\b/i,w6=/\bprevious\b/gi;jA=class{getParsedDate(t,e=new Date){let n=t.replace(w6,"last");return I1(n,e,{forwardDate:C6(n)})}parseDate(t){if(!t||!t.trim())return null;try{let e=this.getParsedDate(t);return e?window.moment?{moment:window.moment(e)}:(console.warn("Moment.js is not available"),null):null}catch(e){return console.warn("Failed to parse date:",t,e),null}}},So=new jA});function lv(r){return typeof r=="string"&&av.includes(r)}function Qa(r){if(!r||typeof r!="object")return;let t=r;switch(t.kind){case"now":return{kind:"now"};case"ask":{let e=typeof t.defaultValue=="string"?t.defaultValue.trim():"";return e?{kind:"ask",defaultValue:e}:{kind:"ask"}}case"relative":return typeof t.offset!="number"||!Number.isInteger(t.offset)||!lv(t.unit)?void 0:{kind:"relative",offset:t.offset,unit:t.unit};case"variable":return typeof t.name!="string"||!t.name.trim()?void 0:{kind:"variable",name:t.name.trim()};default:return}}var av,Xp=x(()=>{av=["days","weeks","months","years"]});function mC(r){return F6.has(r)}function Xa(r){if(!r||r.kind==="now")return"today";if(r.kind==="ask")return"ask";if(r.kind==="variable")return"variable";for(let t of KA)if(r.offset===t.offset&&r.unit===t.unit)return t.id;return"custom"}function fC(r){let{preset:t,previous:e}=r;if(t!=="today"){if(t==="ask")return e?.kind==="ask"?e:R1(Xa(e));if(t==="variable")return e?.kind==="variable"?e:{kind:"variable",name:""};if(t==="custom")return e?.kind==="relative"&&Xa(e)==="custom"?e:{kind:"relative",offset:-2,unit:"days"};for(let n of KA)if(n.id===t)return{kind:"relative",offset:n.offset,unit:n.unit}}}function R1(r){for(let t of pC)if(t.id===r&&t.defaultValue)return{kind:"ask",defaultValue:t.defaultValue};return{kind:"ask"}}function uv(r){let t=(r??"").trim().toLowerCase();for(let e of pC)if(e.aliases.some(n=>n===t))return e.id;return"kept"}function hC(r){let t=pC.map(e=>({value:e.id,label:e.label}));if(uv(r)==="kept"){let e=r?.trim();e&&t.push({value:"kept",label:e})}return t}function gC(r,t){if(r==="kept"){let e=t?.trim();return e||void 0}for(let e of pC)if(e.id===r)return e.defaultValue}function O1(r){return typeof r=="string"&&r.trim().toLowerCase()==="ask"}function Jp(r){return r?.kind==="ask"?r:R1(Xa(r))}var $6,oC,sC,aC,lC,cv,cC,dv,dC,KA,uC,pC,F6,uc=x(()=>{$6=["today","ask","yesterday","last-week","next-week","last-month","custom","variable"],oC="Which day",sC="The day {{DATE}} writes. The clock stays now. Hold Shift in the QuickAdd menu to pick a different day.",aC="Picker starts on",lC="The date the picker suggests first. You can still pick a different day.",cv="How far from today",cC="How many days, weeks, months, or years from today. Negative is the past.",dv="Variable name",dC="A VDATE or script value that already has the day.",KA=[{id:"yesterday",label:"Yesterday",offset:-1,unit:"days"},{id:"last-week",label:"Last week",offset:-1,unit:"weeks"},{id:"next-week",label:"Next week",offset:1,unit:"weeks"},{id:"last-month",label:"Last month",offset:-1,unit:"months"}],uC=[{value:"today",label:"Today"},{value:"ask",label:"Ask each time"},...KA.map(r=>({value:r.id,label:r.label})),{value:"custom",label:"Custom\u2026"},{value:"variable",label:"A variable\u2026"}],pC=[{id:"today",label:"Today",defaultValue:void 0,aliases:["","today"]},{id:"yesterday",label:"Yesterday",defaultValue:"yesterday",aliases:["yesterday","yd"]},{id:"last-week",label:"Last week",defaultValue:"last week",aliases:["last week","lw"]},{id:"next-week",label:"Next week",defaultValue:"next week",aliases:["next week","nw"]},{id:"last-month",label:"Last month",defaultValue:"last month",aliases:["last month","lm"]}],F6=new Set($6)});function Y6(r,t){let e=[r,...t??[]].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return e.length>0?e:void 0}function N1(r){let t=Dn.parse(`__capture_scope|${r}`);return{filter:t.filters,multiSelect:t.multiSelect??!1}}function K6(r){return!!(r.folder||r.folders?.length||r.tags?.length||r.excludeFolders?.length||r.excludeTags?.length||r.excludeFiles?.length)}function em(r){let t=r.trim();if(!t)return null;if(t.startsWith("#")){let o=bo(t),s=(o.shift()??"").replace(/^#/,"").replace(/\.md$/i,"").trim();if(!s)return null;let a=o.length>0?N1(o.join("|")):{filter:{},multiSelect:!1};return{filter:{...a.filter,tags:Y6(s,a.filter.tags)},multiSelect:a.multiSelect}}let e=bo(t)[0]??"",n=wo(e);if(!n||!j6.has(n.key))return null;let i=N1(t);return K6(i.filter)?i:null}var j6,CC=x(()=>{Da();jl();j6=new Set(["folder","tag","exclude-folder","exclude-tag","exclude-file"])});function tm(r){let t=r.trim();if(!V1.test(t))return null;let e=t.replace(V1,""),{fieldName:n,filters:i}=Dn.parse(e),o=n.indexOf("="),s=(o>=0?n.slice(0,o):n).trim(),a=o>=0?n.slice(o+1).trim():"",l=a.length>0?a:void 0;return{field:s,value:l,filter:i}}var V1,xC=x(()=>{Da();V1=/^property:/i});function nV(r){let t=SC.find(e=>e.id===(r===void 0?"open":r));if(!t)throw new Error(`Unknown existing-note action: ${String(r)}`);return t}function AC(r){return nV(r).id}function fc(r){return nV(r).verb}function am(r){let t=_X.get(r);if(!t)throw new Error(`Unknown file exists mode: ${r}`);return t}function iV(r){return cI.filter(t=>t.category===r)}function oV(r){return am(r).category}function sV(){return[...cI]}function aV(r){return r.kind==="prompt"?"prompt":oV(r.mode)}function lV(r,t){return r==="prompt"?{kind:"prompt"}:t?.kind==="apply"&&oV(t.mode)===r?t:{kind:"apply",mode:kX[r]}}function cV(r){return typeof r!="string"||!Object.prototype.hasOwnProperty.call(tV,r)?null:tV[r]??null}async function dV(r,t,e){return await SX[t](r,e)}async function AX(r,t){let e=r;for(;await t(e);){let{basename:n,extension:i}=uV(e),o=n.match(/^(.*?)(\d+)$/);e=`${o?`${o[1]}${String(BigInt(o[2])+1n).padStart(o[2].length,"0")}`:`${n}1`}${i}`}return e}async function IX(r,t){let e=r;for(;await t(e);){let{basename:n,extension:i}=uV(e),o=n.match(/^(.*) \((\d+)\)$/);e=`${o?`${o[1]} (${String(BigInt(o[2])+1n)})`:`${n} (1)`}${i}`}return e}function uV(r){return lr.test(r)?{basename:r.replace(lr,""),extension:".canvas"}:Rn.test(r)?{basename:r.replace(Rn,""),extension:".base"}:{basename:r.replace(xt,""),extension:".md"}}var rV,cI,SC,_X,kX,tV,SX,Za=x(()=>{Le();rV=[{id:"prompt",label:"Ask every time"},{id:"update",label:"Update existing file"},{id:"create",label:"Create another file"},{id:"keep",label:"Keep existing file"}],cI=[{id:"appendBottom",category:"update",label:"Append to bottom",description:"Adds the template content to the end of the existing file.",requiresExistingFile:!0,resolutionKind:"modifyExisting"},{id:"appendTop",category:"update",label:"Append to top",description:"Adds the template content to the beginning of the existing file.",requiresExistingFile:!0,resolutionKind:"modifyExisting"},{id:"overwrite",category:"update",label:"Overwrite file",description:"Replaces the existing file content with the template.",requiresExistingFile:!0,resolutionKind:"modifyExisting"},{id:"increment",category:"create",label:"Increment trailing number",description:"Changes trailing digits only. Example: Draft009.md -> Draft010.md.",requiresExistingFile:!1,resolutionKind:"createNew"},{id:"duplicateSuffix",category:"create",label:"Append duplicate suffix",description:"Keeps the original name and adds a duplicate marker. Example: Project Plan.md -> Project Plan (1).md.",requiresExistingFile:!1,resolutionKind:"createNew"},{id:"doNothing",category:"keep",label:"Do nothing",description:"Leaves the file unchanged and opens the existing file.",requiresExistingFile:!0,resolutionKind:"reuseExisting"}],SC=[{id:"open",label:"Open note",verb:"Open"},{id:"appendBottom",label:"Append template to bottom",verb:"Append to"},{id:"appendTop",label:"Insert template at top",verb:"Insert into"},{id:"overwrite",label:"Replace entire note",verb:"Replace"}];_X=new Map(cI.map(r=>[r.id,r])),kX={update:"appendBottom",create:"duplicateSuffix",keep:"doNothing"},tV={"Append to the bottom of the file":"appendBottom","Append to the top of the file":"appendTop","Overwrite the file":"overwrite","Increment the file name":"increment","Append duplicate suffix":"duplicateSuffix",Nothing:"doNothing",appendBottom:"appendBottom",appendTop:"appendTop",overwrite:"overwrite",increment:"increment",duplicateSuffix:"duplicateSuffix",doNothing:"doNothing"},SX={increment:AX,duplicateSuffix:IX}});function RI(r,t){if(!r.fileNameFormat?.enabled)return!0;let e=t.trim().toLowerCase();return e===xr.toLowerCase()||e===mD.toLowerCase()}function OI(r,t){return r.discoverExistingNotesBeforeCreate===!0&&RI(r,t)}function xc(r,t,e){return!(!OI(r,t)||e!=null)}var ou=x(()=>{Le()});function Ei(r,{title:t,message:e,action:n,destructive:i=!0}){return new Promise(o=>{let s=!1,a=new ZV.ConfirmationModal(r);a.setTitle(t),e&&a.setContent(e),a.addCancelButton().addButton(l=>{l.setButtonText(n).setCta().setInitialFocus().onClick(()=>{s=!0}),i&&l.setDestructive()}),a.buttonContainerEl.querySelectorAll("button").forEach(KC),a.setCloseCallback(()=>o(s)),a.open()})}function KC(r){let t=e=>{e.preventDefault(),e.stopPropagation()};r.addEventListener("pointerdown",t),r.addEventListener("mousedown",t)}function QC(r){r.forEach(t=>{t.addEventListener("keydown",e=>{if(e.key==="ArrowRight"||e.key==="ArrowLeft"){let i=(r.indexOf(t)+(e.key==="ArrowRight"?1:-1)+r.length)%r.length;r[i].focus(),e.preventDefault()}})})}var ZV,tl=x(()=>{ZV=require("obsidian")});function eB(r){NI=r}function Wr(){if(!NI)throw new Error("QuickAdd plugin instance accessed before it was initialised.");return NI}var NI,ss=x(()=>{});var jt,er=x(()=>{jt=(c=>(c.Obsidian="Obsidian",c.UserScript="UserScript",c.Choice="Choice",c.Wait="Wait",c.NestedChoice="NestedChoice",c.EditorCommand="EditorCommand",c.AIAssistant="AIAssistant",c.OpenFile="OpenFile",c.Conditional="Conditional",c))(jt||{})});function Ws(r){let t=0,e=0,n=!1,i=0,o=0,s=0;for(;t<=r.length;){let a=r.indexOf(` `,t),l=a===-1?r.length:a,c=r.slice(t,l).replace(/\r$/,""),d=a===-1?r.length+1:a+1,u=h8.exec(c);if(n){if(u&&u[1].length>=i&&u[2].trim().length===0)return nB(r.slice(o,t),s)}else if(u){let p=u[2].trim().split(/\s+/)[0]?.toLowerCase();(p==="js"||p==="javascript")&&(n=!0,i=u[1].length,o=d,s=e+1)}if(t=d,e++,a===-1)break}return n?nB(r.slice(o),s):{code:null,error:g8}}function nB(r,t){return r.trim().length===0?{code:"",error:v8}:{code:` `.repeat(t)+r}}var h8,g8,v8,_m=x(()=>{h8=/^ {0,3}(`{3,})(.*)$/,g8="No ```js (or ```javascript) code block found in the note.",v8="The ```js code block is empty."});function as(r,t){let e=t;for(;e=r.length)break;let n=zI(r,e,new Map);if(!n?.name){e+=1;continue}if(e=as(r,n.end),r[e]!==":"){e+=1;continue}if(e=as(r,e+1),r[e]==='"'||r[e]==="'"||r[e]==="`"){let o=Ov(r,e);if(!o)break;t.set(n.name,o.value),e=o.end;continue}if(r.slice(e,e+4)==="true"){t.set(n.name,!0),e+=4;continue}if(r.slice(e,e+5)==="false"){t.set(n.name,!1),e+=5;continue}let i=r[e];if(i==="{"||i==="["){let o=XC(r,e,i,i==="{"?"}":"]");if(o===-1)break;e=o+1;continue}for(;e=a)break;let c=zI(e,l,o);if(!c){l+=1;continue}if(l=as(e,c.end),e[l]!==":"){l+=1;continue}if(l=as(e,l+1),e[l]!=="{"){l+=1;continue}let d=XC(e,l,"{","}");if(d===-1||d>a)break;let u=e.slice(l+1,d);C8(u)&&(i=!0,c.name&&n.add(c.name)),l=d+1}}return{names:n,foundSecretOptions:i}}var y8,sB=x(()=>{_m();y8=/\.md$/i});function Tr(r){return typeof r=="object"&&r!==null}function rl(r){return Tr(r)&&!Array.isArray(r)}function x8(r){return rl(r)?!1:Array.isArray(r)?r.length>0:Wt(r)}function ur(r){return rl(r)?r.commands:x8(r)?r:void 0}function Mt(r){return Array.isArray(r)?r:[]}function km(r){return Array.isArray(r)?r:[]}function Lv(r){return Array.isArray(r)}function HI(r){let t=Mt(r),e=new Set,n=!1,i=[];for(let o of t){if(Array.isArray(o)){let l=HI(o);for(let c of l.commands){let d=c.id;if(typeof d=="string"&&d!==""&&!e.has(d)){e.add(d),i.push(c);continue}let u={...c,id:Vt()};e.add(u.id),i.push(u)}n=!0;continue}if(!Tr(o)){n=!0;continue}let s=o.id;if(typeof s=="string"&&s!==""&&!e.has(s)){e.add(s),i.push(o);continue}let a={...o,id:Vt()};e.add(a.id),i.push(a),n=!0}return n?{commands:i,changed:n}:{commands:t,changed:!1}}function aB(r){lB(r,new Set)}function lB(r,t){Tr(r)&&(t.has(r)||(t.add(r),rl(r)&&(r.id=Vt()),JC(ur(r),t)))}function JC(r,t){if(Lv(r))for(let e of r){if(Array.isArray(e)){JC(e,t);continue}if(!Tr(e)||t.has(e))continue;t.add(e),e.id=Vt();let n=e;JC(n.thenCommands,t),JC(n.elseCommands,t),cB(n.choice,t)}}function cB(r,t){if(!Tr(r)||t.has(r))return;t.add(r);let e=r;if(e.id=Vt(),e.type==="Macro"&&lB(e.macro,t),e.type==="Multi"&&Array.isArray(e.choices))for(let n of e.choices)cB(n,t)}var Gr=x(()=>{qh();Qo();qh()});function Am(r){return r!==null&&typeof r=="object"}function nx(r){return r?.secretStorage}function ex(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"setting"}function T8(r){let t=5381;for(let e=0;e>>0).toString(36).slice(0,E8)}function uB(r,t){return r.length<=t?r:r.slice(0,t).replace(/-+$/g,"")||"setting"}function mB(r,t){let e=t?.id;return typeof e=="string"&&e.trim().length>0?e:r}function WI(r,t,e){let i=(e?[ZC,r,t,e]:[ZC,r,t]).join("-");if(i.length<=dB)return i;let o=T8([r,t,e].filter(Boolean).join(":")),s=e?4:3,a=dB-ZC.length-o.length-(e?.length??0)-s,l=Math.max(8,Math.floor(a*.6)),c=Math.max(8,a-l);return[ZC,uB(r,l),uB(t,c),...e?[e]:[],o].join("-")}function GI(r){return r?.message??String(r)}function Im(r){return Am(r)?r.type==="secret"||(r.type==="text"||r.type==="input")&&r.secret===!0:!1}function Sm(r){return Am(r)&&r[pB]===!0&&typeof r.secretRef=="string"&&r.secretRef.trim().length>0}function tx(r){return{[pB]:!0,secretRef:r}}function _8(r,t,e){let n=r.id?.trim()||r.path||r.name||"script";return WI(ex(n),ex(mB(t,e)))}function k8(r){let t=r?.options;return t?Object.entries(t).filter(([,e])=>Im(e)).map(([e])=>e):[]}function S8(r){let t=r?.options;return t?Object.entries(t).filter(([,e])=>Im(e)):[]}function A8(r){return typeof r.id=="string"&&r.id.trim().length>0}async function jI(r,t){let e=nx(r);if(!e?.getSecret)return null;try{return await Promise.resolve(e.getSecret(t))}catch(n){return S.logWarning(`Failed to read user script SecretStorage entry "${t}": ${GI(n)}`),null}}async function I8(r,t,e){let n=nx(r);if(!n?.setSecret)return!1;try{return await Promise.resolve(n.setSecret(t,e)),!0}catch(i){return S.logWarning(`Failed to write user script SecretStorage entry "${t}": ${GI(i)}`),!1}}async function P8(r,t,e,n,i){let o=t.id?.trim()||t.path||t.name||"script",s=ex(o),a=ex(mB(e,i)),l=WI(s,a),c=1;for(;;){let d=await jI(r,l);if(!d||d===n)return l;c+=1,l=WI(s,a,String(c))}}async function YI(r,t,e,n,i,o){if(n.length===0)return null;let s=i?.trim()||await P8(r,t,e,n,o);return await I8(r,s,n)?s:null}async function KI(r,t){let e=t?.trim();if(!e)return!0;let n=nx(r);if(!n)return!0;let i=n.deleteSecret??n.removeSecret??n.delete;try{if(i)return await Promise.resolve(i.call(n,e)),!0;if(n.setSecret)return await Promise.resolve(n.setSecret(e,"")),!0}catch(o){S.logWarning(`Failed to clear user script SecretStorage entry "${e}": ${GI(o)}`)}return!1}async function fB(r,t,e){let n=t.settings??{},i={...n},o=new Set(k8(e));for(let[s,a]of Object.entries(n)){if(Sm(a)){let l=await jI(r,a.secretRef);if(l){i[s]=l;continue}throw new Error(`Secret setting "${s}" for user script "${t.name}" is unavailable. Re-enter it on this device.`)}o.has(s)&&(i[s]=typeof a=="string"?a:"")}return i}async function ix(r,t,e){let n=S8(e);if(n.length===0)return!1;let i=nx(r);if(!i?.getSecret||!i?.setSecret)return n.some(([a])=>{let l=t.settings?.[a];return typeof l=="string"&&l.length>0})&&S.logWarning(`SecretStorage unavailable; leaving plaintext user script secret settings for "${t.name}" unchanged.`),!1;let o=!1;for(let[s,a]of n){let l=t.settings?.[s];if(Sm(l))continue;if(typeof l!="string"||l.length===0){if(!A8(a))continue;let d=_8(t,s,a);if(!await jI(r,d))continue;t.settings[s]=tx(d);for(let[p,m]of Object.entries(t.settings))p!==s&&Sm(m)&&m.secretRef===d&&delete t.settings[p];o=!0;continue}let c=await YI(r,t,s,l,void 0,a);c&&(t.settings[s]=tx(c),o=!0)}return o}function ox(r,t){let e=r.settings?.[t];return Sm(e)?e.secretRef:void 0}async function $8(r,t){if(!Am(t))return!0;let e=Object.values(t).filter(Sm).map(i=>i.secretRef);return(await Promise.all(e.map(i=>KI(r,i)))).every(Boolean)}function*QI(r){if(Am(r)&&(r.type==="Macro"&&(yield*rx(ur(r.macro))),r.type==="Multi"&&Array.isArray(r.choices)))for(let t of r.choices)yield*QI(t)}function*XI(r){Am(r)&&(r.type==="UserScript"&&(yield r),yield*rx(r.thenCommands),yield*rx(r.elseCommands),yield*QI(r.choice))}function*rx(r){if(Array.isArray(r))for(let t of r)yield*Array.isArray(t)?rx(t):XI(t)}async function F8(r,t){let e=!0;for(let n of t)e=await $8(r,n.settings)&&e;return e}async function sx(r,t){return F8(r,XI(t))}function M8(r,t){let e=r.path;if(typeof e=="string")return t?.secretOptionNamesByPath?.get(e)}function R8(r,t,e){if(Am(r))for(let[n,i]of Object.entries(r)){if(Sm(i)){delete r[n];continue}typeof i=="string"&&(t===null||t?.has(n)||t===void 0&&e?.stripUnknownStringSettings===!0)&&delete r[n]}}function hB(r,t){for(let e of r)R8(e.settings,M8(e,t),t)}function gB(r,t){hB(XI(r),t)}function ax(r,t){hB(QI(r),t)}var ZC,pB,dB,E8,nl=x(()=>{ye();sB();Gr();ZC="quickadd-user-script",pB="__quickaddSecret",dB=64,E8=8});function Pm(r,t){if(t.options)for(let e in t.options){let n=r[e]===void 0,i="defaultValue"in t.options[e]&&t.options[e].defaultValue!==void 0;n&&i&&!Im(t.options[e])&&(r[e]=t.options[e].defaultValue)}}var lx=x(()=>{nl()});function px(r){return r instanceof dx}function L8(r){return r.charCodeAt(0)===65279?r.slice(1):r}function N8(r){return L8(r).trimStart().slice(0,D8).toLowerCase()}function V8(r){return/^<(?:!doctype\s+html|html\b|head\b|body\b|script\b|meta\b|title\b|div\b)/.test(N8(r))}function $m(r,t){let e=new dx(r);throw t.reportLoadErrors!==!1&&Me(e),e}function B8(r){return`QuickAdd could not run ${r}. A user script must be a .js file or a note with a \`\`\`js code block. Rename the file so it ends in .js.`}function U8(r){return`QuickAdd could not find ${r}. If you moved or renamed the script, update its path in the macro.`}function q8(r){return`QuickAdd could not load ${r}. This file looks like a saved webpage, not a JavaScript file. Open the script on GitHub, use the Raw button, then download the .js file and select that file in QuickAdd.`}function z8(r){return`QuickAdd loaded ${r}, but its default export is not a function. Change it to module.exports = async (params) => { ... } or exports.default = async (params) => { ... }. If you meant to export several functions, use module.exports = { run } and select Script::run.`}function H8(r,t){let e=t?`the required module "${t}"`:"a required module";return`QuickAdd could not load ${r} because it could not find ${e}. Check that the required file or package exists, and that the capitalization in require(...) matches the file name exactly.`}function W8(r,t,e){let n=e===void 0?"":` on line ${e}`;return`QuickAdd could not load ${r} because it has a syntax error${n}: ${t}. Fix the script and run it again.`}function G8(r,t){if(r.startsWith("#!"))return;let e=window.require?.("vm");try{e?.compileFunction(r,bB,{filename:"user-script"})}catch(n){if(!(n instanceof Error)||n.message!==t)return;let i=n.stack?.match(/^user-script:(\d+)\n/)?.[1];if(i)return Number(i)}}function j8(r){return wB(r)?(r instanceof Error?r.message:String(r)).match(/Cannot find module ['"]([^'"]+)['"]/)?.[1]:void 0}function wB(r){return!r||typeof r!="object"?!1:r.code==="MODULE_NOT_FOUND"?!0:(r instanceof Error?r.message:String(r)).includes("Cannot find module")}function JI(r){return r!==null&&typeof r=="object"}function Y8(r){return typeof r.entry=="function"?!0:Object.entries(r).some(([t,e])=>t!=="settings"&&t!=="quickadd"&&typeof e=="function")}function K8(r){return typeof r=="function"?!0:JI(r)?Y8(r):!1}function Fm(r){let t=r.split("::").map(e=>e.trim()).filter(Boolean);return{basename:t[0],memberAccess:t.slice(1)}}function mx(r){let t=r.path??r.id;if(t===void 0)return;let{memberAccess:e}=Fm(r.name??"");return e&&e.length>0?`${t}::${e.join("::")}`:t}function yB(r){if(!JI(r)&&typeof r!="function")return;let t=r.settings;return JI(t)?t:void 0}function Q8(r,t){let e=r,n=yB(e);for(let i of t)e=e[i],n=yB(e)??n;return{script:e,settings:n}}async function Nv(r,t,e={}){return(await su(r,t,e))?.script}async function su(r,t,e={}){let n=t.vault.getAbstractFileByPath(r.path);if(n||$m(U8(r.path),e),n instanceof ux.TFile){let i=xt.test(n.path);!i&&!Fh.test(n.path)&&$m(B8(r.path),e);let o=g=>window.require&&window.require(g),s={},a={exports:s},l=await t.vault.read(n),c=l;if(i){let{code:g,error:v}=Ws(l);if(g===null||g.length===0){e.reportLoadErrors!==!1&&new ux.Notice(`QuickAdd: ${v} (${r.path})`);return}c=g}V8(c)&&$m(q8(r.path),e);let d;try{d=new Function(...bB,c)}catch(g){throw g instanceof SyntaxError&&$m(W8(r.path,g.message,G8(c,g.message)),e),g}try{d(o,a,s)}catch(g){throw wB(g)&&$m(H8(r.path,j8(g)),e),g}let u=s.default||a.exports;if(!u)return;let p=!!s.default,m=Fm(r.name).memberAccess??[],h=Q8(u,m);return p&&m.length===0&&!K8(h.script)&&$m(z8(r.path),e),h}}var ux,D8,dx,bB,au=x(()=>{ux=require("obsidian");Le();_m();nt();D8=1024,dx=class extends Error{constructor(t){super(t),this.name="UserScriptLoadError"}};bB=["require","module","exports"]});function Tc(r){return Array.isArray?Array.isArray(r):IB(r)==="[object Array]"}function e9(r){if(typeof r=="string")return r;if(typeof r=="bigint")return r.toString();let t=r+"";return t=="0"&&1/r==-1/0?"-0":t}function tP(r){return r==null?"":e9(r)}function Vn(r){return typeof r=="string"}function gx(r){return typeof r=="number"}function t9(r){return r===!0||r===!1||r9(r)&&IB(r)=="[object Boolean]"}function AB(r){return typeof r=="object"}function r9(r){return AB(r)&&r!==null}function ji(r){return r!=null}function hx(r){return!r.trim().length}function IB(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}function PB(r){let t=null,e=null,n=null,i=1,o=null;if(Vn(r)||Tc(r))n=r,t=xB(r),e=vx(r);else{if(!CB.call(r,"name"))throw new Error(s9("name"));let s=r.name;if(n=s,CB.call(r,"weight")&&r.weight!==void 0&&(i=r.weight,i<=0))throw new Error(a9(vx(s)));t=xB(s),e=vx(s),o=r.getFn??null}return{path:t,id:e,weight:i,src:n,getFn:o}}function xB(r){return Tc(r)?r:r.split(".")}function vx(r){return Tc(r)?r.join("."):r}function d9(r,t){let e=[],n=!1,i=(o,s,a,l)=>{if(ji(o))if(!s[a])e.push(l!==void 0?{v:o,i:l}:o);else{let c=o[s[a]];if(!ji(c))return;if(a===s.length-1&&(Vn(c)||gx(c)||t9(c)||typeof c=="bigint"))e.push(l!==void 0?{v:tP(c),i:l}:tP(c));else if(Tc(c)){n=!0;for(let d=0,u=c.length;d=9&&r<=13||r===32||r===160}function g9(r=1,t=3){let e=new Map,n=Math.pow(10,t);return{get(i){let o=0,s=!1;for(let l=0;l=t&&e.push([n,i]),n=-1)}return r[o-1]&&o-n>=t&&e.push([n,o-1]),e}function b9(r,t,e,{location:n=Ue.location,distance:i=Ue.distance,threshold:o=Ue.threshold,findAllMatches:s=Ue.findAllMatches,minMatchCharLength:a=Ue.minMatchCharLength,includeMatches:l=Ue.includeMatches,ignoreLocation:c=Ue.ignoreLocation}={}){if(t.length>32)throw new Error(o9(32));let d=t.length,u=r.length,p=Math.max(0,Math.min(n,u)),m=o,h=p,g=(D,N)=>{let K=D/d;if(c)return K;let ne=Math.abs(p-N);return i?K+ne/i:ne?1:K},v=a>1||l,b=v?Array(u):[],y;for(;(y=r.indexOf(t,h))>-1;){let D=g(0,y);if(m=Math.min(D,m),h=y+d,v){let N=0;for(;N=ne;G-=1){let V=G-1,M=e[r[V]];if(O[G]=(O[G+1]<<1|1)&M,D&&(O[G]|=(C[G+1]|C[G])<<1|1|C[G+1]),O[G]&_&&(w=g(D,V),w<=m)){if(m=w,h=V,T=D,h<=p)break;ne=Math.max(1,2*p-h)}}if(g(D+1,p)>m)break;C=O}if(v&&h>=0){let D=Math.min(u-1,h+d-1+T);for(let N=h;N<=D;N+=1)e[r[N]]&&(b[N]=1)}let I={isMatch:h>=0,score:Math.max(.001,w)};if(v){let D=y9(b,a);D.length?l&&(I.indices=D):I.isMatch=!1}return I}function w9(r){let t={};for(let e=0,n=r.length;ee[0]-n[0]||e[1]-n[1]);let t=[r[0]];for(let e=1,n=r.length;e=e)break;let i=n;for(;i=e||r[o]===" "){i++;break}if(r[o]==="$"&&(o+1>=e||r[o+1]===" ")){i+=2;break}}i++}t.push(r.substring(n,i)),n=i}else{for(;i{let n=k9(e.replace(/\u0000/g,"|").trim()).filter(o=>o&&!!o.trim()),i=[];for(let o=0,s=n.length;o{if(Vn(i)){let l={keyId:null,pattern:i};return e&&(l.searcher=yx(i,t)),l}let o=Object.keys(i),s=I9(i);if(!s&&o.length>1&&!sP(i))return n(_B(i));if(P9(i)){let l=s?i[oP.PATH]:o[0],c=s?i[oP.PATTERN]:i[l];if(!Vn(c))throw new Error(i9(l));let d={keyId:vx(l),pattern:c};return e&&(d.searcher=yx(c,t)),d}let a={children:[],operator:o[0]};return o.forEach(l=>{let c=i[l];Tc(c)&&c.forEach(d=>{a.children.push(n(d))})}),a};return sP(r)||(r=_B(r)),n(r)}function aP(r,{ignoreFieldNorm:t=Ue.ignoreFieldNorm}){let e=1;return r.forEach(({key:n,norm:i,score:o})=>{let s=n?n.weight:null;e*=Math.pow(o===0&&s?Number.EPSILON:o,(s||1)*(t?1:i))}),e}function $9(r,{ignoreFieldNorm:t=Ue.ignoreFieldNorm}){r.forEach(e=>{e.score=aP(e.matches,{ignoreFieldNorm:t})})}function M9(r){let t=[];return r.matches.forEach(e=>{if(!ji(e.indices)||!e.indices.length)return;let n={indices:e.indices,value:e.value};e.key&&(n.key=e.key.id),e.idx>-1&&(n.refIndex=e.idx),t.push(n)}),t}function R9(r,t,{includeMatches:e=Ue.includeMatches,includeScore:n=Ue.includeScore}={}){return r.map(i=>{let{idx:o}=i,s={item:t[o],refIndex:o};return e&&(s.matches=M9(i)),n&&(s.score=i.score),s})}function D9(r){kB.has(r)||(kB.add(r),console.warn(`[Fuse] tokenize regex ${r} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function L9(r){if(typeof r=="function"){let t=!1;return e=>{let n=r(e);if(!t&&(t=!0,!Array.isArray(n)||n.some(i=>typeof i!="string")))throw new Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(n)?"array containing non-strings":typeof n}.`);return n}}return r instanceof RegExp?(r.global||D9(r),t=>t.match(r)||[]):t=>t.match(O9)||[]}function lP({isCaseSensitive:r=!1,ignoreDiacritics:t=!1,tokenize:e}={}){let n=L9(e);return{tokenize(i){return r||(i=i.toLowerCase()),t&&(i=Vv(i)),n(i)}}}function eP(r,t,e,n){let i=n.tokenize(t);if(!i.length)return;r.fieldCount++,r.docFieldCount.set(e,(r.docFieldCount.get(e)||0)+1);let o=new Set(i),s=r.docTermFieldHits.get(e);s||(s=new Map,r.docTermFieldHits.set(e,s));for(let a of o)s.set(a,(s.get(a)||0)+1),r.df.set(a,(r.df.get(a)||0)+1)}function RB(r,t,e,n){let{i,v:o,$:s}=t;if(o!==void 0){eP(r,o,i,n);return}if(s)for(let a=0;aa-l);for(let a of e)U9(r,a);let n=a=>{let l=0,c=e.length;for(;l>>1;e[d]i?n(a):a,l);r.docFieldCount=o;let s=new Map;for(let[a,l]of r.docTermFieldHits)s.set(a>i?n(a):a,l);r.docTermFieldHits=s}var n9,rP,i9,o9,s9,a9,l9,CB,c9,u9,p9,m9,f9,Ue,cP,FB,C9,Vv,uP,x9,nP,EB,T9,_9,A9,iP,bx,oP,sP,I9,P9,_B,F9,O9,kB,N9,_c,kc,wx=x(()=>{n9="Incorrect 'index' type",rP="Invalid doc index: must be a non-negative integer within the bounds of the docs array",i9=r=>`Invalid value for key ${r}`,o9=r=>`Pattern length exceeds max of ${r}.`,s9=r=>`Missing ${r} property in key`,a9=r=>`Property 'weight' in key '${r}' must be a positive integer`,l9="Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.",CB=Object.prototype.hasOwnProperty,c9=class{constructor(r){this._keys=[],this._keyMap={};let t=0;r.forEach(e=>{let n=PB(e);this._keys.push(n),this._keyMap[n.id]=n,t+=n.weight}),this._keys.forEach(e=>{e.weight/=t})}get(r){return this._keyMap[r]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};u9={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},p9={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(r,t)=>r.score===t.score?r.idx{this._keysMap[t.id]=e})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let r=this.docs.length;this.records=new Array(r);let t=0;if(Vn(this.docs[0]))for(let e=0;er&&(this.records[t].i-=1)}removeAll(r){let t=new Set;for(let n of r)Number.isInteger(n)&&n>=0&&t.add(n);if(t.size===0)return;this.records=this.records.filter(n=>!t.has(n.i));let e=Array.from(t).sort((n,i)=>n-i);for(let n of this.records){let i=0,o=e.length;for(;i>>1;e[s]t),records:this.records}}};FB={\u0142:"l",\u0141:"L",\u0111:"d",\u0110:"D",\u00F8:"o",\u00D8:"O",\u0127:"h",\u0126:"H",\u0167:"t",\u0166:"T",\u0131:"i",\u00DF:"ss"},C9=new RegExp("["+Object.keys(FB).join("")+"]","g"),Vv=typeof String.prototype.normalize=="function"?r=>r.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"").replace(C9,t=>FB[t]):r=>r,uP=class{constructor(r,{location:t=Ue.location,threshold:e=Ue.threshold,distance:n=Ue.distance,includeMatches:i=Ue.includeMatches,findAllMatches:o=Ue.findAllMatches,minMatchCharLength:s=Ue.minMatchCharLength,isCaseSensitive:a=Ue.isCaseSensitive,ignoreDiacritics:l=Ue.ignoreDiacritics,ignoreLocation:c=Ue.ignoreLocation}={}){if(this.options={location:t,threshold:e,distance:n,includeMatches:i,findAllMatches:o,minMatchCharLength:s,isCaseSensitive:a,ignoreDiacritics:l,ignoreLocation:c},r=a?r:r.toLowerCase(),r=l?Vv(r):r,this.pattern=r,this.chunks=[],!this.pattern.length)return;let d=(p,m)=>{this.chunks.push({pattern:p,alphabet:w9(p),startIndex:m})},u=this.pattern.length;if(u>32){let p=0,m=u%32,h=u-m;for(;p{let{isMatch:b,score:y,indices:C}=b9(r,h,g,{location:i+v,distance:o,threshold:s,findAllMatches:a,minMatchCharLength:l,includeMatches:n,ignoreLocation:c});b&&(p=!0),u+=y,b&&C&&d.push(...C)});let m={isMatch:p,score:p?u/this.chunks.length:1};return p&&n&&(m.indices=dP(d)),m}},x9=new Set(["fuzzy","include"]);nP=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:r=>({type:"exact",search(t){let e=t===r;return{isMatch:e,score:e?0:1,indices:[0,r.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:r=>({type:"include",search(t){let e=0,n,i=[],o=r.length;for(;(n=t.indexOf(r,e))>-1;)e=n+o,i.push([n,e-1]);let s=!!i.length;return{isMatch:s,score:s?0:1,indices:i}}})},{type:"prefix-exact",multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:r=>({type:"prefix-exact",search(t){let e=t.startsWith(r);return{isMatch:e,score:e?0:1,indices:[0,r.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:r=>({type:"inverse-prefix-exact",search(t){let e=!t.startsWith(r);return{isMatch:e,score:e?0:1,indices:[0,t.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:r=>({type:"inverse-suffix-exact",search(t){let e=!t.endsWith(r);return{isMatch:e,score:e?0:1,indices:[0,t.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:r=>({type:"suffix-exact",search(t){let e=t.endsWith(r);return{isMatch:e,score:e?0:1,indices:[t.length-r.length,t.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:r=>({type:"inverse-exact",search(t){let e=t.indexOf(r)===-1;return{isMatch:e,score:e?0:1,indices:[0,t.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(r,t={})=>{let e=new uP(r,{location:t.location??Ue.location,threshold:t.threshold??Ue.threshold,distance:t.distance??Ue.distance,includeMatches:t.includeMatches??Ue.includeMatches,findAllMatches:t.findAllMatches??Ue.findAllMatches,minMatchCharLength:t.minMatchCharLength??Ue.minMatchCharLength,isCaseSensitive:t.isCaseSensitive??Ue.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics??Ue.ignoreDiacritics,ignoreLocation:t.ignoreLocation??Ue.ignoreLocation});return{type:"fuzzy",search(n){return e.searchIn(n)}}}}],EB=nP.length,T9="\0",_9="|";A9=class{constructor(r,{isCaseSensitive:t=Ue.isCaseSensitive,ignoreDiacritics:e=Ue.ignoreDiacritics,includeMatches:n=Ue.includeMatches,minMatchCharLength:i=Ue.minMatchCharLength,ignoreLocation:o=Ue.ignoreLocation,findAllMatches:s=Ue.findAllMatches,location:a=Ue.location,threshold:l=Ue.threshold,distance:c=Ue.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:e,includeMatches:n,minMatchCharLength:i,findAllMatches:s,ignoreLocation:o,location:a,threshold:l,distance:c},r=t?r:r.toLowerCase(),r=e?Vv(r):r,this.pattern=r,this.query=S9(this.pattern,this.options)}static condition(r,t){return t.useExtendedSearch}searchIn(r){let t=this.query;if(!t)return{isMatch:!1,score:1};let{includeMatches:e,isCaseSensitive:n,ignoreDiacritics:i}=this.options;r=n?r:r.toLowerCase(),r=i?Vv(r):r;let o=0,s=[],a=0,l=!1;for(let c=0,d=t.length;c!!(r[bx.AND]||r[bx.OR]),I9=r=>!!r[oP.PATH],P9=r=>!Tc(r)&&AB(r)&&!sP(r),_B=r=>({[bx.AND]:Object.keys(r).map(t=>({[t]:r[t]}))});F9=class{constructor(r,t){this.limit=r,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(r){this.size0;){let e=r-1>>1;if(this.comparator(t[r],t[e])<=0)break;let n=t[r];t[r]=t[e],t[e]=n,r=e}}_sinkDown(r){let t=this.heap,e=t.length,n=r;do{r=n;let i=2*r+1,o=2*r+2;if(i0&&(n=i),o0&&(n=o),n!==r){let s=t[r];t[r]=t[n],t[n]=s}}while(n!==r)}};O9=/[\p{L}\p{M}\p{N}_]+/gu,kB=new WeakSet;N9=class{static condition(r,t){return t.useTokenSearch}constructor(r,t){this.options=t,this.analyzer=lP({isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,tokenize:t.tokenize});let e=this.analyzer.tokenize(r),{df:n,fieldCount:i}=t._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let o of e){this.termSearchers.push(new uP(o,{location:t.location,threshold:t.threshold,distance:t.distance,includeMatches:t.includeMatches,findAllMatches:t.findAllMatches,minMatchCharLength:t.minMatchCharLength,isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,ignoreLocation:!0}));let s=n.get(o)||0,a=Math.log(1+(i-s+.5)/(s+.5));this.idfWeights.push(a)}this.combineAll=t.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(r){if(!this.termSearchers.length)return{isMatch:!1,score:1};let t=[],e=0,n=0,i=0,o=0,s=this.combineAll&&!this.useMask?new Set:null;for(let c=0;c0?1-e/n:0,l={isMatch:!0,score:Math.max(.001,a)};return this.options.includeMatches&&t.length&&(l.indices=dP(t)),this.combineAll&&(this.useMask?l.matchedMask=o:l.matchedTerms=s,l.termCount=this.numTerms),l}};_c=class{constructor(r,t,e){this.options={...Ue,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new c9(this.options.keys),this._docs=r,this._myIndex=null,this._invertedIndex=null,this.setCollection(r,e),this._lastQuery=null,this._lastSearcher=null}_getSearcher(r){if(this._lastQuery===r)return this._lastSearcher;let t=yx(r,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=r,this._lastSearcher=t,t}setCollection(r,t){if(this._docs=r,t&&!(t instanceof cP))throw new Error(n9);if(this._myIndex=t||$B(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=lP({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=V9(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(r){if(!ji(r))return;this._docs.push(r);let t=this._myIndex.add(r,this._docs.length-1);if(this._invertedIndex&&t){let e=lP({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});B9(this._invertedIndex,t,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}remove(r=()=>!1){let t=[],e=[];for(let n=0,i=this._docs.length;n!n.has(o)),this._myIndex.removeAll(e),this._invalidateSearcherCache()}return t}removeAt(r){if(!Number.isInteger(r)||r<0||r>=this._docs.length)throw new Error(rP);this._invertedIndex&&SB(this._invertedIndex,[r]);let t=this._docs.splice(r,1)[0];return this._myIndex.removeAt(r),this._invalidateSearcherCache(),t}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(r=>this._keyStore.get(r.id)||r)}search(r,t){let{limit:e=-1}=t||{},{includeMatches:n,includeScore:i,shouldSort:o,sortFn:s,ignoreFieldNorm:a}=this.options;if(Vn(r)&&!r.trim()){let p=this._docs.map((m,h)=>({item:m,refIndex:h}));return gx(e)&&e>-1&&(p=p.slice(0,e)),p}let l=o&&gx(e)&&e>0&&Vn(r),c=s,d=(p,m)=>c(p,m)||p.idx-m.idx,u;if(l){let p=new F9(e,d);Vn(this._docs[0])?this._searchStringList(r,{heap:p,ignoreFieldNorm:a}):this._searchObjectList(r,{heap:p,ignoreFieldNorm:a}),u=p.extractSorted()}else u=Vn(r)?Vn(this._docs[0])?this._searchStringList(r):this._searchObjectList(r):this._searchLogical(r),$9(u,{ignoreFieldNorm:a}),o&&u.sort(Vn(r)?d:c),gx(e)&&e>-1&&(u=u.slice(0,e));return R9(u,this._docs,{includeMatches:n,includeScore:i})}_searchStringList(r,{heap:t,ignoreFieldNorm:e}={}){let n=this._getSearcher(r),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,s=t?null:[];return o.forEach(({v:a,i:l,n:c})=>{if(!ji(a))return;let d=n.searchIn(a);if(d.isMatch){let u={score:d.score,value:a,norm:c,indices:d.indices};i&&(u.matchedMask=d.matchedMask,u.matchedTerms=d.matchedTerms,u.termCount=d.termCount);let p=[u];if(!i||this._coversAllTokens(p)){let m={item:a,idx:l,matches:p};t?(m.score=aP(m.matches,{ignoreFieldNorm:e}),t.insert(m)):s.push(m)}}}),s}_searchLogical(r){let t=MB(r,this.options),e=this._normalizedKeys(),n=(a,l,c)=>{if(!("children"in a)){let{keyId:m,searcher:h}=a,g;return m===null?(g=[],e.forEach((v,b)=>{g.push(...this._findMatches({key:v,value:l[b],searcher:h}))})):g=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(l,m),searcher:h}),g&&g.length?[{idx:c,item:l,matches:g}]:[]}let{children:d,operator:u}=a,p=[];for(let m=0,h=d.length;m{if(ji(a)){let c=n(t,a,l);c.length&&(o.has(l)||(o.set(l,{idx:l,item:a,matches:[]}),s.push(o.get(l))),c.forEach(({matches:d})=>{o.get(l).matches.push(...d)}))}}),s}_searchObjectList(r,{heap:t,ignoreFieldNorm:e}={}){let n=this._getSearcher(r),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,s=this._normalizedKeys(),a=t?null:[];return o.forEach(({$:l,i:c})=>{if(!ji(l))return;let d=[],u=!1,p=!1;if(s.forEach((m,h)=>{let g=this._findMatches({key:m,value:l[h],searcher:n});g.length?(d.push(...g),g[0].hasInverse&&(p=!0)):u=!0}),!(p&&u)&&d.length&&(!i||this._coversAllTokens(d))){let m={idx:c,item:l,matches:d};t?(m.score=aP(m.matches,{ignoreFieldNorm:e}),t.insert(m)):a.push(m)}}),a}_findMatches({key:r,value:t,searcher:e}){if(!ji(t))return[];let n=[];if(Tc(t))t.forEach(({v:i,i:o,n:s})=>{if(!ji(i))return;let a=e.searchIn(i);if(a.isMatch){let l={score:a.score,key:r,value:i,idx:o,norm:s,indices:a.indices,hasInverse:a.hasInverse};a.termCount!==void 0&&(l.matchedMask=a.matchedMask,l.matchedTerms=a.matchedTerms,l.termCount=a.termCount),n.push(l)}});else{let{v:i,n:o}=t,s=e.searchIn(i);if(s.isMatch){let a={score:s.score,key:r,value:i,norm:o,indices:s.indices,hasInverse:s.hasInverse};s.termCount!==void 0&&(a.matchedMask=s.matchedMask,a.matchedTerms=s.matchedTerms,a.termCount=s.termCount),n.push(a)}}return n}_coversAllTokens(r){let t=r.length?r[0].termCount:void 0;if(t===void 0)return!0;if(t<=31){let n=0;for(let i=0;ipP(t))};kc=_c});function q9(r){if(!r)return[];let t=[];for(let[e,n]of Object.entries(r)){let i=e.toLowerCase();if(i!=="alias"&&i!=="aliases")continue;let o=typeof n=="string"?n.split(","):n;Array.isArray(o)&&t.push(...o.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean))}return t}function OB(r,t,e){let n=r.metadataCache.getFileCache(t),i=n?.frontmatter,o=q9(i),s=o.map(d=>Ht(d)),a=(n?.headings??[]).map(d=>NS(d.heading)),l=[];if(n?.blocks)for(let d of Object.values(n.blocks))d.id&&l.push(d.id);let c=n?.tags?.map(d=>d.tag)??[];if(i?.tags){let d=Array.isArray(i.tags)?i.tags:[i.tags];c.push(...d.filter(u=>typeof u=="string"))}return{path:t.path,pathNormalized:Ht(t.path),basename:t.basename,basenameNormalized:Ht(t.basename),aliases:o,aliasesNormalized:s,headings:a,blockIds:l,tags:c,modified:t.stat.mtime,openedAt:e,folder:t.parent?.path??""}}var DB=x(()=>{an()});function LB(r,t,e,n,i,o,s){let a=n;if(e.currentFolder&&r.folder===e.currentFolder&&(a+=i.boosts.sameFolder),r.openedAt&&(Date.now()-r.openedAt)/864e5o.tags.includes(h));m.length>0&&(a+=i.boosts.tagOverlap*Math.min(m.length,Math.abs(i.boosts.tagOverlapMax/i.boosts.tagOverlap)))}let l=Ht(t),c=s==="alias"&&r.aliases.length>0?r.aliasesNormalized.findIndex(m=>m.includes(l)):-1,d=c>=0?r.aliases[c].length:r.basename.length;if(s==="alias"){let m=Math.max(0,(d-i.penalties.titleLengthThreshold)*i.penalties.aliasLengthMultiplier),h=Math.min(i.penalties.aliasMaxPenalty,i.penalties.aliasMinPenalty+m);a+=h}d>i.penalties.titleLengthThreshold&&(a+=(d-i.penalties.titleLengthThreshold)*i.penalties.titleLengthMultiplier);let p=(c>=0?r.aliasesNormalized[c]:r.basenameNormalized).indexOf(l);return p>=0&&(a+=p*i.penalties.positionMultiplier),a}var Cx,mP=x(()=>{an();Cx={base:{basenameExact:-1e3,aliasExact:-900,basenamePrefix:-500,aliasPrefix:-500,substringBasename:-300,fuzzyMatch:0},boosts:{sameFolder:-.15,recency:-.1,tagOverlap:-.05,tagOverlapMax:-.2},penalties:{titleLengthThreshold:15,titleLengthMultiplier:.02,aliasMinPenalty:.05,aliasMaxPenalty:.6,aliasLengthMultiplier:.04,positionMultiplier:.05},thresholds:{recencyDays:1,fuzzyRelaxCount:5}}});var Bv,fP,z9,H9,NB,Mm,hP=x(()=>{Bv=require("obsidian");wx();DB();mP();mP();an();fP=class{constructor(t=100){this.cache=new Map;this.maxSize=t}peek(t){return this.cache.get(t)}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(t,e)}clear(){this.cache.clear()}},z9=20,H9=100,NB=/\w/,Mm=class r{constructor(t,e){this.fileMap=new Map;this.recentFiles=new fP;this.unresolvedLinks=[];this.unresolvedLinksDirty=!0;this.isIndexing=!1;this.indexPromise=null;this.reindexTimeout=null;this.fuseUpdateTimeout=null;this.pendingFuseUpdates=new Map;this.reindexBuffer=null;this.effectiveWeights=Cx;this.app=t,this.plugin=e;let n={keys:[{name:"basenameNormalized",weight:.8},{name:"aliasesNormalized",weight:.6},{name:"pathNormalized",weight:.2}],ignoreLocation:!0,findAllMatches:!0,shouldSort:!1,includeScore:!0,includeMatches:!0};this.fuseStrict=new kc([],{...n,threshold:.2}),this.fuseRelaxed=new kc([],{...n,threshold:.4}),this.setupEventListeners(),this.effectiveWeights=Cx}static getInstance(t,e){return r.instance||(r.instance=new r(t,e)),r.instance}static getInstanceIfExists(){return r.instance??void 0}getLastOpenedAt(t){return this.recentFiles.peek(t)}setupEventListeners(){this.plugin.registerEvent(this.app.workspace.on("file-open",t=>{if(t){this.recentFiles.set(t.path,Date.now());let e=this.fileMap.get(t.path);e&&(e.openedAt=Date.now())}})),this.plugin.registerEvent(this.app.metadataCache.on("changed",t=>{t instanceof Bv.TFile&&t.extension==="md"&&this.updateFile(t)})),this.plugin.registerEvent(this.app.metadataCache.on("resolved",()=>{this.unresolvedLinksDirty=!0,this.fileMap.size===0&&this.scheduleReindex()})),this.plugin.registerEvent(this.app.vault.on("create",t=>{t instanceof Bv.TFile&&t.extension==="md"&&this.addFile(t)})),this.plugin.registerEvent(this.app.vault.on("delete",t=>{t instanceof Bv.TFile&&this.removeFile(t)})),this.plugin.registerEvent(this.app.vault.on("rename",(t,e)=>{t instanceof Bv.TFile&&t.extension==="md"&&(this.removeFileByPath(e),this.addFile(t))}))}async ensureIndexed(){if(this.isIndexing&&this.indexPromise)return this.indexPromise;if(this.fileMap.size===0)return this.reindex()}scheduleReindex(){this.reindexTimeout!==null&&window.clearTimeout(this.reindexTimeout),this.reindexTimeout=window.setTimeout(()=>{this.reindex()},500)}async reindex(){if(this.isIndexing&&this.indexPromise)return this.indexPromise;this.isIndexing=!0,this.indexPromise=this.performReindex();try{await this.indexPromise}finally{this.isIndexing=!1,this.indexPromise=null}}async performReindex(){let t=new Map;this.reindexBuffer=t;try{let e=this.app.vault.getMarkdownFiles(),n=new Map;await(async(o,s=50)=>{for(let a=0;awindow.setTimeout(c,0))}})(e),this.fileMap=n;for(let[o,s]of t)s.op==="remove"?this.fileMap.delete(o):s.file&&this.fileMap.set(o,this.createIndexedFile(s.file));this.updateFuseIndex(),this.updateUnresolvedLinks()}catch(e){try{this.updateFuseIndex()}catch{}throw e}finally{this.reindexBuffer=null}}createIndexedFile(t){return OB(this.app,t,this.recentFiles.peek(t.path))}addFile(t){this.upsertFile(t,"add")}updateFile(t){this.upsertFile(t,"update"),this.unresolvedLinksDirty=!0}upsertFile(t,e){this.fileMap.set(t.path,this.createIndexedFile(t)),this.scheduleFuseUpdate(t.path,e),this.reindexBuffer?.set(t.path,{op:"upsert",file:t})}removeFile(t){this.removeFileByPath(t.path)}removeFileByPath(t){this.fileMap.delete(t),this.scheduleFuseUpdate(t,"remove"),this.reindexBuffer?.set(t,{op:"remove"})}updateFuseIndex(){let t=Array.from(this.fileMap.values());this.fuseStrict.setCollection(t),this.fuseRelaxed.setCollection(t)}scheduleFuseUpdate(t,e){if(this.isIndexing)return;let n=this.pendingFuseUpdates.get(t);if(n==="add"&&e==="remove"){this.pendingFuseUpdates.delete(t);return}this.pendingFuseUpdates.set(t,n==="remove"&&e==="add"?"update":e),this.fuseUpdateTimeout!==null&&window.clearTimeout(this.fuseUpdateTimeout),this.fuseUpdateTimeout=window.setTimeout(()=>{this.processPendingFuseUpdates()},H9)}processPendingFuseUpdates(){if(this.pendingFuseUpdates.size!==0){if(this.isIndexing){this.pendingFuseUpdates.clear();return}if(this.pendingFuseUpdates.size>z9){this.updateFuseIndex(),this.pendingFuseUpdates.clear();return}for(let[t,e]of this.pendingFuseUpdates)for(let n of[this.fuseStrict,this.fuseRelaxed]){n.remove(o=>o.path===t);let i=e!=="remove"&&this.fileMap.get(t);i&&n.add(i)}this.pendingFuseUpdates.clear()}}updateUnresolvedLinks(){let t=this.app.metadataCache.unresolvedLinks,e=new Set;for(let n in t)for(let i in t[n])e.add(i);this.unresolvedLinks=Array.from(e,n=>{let i=n.lastIndexOf("/"),o=n.slice(i+1);return{path:n,pathNormalized:Ht(n),basename:o,basenameNormalized:Ht(o),aliases:[],aliasesNormalized:[],headings:[],blockIds:[],tags:[],modified:0,folder:i===-1?"":n.slice(0,i)}}),this.unresolvedLinksDirty=!1}search(t,e={},n=50){if(this.unresolvedLinksDirty&&this.updateUnresolvedLinks(),t.includes("#"))return this.searchWithHeadings(t,e,n);let i=Ht(t),o=this.matchFiles(t,e,n);if(t.length>=2){let s=this.effectiveWeights.base;for(let a of this.unresolvedLinks){if(!a.pathNormalized.includes(i))continue;let l=i.includes("/")?a.pathNormalized:a.basenameNormalized,c=l.indexOf(i),d=c===0?l===i?s.basenameExact:s.basenamePrefix:c>0&&!NB.test(l[c-1])?s.substringBasename:s.fuzzyMatch;o.push({file:a,score:this.calculateScore(a,t,e,d),matchType:"unresolved",displayText:a.path})}}return o.sort((s,a)=>s.score-a.score).slice(0,n)}calculateScore(t,e,n,i,o){return LB(t,e,n,i,this.effectiveWeights,n.currentFile?this.fileMap.get(n.currentFile.path):void 0,o)}searchWithHeadings(t,e,n){let[i,o]=t.split("#"),s=Ht(o??""),a=[];if(i===""){let l=0,c=200,d=Array.from(this.fileMap.values());for(let u of d){if(l>=c)break;for(let p of u.headings){if(l>=c)break;Ht(p).includes(s)&&(a.push({file:u,score:this.calculateScore(u,t,e,.1),matchType:"heading",displayText:`${u.basename}#${p}`}),l++)}}}else{let l=this.searchFiles(i,e,n);if(l.length===0)return[];for(let c of l)for(let d of c.file.headings)Ht(d).includes(s)&&a.push({file:c.file,score:c.score+.05,matchType:"heading",displayText:`${c.file.basename}#${d}`})}return a.sort((l,c)=>l.score-c.score).slice(0,n)}searchFiles(t,e,n){return this.matchFiles(t,e,n,{...this.effectiveWeights.base,basenameExact:-1e3,basenamePrefix:-500,aliasPrefix:-500,substringBasename:-300}).sort((i,o)=>i.score-o.score).slice(0,n)}matchFiles(t,e,n,i=this.effectiveWeights.base){let o=[],s=Ht(t),a=new Set,l=Array.from(this.fileMap.values()),c=(u,p,m,h)=>{a.has(u.path)||(o.push({file:u,score:this.calculateScore(u,t,e,p,m),matchType:m,displayText:h}),a.add(u.path))};for(let u of l)u.basenameNormalized===s&&c(u,i.basenameExact,"exact",u.basename);for(let u of l){let p=u.aliasesNormalized.indexOf(s);p!==-1&&c(u,i.aliasExact,"alias",u.aliases[p])}for(let u of l)u.basenameNormalized.startsWith(s)&&c(u,i.basenamePrefix,"fuzzy",u.basename);for(let u of l){let p=u.aliasesNormalized.findIndex(m=>m.startsWith(s));p!==-1&&c(u,i.aliasPrefix,"alias",u.aliases[p])}for(let u of l){let p=u.basenameNormalized.indexOf(s);p>0&&!NB.test(u.basenameNormalized[p-1])&&c(u,i.substringBasename,"fuzzy",u.basename)}let d=this.fuseStrict.search(s,{limit:n*2});d.lengthv.key==="aliasesNormalized"),m=!!p,h=m?"alias":"fuzzy",g=u.item.basename;if(m){let v=typeof p?.value=="string"?p.value:void 0,b=v?u.item.aliasesNormalized.findIndex(y=>y===v):u.item.aliasesNormalized.findIndex(y=>y.includes(s));b>=0&&(g=u.item.aliases[b])}c(u.item,(u.score??.5)+i.fuzzyMatch,h,g)}return o}getFile(t){return this.fileMap.get(t)}getHeadings(t){return t.headings}getBlockIds(t){return t.blockIds}getIndexedFileCount(){return this.fileMap.size}}});function W9(r,t){let e=At(r,"span");switch(e.classList.add("qa-suggestion-pill"),t){case"alias":return e.classList.add("qa-alias-pill"),e.textContent="alias",e;case"heading":return e.classList.add("qa-heading-pill"),e.textContent="H",e;case"block":return e.classList.add("qa-block-pill"),e.textContent="^",e;case"unresolved":return e.classList.add("qa-unresolved-pill"),e.textContent="unresolved",e;default:return null}}var xx,Rm,gP=x(()=>{Ms();xx=require("obsidian");Le();hP();an();ss();Ko();Rm=class extends Er{constructor(e,n,i){super(e,n);this.app=e;this.inputEl=n;this.lastInput="";this.sourcePathOverride=i?.sourcePath,this.fileIndex=Mm.getInstance(e,Wr()),this.fileIndex.ensureIndexed()}normalizeFolderPath(e){return!e||e==="/"?"":e.replace(/\/+$/,"")}getSourcePath(){return this.sourcePathOverride??this.app.workspace.getActiveFile()?.path??""}getSourceFolder(){let e=this.getSourcePath();if(!e)return"";let n=this.app.fileManager.getNewFileParent(e);return this.normalizeFolderPath(n?.path)}resolveRelative(e,n){let i=this.normalizeFolderPath(e),o=n;for(o.startsWith("./")&&(o=o.slice(2));o.startsWith("../");){let s=i.split("/");if(!i||s.length===0||s.length===1&&s[0]==="")break;s.pop(),i=s.join("/"),o=o.slice(3)}return{folder:this.normalizeFolderPath(i),query:o}}getSuggestions(e){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=e.slice(0,n),o=vD.exec(i);if(!o)return[];let s=o[1];if(this.lastInput=s,s.includes("#^"))return this.getBlockSuggestions(s);if(s.indexOf("#")>0)return this.getHeadingSuggestions(s);if(s.startsWith("./")||s.startsWith("../"))return this.getRelativePathSuggestions(s);if(i.includes("![["))return this.getAttachmentSuggestions(s);let c=this.getSourceFolder(),d=this.app.workspace.getActiveFile(),u={currentFile:this.sourcePathOverride?void 0:d??void 0,currentFolder:c};return this.fileIndex.search(s,u,50)}getHeadingSuggestions(e){let[n,i]=e.split("#"),o=n.trim()==="",s=Ht(i??""),a=[];if(o){let c=this.app.workspace.getActiveFile();if(c){let d=this.fileIndex.getFile(c.path);d&&(a=[d])}}else a=this.fileIndex.searchFiles(n,{},1).map(c=>c.file);if(a.length===0)return[];let l=[];for(let c of a){let u=this.fileIndex.getHeadings(c).filter(p=>i===""||Ht(p).includes(s)).slice(0,20);for(let p of u)l.push({file:c,score:0,matchType:"heading",displayText:o?`#${p}`:`${c.basename}#${p}`})}return l}getBlockSuggestions(e){let[n,i]=e.split("#^"),o=Ht(i??""),s=this.fileIndex.searchFiles(n,{},1);if(s.length===0)return[];let a=s[0].file;return this.fileIndex.getBlockIds(a).filter(c=>i===""||Ht(c).includes(o)).slice(0,20).map(c=>({file:a,score:0,matchType:"block",displayText:`${a.basename}#^${c}`}))}getRelativePathSuggestions(e){let n=this.getSourceFolder(),{folder:i,query:o}=this.resolveRelative(n,e);if(o)return this.fileIndex.search(o,{currentFolder:i},20);let s=this.fileIndex.search("",{currentFolder:i},50),a=l=>this.normalizeFolderPath(l||"");return s.filter(l=>a(l.file.folder)===a(i))}getAttachmentSuggestions(e){let n=this.app.vault.getFiles(),i=["png","jpg","jpeg","gif","svg","pdf","mp4","webm","mov","canvas"],o=Ht(e);return n.filter(a=>i.includes(a.extension.toLowerCase())&&(e===""||Ht(a.basename).includes(o))).slice(0,20).map(a=>({file:{path:a.path,pathNormalized:Ht(a.path),basename:a.basename,basenameNormalized:Ht(a.basename),aliases:[],aliasesNormalized:[],headings:[],blockIds:[],tags:[],modified:a.stat.mtime,folder:this.normalizeFolderPath(a.parent?.path||"")},score:0,matchType:"exact",displayText:a.name}))}renderSuggestion(e,n){let{file:i,matchType:o,displayText:s}=e;n.classList.add("qaFileSuggestionItem"),n.classList.add(`qa-suggest-${o}`);let a=s,l="",c=!1,d="";switch(o){case"exact":case"fuzzy":a=i.basename,l=i.path;break;case"alias":a=s,l=i.path;break;case"heading":{let[g,v]=s.split("#"),b=this.lastInput.includes("#")?this.lastInput.split("#")[1]:"",y=Ht(b??"");b&&Ht(v).includes(y)?(a=v,c=!0,d=b):a=v,l=g;break}case"block":{let[g,v]=s.split("#^");a=v,l=g;break}case"unresolved":a=s,l="Unresolved link";break}let u=At(n,"div");u.className="qa-suggestion-content";let p=At(n,"span");p.className="suggestion-main-text",c?this.renderMatch(p,a,d):p.textContent=a,u.appendChild(p);let m=W9(n,o);m&&u.appendChild(m);let h=At(n,"span");h.className="suggestion-sub-text",h.textContent=l,n.replaceChildren(u,h),this.addHoverTooltip(n,i)}open(e,n){if(super.open(e,n),!this.scrollListener){let i=Bi(this.inputEl),o=()=>this.hideTooltip();i.addEventListener("scroll",o,{passive:!0}),this.scrollListener=o,this.scrollListenerDocument=i}}hideTooltip(){let e=Bi(this.inputEl);this.tooltipTimeout!==void 0&&(window.clearTimeout(this.tooltipTimeout),this.tooltipTimeout=void 0),e.querySelector(".qa-file-tooltip")?.remove()}addHoverTooltip(e,n){let i=Bi(e);e.addEventListener("mouseenter",()=>{this.hideTooltip(),this.tooltipTimeout=window.setTimeout(()=>{let o=this.createTooltip(n);o&&(i.body.appendChild(o),this.positionTooltip(o,e))},200)}),e.addEventListener("mouseleave",()=>this.hideTooltip()),e.addEventListener("blur",()=>this.hideTooltip())}createTooltip(e){let n=this.app.vault.getAbstractFileByPath(e.path);if(!n||!(n instanceof xx.TFile))return null;let i=this.inputEl,o=At(i,"div");o.className="qa-file-tooltip";let s=At(i,"div");s.className="qa-tooltip-header",s.textContent=n.basename;let a=At(i,"div");a.className="qa-tooltip-content";let l=At(i,"div");l.textContent=`Path: ${n.path}`;let c=At(i,"div");return c.textContent=`Modified: ${new Date(n.stat.mtime).toLocaleDateString()}`,a.append(l,c),o.append(s,a),o}positionTooltip(e,n){let i=n.getBoundingClientRect();e.style.left=`${i.right+10}px`,e.style.top=`${i.top}px`}close(){this.hideTooltip(),this.scrollListener&&this.scrollListenerDocument&&(this.scrollListenerDocument.removeEventListener("scroll",this.scrollListener),this.scrollListener=void 0,this.scrollListenerDocument=void 0),super.close()}selectSuggestion(e){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.lastInput.length,o=this.inputEl.value,s=0,c=this.inputEl.value.slice(n-this.lastInput.length-3,n-this.lastInput.length)==="![["||e.matchType==="unresolved"||e.matchType==="heading"||e.matchType==="block"?void 0:this.app.vault.getAbstractFileByPath(e.file.path);c instanceof xx.TFile?s=this.makeLinkObsidianMethod(c,o,n,i,e.matchType==="alias"?e.displayText:void 0):s=this.makeLinkManually(o,e.matchType==="unresolved"?e.displayText.replace(/.md$/,""):e.displayText,n,i),this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(s,s)}makeLinkObsidianMethod(e,n,i,o,s){let a=this.app.vault.getAbstractFileByPath(e.path);if(!(a instanceof xx.TFile))return this.makeLinkManually(n,e.path,i,o);let l=this.app.fileManager.generateMarkdownLink(a,this.getSourcePath(),"",s??"");return this.inputEl.value=this.getNewInputValueForFileLink(n,l,i,o),i-o+l.length+2}makeLinkManually(e,n,i,o){return this.inputEl.value=this.getNewInputValueForFileName(e,n,i,o),i-o+n.length+2}getNewInputValueForFileLink(e,n,i,o){return`${e.slice(0,i-o-2)}${n}${e.slice(i)}`}getNewInputValueForFileName(e,n,i,o){return`${e.slice(0,i-o)}${n}]]${e.slice(i)}`}}});var VB,Ex,BB=x(()=>{wx();VB={threshold:.4,includeScore:!0,keys:[""]},Ex=class r{constructor(t,e){this.sortedTags=[];this.fuse=new kc([],VB);this.app=t,this.refresh(),e.registerEvent(this.app.metadataCache.on("resolved",()=>this.refresh()))}static getInstance(t,e){return r.instance||(r.instance=new r(t,e)),r.instance}refresh(){let t=this.app.metadataCache.getTags(),e=Object.keys(t);this.sortedTags=e.sort((n,i)=>n.length!==i.length?n.length-i.length:n.localeCompare(i)),this.fuse=new kc(this.sortedTags,VB)}getSortedTags(){return this.sortedTags}search(t){return this.fuse.search(t)}}});function G9(r,t){let e=r.slice(0,t),n=e.lastIndexOf("[[");return n===-1?!1:e.lastIndexOf("]]"){Le();Ms();an();ss();BB();Om=class extends Er{constructor(e,n,i){super(e,n);this.app=e;this.inputEl=n;this.lastInput="";this.lastInputStart=0;this.lastInputLength=0;this.tagIndex=Ex.getInstance(e,Wr()),i?.refreshIndex!==!1&&this.tagIndex.refresh()}getSuggestions(e){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=e.slice(0,n),o=yD.exec(i);if(!o)return[];if(o.index===void 0)return[];if(G9(i,o.index))return[];let s=o[1];this.lastInput=s,this.lastInputStart=o.index,this.lastInputLength=o[0].length;let a=this.tagIndex.getSortedTags(),l=s.toLowerCase(),c=a.filter(m=>m.replace(/^#/,"").toLowerCase().startsWith(l)).slice(0,5),d=this.tagIndex.search(s).filter(m=>m.score!==void 0&&m.score<.8).map(m=>m.item).slice(0,10),u=new Set(c),p=[...c];for(let m of d)!u.has(m)&&p.length<15&&(p.push(m),u.add(m));return p}renderSuggestion(e,n){this.renderMatch(n,e,this.lastInput)}selectSuggestion(e){let n=this.inputEl;if(n.selectionStart===null)return;let i=this.lastInputStart,o=i+this.lastInputLength,s=e.startsWith("#")?e:`#${e}`;lw(n,i,o,s,{fromCompletion:!0}),this.close()}}});var Bn,Dm=x(()=>{Bn=class r{constructor(){this.drafts=new Map;this.executionScopes=[];this.MAX_ENTRIES=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}makeKey(t){return JSON.stringify({v:1,kind:t.kind,header:t.header,placeholder:t.placeholder??"",linkSourcePath:t.linkSourcePath??"",scopeId:t.scopeId??""})}get(t){let e=this.drafts.get(t);if(e)return e.timestamp=Date.now(),e.value}takeDraftForPrompt(t){if(this.executionScopes.some(e=>e.submittedDraftKeys.has(t))){this.clear(t);return}return this.get(t)}set(t,e){this.drafts.size>=this.MAX_ENTRIES&&!this.drafts.has(t)&&this.evictOldest(1),this.drafts.set(t,{value:e,timestamp:Date.now()})}handleSubmittedDraft(t,e){let n=this.executionScopes.at(-1);if(!n){this.clear(t);return}this.set(t,e),n.submittedDraftKeys.add(t)}beginExecutionScope(){let t={submittedDraftKeys:new Set,failed:!1};return this.executionScopes.push(t),t}commitExecutionScope(t){if(!(!this.endExecutionScope(t)||t.failed))for(let e of t.submittedDraftKeys)this.clear(e)}rollbackExecutionScope(t){this.endExecutionScope(t)&&this.markExecutionScopeFailed()}markExecutionScopeFailed(){for(let t of this.executionScopes)t.failed=!0}hasActiveExecutionScope(){return this.executionScopes.length>0}clear(t){this.drafts.delete(t);for(let e of this.executionScopes)e.submittedDraftKeys.delete(t)}clearAll(){this.drafts.clear(),this.executionScopes=[]}endExecutionScope(t){let e=this.executionScopes.indexOf(t);return e===-1?!1:(this.executionScopes.splice(e,1),!0)}evictOldest(t){let e=Array.from(this.drafts.entries()).sort(([,n],[,i])=>n.timestamp-i.timestamp).slice(0,t);for(let[n]of e)this.clear(n)}}});var Tx,UB=x(()=>{je();Dm();Tx=class{constructor(t,e){this.store=Bn.getInstance();this.initialValue="";this.didChange=!1;this.draftKey=this.store.makeKey(t),this.shouldPersist=e??(()=>U.getState().persistInputPromptDrafts)}hydrate(t){return this.initialValue=t,this.shouldPersist()?this.store.takeDraftForPrompt(this.draftKey)??t:t}markChanged(){this.didChange=!0}persist(t,e){if(this.shouldPersist()){if(e){this.store.handleSubmittedDraft(this.draftKey,t);return}if(this.didChange){if(!t.trim()||t===this.initialValue){this.store.clear(this.draftKey);return}this.store.set(this.draftKey,t)}}}}});function _x(r,t){if(r.focus(),t?.cursorAtEnd){let e=r.value.length;r.setSelectionRange(e,e);return}r.select()}var yP=x(()=>{});function qB(r,t,e){let n=t?.trim();if(!n)return;let i=r.createDiv({text:n,cls:"qa-prompt-context"});return i.setAttr("title",e?.trim()||n),i}var zB=x(()=>{});function HB(r){return(r??"").trim().replace(/\\/g,"/")}function j9(r){return r.startsWith("/")||/^[a-zA-Z]:/.test(r)}function Y9(r){return r.split("/").some(t=>/^\.\.[. ]*$/u.test(t))}function Ut(r){let t=HB(r);return t?j9(t)||Y9(t):!1}function kx(r){let t=HB(r);return!t||Ut(t)?!1:!t.split("/").some(e=>e.startsWith(".")&&!e.startsWith("..%"))}var Yi=x(()=>{});function ol(r){return Object.hasOwn(il,r)}function WB(r){let t=r.toLowerCase();return t==="jpeg"||Object.values(il).includes(t)}function K9(r){let t=e=>String(e).padStart(2,"0");return`${r.getFullYear()}-${t(r.getMonth()+1)}-${t(r.getDate())} ${t(r.getHours())}.${t(r.getMinutes())}.${t(r.getSeconds())}`}function X9(r){return r.replace(Q9,"").replace(/\s+/g," ").replace(/[. ]+$/g,"").trim()}function Sx(r){if(r.nameAfterNoteTitle){let t=X9(Ap(r.sourcePath));if(t.length>0&&zS(t))return`${t}.${r.extension}`}return`Clipboard image ${K9(r.now)}.${r.extension}`}function GB(r,t){if(!ol(r))throw new Error(`Unsupported clipboard image type: ${r}`);return Sx({extension:il[r],sourcePath:"",now:t,nameAfterNoteTitle:!1})}function jB(r){let t=r.split(/[\\/]/u).at(-1)??"",e=t.lastIndexOf("."),n=e>=0?t.slice(0,e):t;return zS(n)?n:null}async function bP(r,t,e,n,i){if(!ol(e))throw new Error(`Unsupported image type: ${e}`);let o=await r.fileManager.getAvailablePathForAttachment(i,n||void 0);if(Ut(o))throw new Error(`Refusing to save image outside the vault: '${o}'`);return r.vault.createBinary(o,t)}async function Ax(r,t,e,n,i){if(!ol(e))throw new Error(`Unsupported clipboard image type: ${e}`);let o=i?.nameAfterNoteTitle??U.getState().namePastedImagesAfterNoteTitle;return bP(r,t,e,n,Sx({extension:il[e],sourcePath:n,now:i?.now??new Date,nameAfterNoteTitle:o}))}function Ix(r,t,e){let n=r.fileManager.generateMarkdownLink(t,e);return n.startsWith("!")?n:`!${n}`}var il,Q9,Px=x(()=>{je();Ln();Xh();Yi();il=Object.assign(Object.create(null),{"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"});Q9=/[/\\:*?"<>|#^[\]]/g});function J9(){let r=$x.filter(e=>e.inputEl.isConnected);return r.find(e=>document.activeElement!==null&&e.inputEl.contains(document.activeElement))??r.at(-1)??null}function Mx(r,t,e={}){let n=e.sourcePath??"",i=null,o=!1,s=!1,a=()=>{s=!0},l=()=>{s=!1},c=(b,y,C,w)=>{switch(C.kind){case"stand-down":return;case"take":if(y.preventDefault(),i){new Uv.Notice(b==="paste"?"QuickAdd: an image is still being saved \u2014 paste again in a moment.":"QuickAdd: an image is still being saved \u2014 drop again in a moment.");return}i=h(C.images,w).then(()=>{}).finally(()=>{i=null});return;default:return Fx(C)}},d=b=>{let y=b.clipboardData;if(!y||s)return;let C=new Date;c("paste",b,YB("paste",y,r),C)},u=b=>{if(s)return;let y=b.dataTransfer;!y||!QB(y)||(b.preventDefault(),y.dropEffect="copy",t.classList.add("qa-image-drop-target"))},p=()=>{t.classList.remove("qa-image-drop-target")},m=b=>{if(p(),s)return;let y=b.dataTransfer;if(!y||!QB(y))return;let C=new Date;c("drop",b,YB("drop",y,r),C)};async function h(b,y){let C=t.readOnly;t.readOnly=!0,t.setAttribute("aria-busy","true"),t.classList.add("qa-image-paste-busy");let w=[];try{for(let P of b){let _;switch(P.origin){case"vault":_=P.file;break;case"bytes":{let I=await P.file.arrayBuffer(),D=r7(P,y,n);_=await n7(()=>bP(r,I,P.mimeType,n,D));break}default:return Fx(P)}w.push(Ix(r,_,n))}}catch(P){S.logError(`Failed to save image: ${P instanceof Error?P.message:String(P)}`),new Uv.Notice("QuickAdd: failed to save image.")}finally{t.readOnly=C,t.removeAttribute("aria-busy"),t.classList.remove("qa-image-paste-busy")}if(w.length===0||o)return"";let T=w.join(t.tagName==="TEXTAREA"?` `:" ");try{return i7(t,T),T}catch(P){return S.logError(`Failed to insert image link: ${P instanceof Error?P.message:String(P)}`),new Uv.Notice("QuickAdd: saved the image but could not insert its link."),""}}async function g(b){let y=new Date,C=t7(b);if(C.length===0)return S.logMessage("QuickAdd: image ingest skipped (no-images)."),"";if(i)return new Uv.Notice("QuickAdd: an image is still being saved \u2014 drop again in a moment."),S.logMessage("QuickAdd: image ingest skipped (busy)."),"";let w="";return i=(async()=>{w=await h(C,y)})().finally(()=>{i=null}),await i,w.length>0&&S.logMessage(`QuickAdd: ingested ${C.length} image(s) into the active prompt.`),w}t.addEventListener("paste",d),t.addEventListener("dragenter",u),t.addEventListener("dragover",u),t.addEventListener("dragleave",p),t.addEventListener("drop",m),t.addEventListener("compositionstart",a),t.addEventListener("compositionend",l);let v={isBusy:()=>i!==null,whenIdle:()=>i??Promise.resolve(),ingestFiles:g,detach:()=>{o=!0,p(),t.removeEventListener("paste",d),t.removeEventListener("dragenter",u),t.removeEventListener("dragover",u),t.removeEventListener("dragleave",p),t.removeEventListener("drop",m),t.removeEventListener("compositionstart",a),t.removeEventListener("compositionend",l);let b=$x.findIndex(y=>y.handle===v);b>=0&&$x.splice(b,1)}};return $x.push({handle:v,inputEl:t}),v}async function JB(r){let t=J9();if(!t)return S.logMessage("QuickAdd: image ingest skipped (no-active-prompt)."),{ok:!1,reason:"no-active-prompt"};if(t.handle.isBusy())return S.logMessage("QuickAdd: image ingest skipped (busy)."),{ok:!1,reason:"busy"};let e=await t.handle.ingestFiles(r);return e.length===0?{ok:!1,reason:"no-images"}:{ok:!0,inserted:e}}function YB(r,t,e){switch(r){case"paste":{if(t.getData("text/plain").length>0)return{kind:"stand-down"};let n=KB(t).map(i=>({origin:"bytes",...i,naming:{kind:"paste-name"}}));return n.length>0?{kind:"take",images:n}:{kind:"stand-down"}}case"drop":{let n=Z9(t,e);if(n.length>0)return{kind:"take",images:n};let i=KB(t).map(o=>({origin:"bytes",...o,naming:ZB(o)}));return i.length>0?{kind:"take",images:i}:{kind:"stand-down"}}default:return Fx(r)}}function Z9(r,t){let e=[];for(let n of r.getData("text/plain").split(/\r?\n/u)){let i=n.trim();if(i.length===0||i.toLowerCase().startsWith("file://")||Ut(i))continue;let o=t.vault.getAbstractFileByPath(i);e7(o)&&e.push({origin:"vault",file:o})}return e}function e7(r){return r!==null&&"extension"in r&&typeof r.extension=="string"&&WB(r.extension)}function KB(r){let t=[],e=0;for(let o of Array.from(r.items??[])){if(o.kind!=="file"||(e++,!ol(o.type)))continue;let s=o.getAsFile();s&&t.push({file:s,mimeType:o.type})}if(e>0&&t.length===e)return t;if(t.length===0){let o=[];for(let s of Array.from(r.files??[]))ol(s.type)&&o.push({file:s,mimeType:s.type});return o}let n=[...t],i=new Set(t.map(({file:o,mimeType:s})=>`${o.name}\0${o.size}\0${s}\0${o.lastModified}`));for(let o of Array.from(r.files??[])){if(!ol(o.type))continue;let s=`${o.name}\0${o.size}\0${o.type}\0${o.lastModified}`;i.has(s)||(i.add(s),n.push({file:o,mimeType:o.type}))}return n}function t7(r){return r.flatMap(t=>{if(!ol(t.type))return[];let e={file:t,mimeType:t.type};return[{origin:"bytes",...e,naming:ZB(e)}]})}function ZB(r){let t=jB(r.file.name);return t===null?{kind:"clipboard-stamp"}:{kind:"original-stem",stem:t}}function r7(r,t,e){switch(r.naming.kind){case"clipboard-stamp":return GB(r.mimeType,t);case"paste-name":return Sx({extension:il[r.mimeType],sourcePath:e,now:t,nameAfterNoteTitle:U.getState().namePastedImagesAfterNoteTitle});case"original-stem":return`${r.naming.stem}.${il[r.mimeType]}`;default:return Fx(r.naming)}}function QB(r){return Array.from(r.types??[]).some(t=>t==="Files"||ol(t))}function Fx(r){throw new Error(`Unexpected image intake value: ${String(r)}`)}function n7(r){let t=XB.then(r,r);return XB=t.catch(()=>{}),t}function i7(r,t){r.focus();let e=!1;try{e=r.ownerDocument.execCommand("insertText",!1,t)}catch{e=!1}if(e)return;let n=r.selectionStart??r.value.length,i=r.selectionEnd??n;r.setRangeText(t,n,i,"end"),r.dispatchEvent(new Event("input",{bubbles:!0}))}var Uv,$x,XB,Rx=x(()=>{Uv=require("obsidian");ye();Px();je();Yi();$x=[];XB=Promise.resolve()});function Un(r){let t=r.workspace.getActiveViewOfType(eU.MarkdownView);return t?.editor?t:null}function qv(r){return Un(r)?.editor.getSelection()??""}var eU,sl=x(()=>{eU=require("obsidian")});function tU(r,t){return!r.isComposing&&r.key.toLowerCase()===t.toLowerCase()&&r.shiftKey&&(r.ctrlKey||r.metaKey)}function rU(r){return tU(r,"Enter")}function iU(r){return tU(r,zv)}function oU(r){return r?`Look at the note without losing this draft. ${nU}`:"Look at the note without losing this draft."}function sU(){return`${nU} returns to the prompt`}var zv,nU,Hv=x(()=>{zv="E",nU="Ctrl/Cmd+Shift+E"});function aU(r,t,e,n){let i=Math.max(0,Math.min(t,r.length)),o=Math.max(i,Math.min(e,r.length));return{text:r.slice(0,i)+n+r.slice(o),cursor:i+n.length}}function lU(r,t=42){let e=r.slice(0,t*4),n=e.replace(/\s+/g," ").trim();return n.length<=t?e.length{});function xP(r){CP.add(r)}function EP(r){CP.delete(r)}function cU(){return CP.size>0}var CP,TP=x(()=>{CP=new Set});function o7(r,t){let e=new Set([t]);return r.workspace.iterateAllLeaves?.(i=>{let o=i.view?.containerEl?.ownerDocument;o&&e.add(o)}),[...e]}var kn,ls,al,Ox=x(()=>{kn=require("obsidian");sl();Ko();Hv();wP();TP();ls=class ls{constructor(t,e){this.app=t;this.handle=e;this.chipEl=null;this.insertButton=null;this.compactChrome=!1;this.returnScope=null;this.selectionDocuments=[];this.selectionListener=null;this.chipKeyListener=null;this.hasSelection=null;this.selectionPreview=""}static isPeeking(){return ls.active!==null}static getActive(){return ls.active}static activate(t,e){let n=ls.active;if(n){let o=n.handle.title;n.cancel(),new kn.Notice(`QuickAdd: cancelled the peeked prompt "${o}".`)}let i=new ls(t,e);return ls.active=i,i.mount(),i}static discard(){ls.active?.destroy()}discard(){this.destroy()}resume(){if(!this.canReturnNow())return;let t=this.handle;this.destroy(),t.resume()}cancel(){let t=this.handle;this.destroy(),t.cancel()}insertSelectionAndResume(){if(!this.canReturnNow())return;let t=qv(this.app);if(!t){this.resume();return}let e=this.handle;this.destroy(),e.insertSelectionAndResume(t)}canReturnNow(){return cU()?(new kn.Notice("QuickAdd: close the open prompt before returning to the peeked one."),!1):!0}mount(){let n=(this.app.workspace.containerEl?.ownerDocument??document).body;this.compactChrome=kn.Platform.isPhone;let i=n.createDiv({cls:"qa-peek-chip"});i.setAttribute("role","status"),i.setAttribute("aria-live","polite"),this.compactChrome&&i.addClass("qa-peek-chip--compact","qa-peek-chip--top");let o=i.createDiv({cls:"qa-peek-chip-header"}),s=o.createSpan({cls:"qa-peek-chip-icon"});s.setAttribute("aria-hidden","true"),(0,kn.setIcon)(s,"eye");let a=o.createDiv({cls:"qa-peek-chip-titles"});a.createDiv({cls:"qa-peek-chip-title",text:this.compactChrome?this.handle.title:"QuickAdd is waiting"}),this.compactChrome||(a.createDiv({cls:"qa-peek-chip-subtitle",text:this.handle.title}),i.createEl("p",{cls:"qa-peek-chip-hint",text:"Look at the note, copy or select text, then come back. Your draft is still there."}));let l=i.createDiv({cls:"qa-peek-chip-actions"});this.insertButton=new kn.ButtonComponent(l).setButtonText(this.compactChrome?"Insert":"Insert selection").setCta().setTooltip("Drop the selected text into your draft and return").onClick(()=>this.insertSelectionAndResume()),this.insertButton.buttonEl.setAttribute("aria-label","Insert the selected text and return to QuickAdd"),new kn.ButtonComponent(l).setButtonText("Return").setTooltip("Go back to the prompt without inserting").onClick(()=>this.resume());let c=new kn.ButtonComponent(l).setTooltip("Discard this run").onClick(()=>this.cancel());if(c.buttonEl.addClass("qa-peek-chip-cancel"),c.buttonEl.setAttribute("aria-label","Cancel this run"),this.compactChrome){let d=At(c.buttonEl,"span");d.className="qa-peek-chip-cancel-icon",d.setAttribute("aria-hidden","true"),(0,kn.setIcon)(d,"x"),c.buttonEl.replaceChildren(d)}else c.setButtonText("Cancel");kn.Platform.isMobile||i.createEl("p",{cls:"qa-peek-chip-keys",text:sU()}),this.chipEl=i,this.refreshInsertButton(),this.listenForSelection(),this.listenForChipEscape(),this.pushReturnShortcut()}listenForSelection(){let t=(0,kn.debounce)(()=>this.refreshInsertButton(),100,!0);this.selectionListener=t,this.selectionDocuments=o7(this.app,this.chipEl?.ownerDocument??document);for(let e of this.selectionDocuments)e.addEventListener("selectionchange",t)}refreshInsertButton(){let t=this.insertButton;if(!t)return;let e=qv(this.app),n=e.length>0,i=n&&!this.compactChrome?lU(e):"";n===this.hasSelection&&i===this.selectionPreview||(this.hasSelection=n,this.selectionPreview=i,t.setDisabled(!n),t.buttonEl.classList.toggle("qa-peek-insert-ready",n),this.compactChrome||t.setButtonText(n?`Insert \u201C${i}\u201D`:"Insert selection"))}listenForChipEscape(){let t=this.chipEl;t&&(this.chipKeyListener=e=>{if(e.isComposing||e.key!=="Escape")return;let n=e.target;!(n instanceof Node)||!t.contains(n)||(e.preventDefault(),this.resume())},t.addEventListener("keydown",this.chipKeyListener))}pushReturnShortcut(){this.returnScope=new kn.Scope(this.app.scope),this.returnScope.register(["Mod","Shift"],zv,()=>(this.resume(),!1)),this.app.keymap.pushScope(this.returnScope)}destroy(){if(ls.active===this&&(ls.active=null),this.returnScope&&(this.app.keymap.popScope(this.returnScope),this.returnScope=null),this.chipKeyListener&&this.chipEl&&(this.chipEl.removeEventListener("keydown",this.chipKeyListener),this.chipKeyListener=null),this.selectionListener){for(let t of this.selectionDocuments)t.removeEventListener("selectionchange",this.selectionListener);this.selectionListener.cancel?.(),this.selectionListener=null}this.selectionDocuments=[],this.chipEl?.remove(),this.chipEl=null,this.insertButton=null}};ls.active=null;al=ls});function s7(r){Un(r)?.editor?.focus?.()}var dU,Lm,_P=x(()=>{sl();Ox();wP();TP();dU="qa-prompt-peek-hidden",Lm=class{constructor(t){this.host=t;this.peeking=!1;this.session=null}peek(){if(this.peeking)return;let t=this.host.getField();t&&this.host.setValue(t.value),this.host.persistDraft(),this.peeking=!0,this.hideModal(),this.session=al.activate(this.host.app,{title:this.host.title,resume:()=>this.resume(),cancel:()=>this.cancel(),insertSelectionAndResume:e=>this.insertSelectionAndResume(e)})}onHostOpened(){xP(this.host)}onHostClosed(){EP(this.host),this.peeking&&(this.peeking=!1,this.session?.discard(),this.session=null)}hideModal(){EP(this.host),this.host.containerEl.addClass(dU),this.host.app.keymap.popScope(this.host.scope),s7(this.host.app)}showModal(){this.host.app.keymap.pushScope(this.host.scope),this.host.containerEl.removeClass(dU),xP(this.host),this.host.getField()?.focus()}resume(){this.peeking&&(this.peeking=!1,this.session=null,this.showModal())}insertSelectionAndResume(t){if(!this.peeking)return;let e=this.host.getField();if(e){let n=e.selectionStart??e.value.length,i=e.selectionEnd??n,o=aU(e.value,n,i,t);e.value=o.text,e.setSelectionRange(o.cursor,o.cursor),this.host.setValue(o.text)}else this.host.setValue(this.host.getValue()+t);this.host.markDraftChanged(),this.host.persistDraft(),this.resume()}cancel(){this.peeking&&(this.peeking=!1,this.session=null,this.host.app.keymap.pushScope(this.host.scope),this.host.close())}}});function uU(r){return Wv.Platform.isPhone||(r?.innerWidth??Number.POSITIVE_INFINITY)<=540}function Dx(r){let t=uU(r.ownerDocument.defaultView);return r.classList.toggle("qa-prompt-compact",t),t}function Lx(r){let t=uU(r.buttonEl.ownerDocument.defaultView);r.setButtonText(t?l7:a7),r.setTooltip(oU(!Wv.Platform.isMobile)),r.buttonEl.setAttribute("aria-label","Peek at the note. Your draft stays."),r.buttonEl.classList.add("qa-peek-button");let e=At(r.buttonEl,"span");return e.className="qa-peek-button-icon",e.setAttribute("aria-hidden","true"),(0,Wv.setIcon)(e,"eye"),r.buttonEl.prepend(e),r}var Wv,a7,l7,kP=x(()=>{Wv=require("obsidian");Ko();Hv();a7="Peek at note",l7="Peek"});var Nx,Nm,SP=x(()=>{Nx=require("obsidian");gP();vP();UB();yP();zB();Rx();rr();_P();Hv();kP();Nm=class extends Nx.Modal{constructor(e,n,i,o,s,a){super(e);this.header=n;this.options=a;this.didSubmit=!1;this.didClose=!1;this.submitClickCallback=e=>this.submit();this.cancelClickCallback=e=>this.cancel();this.skipClickCallback=e=>this.skip();this.submitEnterCallback=e=>{if(this.supportsPeek()&&iU(e)){e.preventDefault(),this.peek.peek();return}if(this.isOptionalPrompt&&rU(e)){e.preventDefault(),this.skip();return}this.shouldSubmit(e)&&(e.preventDefault(),this.submit())};this.placeholder=i??"",this.description=s?.trim()||void 0,this.draftHandler=new Tx({kind:this.getPromptKind(),header:this.header,placeholder:this.placeholder,linkSourcePath:a?.linkSourcePath,scopeId:a?.draftScopeId}),this.input=this.draftHandler.hydrate(o??""),this.waitForClose=new Promise((l,c)=>{this.resolvePromise=l,this.rejectPromise=c}),this.peek=new Lm({app:e,title:this.header,containerEl:this.containerEl,scope:this.scope,getField:()=>this.inputComponent?.inputEl,getValue:()=>this.input,setValue:l=>{this.input=l},markDraftChanged:()=>this.draftHandler.markChanged(),persistDraft:()=>this.persistDraft(),close:()=>this.close()}),this.display(),this.open(),this.attachSuggesters()}display(){this.containerEl.addClass("quickAddModal",this.getPromptKind()==="single"?"qaInputPrompt":"qaWideInputPrompt"),Dx(this.containerEl),this.contentEl.empty(),this.titleEl.textContent=this.header,qB(this.contentEl,this.options?.contextLine,this.options?.contextLineFull),this.description&&this.contentEl.createDiv({text:this.description,cls:"setting-item-description"}).setCssStyles({marginBottom:"0.75rem"}),this.isOptionalPrompt&&this.contentEl.createDiv({text:"Optional \u2014 leave empty, press Skip, or ctrl/cmd+shift+\u21B5.",cls:"setting-item-description"}).setCssStyles({marginBottom:"0.75rem"});let e=this.contentEl.createDiv();this.inputComponent=this.createInputField(e,this.placeholder,this.input),this.createButtonBar(e)}get isOptionalPrompt(){return this.options?.optional===!0}supportsPeek(){return this.options?.allowPeek===!0}configureInput(e,n,i){return e.setPlaceholder(n??"").setValue(i??"").onChange(o=>this.onInputChanged(o)),e.inputEl.addEventListener("keydown",this.submitEnterCallback),this.options?.imagePaste&&(this.imagePasteHandle=Mx(this.app,e.inputEl,this.options.imagePaste)),e}disposeInput(){}createButton(e,n,i){let o=new Nx.ButtonComponent(e);return o.setButtonText(n).onClick(i),o}createButtonBar(e){let n=e.createDiv({cls:"qa-prompt-actions"}),i=n.createDiv({cls:"qa-prompt-actions-primary"});if(this.createButton(i,"Ok",this.submitClickCallback).setCta().buttonEl.setCssStyles({marginRight:"0"}),this.createButton(i,"Cancel",this.cancelClickCallback),this.isOptionalPrompt){let o=this.createButton(i,"Skip",this.skipClickCallback);o.setTooltip("Leave this field empty"),o.buttonEl.setAttribute("aria-label","Skip and leave empty")}if(this.supportsPeek()){let o=n.createDiv({cls:"qa-prompt-actions-secondary"});Lx(this.createButton(o,"Peek at note",()=>this.peek.peek()))}}transformInputOnSubmit(e){return e}submit(){if(this.didSubmit||this.didClose)return;if(this.imagePasteHandle?.isBusy()){this.imagePasteHandle.whenIdle().then(()=>this.submit());return}let e=this.inputComponent?.inputEl?.value??this.input;this.input=this.transformInputOnSubmit(e),this.didSubmit=!0,this.close()}skip(){this.getPromptKind()==="multi"&&this.didSubmit||(this.input="",this.didSubmit=!0,this.close())}cancel(){this.close()}resolveInput(){this.didSubmit?this.resolvePromise(this.input):this.rejectPromise(on())}onInputChanged(e){this.draftHandler.markChanged(),this.input=e}syncInputFromEl(){this.inputComponent?.inputEl&&(this.input=this.inputComponent.inputEl.value)}persistDraft(){this.draftHandler.persist(this.input,this.didSubmit)}attachSuggesters(){this.fileSuggester=new Rm(this.app,this.inputComponent.inputEl,{sourcePath:this.options?.linkSourcePath}),this.tagSuggester=new Om(this.app,this.inputComponent.inputEl)}removeInputListener(){this.inputComponent.inputEl.removeEventListener("keydown",this.submitEnterCallback),this.disposeInput(),this.imagePasteHandle?.detach()}onOpen(){super.onOpen(),this.peek.onHostOpened(),_x(this.inputComponent.inputEl,this.options)}onClose(){this.didClose=!0,this.didSubmit||this.syncInputFromEl(),this.persistDraft(),this.peek.onHostClosed(),this.resolveInput(),this.removeInputListener(),this.fileSuggester?.destroy(),this.tagSuggester?.destroy(),super.onClose()}}});var pU,ir,Gs=x(()=>{pU=require("obsidian");SP();ir=class r extends Nm{static Prompt(t,e,n,i,o,s){return new r(t,e,n,i,o,s).waitForClose}getPromptKind(){return"single"}createInputField(t,e,n){let i=new pU.TextComponent(t);return i.inputEl.setCssStyles({width:"100%"}),this.configureInput(i,e,n)}shouldSubmit(t){return!t.isComposing&&t.key==="Enter"}}});function Ti(r){if(r.length===0)return 0;let t=new TextEncoder().encode(r).length,e=!1;for(let i=0;i127){e=!0;break}return Math.max(1,Math.ceil(t/(e?3:4)))}function mU(r){return!Number.isFinite(r)||r<=0?1:Math.max(1,Math.floor(r*.45))}var Gv=x(()=>{});function vU(){return U.getState().ai.providers.flatMap(t=>t.models).map(t=>t.name)}function IP(){return U.getState().ai.providers}function fU(r,t){for(let e of r){let n=e.models.find(i=>i.name===t);if(n)return{provider:e,model:n}}}function AP(r){let t=IP();return t.filter(e=>e.models.some(n=>n.name===r)).map(e=>{let n=`${e.id??e.name}/${r}`;return t.some(o=>o.models.some(s=>s.name===n))?`{ name: "${r}", provider: "${e.id??e.name}" } (the string "${n}" is itself a model id on another provider)`:n})}function gU(r,t){hU.has(r)||(hU.add(r),S.logWarning(t))}function lu(r,t){let e=IP(),n=t?.silent===!0;if(r==null)return;if(typeof r!="string"){let s=e.find(c=>c.id===r.providerId),a=s?.models.find(c=>c.name===r.name);if(s&&a)return{provider:s,model:a};let l=fU(e,r.name);return l?(n||gU(`pin:${r.providerId}/${r.name}\u2192${l.provider.id??l.provider.name}`,`Model "${r.name}" is pinned to provider "${r.providerId}", which no longer serves it. Using "${l.provider.name}" instead \u2014 re-select the model in the command's settings to pin it again.`),l):void 0}let i=fU(e,r);if(i){let s=AP(r);return s.length>1&&!n&&gU(`ambiguous:${r}\u2192${i.provider.id??i.provider.name}`,`Model "${r}" is served by ${s.length} providers; using "${i.provider.name}". Qualify it to choose explicitly: ${s.join(", ")}.`),i}let o=r.indexOf("/");if(!(o<=0||o===r.length-1))return yU(r.slice(0,o),r.slice(o+1))}function yU(r,t){let e=IP(),n=r.trim().toLowerCase(),i=e.find(s=>s.id?.toLowerCase()===n)??e.find(s=>s.name.trim().toLowerCase()===n),o=i?.models.find(s=>s.name===t);if(i&&o)return{provider:i,model:o}}function jv(r){let t=typeof r=="string"?r:r?.name;if(!t)throw new Error('Invalid model parameter. Expected a string (e.g., "gpt-4o" or "openai/gpt-4o") or an object with a name property (e.g., {name: "gpt-4o", provider: "openai"})');let e=typeof r!="string"&&r.provider?yU(r.provider,t):lu(t);if(!e){let n=t.includes("/")?t.slice(t.indexOf("/")+1):t,i=[...AP(t),...n!==t?AP(n):[]],o=i.length?` Did you mean ${i.join(" or ")}?`:" Add it in Settings \u2192 QuickAdd \u2192 AI Assistant \u2192 your provider, or turn on Auto-sync models for that provider.";throw new Error(`Model '${typeof r=="string"?r:`${r.provider??""}/${t}`}' not found in configured providers.${o}`)}return e}var hU,Vm=x(()=>{ye();je();hU=new Set});var qx=x(()=>{});var Ki=x(()=>{});var hn,ll=x(()=>{Qo();hn=class{constructor(t,e){this.name=t,this.type=e,this.id=Vt()}}});var ht,cs=x(()=>{er();ll();sl();ye();ht=class extends hn{constructor(t){super(t,"EditorCommand"),this.editorCommandType=t}static getSelectedText(t){return this.getActiveMarkdownView(t).editor.getSelection()}static getActiveMarkdownView(t){let e=Un(t);if(!e)throw S.logError("no active markdown editor."),new Error("no active markdown editor.");return e}}});var Um,MP=x(()=>{Ki();cs();Um=class extends ht{constructor(){super("Copy")}static async run(t){let e=ht.getSelectedText(t);await navigator.clipboard.writeText(e)}}});var qm,RP=x(()=>{Ki();cs();ye();qm=class extends ht{constructor(){super("Cut")}static async run(t){let e=ht.getSelectedText(t),n=ht.getActiveMarkdownView(t);if(!e){S.logError("nothing selected.");return}await navigator.clipboard.writeText(e),n.editor.replaceSelection("")}}});var zm,OP=x(()=>{Ki();ye();cs();zm=class extends ht{constructor(){super("Paste")}static async run(t){let e=await navigator.clipboard.readText(),n=ht.getActiveMarkdownView(t);if(!n){S.logError("no active markdown view.");return}n.editor.replaceSelection(e)}}});var EU,Hm,DP=x(()=>{EU=require("obsidian");ye();cs();Ki();Hm=class extends ht{constructor(){super("Paste with format")}static async run(t){let e=ht.getActiveMarkdownView(t);if(!e){S.logError("no active markdown view.");return}let n="";try{if("read"in navigator.clipboard&&navigator.clipboard.read){let i=await navigator.clipboard.read(),o=!1;for(let s of i)if(s.types.includes("text/html")){let l=await(await s.getType("text/html")).text();n=(0,EU.htmlToMarkdown)(l),o=!0;break}o||(n=await navigator.clipboard.readText())}else n=await navigator.clipboard.readText();e.editor.replaceSelection(n)}catch(i){S.logWarning(`Formatted paste failed. Falling back to plain text: ${i}`);try{let o=await navigator.clipboard.readText();e.editor.replaceSelection(o)}catch(o){S.logError(`Failed to read clipboard text: ${o}`)}}}}});var Wm,LP=x(()=>{Ki();cs();Wm=class extends ht{constructor(){super("Select active line")}static run(t){let e=ht.getActiveMarkdownView(t),{line:n}=e.editor.getCursor(),o=e.editor.getLine(n).length;e.editor.setSelection({line:n,ch:0},{line:n,ch:o})}}});var Gm,NP=x(()=>{cs();Ki();Le();ye();Gm=class extends ht{constructor(){super("Select link on active line")}static run(t){let e=ht.getActiveMarkdownView(t),{line:n}=e.editor.getCursor(),i=e.editor.getLine(n),o=zD.exec(i);if(!o){S.logError(`no internal link found on line ${n}.`);return}let s=o.index,a=o[0].length+s;e.editor.setSelection({line:n,ch:s},{line:n,ch:a})}}});var jm,VP=x(()=>{cs();Ki();jm=class extends ht{constructor(){super("Move cursor to file start")}static run(t){ht.getActiveMarkdownView(t).editor.setCursor({line:0,ch:0})}}});var Ym,BP=x(()=>{cs();Ki();Ym=class extends ht{constructor(){super("Move cursor to file end")}static run(t){let e=ht.getActiveMarkdownView(t),n=e.editor.lastLine(),i=e.editor.getLine(n).length;e.editor.setCursor({line:n,ch:i})}}});var Km,UP=x(()=>{cs();Ki();Km=class extends ht{constructor(){super("Move cursor to line start")}static run(t){let e=ht.getActiveMarkdownView(t),{line:n}=e.editor.getCursor();e.editor.setCursor({line:n,ch:0})}}});var Qm,qP=x(()=>{cs();Ki();Qm=class extends ht{constructor(){super("Move cursor to line end")}static run(t){let e=ht.getActiveMarkdownView(t),{line:n}=e.editor.getCursor(),i=e.editor.getLine(n).length;e.editor.setCursor({line:n,ch:i})}}});var Qs,Xm,WP=x(()=>{Qs=require("obsidian");ye();an();rr();hp();Xm=class extends Qs.FuzzySuggestModal{constructor(e,n,i,o,s){super(e);this.indexByItem=new Map;this.aliasByMatch=new WeakMap;this.warnedOnEmptyDisplay=!1;this.warnRenderItemFailure=pp("Custom renderItem threw an error; falling back to default rendering");this.modalEl.addClass("qa-suggester"),this.renderItem=o,this.items=i,this.displayItems=n.map(a=>sn(a)),this.promise=new Promise((a,l)=>{this.resolvePromise=a,this.rejectPromise=l}),s?.skippable&&r0(this,()=>this.skip()),this.inputEl.addEventListener("keydown",a=>{if(a.code!=="Tab"||!("chooser"in this))return;let{values:l,selectedItem:c}=this.chooser,{value:d}=this.inputEl;this.inputEl.value=l[c]?.item??d}),this.displayItems.length!==this.items.length&&(this.displayItems=this.items.map((a,l)=>{let c=this.displayItems[l];return sn(c??a)})),this.items.forEach((a,l)=>{this.indexByItem.has(a)||this.indexByItem.set(a,l)}),this.aliases=s?.aliases}indexOfItem(e){return this.indexByItem.get(e)??-1}getItemText(e){let n=this.indexOfItem(e),i=n>=0?this.displayItems[n]:void 0;return sn(i??e)}getItems(){return this.items}getSuggestions(e){let n=zl(e);if(!this.aliases||!n.trim())return super.getSuggestions(n);let i=(0,Qs.prepareFuzzySearch)(n.trim()),o=[];return this.items.forEach((s,a)=>{let l=BS(i,this.getItemText(s),this.aliases?.[a]);if(!l)return;let c={item:s,match:l.result};l.alias!==void 0&&this.aliasByMatch.set(c,l.alias),o.push(c)}),(0,Qs.sortSearchResults)(o),o}selectSuggestion(e,n){this.resolved=!0,super.selectSuggestion(e,n)}renderSuggestion(e,n){let i=this.aliasByMatch.get(e);if(i!==void 0){this.renderAliasSuggestion(e,i,n);return}if(!this.renderItem){super.renderSuggestion(e,n);return}try{n.empty(),this.renderItem(e.item,n,e.match.matches)}catch(o){this.warnRenderItemFailure(o),n.empty(),super.renderSuggestion(e,n)}}renderAliasSuggestion(e,n,i){i.empty(),i.addClass("mod-complex");let o=i.createDiv({cls:"suggestion-content"});(0,Qs.renderMatches)(o.createDiv({cls:"suggestion-title"}),n,e.match.matches);let s=this.indexOfItem(e.item);o.createDiv({cls:"suggestion-note",text:this.displayItems[s]??""});let a=i.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"});a.setAttribute("aria-label","Alias"),(0,Qs.setIcon)(a,"forward")}renderDefaultSuggestion(e,n){super.renderSuggestion(e,n)}onChooseItem(e,n){this.resolved=!0,this.resolvePromise(e)}skip(){this.resolved=!0,this.resolvePromise(""),this.close()}onClose(){super.onClose(),this.resolved||this.rejectPromise(on())}warnIfEmptyDisplay(){if(this.warnedOnEmptyDisplay)return;this.displayItems.some(n=>n.length===0)&&(this.warnedOnEmptyDisplay=!0,S.logWarning("QuickAdd suggester received empty display values. Check your displayItems mapping."))}}});var AU,vr,cl=x(()=>{AU=require("obsidian");an();WP();vr=class r extends Xm{constructor(e,n,i,o={}){super(e,n,i,o.renderItem,o);this.warnCustomValueFailure=pp("Custom create-row rendering threw an error; falling back to default rendering");this.allowCustomValue=!0;this.searchItems=o.searchItems?.map(s=>sn(s))??[],this.allowCustomValue=o.allowCustomValue??!0,this.customValueLabel=o.customValueLabel,this.valueExists=o.valueExists,o.placeholder&&this.setPlaceholder(o.placeholder),typeof o.limit=="number"&&(this.limit=o.limit),o.emptyStateText&&(this.emptyStateText=o.emptyStateText),this.searchItems.length!==this.items.length&&(this.searchItems=this.items.map((s,a)=>sn(this.searchItems[a]??this.displayItems[a]??s))),this.warnIfEmptyDisplay(),this.open()}static Suggest(e,n,i,o={}){return new r(e,n,i,o).promise}getItemText(e){if(e===this.inputEl.value)return e;let n=this.indexOfItem(e),i=n>=0?this.searchItems[n]:void 0;return sn(i??e)}getSuggestions(e){let n=super.getSuggestions(e);if(!this.allowCustomValue)return n;let i=zl(this.inputEl.value);if(!i||this.items.includes(i)||this.valueExists?.(i)||n.some(a=>a.item===i))return n;let s={item:i,match:{score:Number.NEGATIVE_INFINITY,matches:[]}};return this.customValueLabel?n.unshift(s):n.push(s),n}renderSuggestion(e,n){if(this.customValueLabel&&e.match.score===Number.NEGATIVE_INFINITY){this.renderCustomValue(e.item,n);return}super.renderSuggestion(e,n)}renderCustomValue(e,n){try{n.empty(),n.addClass("mod-complex"),n.createDiv({cls:"suggestion-content"}).createDiv({cls:"suggestion-title",text:this.customValueLabel?.(e)??e});let o=n.createDiv({cls:"suggestion-aux"});(0,AU.setIcon)(o.createSpan({cls:"suggestion-flair"}),"file-plus")}catch(i){this.warnCustomValueFailure(i),n.empty(),this.renderDefaultSuggestion({item:e,match:{score:0,matches:[]}},n)}}}});var It,Qi=x(()=>{WP();It=class r extends Xm{static Suggest(t,e,n,i,o,s){let a=new r(t,e,n,o,s);return i&&a.setPlaceholder(i),a.promise}constructor(t,e,n,i,o){super(t,e,n,i,o),this.warnIfEmptyDisplay(),this.open()}}});function qn(r){return r.type==="Template"}function pl(r){return r.type==="Capture"}function Xi(r){return r.type==="Macro"}function uu(r){return r.type==="Multi"}var ml=x(()=>{});function sq(r){let t=[],e=new RegExp(kJ.source,"gi"),n=0;for(;n{Dr();oq="{{TEMPLATE:",kJ=/{{TEMPLATE:/gi,SJ=/\.(?:md|canvas|base)$/i});function Aq(r){try{let t=window.require;return t?t(r):null}catch{return null}}async function cf(r,t){let e=r.vault.adapter;if(typeof h$.FileSystemAdapter!="function"||!(e instanceof h$.FileSystemAdapter))return;let n=Aq("fs"),i=Aq("path");if(!n?.promises||!i)return;let o=await n.promises.realpath(e.getBasePath()),a=e.getFullPath(t);for(;!QJ(n,a);){let p=i.dirname(a);if(p===a)break;a=p}let l;try{l=await n.promises.realpath(a)}catch{throw new ty(`Refusing to write to "${t}": it resolves through an unresolvable (dangling) symlink.`)}let c=i.relative(o,l);if(c===".."||c.startsWith(`..${i.sep}`)||i.isAbsolute(c))throw new ty(`Refusing to write to "${t}": it resolves (via a symlink) outside the vault.`);if(c.split(i.sep).some(p=>p.startsWith(".")))throw new ty(`Refusing to write to "${t}": it resolves (via a symlink) into a config/hidden directory.`)}function QJ(r,t){try{return r.lstatSync(t),!0}catch{return!1}}var h$,ty,g$=x(()=>{h$=require("obsidian"),ty=class extends Error{constructor(t){super(t),this.name="VaultWriteEscapeError"}}});function Q$(r,t=new Set){if(r==null||t.has(r))return[];if(t.add(r),typeof r=="string")return[r];if(typeof r!="object")return[String(r)];let e=r,n=[];for(let i of Ree){let o=e[i];o!==void 0&&n.push(...Q$(o,t))}return n}function QE(r){return Number(r.replace(/,/g,""))}function Oee(r){let t=r.match(/context (?:length|window)(?:\s+is)?(?:\s+of)?\s*(\d[\d,]*)/i);return t?QE(t[1]):null}function Dee(r){let t=r.match(/(\d[\d,]*)\s*(?:tokens?\s+)?in the completion\b/i);if(t){let n=QE(t[1]),i=Oee(r);return i===null?"input":n>=i?"output":"input"}let e=r.match(/input length and max_tokens exceed context limit:?\s*(\d[\d,]*)\s*\+\s*(\d[\d,]*)(?:\s*>\s*(\d[\d,]*))?/i);if(e){let n=QE(e[2]),i=e[3]?QE(e[3]):null;return i===null?"input":n>=i?"output":"input"}return null}function cy(r){let t=Q$(r).join(" "),e=Dee(t);return e==="output"?"output_budget":e==="input"?"input_context":Mee.some(n=>n.test(t))?"output_budget":Fee.some(n=>n.test(t))?"input_context":"other"}function dz(r){return cy(r)==="input_context"}function uz(r){return Lee.test(Q$(r).join(" "))}function XE(r,t){let e="",n="",i;try{i=t.json}catch{i=void 0}if(i&&typeof i=="object"){let s=i,a=s.error??s;e=String(a.message??s.message??""),n=String(a.code??a.type??a.status??"")}e||(e=typeof t.text=="string"&&t.text.length>0?t.text:`HTTP ${t.status}`);let o=new Error(`${r} request failed (HTTP ${t.status})${n?` [${n}]`:""}: ${e}`);return o.status=t.status,n&&(o.providerCode=n),o}var Fee,Mee,Ree,Lee,ff=x(()=>{Fee=[/context[_ -]?length[_ -]?exceeded/i,/context[_ -]?window[_ -]?exceeded/i,/maximum context length/i,/context window/i,/too many input tokens/i,/input(?: is)? too long/i,/prompt(?: is)? too long/i,/input token count/i,/reduce the length of (?:the |your )?(?:messages|prompt|input)/i,/exceed(?:s|ed|ing)? (?:the )?(?:maximum |allowed )?(?:input |prompt )?(?:token|context)/i],Mee=[/max_tokens/i,/max_completion_tokens/i,/max(?:imum)? output tokens/i,/output token limit/i],Ree=["message","code","type","status","statusText","providerCode","error","response","json","cause"];Lee=/tool_choice:\s*type\s*"tool"\s*and\s*"any"\s*are not supported/i});function Yee(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Kee(r){let t=r.name?.trim()||"provider";return`${jee}-${Yee(t)}`}async function hz(r,t){if(!r?.secretStorage?.getSecret)return null;try{return await Promise.resolve(r.secretStorage.getSecret(t))}catch(e){return S.logWarning(`Failed to read SecretStorage entry "${t}": ${e.message??e}`),null}}async function Po(r,t){let e=t.apiKeyRef?.trim();if(e){let n=await hz(r,e);if(n)return n}return t.apiKey??""}async function gz(r,t,e){let n=e?.trim();if(!n||!r?.secretStorage?.getSecret||!r.secretStorage?.setSecret)return null;let i=Kee(t),o=i,s=1;for(;;){let a=await hz(r,o);if(!a)break;if(a===n)return o;s+=1,o=`${i}-${s}`}try{return await Promise.resolve(r.secretStorage.setSecret(o,n)),o}catch(a){return S.logWarning(`Failed to write SecretStorage entry "${o}": ${a.message??a}`),null}}var jee,Ic=x(()=>{ye();jee="quickadd-ai"});async function my(r,t,e){let n=Date.now();if(!(r instanceof Promise))throw new TypeError("Promise must be an instance of Promise.");let i=!1,o=()=>{i=!0};for(r.then(o,o);!i;)t.setMessage(e[0],`${e[1]} (${((Date.now()-n)/1e3).toFixed(2)}s)`),await sleep(100);return t.setMessage("finished",`Took ${((Date.now()-n)/1e3).toFixed(2)}s.`),await r}function fy(r,t){return{[r]:t,[`${r}-quoted`]:("> "+t).replace(/\n/g,` > `)}}var nF=x(()=>{});var de,Sn=x(()=>{ri();de=class extends at{}});function gf(r){return iF.filter(t=>typeof r[t]=="number")}function pT(r){let t={...r};for(let e of iF)delete t[e];return t}function oF(r,t){return r.supportsTemperature===!1&&gf(t).length>0?pT(t):t}function Mz(r,t){return t.length===0?!1:ute.some(e=>e.test(r))}function sF(r){let t=r.map(e=>dte[e]);return t.length<=1?t.join(""):t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function hy(r,t){let e={};return typeof t.temperature=="number"&&(e.temperature=t.temperature),typeof t.top_p=="number"&&(e[r==="gemini"?"topP":"top_p"]=t.top_p),e}var iF,dte,uT,ute,mT=x(()=>{iF=["temperature","top_p","frequency_penalty","presence_penalty"],dte={temperature:"Temperature",top_p:"Top P",frequency_penalty:"Frequency penalty",presence_penalty:"Presence penalty"};uT=iF.join("|"),ute=[new RegExp(`unsupported (?:parameter|value)[^.]{0,40}['\`"]?(?:${uT})['\`"]?`,"i"),new RegExp(`['\`"]?(?:${uT})['\`"]?[^.]{0,40}(?:is deprecated|is not supported|not supported|does not support)`,"i"),new RegExp(`unrecognized request argument[^.]{0,40}(?:${uT})`,"i"),new RegExp(`(?:${uT})[^.]{0,40}extra inputs are not permitted`,"i")]});function aF(r){return{...r,modelOptions:{...r.modelOptions},usage:r.usage?{...r.usage}:void 0}}function lF(r){let t=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,e=Date.now();return Fo.push({...r,modelOptions:{...r.modelOptions??{}},id:t,createdAt:e,status:"pending"}),Oz(),t}function gy(r,t){let e=Fo.find(n=>n.id===r);e&&(e.status=t.status,e.durationMs=t.durationMs,e.usage=t.usage,e.errorMessage=t.errorMessage,Oz())}function Rz(r=10){Number.isFinite(r)||(r=10);let t=Math.floor(r);return t<=0?[]:Fo.slice(-t).map(aF).reverse()}function Oz(){if(Fo.length<=25)return;let r=Fo.length-25;for(;r>0;){let t=Fo.findIndex(e=>e.status!=="pending");if(t===-1)break;Fo.splice(t,1),r-=1}}function Dz(r){let t=Fo.find(e=>e.id===r);return t?aF(t):null}function Lz(){let r=Fo[Fo.length-1];return r?aF(r):null}function Nz(){Fo.splice(0,Fo.length)}var Fo,cF=x(()=>{Fo=[]});function fT(r){let t=r.workspace.activeEditor?.editor?.getCursor(),e=r.workspace.activeEditor?.editor?.listSelections();return()=>{t&&r.workspace.activeEditor?.editor?.setCursor(t),e&&r.workspace.activeEditor?.editor?.setSelections(e)}}var dF=x(()=>{});function mu(r){let t=Array.isArray(r)?r:{...r},e=t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")||t.properties!==void 0;if(t.properties){let n={};for(let[i,o]of Object.entries(t.properties))n[i]=mu(o);t.properties=n}return t.items&&!Array.isArray(t.items)&&(t.items=mu(t.items)),e&&(t.additionalProperties=!1,t.required=t.properties?Object.keys(t.properties):[]),t}function pte(r){let t=[];for(let e of r)if(e.role==="system")t.push({role:"system",content:e.content});else if(e.role==="user")t.push({role:"user",content:e.content});else if(e.role==="assistant"){let n={role:"assistant",content:e.content??""};e.toolCalls&&e.toolCalls.length>0&&(n.tool_calls=e.toolCalls.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:i.rawArgs??JSON.stringify(i.args??{})}}))),t.push(n)}else for(let n of e.results)t.push({role:"tool",tool_call_id:n.toolCallId,content:n.isError?`ERROR: ${n.content}`:n.content});return t}function mte(r){return r.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.strict?mu(t.parameters):t.parameters,...t.strict?{strict:!0}:{}}}))}function fte(r){return typeof r=="string"?r:{type:"function",function:{name:r.name}}}function gte(r,t){let e={model:r,...t.modelParams??{},messages:pte(t.messages)};return t.tools&&t.tools.length>0&&(e.tools=mte(t.tools),t.toolChoice&&(e.tool_choice=fte(t.toolChoice)),t.disableParallel&&(e.parallel_tool_calls=!1)),t.maxOutputTokens!==void 0&&(hte.test(r)?e.max_completion_tokens=t.maxOutputTokens:e.max_tokens=t.maxOutputTokens),t.responseFormat&&(e.response_format=t.responseFormat.schema?{type:"json_schema",json_schema:{name:t.responseFormat.name??"response",strict:t.responseFormat.strict??!0,schema:t.responseFormat.strict??!0?mu(t.responseFormat.schema):t.responseFormat.schema}}:{type:"json_object"}),e}function vte(r){let t=r.choices?.[0]??{},e=t.message??{},i=(e.tool_calls??[]).map(d=>Bz(d)),o=String(t.finish_reason??""),s=r.usage??{},a=typeof e.content=="string"?e.content:"",l=typeof e.refusal=="string"?e.refusal:"",c=!a&&l.length>0&&i.length===0;return{content:c?l:a,toolCalls:i,normalizedStopReason:i.length>0||o==="tool_calls"?"tool_calls":o==="length"?"length":o==="stop"&&!c?"stop":"other",rawStopReason:c?"refusal":o,usage:{promptTokens:s.prompt_tokens??0,completionTokens:s.completion_tokens??0,totalTokens:s.total_tokens??0}}}function Vz(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function Bz(r){let t=r.function.arguments;if(typeof t=="string")try{let n=Vz(JSON.parse(t||"{}"));if(!n)throw new Error("tool arguments are not a JSON object");return{id:r.id,name:r.function.name,args:n,rawArgs:t}}catch{return{id:r.id,name:r.function.name,args:null,rawArgs:t,parseError:!0}}let e=Vz(t);return e?{id:r.id,name:r.function.name,args:e}:{id:r.id,name:r.function.name,args:null,rawArgs:typeof t=="string"?t:JSON.stringify(t??{}),parseError:!0}}function yte(r){let t=[];for(let e of r)if(e.role==="system"||e.role==="user")t.push({role:e.role,content:e.content});else if(e.role==="assistant"){if(Array.isArray(e.providerRaw)){t.push(...e.providerRaw);continue}e.content&&t.push({role:"assistant",content:e.content});for(let n of e.toolCalls??[])t.push({type:"function_call",call_id:n.id,name:n.name,arguments:n.rawArgs??JSON.stringify(n.args??{})})}else for(let n of e.results)t.push({type:"function_call_output",call_id:n.toolCallId,output:n.isError?`ERROR: ${n.content}`:n.content});return t}function bte(r){return typeof r=="string"?r:{type:"function",name:r.name}}function wte(r,t){let{reasoning_effort:e,max_tokens:n,max_completion_tokens:i,...o}=t.modelParams??{},s={model:r,...o,input:yte(t.messages),store:!1,include:["reasoning.encrypted_content"]};e!==void 0&&(s.reasoning={effort:e});let a=t.maxOutputTokens??i??n;if(a!==void 0&&(s.max_output_tokens=a),t.tools&&t.tools.length>0&&(s.tools=t.tools.map(l=>({type:"function",name:l.name,description:l.description,parameters:l.strict?mu(l.parameters):l.parameters,strict:l.strict===!0})),t.toolChoice&&(s.tool_choice=bte(t.toolChoice)),t.disableParallel&&(s.parallel_tool_calls=!1)),t.responseFormat){let l=t.responseFormat.strict??!0;s.text={format:t.responseFormat.schema?{type:"json_schema",name:t.responseFormat.name??"response",strict:l,schema:l?mu(t.responseFormat.schema):t.responseFormat.schema}:{type:"json_object"}}}return s}function Cte(r){let t=r.output??[],e=t.filter(d=>d.type==="function_call").map(d=>Bz({id:d.call_id??"",function:{name:d.name??"",arguments:d.arguments}})),n=t.filter(d=>d.type==="message").flatMap(d=>d.content??[]),i=n.filter(d=>d.type==="output_text").map(d=>d.text??"").join(""),o=n.filter(d=>d.type==="refusal").map(d=>d.refusal??"").join(""),s=!i&&o.length>0,a=String(r.status??""),l=String(r.incomplete_details?.reason??""),c=r.usage??{};return{content:s?o:i,toolCalls:e,normalizedStopReason:e.length>0?"tool_calls":l==="max_output_tokens"?"length":a==="completed"&&!s?"stop":"other",rawStopReason:s?"refusal":l||a,usage:{promptTokens:c.input_tokens??0,completionTokens:c.output_tokens??0,totalTokens:c.total_tokens??0},providerRaw:t}}function xte(r,t,e){let n=[],i=[];for(let s of t.messages)if(s.role==="system")s.content&&n.push(s.content);else if(s.role==="user")i.push({role:"user",content:s.content});else if(s.role==="assistant"){let a=[];s.content&&a.push({type:"text",text:s.content});for(let l of s.toolCalls??[])a.push({type:"tool_use",id:l.id,name:l.name,input:l.args??{}});i.push({role:"assistant",content:a})}else i.push({role:"user",content:s.results.map(a=>({type:"tool_result",tool_use_id:a.toolCallId,content:a.content,...a.isError?{is_error:!0}:{}}))});let o={model:r,max_tokens:t.maxOutputTokens??e,messages:i};return n.length>0&&(o.system=n.join(` `)),Object.assign(o,hy("anthropic",t.modelParams??{})),t.tools&&t.tools.length>0&&(o.tools=t.tools.map(s=>({name:s.name,description:s.description,input_schema:s.parameters})),t.toolChoice?o.tool_choice=Ete(t.toolChoice,t.disableParallel):t.disableParallel&&(o.tool_choice={type:"auto",disable_parallel_tool_use:!0})),t.responseFormat?.schema&&(o.output_config={format:{type:"json_schema",schema:mu(t.responseFormat.schema)}}),o}function Ete(r,t){let e=t?{disable_parallel_tool_use:!0}:{};return typeof r=="string"?r==="required"?{type:"any",...e}:r==="none"?{type:"none"}:{type:"auto",...e}:{type:"tool",name:r.name,...e}}function Tte(r){let t=r.content??[],e=t.filter(a=>a.type==="tool_use").map(a=>({id:a.id??"",name:a.name??"",args:a.input??{}})),n=String(r.stop_reason??""),i=r.usage??{},o=i.input_tokens??0,s=i.output_tokens??0;return{content:t.filter(a=>a.type==="text").map(a=>a.text??"").join(""),toolCalls:e,normalizedStopReason:n==="tool_use"||e.length>0?"tool_calls":n==="max_tokens"?"length":n==="end_turn"||n==="stop_sequence"?"stop":"other",rawStopReason:n,usage:{promptTokens:o,completionTokens:s,totalTokens:o+s}}}function _te(r,t){let e=[],n=[];for(let s of t.messages)if(s.role==="system")s.content&&e.push(s.content);else if(s.role==="user")n.push({role:"user",parts:[{text:s.content}]});else if(s.role==="assistant")if(Array.isArray(s.providerRaw))n.push({role:"model",parts:s.providerRaw});else{let a=[];s.content&&a.push({text:s.content});for(let l of s.toolCalls??[])a.push({functionCall:{name:l.name,args:l.args??{}}});n.push({role:"model",parts:a})}else n.push({role:"user",parts:s.results.map(a=>({functionResponse:{name:a.name,response:a.isError?{error:a.content}:{result:a.content}}}))});let i={contents:n};e.length>0&&(i.systemInstruction={role:"system",parts:[{text:e.join(` `)}]}),t.tools&&t.tools.length>0&&(i.tools=[{functionDeclarations:t.tools.map(s=>({name:s.name,description:s.description,parameters:s.parameters}))}],t.toolChoice&&(i.toolConfig=kte(t.toolChoice)));let o=hy("gemini",t.modelParams??{});return t.maxOutputTokens!==void 0&&(o.maxOutputTokens=t.maxOutputTokens),t.responseFormat?.schema&&(o.responseMimeType="application/json",o.responseSchema=t.responseFormat.schema),Object.keys(o).length>0&&(i.generationConfig=o),i}function kte(r){return typeof r=="string"?{functionCallingConfig:{mode:r==="required"?"ANY":r==="none"?"NONE":"AUTO"}}:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[r.name]}}}function Ste(r){let t=r.candidates?.[0]??{},n=(t.content??{}).parts??[],i=n.filter(a=>a.functionCall).map((a,l)=>({id:a.functionCall?.id??`gemini-call-${l}`,name:a.functionCall?.name??"",args:a.functionCall?.args??{}})),o=String(t.finishReason??""),s=r.usageMetadata??{};return{content:n.filter(a=>typeof a.text=="string").map(a=>a.text??"").join(""),toolCalls:i,normalizedStopReason:i.length>0?"tool_calls":o==="MAX_TOKENS"?"length":o==="STOP"?"stop":"other",rawStopReason:o,usage:{promptTokens:s.promptTokenCount??0,completionTokens:s.candidatesTokenCount??0,totalTokens:s.totalTokenCount??0},providerRaw:n}}function uF(r,t,e,n=8192){switch(r){case"anthropic":return xte(t,e,n);case"gemini":return _te(t,e);case"openai-responses":return wte(t,e);default:return gte(t,e)}}function Uz(r,t){switch(r){case"anthropic":return Tte(t);case"gemini":return Ste(t);case"openai-responses":return Cte(t);default:return vte(t)}}var hte,qz=x(()=>{mT();hte=/^(?:o[1-9]|gpt-(?:[5-9]|\d\d))/i});async function vy({kind:r,apiKey:t,provider:e,model:n,body:i,afterRequest:o}){let s={"Content-Type":"application/json"},a;switch(r){case"anthropic":a="/v1/messages",s["x-api-key"]=t,s["anthropic-version"]="2023-06-01";break;case"gemini":a=`/v1beta/models/${encodeURIComponent(n.name)}:generateContent`,s["x-goog-api-key"]=t;break;case"openai-responses":a="/responses",s.Authorization=`Bearer ${t}`;break;default:a="/chat/completions",s.Authorization=`Bearer ${t}`}let l=(0,zz.requestUrl)({url:e.endpoint+a,method:"POST",headers:s,body:JSON.stringify(i),throw:!1});o?.();let c=await l;if(c.status>=400)throw XE(e.name,c);return c.json}function Ate(r){return{id:r.id,model:r.model,content:r.choices[0].message.content,usage:{promptTokens:r.usage.prompt_tokens,completionTokens:r.usage.completion_tokens,totalTokens:r.usage.total_tokens},stopReason:r.choices[0].finish_reason,stopSequence:null,created:r.created}}function Ite(r){return{id:r.id,model:r.model,content:r.content.filter(t=>t.type==="text").map(t=>t.text??"").join(""),usage:{promptTokens:r.usage.input_tokens,completionTokens:r.usage.output_tokens,totalTokens:r.usage.input_tokens+r.usage.output_tokens},stopReason:r.stop_reason,stopSequence:r.stop_sequence,created:Date.now()}}function yy(r){if(typeof r.maxOutputTokens=="number"&&Number.isFinite(r.maxOutputTokens)&&r.maxOutputTokens>0)return Math.floor(r.maxOutputTokens);let t=4096;return Number.isFinite(r.maxTokens)&&r.maxTokens>0?Math.min(t,r.maxTokens):t}function Pte(r,t,e,n,i){if(r!=="anthropic"&&r!=="gemini")return{model:t.name,...n,messages:[{role:"system",content:e},{role:"user",content:i}]};let o=hy(r,n);return r==="anthropic"?{model:t.name,max_tokens:yy(t),messages:[{role:"user",content:i}],...e&&e.trim().length>0?{system:e}:{},...o}:{contents:[{role:"user",parts:[{text:i}]}],...e&&e.trim().length>0?{systemInstruction:{role:"system",parts:[{text:e}]}}:{},...Object.keys(o).length?{generationConfig:o}:{}}}async function Hz({kind:r,systemPrompt:t,params:e,prompt:n,...i}){let o=Pte(r,i.model,t,e,n),s={...i,kind:r,body:o};switch(r){case"anthropic":return Ite(await vy(s));case"gemini":return $te(await vy(s));default:return Ate(await vy(s))}}function $te(r){let t=r.candidates?.[0],n=(t?.content?.parts??[]).map(i=>typeof i.text=="string"?i.text:"").join("");return{id:`${Date.now()}`,model:r.modelVersion??"gemini",content:n,usage:{promptTokens:r.usageMetadata?.promptTokenCount??0,completionTokens:r.usageMetadata?.candidatesTokenCount??0,totalTokens:r.usageMetadata?.totalTokenCount??0},stopReason:t?.finishReason??"",stopSequence:null,created:Date.now()}}var zz,pF=x(()=>{zz=require("obsidian");ff();mT()});function by(r,t,e,n,i,o={},s=!0){return async function(l){if(U.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let c=Ti(l)+Ti(i),d=Date.now(),u=lF({provider:n.name,endpoint:n.endpoint,model:e.name,systemPrompt:i,prompt:l,modelOptions:o});S.logMessage(`[AI Request ${u}] Started ${n.name}/${e.name}`),Number.isFinite(e.maxTokens)&&e.maxTokens>0&&c>e.maxTokens&&S.logMessage(`[AI Request ${u}] Estimated prompt size is ${c} tokens, above the configured ${e.maxTokens} token context. Sending anyway; the provider will enforce the exact limit.`);try{let p=fT(r),m=Sh(n),h=C=>Hz({kind:m,apiKey:t,model:e,provider:n,systemPrompt:i,params:C,prompt:l,afterRequest:p}),g=oF(e,o),v=gf(g);v.length===0&&gf(o).length>0&&S.logMessage(`[AI Request ${u}] ${e.name} uses fixed sampling; not sending ${sF(gf(o))}.`);let b=await Gz(()=>h(g),()=>h(pT(g)),{sentKeys:v,model:e,provider:n,logPrefix:`AI Request ${u}`,advancedSettings:!0}),y=Date.now()-d;return gy(u,{status:"success",durationMs:y,usage:b.usage}),S.logMessage(`[AI Request ${u}] Success in ${y}ms`),b}catch(p){let m=p.message??String(p),h=Date.now()-d;gy(u,{status:"error",durationMs:h,errorMessage:m}),S.logMessage(`[AI Request ${u}] Failed in ${h}ms: ${m}`);let g=cy(p)==="input_context"?" The prompt likely exceeds the model's context window \u2014 shorten it, choose a model with a larger context, or use the chunked AI prompt API.":"",v=new Error(`Error while making request to ${n.name}: ${m}${g}`,{cause:p});throw s&&Me(v),v}}}async function mF(r,t,e,n,i,o,s=!0){if(U.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let a=lD(n),l={...i,modelParams:oF(e,i.modelParams??{})},c=gf(l.modelParams??{}),d=uF(a,e.name,l,yy(e)),u=i.messages.find(g=>g.role==="system"),p=[...i.messages].reverse().find(g=>g.role==="user"),m=Date.now(),h=lF({provider:n.name,endpoint:n.endpoint,model:e.name,systemPrompt:u&&u.role==="system"?u.content:"",prompt:p&&p.role==="user"?p.content:"[tool-calling turn]",modelOptions:i.modelParams??{}});try{let g=w=>vy({kind:a,apiKey:t,provider:n,model:e,body:w,afterRequest:o}),v=async w=>{try{return await g(w)}catch(T){let P=Mte(a,w,T.message??String(T));if(!P)throw T;return S.logMessage(`[AI Chat ${h}] ${e.name} rejected function tools while reasoning; retrying with reasoning_effort "none".`),g(P)}},b=await Gz(()=>v(d),()=>v(uF(a,e.name,{...l,modelParams:pT(l.modelParams??{})},yy(e))),{sentKeys:c,model:e,provider:n,logPrefix:`AI Chat ${h}`}),y=Uz(a,b),C=Date.now()-m;return gy(h,{status:"success",durationMs:C,usage:y.usage}),S.logMessage(`[AI Chat ${h}] Success in ${C}ms`),{id:b.id??`${Date.now()}`,model:e.name,content:y.content,usage:y.usage,stopReason:y.rawStopReason,stopSequence:null,created:Date.now(),toolCalls:y.toolCalls,normalizedStopReason:y.normalizedStopReason,providerRaw:y.providerRaw}}catch(g){let v=g.message??String(g),b=Date.now()-m;gy(h,{status:"error",durationMs:b,errorMessage:v});let y=uz(g)?` ${e.name} can't be forced to call a tool, so toolChoice "required" and named tools don't work with it. Use toolChoice "auto" (the default) and say in the prompt when to call the tool, or pass a schema to get a fixed JSON shape.`:"",C=new Error(`Error while making request to ${n.name}: ${v}${y}`,{cause:g});throw s&&Me(C),C}}function Mte(r,t,e){return r!=="openai"||!Array.isArray(t.tools)||t.tools.length===0||t.reasoning_effort!==void 0||!Fte.test(e)?null:{...t,reasoning_effort:"none"}}async function Gz(r,t,e){try{return await r()}catch(n){let i=n.message??String(n),{sentKeys:o,model:s,provider:a,logPrefix:l,advancedSettings:c}=e;if(!Mz(i,o))throw n;let d=sF(o),u=o.length>1?"them":"it";return S.logMessage(`[${l}] ${a.name} rejected ${d}; retrying without sampling parameters.`),new Wz.Notice(`${s.name} doesn't accept the ${d} setting${o.length>1?"s":""}, so QuickAdd retried without ${u}.`+(c?` You can remove ${u} from this command's advanced settings.`:"")),t()}}var Wz,Fte,hT=x(()=>{Wz=require("obsidian");mT();je();cF();dF();nt();gi();qz();ye();Gv();ff();pF();pF();Fte=/function tools with reasoning_effort are not supported[\s\S]*reasoning_effort to 'none'/i});function fu(r){if(r){let t=new jz.Notice(fF("starting",""),1e6);return{setMessage:(e,n)=>{t.setMessage(fF(e,n))},hide:()=>t.hide(),fail:e=>{if(Be(e)){t.hide();return}t.setMessage(fF("dead",e?.message??String(e))),XD(e),window.setTimeout(()=>t.hide(),5e3)}}}return{setMessage:()=>{},hide:()=>{},fail:()=>{}}}var jz,fF,gT=x(()=>{jz=require("obsidian");nt();fF=(r,t)=>`${r==="dead"?"AI request failed.":`Assistant is ${r}.`}${t?` ${t}`:""}`});function Ote(){return Array.from(new Set([hF,...["kebab","snake","camel","pascal","title","lower","upper","slug"].map(r=>Jh(hF,r))])).filter(Boolean)}function Kz(r){if(r.length<=1)return null;let t=Math.floor(r.length/2),e=[` `,` `,". "," "],n=-1,i=Number.POSITIVE_INFINITY;for(let a of e){let l=r.lastIndexOf(a,t),c=r.indexOf(a,t),d=[l,c].filter(u=>u>0);for(let u of d){let p=u+a.length;if(p<=0||p>=r.length)continue;let m=Math.abs(p-t);m0&&n=56320&&s<=57343&&(o+=1),o<=0||o>=r.length?null:[r.slice(0,o),r.slice(o)]}function Dte(r){let t=new RegExp(Td.source,"gi"),e=qi(r),n;for(;(n=t.exec(e))!==null;)if(n[1].split("|")[0].trim().toLowerCase()==="chunk")return!0;return!1}function Lte(r){return As.test(r)||nw.test(r)||iw.test(r)||yi(r).length>0}function Nte(r){return Yz.some(t=>r.includes(t))}function Vte(r){return Yz.slice().sort((t,e)=>e.length-t.length).reduce((t,e)=>t.split(e).join(" "),r)}function Qz(r){if(r>yT)throw new Error(`This chunked AI request would split into more than ${yT} prompts, which exceeds the safety limit. Increase the chunk size, use a larger chunk separator, or reduce the input text.`)}function Bte(r,t,e){let n=Math.max(1,Math.floor(t)),i=[r],o=0;for(;i.length>0;){let s=i.pop(),l=Ti(s)<=n?null:Kz(s);if(!l){e.push(s),o+=1,Qz(o);continue}i.push(l[1],l[0])}}function Ute(r){let t=r.flags.replace(/[gy]/g,"");return new RegExp(r.source+"|",t).exec("").length-1}function zte(r,t){if(typeof t=="string"){let s=r.split(t);return{chunks:s,separators:new Array(Math.max(0,s.length-1)).fill(t)}}if(Ute(t)>0||qte.test(t.source))return{chunks:r.split(t),separators:null};let e=new RegExp(`(${t.source})`,t.flags),n=r.split(e),i=[],o=[];for(let s=0;s{let d=[];Bte(l,e,d),d.forEach((u,p)=>{i.push({text:u,joiner:p===0&&c>0?t?.[c-1]??"":""})})}),!n)return i.map(l=>l.text);let o=[],s="",a=0;for(let l of i){let c=Ti(l.text)+Math.max(1,Ti(l.joiner));s!==""&&a+c>=e&&(o.push(s),s="",a=0),s+=s===""?l.text:l.joiner+l.text,a+=c}return s!==""&&o.push(s),o}function Wte(r,t){let e=Math.max(1,Math.floor(r));if(t!==void 0&&Number.isFinite(t)&&t>0){let n=Math.floor(t);return{budget:Math.min(e,n),clamped:n>e}}return{budget:e,clamped:!1}}async function gF(r,t,e){if(U.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=fu(t.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,systemPrompt:l,promptTemplate:c,text:d,modelOptions:u}=t;n.setMessage("chunking","Creating prompt chunks with text and prompt template");let p=t.chunkSeparator||/\n/g,{chunks:m,separators:h}=zte(d,p),g=await e(c,{chunk:hF});if(!(Dte(c)||Lte(c)&&Nte(g)))throw new Error("The chunked prompt template does not reference the chunk text. Add {{VALUE:chunk}} to your prompt template so each chunk is inserted.");let b=o.maxTokens,y=mU(b),C=Vte(g),w=Ti(l)+Ti(C);if(w>=b)throw new Error(`The estimated prompt overhead (${w} tokens) exceeds the model's entire context window (${b} tokens). Shorten the system prompt or prompt template, or use a model with a larger context window.`);let{budget:T,clamped:P}=Wte(y-w,t.maxChunkTokens);P&&S.logMessage(`[ChunkedPrompt] Requested max chunk tokens (${t.maxChunkTokens}) exceeds this model's estimated input budget; using ${T} estimated tokens per chunk instead.`);let _=t.shouldMerge??!0,I=Hte(m,h,T,_);Qz(I.length);let D=by(r,i,o,s,l,u,!t.showAssistantMessages),N=["prompting",`${I.length} prompts being sent.`];n.setMessage(N[0],N[1]);let K=new vT(5,1e3*30),ne=!1,H=0,O=Promise.resolve(),G=W=>{let Z=O.then(()=>{if(ne)throw new Error("Chunked prompt stopped after an earlier failure.");return e(c,{chunk:W})});return O=Z.then(()=>{},()=>{}),Z},V=async(W,Z=0)=>{if(ne)throw new Error("Chunked prompt stopped after an earlier failure.");let se;try{se=await G(W)}catch(ce){throw ne=!0,ce}try{return[(await K.add(()=>{if(ne)throw new Error("Chunked prompt stopped after an earlier failure.");if(H+=1,H>yT)throw new Error(`Chunked AI request exceeded the safety limit of ${yT} provider requests.`);return D(se)})).content]}catch(ce){let $e=Kz(W);if(Z>=Rte||!$e||!dz(ce))throw ne=!0,ce;n.setMessage("prompting","Provider rejected a prompt for context length. Retrying with smaller chunks.");let[Xe,Ye]=$e,he=await V(Xe,Z+1),Re=await V(Ye,Z+1);return[...he,...Re]}},M=Promise.all(I.map(W=>V(W))),te=(await my(M,n,N)).flat().join(t.resultJoiner);return window.setTimeout(()=>n.hide(),5e3),fy(a,te)}catch(i){throw n.fail(i),i}}var vT,Rte,yT,hF,Yz,qte,Xz=x(()=>{je();hT();ff();gT();Gv();ye();Le();Oa();Wd();ww();nF();vT=class{constructor(t,e){this.maxRequests=t;this.intervalMs=e;this.queue=[];this.startTimes=[]}add(t){return new Promise((e,n)=>{this.queue.push(async()=>{try{e(await t())}catch(i){n(i instanceof Error?i:new Error(String(i)))}}),this.schedule()})}schedule(){if(this.queue.length===0)return;let t=Date.now();if(this.startTimes=this.startTimes.filter(i=>t-i=this.maxRequests){let i=this.startTimes[0],o=Math.max(0,this.intervalMs-(t-i));window.setTimeout(()=>this.schedule(),o+1);return}let e=this.queue.shift();if(!e)return;this.startTimes.push(t);let n=e();window.setTimeout(()=>this.schedule(),this.intervalMs),this.schedule()}},Rte=12,yT=500,hF="quickadd_chunk_probe_123456789";Yz=Ote();qte=/(?:^|[^\\])(?:\\\\)*\\[1-9]/});async function Gte(r,t,e,n=!0,i){let o;if(t.enable)o=e.find(c=>c.path.endsWith(t.name));else{let c=e.map(d=>d.basename);if(i)o=await i.suggester(c,e,"Select a prompt template");else if(n)o=await It.Suggest(r,c,e,"Select a prompt template");else throw new de("This AI command asks which prompt template to use, but this run is non-interactive. Enable a specific prompt template in the command, or re-run with the ui flag.")}Vr(o,"Prompt template does not exist");let s=o.path,a=r.vault.getAbstractFileByPath(s);Vr(a instanceof Jz.TFile,`${s} is not a file`);let l=await r.vault.cachedRead(a);return[o.basename,l]}async function Zz(r,t,e){if(U.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=fu(t.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,promptTemplate:l,systemPrompt:c,promptTemplateFolder:d}=t,u=ts(r,d),[p,m]=await Gte(r,l,u,t.interactive??!0,t.promptProvider);n.setMessage("waiting","QuickAdd is formatting the prompt template.");let h=await e(m),g=["prompting",`Using prompt template "${p}".`];n.setMessage(g[0],g[1]);let b=by(r,i,o,s,c,t.modelOptions,!t.showAssistantMessages)(h),C=(await my(b,n,g)).content;return window.setTimeout(()=>n.hide(),5e3),fy(a,C)}catch(i){throw n.fail(i),Be(i)?new et("Input cancelled by user"):i}}async function e2(r,t,e){if(U.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=fu(t.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,systemPrompt:l,prompt:c,modelOptions:d}=t;n.setMessage("waiting","QuickAdd is formatting the prompt template.");let u=await e(c),p=["prompting","Using custom prompt."];n.setMessage(p[0],p[1]);let h=by(r,i,o,s,l,d,!t.showAssistantMessages)(u),v=(await my(h,n,p)).content;return window.setTimeout(()=>n.hide(),5e3),fy(a,v)}catch(i){throw n.fail(i),i}}var Jz,vF=x(()=>{nF();Jz=require("obsidian");rr();Sn();Qi();je();bi();Nd();nt();hT();gT();cF();Xz()});function t2(r){return r.replace(jte,t=>t+"\uFDD0")}function An(r){return r.includes("\uFDD0")?r.replace(Yte,"$1"):r}function wy(r,t){if(!r.includes("\uFDD0"))return{content:r,offsets:t};let e=n=>An(r.slice(0,n)).length;return{content:An(r),offsets:typeof t=="number"?e(t):t.map(e)}}function bT(r){let{cursor:t}=r,e=wy(r.content,t.kind==="offset"?t.value:0);return{content:e.content,cursor:t.kind==="offset"?{...t,value:e.offsets}:t}}var jte,Yte,vf=x(()=>{jte=/\{(?=\{)|<(?=%)|%(?=>)/g,Yte=/([{<%])\uFDD0(?=[{%>])/g});var r2,Pc,yF=x(()=>{r2=require("obsidian");SP();Hh();Pc=class r extends Nm{static Prompt(t,e,n,i,o,s){return new r(t,e,n,i,o,s).waitForClose}getPromptKind(){return"multi"}createInputField(t,e,n){let i=new r2.TextAreaComponent(t);return i.inputEl.classList.add("wideInputPromptInputEl"),i.inputEl.setAttribute("dir","auto"),this.disposeIndent=zh(i.inputEl),this.configureInput(i,e,n)}shouldSubmit(t){return(t.ctrlKey||t.metaKey)&&t.key==="Enter"}disposeInput(){this.disposeIndent?.()}}});var Cy,n2=x(()=>{Gs();xo();Cy=class r extends ir{supportsPeek(){return!1}static Prompt(t,e,n,i,o,s){return new r(t,e,n,i,o,s).waitForClose}createInputField(t,e,n){let i=super.createInputField(t,e,n);i.inputEl.type="number",i.inputEl.inputMode="decimal";let o=this.options?.numeric;return o?.min!==void 0&&(i.inputEl.min=String(o.min)),o?.max!==void 0&&(i.inputEl.max=String(o.max)),i.inputEl.setAttr("step",o?.step!==void 0?String(o.step):"any"),i}transformInputOnSubmit(t){return this.options?.numeric?t===""&&this.isOptionalPrompt?"":Co(t,this.options.numeric):t}}});var bF,xy,i2=x(()=>{Gs();xo();bF={min:0,max:100,step:1},xy=class r extends ir{supportsPeek(){return!1}static Prompt(t,e,n,i,o,s){return new r(t,e,n,i,o,s).waitForClose}createInputField(t,e,n){let i=this.options?.slider??bF,o=this.isOptionalPrompt&&!n,s=Tp(n,i);this.sliderEl=t.createEl("input"),this.sliderEl.type="range",this.sliderEl.min=String(i.min),this.sliderEl.max=String(i.max),this.sliderEl.step=String(i.step),this.sliderEl.value=s,this.sliderEl.setCssStyles({width:"100%"});let a=super.createInputField(t,void 0,s);return this.numberEl=a.inputEl,this.numberEl.type="number",this.numberEl.inputMode="decimal",this.numberEl.min=String(i.min),this.numberEl.max=String(i.max),this.numberEl.step=String(i.step),o&&(this.numberEl.value=""),this.sliderEl.addEventListener("input",()=>this.syncFromSlider()),this.numberEl.addEventListener("input",()=>this.syncFromNumber()),a}syncFromSlider(){!this.sliderEl||!this.numberEl||(this.numberEl.value=this.sliderEl.value,this.onInputChanged(this.sliderEl.value))}syncFromNumber(){if(!this.sliderEl||!this.numberEl)return;let t=this.numberEl.value;if(t===""&&this.isOptionalPrompt){this.onInputChanged("");return}let e=Co(t,this.options?.slider??bF);e!==""&&(this.sliderEl.value=e),this.onInputChanged(t)}transformInputOnSubmit(t){return t===""&&this.isOptionalPrompt?"":Tp(t,this.options?.slider??bF)}}});var hu,wF=x(()=>{yF();Gs();n2();i2();ss();hu=class{factory(t){return t==="multiline"?Pc:t==="number"?Cy:t==="slider"?xy:Wr().settings.inputPrompt==="multi-line"?Pc:ir}}});function CF(r){return r.normalize("NFKD").toLowerCase()}var s2,o2,Kte,gu,xF=x(()=>{s2=require("obsidian"),o2=200,Kte=0;gu=class{constructor(t,e){this.options=e;this.instanceId=++Kte;this.indexedItems=[];this.renderedRows=[];this.query="";this.rootEl=t.createDiv({cls:"qa-searchable-multi-select"});let n=this.rootEl.createDiv({cls:"search-input-container qa-searchable-multi-select__search-container"});this.searchInputEl=n.createEl("input",{cls:"qa-searchable-multi-select__search",type:"search",placeholder:e.searchPlaceholder??"Search options..."}),this.searchInputEl.name=`qa-multi-select-search-${this.instanceId}`,this.searchInputEl.setAttribute("aria-label",this.searchInputEl.placeholder),this.searchInputEl.setAttribute("autocomplete","off"),this.searchInputEl.setAttribute("spellcheck","false"),this.summaryEl=this.rootEl.createDiv({cls:"qa-searchable-multi-select__summary"}),this.summaryEl.setAttribute("aria-live","polite"),this.listEl=this.rootEl.createDiv({cls:"qa-searchable-multi-select__list"}),this.listEl.setAttribute("role","group"),this.listEl.setAttribute("aria-label","Options"),this.searchInputEl.addEventListener("input",()=>{this.query=this.searchInputEl.value,this.renderList()}),this.searchInputEl.addEventListener("keydown",i=>{if(i.key==="ArrowDown"){i.preventDefault(),this.renderedRows[0]?.input.focus();return}i.key==="ArrowUp"&&(i.preventDefault(),this.renderedRows.at(-1)?.input.focus())}),this.setItems(e.items)}setItems(t){this.indexedItems=t.map((e,n)=>({item:e,index:n,searchableText:CF(`${e.label} ${e.searchText??""}`),searchableAliases:(e.aliases??[]).map(CF)})),this.searchInputEl.disabled=t.length===0,this.renderList()}clearSearch(){return this.query?(this.query="",this.searchInputEl.value="",this.renderList(),this.searchInputEl.focus(),!0):!1}focusSearchOnOpen(){document.body.classList.contains("is-mobile")||this.searchInputEl.focus()}refreshSelection(){for(let{item:t,input:e}of this.renderedRows)e.checked=this.options.isSelected(t),e.closest("label")?.classList.toggle("is-selected",e.checked);this.updateSummary()}getMatchingItems(){let t=CF(this.query.trim()).split(/\s+/).filter(Boolean);if(t.length===0)return this.indexedItems;let e=i=>t.every(o=>i.includes(o)),n=[];for(let i of this.indexedItems){if(e(i.searchableText)){n.push(i);continue}let o=i.searchableAliases.findIndex(e);o>=0&&n.push({...i,alias:i.item.aliases?.[o]})}return n}getVisibleItems(t){if(t.length<=o2)return t;let e=[],n=[];for(let i of t)(this.options.isSelected(i.item)?e:n).push(i);return[...e,...n].slice(0,o2)}renderList(){this.listEl.replaceChildren(),this.renderedRows=[];let t=this.getMatchingItems(),e=this.getVisibleItems(t);if(e.length===0){let n=this.listEl.createDiv({cls:"qa-searchable-multi-select__empty"});n.setAttribute("role","status"),n.textContent=this.indexedItems.length?`No options match \u201C${this.query.trim()}\u201D`:this.options.emptyText??"No options available"}for(let n of e)this.renderRow(n);if(t.length>e.length){let n=this.listEl.createDiv({cls:"qa-searchable-multi-select__limit"});n.setAttribute("role","status"),n.textContent=`Showing ${e.length} of ${t.length} options. Refine your search to see the rest.`}this.updateSummary(t.length)}renderRow(t){let{item:e,index:n,alias:i}=t,o=this.listEl.createEl("label",{cls:"qa-searchable-multi-select__option"}),s=o.createSpan({cls:"qa-searchable-multi-select__option-text"});if(s.createSpan({cls:"qa-searchable-multi-select__option-label",text:i??e.label}),i!==void 0){s.createSpan({cls:"qa-searchable-multi-select__option-note",text:e.label});let l=o.createSpan({cls:"qa-searchable-multi-select__option-flair"});l.setAttribute("aria-label","Alias"),(0,s2.setIcon)(l,"forward")}let a=o.createEl("input",{type:"checkbox"});a.name=`qa-multi-select-${this.instanceId}`,a.id=`qa-multi-select-${this.instanceId}-${n}`,a.checked=this.options.isSelected(e),o.htmlFor=a.id,o.classList.toggle("is-selected",a.checked),a.addEventListener("change",()=>{this.options.onToggle(e,a.checked),this.refreshSelection()}),a.addEventListener("keydown",l=>{this.handleOptionKeydown(l,a)}),this.renderedRows.push({item:e,input:a})}handleOptionKeydown(t,e){let n=this.renderedRows.findIndex(i=>i.input===e);if(t.key==="ArrowDown"){t.preventDefault(),this.renderedRows[n+1]?.input.focus();return}if(t.key==="ArrowUp"){t.preventDefault(),n===0?this.searchInputEl.focus():this.renderedRows[n-1]?.input.focus();return}if(t.key==="Home"){t.preventDefault(),this.renderedRows[0]?.input.focus();return}if(t.key==="End"){t.preventDefault(),this.renderedRows.at(-1)?.input.focus();return}if(t.key==="Enter"||t.key===" "){t.preventDefault(),e.checked=!e.checked,e.dispatchEvent(new Event("change",{bubbles:!0}));return}t.key==="/"&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&(t.preventDefault(),this.searchInputEl.focus())}updateSummary(t=this.getMatchingItems().length){let n=`${this.options.getSelectedCount?.()??new Set(this.indexedItems.filter(({item:i})=>this.options.isSelected(i)).map(({item:i})=>i.key)).size} selected`;if(!this.query.trim()){let i=this.indexedItems.length;this.summaryEl.textContent=`${n} \xB7 ${i} ${i===1?"option":"options"}`;return}this.summaryEl.textContent=`${n} \xB7 ${t} ${t===1?"match":"matches"}`}}});var $c,Fc,EF=x(()=>{$c=require("obsidian");an();rr();Ln();xF();Fc=class r extends $c.Modal{constructor(e,n,i,o={}){super(e);this.didSubmit=!1;this.skipped=!1;this.selected=new Set;this.customValues=[];this.draft="";this.items=i,this.displayItems=n.length===i.length?n:i,this.opts=o,this.seedPreselection(o.preselected),this.waitForClose=new Promise((s,a)=>{this.resolvePromise=s,this.rejectPromise=a}),this.render(),this.open(),this.picker.focusSearchOnOpen()}static Suggest(e,n,i,o={}){return new r(e,n,i,o).waitForClose}onEscapeKey(e){if(this.picker.clearSearch()){e.preventDefault();return}super.onEscapeKey(e)}selectValue(e){!this.items.includes(e)&&!this.customValues.includes(e)&&this.customValues.push(e),this.selected.add(e)}seedPreselection(e){if(e?.length)for(let n of e){let i=n?.trim();i&&this.selectValue(i)}}render(){this.containerEl.addClass("quickAddModal","qaSearchableMultiSelectModal","qaMultiSuggester"),this.titleEl.setText(this.opts.placeholder??"Select one or more");let{contentEl:e}=this;e.empty();let n=e.createDiv({cls:"qa-multi-list"});this.picker=new gu(n,{items:this.getSearchableItems(),isSelected:({value:o})=>this.selected.has(o),onToggle:({value:o},s)=>{s?this.selected.add(o):this.selected.delete(o)},getSelectedCount:()=>this.selected.size}),this.opts.allowCustomValue&&new $c.Setting(e).setName("Add a custom value").addText(s=>{s.setPlaceholder("Not in the list\u2026").setValue(this.draft).onChange(a=>this.draft=a),s.inputEl.addClass("qa-multi-custom-input"),s.inputEl.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.commitDraft())})}).addButton(s=>s.setButtonText("Add").onClick(()=>this.commitDraft())).settingEl.addClass("qa-multi-custom");let i=new $c.Setting(e);i.settingEl.addClass("qa-multi-actions"),this.opts.skippable&&i.addButton(o=>o.setButtonText("Skip").setTooltip("Leave empty").onClick(()=>{this.skipped=!0,this.didSubmit=!0,this.close()})),i.addButton(o=>o.setButtonText("Cancel").onClick(()=>this.close())),i.addButton(o=>o.setButtonText("Done").setCta().onClick(()=>this.submit()))}getSearchableItems(){return[...this.items.map((e,n)=>({key:e,value:e,label:sn(this.displayItems[n]??e),searchText:e,aliases:this.opts.aliases?.[n]})),...this.customValues.map(e=>({key:e,value:e,label:e}))]}commitDraft(){let e=this.draft.trim();if(!e)return new $c.Notice("Enter a value to add."),!1;let n=this.typedValue(e);return(this.items.includes(n)||this.customValues.includes(n))&&this.selected.has(n)?(new $c.Notice(`"${e}" is already added.`),!1):(this.selectValue(n),this.draft="",this.render(),this.focusCustomInput(),!0)}typedValue(e){return Dd(this.items,this.opts.aliases??[],e)??e}focusCustomInput(){this.contentEl.querySelector(".qa-multi-custom-input")?.focus()}submit(){this.opts.allowCustomValue&&this.draft.trim()&&(this.selectValue(this.typedValue(this.draft.trim())),this.draft=""),this.didSubmit=!0,this.close()}collectResult(){return[...this.items,...this.customValues].filter(e=>this.selected.has(e))}onClose(){super.onClose(),this.didSubmit?this.resolvePromise(this.skipped?[]:this.collectResult()):this.rejectPromise(on())}}});var wT,Mc,Qte,Xte,Jte,l2,TF,Ey,_F,a2,CT,xT,kF=x(()=>{wT=require("obsidian");je();Mc=r=>r.toString().padStart(2,"0"),Qte=r=>{if(typeof r=="number"&&r>=0&&r<=6)return r;let e=window.moment?.localeData?.()?.firstDayOfWeek?.();return typeof e=="number"&&e>=0&&e<=6?e:0},Xte=r=>{let t=new Intl.DateTimeFormat(void 0,{weekday:"short"}),e=new Date(2021,7,1),n=Array.from({length:7},(i,o)=>{let s=new Date(e.getFullYear(),e.getMonth(),e.getDate()+o);return t.format(s)});return n.slice(r).concat(n.slice(0,r))},Jte=(r,t)=>new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(r,t,1)),l2=(r,t,e)=>`${r}-${Mc(t+1)}-${Mc(e)}`,TF=r=>l2(r.getFullYear(),r.getMonth(),r.getDate()),Ey=r=>{if(!r)return null;let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(t){let[,n,i,o]=t;return new Date(Number.parseInt(n,10),Number.parseInt(i,10)-1,Number.parseInt(o,10))}let e=new Date(r);return Number.isNaN(e.getTime())?null:e},_F=(r,t,e,n)=>{let i=l2(r,t,e);return n?`${i}T${Mc(n.hour)}:${Mc(n.minute)}:00`:i},a2=r=>{if(!r)return null;let t=/[T ](\d{2}):(\d{2})/.exec(r);if(!t)return null;if(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(r)){let i=new Date(r);return Number.isNaN(i.getTime())?null:{hour:i.getHours(),minute:i.getMinutes()}}let e=Number.parseInt(t[1],10),n=Number.parseInt(t[2],10);return Number.isNaN(e)||Number.isNaN(n)||e<0||e>23||n<0||n>59?null:{hour:e,minute:n}},CT=r=>{let t=Qte(r.weekStartsOn),e=Xte(t),n=Ey(r.initialIso)??new Date,i=n.getFullYear(),o=n.getMonth(),s=r.initialIso,a=r.withTime===!0,l=a?a2(r.initialIso)??{hour:0,minute:0}:null,c=r.container.createDiv({cls:"qa-date-picker"}),d=c.createDiv({cls:"qa-date-picker__header"}),u=d.createEl("button",{cls:"qa-date-picker__nav clickable-icon"});(0,wT.setIcon)(u,"chevron-left"),u.type="button",u.tabIndex=-1,u.setAttr("aria-label","Previous month");let p=d.createDiv({cls:"qa-date-picker__label"}),m=d.createEl("button",{cls:"qa-date-picker__nav clickable-icon"});(0,wT.setIcon)(m,"chevron-right"),m.type="button",m.tabIndex=-1,m.setAttr("aria-label","Next month");let h=c.createDiv({cls:"qa-date-picker__weekdays"});e.forEach(I=>{let D=h.createDiv({cls:"qa-date-picker__weekday"});D.textContent=I});let g=c.createDiv({cls:"qa-date-picker__grid"}),v=c.createDiv({cls:"qa-date-picker__actions"}),b=v.createEl("button",{cls:"qa-date-picker__action",text:"Today"});b.type="button",b.tabIndex=-1;let y=v.createEl("button",{cls:"qa-date-picker__action",text:"Clear"});y.type="button",y.tabIndex=-1;let C;if(a){let I=c.createDiv({cls:"qa-date-picker__time"});I.createEl("label",{cls:"qa-date-picker__time-label",text:"Time"}),C=I.createEl("input",{cls:"qa-date-picker__time-input",attr:{"aria-label":"Time"}}),C.type="time",C.tabIndex=-1,l&&(C.value=`${Mc(l.hour)}:${Mc(l.minute)}`)}let w=I=>{o+=I,o>11?(o=0,i+=1):o<0&&(o=11,i-=1),_()},T=(I,D)=>{s=I,r.onSelect(I,D),_()},P=I=>{s=void 0,r.onSelect(null,I),_()};u.addEventListener("click",()=>w(-1)),m.addEventListener("click",()=>w(1)),b.addEventListener("click",()=>{let I=new Date,D=_F(I.getFullYear(),I.getMonth(),I.getDate(),l);i=I.getFullYear(),o=I.getMonth(),T(D,"action")}),y.addEventListener("click",()=>P("action")),C&&C.addEventListener("change",()=>{if(C.value.trim()==="")l={hour:0,minute:0};else{let[I,D]=C.value.split(":").map(N=>Number.parseInt(N,10));if(Number.isNaN(I)||Number.isNaN(D))return;l={hour:I,minute:D}}if(s){let I=Ey(s);I&&T(_F(I.getFullYear(),I.getMonth(),I.getDate(),l),"picker")}});let _=()=>{p.textContent=Jte(i,o),g.empty();let D=(new Date(i,o,1).getDay()-t+7)%7,N=new Date(i,o,1-D),K=TF(new Date),ne=s?Ey(s):null,H=ne?TF(ne):void 0,O=new Intl.DateTimeFormat(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"});for(let G=0;G<42;G+=1){let V=new Date(N);V.setDate(N.getDate()+G);let M=TF(V),B=V.getMonth()!==o,J=M===K,te=H&&M===H,W=g.createEl("button",{cls:"qa-date-picker__day",text:String(V.getDate())});W.type="button",W.tabIndex=-1,W.setAttr("aria-label",O.format(V)),B&&W.addClass("is-outside"),J&&W.addClass("is-today"),te&&(W.addClass("is-selected"),W.setAttr("aria-pressed","true")),W.addEventListener("click",()=>{let Z=_F(V.getFullYear(),V.getMonth(),V.getDate(),l);T(Z,"picker")})}};return _(),{setSelectedIso:(I,{updateView:D}={})=>{if(s=I,I&&D!==!1){let N=Ey(I);N&&(i=N.getFullYear(),o=N.getMonth())}if(a&&I){let N=a2(I);N&&(l=N,C&&(C.value=`${Mc(N.hour)}:${Mc(N.minute)}`))}_()},setViewFromIso:I=>{let D=Ey(I);D&&(i=D.getFullYear(),o=D.getMonth(),_())},destroy:()=>{c.remove()}}},xT=(r,t)=>{let e=r.createEl("button",{cls:"qa-date-field__calendar clickable-icon"});e.type="button",e.tabIndex=-1,(0,wT.setIcon)(e,"calendar"),e.addEventListener("mousedown",i=>i.preventDefault()),e.addEventListener("click",()=>{U.setState({showDateCalendar:!U.getState().showDateCalendar})});let n=i=>{t.toggle(i),e.toggleClass("is-shown",i),e.setAttr("aria-label",i?"Hide calendar":"Show calendar")};return n(U.getState().showDateCalendar),U.subscribe(i=>n(i.showDateCalendar))}});function Rc(r,t,e=So,n){if(!r||!r.trim())return{isValid:!1,error:"Empty input"};try{let i=n??U.getState().dateAliases,o=Ih(r,i),s=e.parseDate(o);if(s?.moment?.isValid()){let a=s.moment.toISOString(),l=t?s.moment.format(t):s.moment.format("YYYY-MM-DD");return{isValid:!0,isoString:a,formatted:l}}else return{isValid:!1,error:"Unable to parse date"}}catch(i){return{isValid:!1,error:`Parse error: ${i instanceof Error?i.message:"Unknown error"}`}}}function Mo(r,t){if(!window.moment)return null;try{let e=window.moment(r);if(e.isValid())return e.format(t)}catch{}return null}var vu=x(()=>{Qd();je();wd()});var bf,yf,fl,ET=x(()=>{bf=require("obsidian");Gs();kF();vu();yP();je();wd();yf=class yf extends ir{constructor(e,n,i,o,s,a,l){super(e,n,i,o??"",void 0,a);this.isOpen=!0;if(this.containerEl.addClass("qaDatePrompt"),this.withTime=l===!0,this.dateFormat=s||(this.withTime?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"),this.defaultValue=o,this.currentInput=this.inputComponent?.inputEl?.value??o??"",this.mountDatePicker(),this.currentInput.startsWith("@date:")){let c=this.currentInput.slice(6).trim();c&&Mo(c,this.dateFormat)!==null&&(this.applyPickerSelection(c,!1),_x(this.inputComponent.inputEl,a))}this.updatePreviewDebounced=(0,bf.debounce)(this.updatePreview.bind(this),250,!0),this.updatePreview()}supportsPeek(){return!1}static Prompt(e,n,i,o,s,a,l){return new yf(e,n,i,o,s,a,l).waitForClose}createInputField(e,n,i){e.addClass("qa-date-input"),this.dateFieldEl=e.createDiv({cls:"qa-date-field"});let o=new bf.TextComponent(this.dateFieldEl);return o.inputEl.addClass("qa-vdate-input"),o.setPlaceholder(n??"").setValue(i??"").onChange(s=>{this.lastPickerDisplayValue=void 0,this.onInputChanged(s),this.currentInput=s,this.updatePreviewDebounced()}).inputEl.addEventListener("keydown",this.submitEnterCallback),this.currentInput=i??"",this.pickerHostEl=e.createDiv({cls:"qa-date-picker-container"}),this.createPreviewElement(e),o}mountDatePicker(){this.datePicker=CT({container:this.pickerHostEl,initialIso:this.selectedIso,withTime:this.withTime,onSelect:e=>{e?this.applyPickerSelection(e):this.clearPickerSelection()}}),this.unsubscribeCalendarToggle=xT(this.dateFieldEl,this.pickerHostEl)}createPreviewElement(e){let n=e.createDiv("vdate-preview-container");n.createDiv({text:"Preview:",cls:"vdate-preview-label"}),this.previewEl=n.createDiv({cls:"vdate-preview-text"}),this.previewEl.textContent=yf.PREVIEW_PLACEHOLDER;let i=Ph(U.getState().dateAliases);if(i.length>0){let o=n.createEl("details",{cls:"vdate-alias-details"});o.createEl("summary",{text:`Aliases (${i.length})`}).addClass("vdate-alias-summary");let a=o.createDiv({cls:"vdate-alias-list"});a.textContent=ew(U.getState().dateAliases)}}updatePreview(){if(!this.isOpen)return;let e=this.currentInput.trim();if(!e&&this.defaultValue&&!this.isOptionalPrompt){this.renderPreviewFromInput(this.defaultValue);return}if(!e){this.selectedIso=void 0,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(),this.setPreviewText(this.isOptionalPrompt?"Will be left empty":yf.PREVIEW_PLACEHOLDER,!1);return}if(e.startsWith("@date:")){let n=e.slice(6).trim();if(n){this.selectedIso=n,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(n),this.renderPreviewFromIso(n);return}}if(this.selectedIso&&this.lastPickerDisplayValue&&e===this.lastPickerDisplayValue){this.syncPickerSelection(this.selectedIso,!1),this.renderPreviewFromIso(this.selectedIso);return}this.renderPreviewFromInput(e)}formatIsoForInput(e){let n=Mo(e,this.dateFormat);return n||(e.length>=10?e.slice(0,10):e)}syncPickerSelection(e,n=!0){this.datePicker?.setSelectedIso(e,{updateView:n})}applyPickerSelection(e,n=!0){let i=this.formatIsoForInput(e);this.selectedIso=e,this.lastPickerDisplayValue=i,this.inputComponent?.inputEl&&(this.inputComponent.inputEl.value=i),n?this.onInputChanged(i):this.input=i,this.currentInput=i,this.syncPickerSelection(e),this.renderPreviewFromIso(e)}clearPickerSelection(){this.inputComponent?.inputEl&&(this.inputComponent.inputEl.value=""),this.onInputChanged(""),this.currentInput="",this.selectedIso=void 0,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(),this.updatePreview()}renderPreviewFromIso(e){this.setPreviewText(this.formatIsoForInput(e),!1)}renderPreviewFromInput(e){let n=Rc(e,this.dateFormat);if(n.isValid&&n.isoString){this.selectedIso=n.isoString,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(n.isoString);let i=n.formatted??this.formatIsoForInput(n.isoString);this.setPreviewText(i,!1)}else{this.selectedIso=void 0,this.lastPickerDisplayValue=void 0,this.syncPickerSelection();let i=n.error||"Unable to parse date";this.setPreviewText(i,!0)}}setPreviewText(e,n){this.previewEl.textContent=e,this.previewEl.toggleClass("is-error",n)}onOpen(){super.onOpen()}transformInputOnSubmit(e){let n=e.trim();if(n.startsWith("@date:"))return n;if(this.selectedIso&&this.lastPickerDisplayValue&&n===this.lastPickerDisplayValue)return`@date:${this.selectedIso}`;if(!n&&this.defaultValue&&!this.isOptionalPrompt){let i=Rc(this.defaultValue,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`}if(n){let i=Rc(n,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`;new bf.Notice(`QuickAdd: "${n}" could not be parsed as a date; using it as-is.`)}return e}onClose(){this.isOpen=!1,this.updatePreviewDebounced.cancel(),this.unsubscribeCalendarToggle?.(),!this.input.trim()&&this.defaultValue&&!this.isOptionalPrompt&&(this.input=this.defaultValue),super.onClose()}};yf.PREVIEW_PLACEHOLDER="Preview will appear here";fl=yf});async function c2(r,t,e){let n=r.executor?.promptProvider;if(n)return e?.type==="VDATE"?await n.datePrompt(e.label??t??"Enter date",{defaultValue:e.defaultValue,dateFormat:e.dateFormat??"YYYY-MM-DD",withTime:e.withTime}):e?.inputTypeOverride==="checkbox"?String(await n.suggester(["true","false"],["true","false"],e.label??t??"Choose value",!1)):await n.inputPrompt(e?.label??t??"Enter value",e?.placeholder,e?.defaultValue);r.assertInteractivePrompt(t?`{{VALUE:${t}}}`:"a template variable");try{let i=e?.label??t??"Enter value",o=hw(r.scope),s=vp(r.runContext,i,{showDestination:o}),a=vp(r.runContext,i,{elide:!1,showDestination:o});return e?.type==="VDATE"?await fl.Prompt(r.app,i,e.withTime?"Enter a date & time (e.g., 'tomorrow at 3pm', '2025-12-25 14:30')":"Enter a date (e.g., 'tomorrow', 'next friday', '2025-12-25')",e.defaultValue,e.dateFormat??"YYYY-MM-DD",{optional:e.optional,contextLine:s,contextLineFull:a,draftScopeId:r.runContext?.draftScopeId},e.withTime):e?.inputTypeOverride==="checkbox"?await It.Suggest(r.app,["true","false"],["true","false"],e.label??t??"Choose value",void 0,e.optional?{skippable:!0}:void 0):await new hu().factory(e?.inputTypeOverride).Prompt(r.app,i,e?.placeholder??(e?.defaultValue?e.defaultValue:void 0),e?.defaultValue,void 0,r.buildInputPromptOptions(e,s,a))}catch(i){throw Be(i)?new et("Input cancelled by user"):i}}async function d2(r,t,e=!1,n){let i=r.executor?.promptProvider;if(i)return String(await i.suggester(n?.displayValues??t,t,n?.placeholder,e));r.assertInteractivePrompt(n?.variableKey?`{{VALUE:${n.variableKey}}}`:"a value choice");try{let o=n?.displayValues??t;return e?await vr.Suggest(r.app,o,t,{...n?.placeholder?{placeholder:n.placeholder}:{},...n?.optional?{skippable:!0}:{}}):await It.Suggest(r.app,o,t,n?.placeholder,void 0,n?.optional?{skippable:!0}:void 0)}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}async function u2(r,t,e=!1,n){let i=n?.displayValues??t,o=r.executor?.promptProvider;if(o)return await o.suggesterMulti(i,t,{placeholder:n?.placeholder,allowCustomInput:e});r.assertInteractivePrompt(n?.variableKey?`{{VALUE:${n.variableKey}}}`:"a multi-select value");try{return await Fc.Suggest(r.app,i,t,{...n?.placeholder?{placeholder:n.placeholder}:{},allowCustomValue:e,...n?.optional?{skippable:!0}:{}})}catch(s){throw Be(s)?new et("Input cancelled by user"):s}}var p2=x(()=>{yp();wF();cl();Qi();EF();ET();rr();nt()});var hl,TT=x(()=>{hl=class r{constructor(){this.cache=new Map;this.TTL=300*1e3;this.MAX_CACHE_ENTRIES=100;this.cleanupInterval=null;this.revision=0}static getInstance(){return r.instance||(r.instance=new r),r.instance}startAutomaticCleanup(t){if(this.cleanupInterval===null&&typeof window<"u"){let e=window.setInterval(()=>{this.cleanExpired()},6e4);this.cleanupInterval=t(e)}}registerInvalidationListeners(t,e){let n=()=>this.clear();e(t.metadataCache.on("changed",n)),e(t.metadataCache.on("deleted",n)),e(t.vault.on("rename",n))}get(t,e){let n=this.makeKey(t,e),i=this.cache.get(n);return i?Date.now()-i.timestamp>this.TTL?(this.cache.delete(n),null):new Set(i.values):null}set(t,e,n){let i=this.makeKey(t,n);this.cache.size>=this.MAX_CACHE_ENTRIES&&!this.cache.has(i)&&this.evictOldestEntries(1),this.cache.set(i,{fieldName:t,values:new Set(e),timestamp:Date.now()})}getRevision(){return this.revision}setIfRevision(t,e,n,i){return this.revision!==i?!1:(this.set(t,e,n),!0)}evictOldestEntries(t){let e=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp-i.timestamp).slice(0,t);for(let[n]of e)this.cache.delete(n)}clear(t){if(this.revision++,!t){this.cache.clear();return}for(let[e,n]of this.cache)n.fieldName===t&&this.cache.delete(e)}cleanExpired(){let t=Date.now();for(let[e,n]of this.cache)t-n.timestamp>this.TTL&&this.cache.delete(e)}getStats(){return{size:this.cache.size,maxSize:this.MAX_CACHE_ENTRIES,cleanupInterval:this.cleanupInterval}}destroy(){this.cleanupInterval=null,this.clear()}makeKey(t,e){return JSON.stringify([t,e||null])}}});var _T,m2=x(()=>{_T=class{static deduplicate(t,e=!1){let n=new Map;for(let o of t){let s=e?o:o.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase();n.has(s)||n.set(s,o)}let i=Array.from(n.values());return i.sort((o,s)=>e?o.localeCompare(s):o.toLowerCase().localeCompare(s.toLowerCase())),{values:i,duplicatesRemoved:t.length-i.length}}}});var ea,SF=x(()=>{Le();m2();ea=class{static processValues(t,e){let n=t.size,i=Array.from(t).filter(l=>!this.isUnresolvedFieldToken(l)),o=_T.deduplicate(i,e.caseSensitive);i=o.values;let{processedValues:s,hasDefault:a}=this.applyDefaultValues(i,e);return i=s,{values:i,hasDefaultValue:a,duplicatesRemoved:o.duplicatesRemoved,totalProcessed:n}}static isUnresolvedFieldToken(t){return this.unresolvedFieldTokenRegex.test(t.trim())}static applyDefaultValues(t,e){if(!e.defaultValue)return{processedValues:t,hasDefault:!1};let n=e.defaultValue,i=[...t],o=!1,s=a=>e.caseSensitive?a===n:this.normalizeForComparison(a)===this.normalizeForComparison(n);return e.defaultAlways?(i=i.filter(a=>!s(a)),i.unshift(n),o=!0):e.defaultEmpty&&t.length===0?(i=[n],o=!0):!e.defaultEmpty&&!e.defaultAlways&&(i.some(s)||(i.unshift(n),o=!0)),{processedValues:i,hasDefault:o}}static promoteValueToFront(t,e,n=!1){let i=o=>n?o===e:this.normalizeForComparison(o)===this.normalizeForComparison(e);return[e,...t.filter(o=>!i(o))]}static canonicalizeAgainst(t,e,n=!1){if(n)return e;let i=this.normalizeForComparison(e);return t.find(o=>this.normalizeForComparison(o)===i)??e}static normalizeForComparison(t){return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}static getSmartDefaults(t,e){let n={status:["To Do","In Progress","Done","Cancelled"],priority:["High","Medium","Low"],type:["Note","Task","Project","Reference"],category:["Personal","Work","Study"],mood:["\u{1F60A} Good","\u{1F610} Neutral","\u{1F614} Bad"],rating:["\u2B50","\u2B50\u2B50","\u2B50\u2B50\u2B50","\u2B50\u2B50\u2B50\u2B50","\u2B50\u2B50\u2B50\u2B50\u2B50"],progress:["0%","25%","50%","75%","100%"],difficulty:["Easy","Medium","Hard"],size:["Small","Medium","Large"]},i=t.toLowerCase();if(Object.prototype.hasOwnProperty.call(n,i))return n[i];for(let[o,s]of Object.entries(n))if(i.includes(o)||o.includes(i))return s;if(e.length>0){let o=new Map;for(let s of e)o.set(s,(o.get(s)||0)+1);return Array.from(o.entries()).sort((s,a)=>a[1]-s[1]).slice(0,5).map(([s])=>s)}return[]}};ea.unresolvedFieldTokenRegex=new RegExp(`^${dp.source}$`,"i")});function f2(r){if(!r.includes(",")){let o=r.trim();return o?[o]:[]}let t=[],e="",n=!1;for(let o=0;o{});var gl,wf,AF=x(()=>{h2();gl=class gl{static parseInlineFields(t,e){let n=new Map,i=this.removeCodeBlocksAndFrontmatter(t,e),o;for(;(o=gl.INLINE_FIELD_REGEX.exec(i))!==null;){let s=o[1].trim(),a=o[2].trim();if(a){n.has(s)||n.set(s,new Set);for(let l of f2(a))n.get(s)?.add(l)}}return gl.INLINE_FIELD_REGEX.lastIndex=0,n}static removeCodeBlocksAndFrontmatter(t,e){return t=t.replace(this.FRONTMATTER_REGEX,""),t=this.filterFencedCodeBlocks(t,e?.includeCodeBlocks),t.replace(this.INLINE_CODE_SPAN_REGEX,"")}static filterFencedCodeBlocks(t,e){if(!t.includes("```"))return t;let n=new Set((e??[]).map(a=>a.trim().toLowerCase()).filter(a=>a.length>0)),i=t.split(` `),o=[],s=null;for(let a of i){if(!s){let l=this.matchFenceOpen(a);l?s={...l,lines:[a]}:o.push(a);continue}if(this.matchFenceClose(a,s.length)){let l=s.info.trim().split(/\s+/)[0]?.toLowerCase();if(n.size>0&&l!==void 0&&l.length>0&&n.has(l))for(let d=1;d=e}static stripTrailingCarriage(t){return t.endsWith("\r")?t.slice(0,-1):t}static getFieldValues(t,e,n){return this.parseInlineFields(t,n).get(e)||new Set}};gl.INLINE_FIELD_REGEX=/(?:^|[\n\r])(?![ \t]*[-*+][ \t]+\[[ xX]\])([^:\n\r]+?)::[ \t]*(.*)$/gmu,gl.FRONTMATTER_REGEX=/^---\r?\n[\s\S]*?\r?\n---\r?\n/,gl.INLINE_CODE_SPAN_REGEX=/`[^`]*`/g,gl.FENCE_OPEN_REGEX=/^[ \t]*(`{3,})([^`]*)$/,gl.FENCE_CLOSE_REGEX=/^[ \t]*(`{3,})[ \t]*$/;wf=gl});function IF(r){let t=[];return r.folder&&t.push(`folder:${r.folder}`),r.folders?.length&&t.push(`folders:${r.folders.join(",")}`),r.tags&&t.push(`tags:${r.tags.join(",")}`),r.inline&&t.push("inline:true"),r.inlineCodeBlocks?.length&&t.push(`inline-code-blocks:${r.inlineCodeBlocks.join(",")}`),r.caseSensitive&&t.push("case-sensitive:true"),r.excludeFolders&&t.push(`exclude-folders:${r.excludeFolders.join(",")}`),r.excludeTags&&t.push(`exclude-tags:${r.excludeTags.join(",")}`),r.excludeFiles&&t.push(`exclude-files:${r.excludeFiles.join(",")}`),r.defaultValue&&t.push(`default:${r.defaultValue}`),r.defaultEmpty&&t.push("default-empty:true"),r.defaultAlways&&t.push("default-always:true"),t.join("|")}async function g2(r,t,e){return(await PF(r,t,e)).values}async function PF(r,t,e){let n=await Zte(r,t,e),i=ea.processValues(n,e);return{values:i.values,hasDefaultValue:i.hasDefaultValue}}async function Zte(r,t,e){let n=hl.getInstance(),i=IF(e),o=n.get(t,i);if(o)return o;let s=n.getRevision(),a=await $F(r,t,e);return n.setIfRevision(t,a,i,s),a}async function $F(r,t,e){let n=t.trim().toLowerCase();if(n==="tags"||n==="tag"){let i=await ere(r,e);if(i.size>0)return i}return await nre(r,t,e)}async function ere(r,t){if(!(!!t.folder||!!t.folders?.length||!!t.tags?.length||!!t.excludeFolders?.length||!!t.excludeTags?.length||!!t.excludeFiles?.length)){let n=tre(r);if(n.size>0)return n}return await rre(r,t)}function tre(r){let t=new Set;try{let e=r.metadataCache.getTags?.();if(!e)return t;for(let n of Object.keys(e)){let o=(n.startsWith("#")?n.substring(1):n).trim();o&&t.add(o)}}catch{}return t}function Ty(r,t){if(t!=null)for(let e of Array.isArray(t)?t:[t]){let n=String(e).trim();n&&r.add(n)}}async function v2(r,t,e){let n=new Set,i=Vs.filterFiles(r.vault.getMarkdownFiles(),t,o=>r.metadataCache.getFileCache(o));for(let o=0;o{let l=new Set;try{await e(a,l)}catch{}return l}));for(let a of s)for(let l of a)n.add(l)}return n}async function rre(r,t){return v2(r,t,(e,n)=>{let i=r.metadataCache.getFileCache(e);Ty(n,i?.frontmatter?.tags),Ty(n,i?.frontmatter?.tag);for(let o of i?.tags??[]){let s=String(o.tag??"").trim().replace(/^#/,"");s&&n.add(s)}})}async function nre(r,t,e){return v2(r,e,async(n,i)=>{let o=r.metadataCache.getFileCache(n)?.frontmatter?.[t];if(Array.isArray(o)?o.forEach(s=>Ty(i,[s])):typeof o!="object"&&Ty(i,o),e.inline){let s=await r.vault.cachedRead(n);Ty(i,[...wf.getFieldValues(s,t,{includeCodeBlocks:e.inlineCodeBlocks})])}})}var kT=x(()=>{jw();TT();SF();AF()});function ire(r,t){let e=t.trim();if(!e||!r)return null;let n=r[e];if(n===void 0){let i=e.toLowerCase(),o=Object.keys(r).find(s=>s.toLowerCase()===i);o!==void 0&&(n=r[o])}if(n==null)return null;if(Array.isArray(n)){let i=[];for(let o of n){let s=y2(o);s!==null&&i.push(s)}return i.length>0?i:null}return y2(n)}function ST(r,t,e){if(!t||t.extension!=="md")return null;let n=r.metadataCache.getFileCache(t)?.frontmatter;return ire(n,e)}function y2(r){if(r==null)return null;let t=typeof r;if(t==="string"||t==="number"||t==="boolean"){let e=String(r).trim();return e.length>0?e:null}return null}var FF=x(()=>{});async function b2({app:r,executor:t,getSourcePath:e},n){let i=t?.promptProvider;try{let{fieldName:o,filters:s,multiSelect:a,label:l}=Dn.parse(n),c=s.defaultFrom==="active"?ST(r,t?.triggerContext?.activeFile??null,o):null,{values:d,hasDefaultValue:u}=await PF(r,o,s),p=d,m=u,h=s.defaultValue;!a&&typeof c=="string"?(p=ea.promoteValueToFront(p,c,s.caseSensitive),h=c,m=!0):!a&&Array.isArray(c)&&c.length>0&&S.logMessage(`{{FIELD:${o}|default-from:active}}: the active note's "${o}" is a list value, which applies only to |multi FIELD prompts, so no default was prefilled.`);let g=l??`Enter value for ${o}`,v=a&&!l?`Select values for ${o}`:g;if(m&&h&&(v=`${v} (default: ${h})`),a){let b=p;if(p.length===0&&!s.defaultValue){let C=ea.getSmartDefaults(o,[]);C.length>0&&(b=C)}let y=c===null?void 0:(Array.isArray(c)?c:[c]).map(C=>ea.canonicalizeAgainst(b,C,s.caseSensitive));return i?await i.suggesterMulti(b,b,{placeholder:v,allowCustomInput:!0,preselected:y&&y.length>0?y:void 0}):await Fc.Suggest(r,b,b,{placeholder:v,allowCustomValue:!0,...y&&y.length>0?{preselected:y}:{}})}if(p.length===0){let b="No existing values were found in your vault.";if(!s.defaultValue){let y=ea.getSmartDefaults(o,[]);y.length>0&&(b+=` Suggested values for ${o}: ${y.slice(0,3).join(", ")}`)}return i?await i.inputPrompt(g,b):await ir.Prompt(r,g,b,void 0,void 0,{allowPeek:!0,linkSourcePath:e()??void 0})}return i?String(await i.suggester(p,p,v,!0)):await vr.Suggest(r,p,p,{placeholder:v})}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}async function w2({app:r,executor:t,getSourcePath:e},n){let i=t?.promptProvider;try{let o=Vp(r,n),s=n.label??`Select a file from ${n.folderPath}`;if(o.length===0){let p=`No matching files found in "${n.folderPath}". Type a value or leave empty.`,m=i?await i.inputPrompt(s,p):await ir.Prompt(r,s,p,void 0,void 0,{optional:n.optional||void 0,allowPeek:!0});return n.multiSelect?m?[`${Jo}${m}`]:[]:m?`${Jo}${m}`:""}let a=Ds(o,p=>r.metadataCache.getFileCache(p)),l=a.map(p=>p.label),c=a.map(p=>p.aliases),d=o.map(p=>`${Jl}${p.path}`);if(n.multiSelect)return(i?(await i.suggesterMulti(l,d,{placeholder:s,allowCustomInput:n.allowCustomInput})).map(m=>d.includes(m)?m:Dd(d,c,m)??m):await Fc.Suggest(r,l,d,{placeholder:s,allowCustomValue:n.allowCustomInput,aliases:c,...n.optional?{skippable:!0}:{}})).map(m=>d.includes(m)?m:`${Jo}${m}`);if(i){let p=String(await i.suggester(l,d,s,n.allowCustomInput));return p?d.includes(p)?p:Dd(d,c,p)??`${Jo}${p}`:""}if(n.allowCustomInput){let p=new Set(o.map(g=>g.basename.toLowerCase())),m=new Set([...l,...c.flat()].map(g=>g.toLowerCase())),h=await vr.Suggest(r,l,d,{placeholder:s,aliases:c,valueExists:g=>p.has(g.toLowerCase())||m.has(g.toLowerCase()),...n.optional?{skippable:!0}:{}});return h?d.includes(h)?h:`${Jo}${h}`:""}return await It.Suggest(r,l,d,s,void 0,{aliases:c,...n.optional?{skippable:!0}:{}})??""}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}var C2=x(()=>{Gs();cl();EF();Qi();Da();kT();SF();FF();Ln();rr();nt();ye();bi()});function are(r){return`\\begin{${r}} \u261A \\end{${r}}\u261A`}var ore,sre,x2,MF=x(()=>{ore=["\\!","\\,","\\:","\\>","\\;","\\#","\\$","\\%","\\&","\\","_","{ }","|","^{\u261A}\u261A","[\u261A]\u261A","\\above","\\abovewithdelims","\\acute","\\aleph","\\alpha","\\amalg","\\And","\\angle","\\approx","\\approxeq","\\arccos","\\arcsin","\\arctan","\\arg","\\array","\\arrowvert","\\Arrowvert","\\ast","\\asymp","\\atop","\\atopwithdelims","\\backepsilon","\\backprime","\\backsim","\\backsimeq","\\backslash","\\bar","\\barwedge","\\Bbb","\\Bbbk","\\because","\\begin","\\beta","\\beth","\\between","\\bf","\\Bigg","\\bigg","\\Big","\\big","\\Biggl","\\Biggm","\\Biggr","\\biggl","\\biggm","\\biggr","\\Bigl","\\Bigm","\\Bigl","\\bigl","\\bigm","\\bigr","\\bigcap","\\bigcirc","\\bigcup","\\bigodot","\\bigoplus","\\bigotimes","\\bigsqcup","\\bigstar","\\bigtriangledown","\\bigtriangleup","\\biguplus","\\bigvee","\\bigwedge","\\binom","\\blacklozenge","\\blacksquare","\\blacktriangle","\\blacktriangledown","\\blacktriangleleft","\\blacktriangleright","\\bmod","\\boldsymbol","\\bot","\\bowtie","\\Box","\\boxdot","\\boxed","\\boxminus","\\boxplus","\\boxtimes","\\brace","\\bracevert","\\brack","\\breve","\\bullet","\\Bumpeq","\\bumpeq","\\cal","\\cancel","\\Cap","\\cap","\\cases","\\cdot","\\cdotp","\\cdots","\\centerdot","\\cfrac{\u261A}{\u261A}\u261A","\\check","\\checkmark","\\chi","\\choose","\\circ","\\circeq","\\circlearrowleft","\\circlearrowright","\\circledast","\\circledcirc","\\circleddash","\\circledR","\\circledS","\\class","\\clubsuit","\\colon","\\color","\\complement","\\cong","\\coprod","\\cos","\\cosh","\\cot","\\coth","\\cr","\\csc","\\cssId","\\Cup","\\cup","\\curlyeqprec","\\curlyeqsucc","\\curlyvee","\\curlywedge","\\curvearrowleft","\\curvearrowright","\\dagger","\\ddagger","\\daleth","\\dashleftarrow","\\dashrightarrow","\\dashv","\\dbinom","\\dot","\\ddot","\\dddot","\\ddddot","\\ddots","\\DeclareMathOperator","\\def","\\deg","\\Delta","\\delta","\\det","\\dfrac{\u261A}{\u261A}\u261A","\\diagdown","\\diagup","\\Diamond","\\diamond","\\diamondsuit","\\digamma","\\dim","\\displaylines","\\displaystyle","\\div","\\divideontimes","\\Doteq","\\doteq","\\dotplus","\\dots","\\dotsb","\\dotsc","\\dotsi","\\dotsm","\\dotso","\\doublebarwedge","\\doublecap","\\doublecup","\\downarrow","\\Downarrow","\\downdownarrows","\\downharpoonleft","\\downharpoonright","\\ell","\\emptyset","\\end","\\enspace","\\epsilon","\\eqalign","\\eqalignno","\\eqcirc","\\eqsim","\\eqslantgtr","\\eqslantless","\\equiv","\\eta","\\eth","\\exists","\\exp","\\fallingdotseq","\\fbox","\\Finv","\\flat","\\forall","\\frac{\u261A}{\u261A}\u261A","\\frak","\\frown","\\Game","\\Gamma","\\gamma","\\gcd","\\ge","\\geq","\\geqq","\\geqslant","\\genfrac","\\gets","\\gg","\\ggg","\\gggtr","\\gimel","\\gtrapprox","\\gnapprox","\\gneq","\\gneqq","\\gvertneqq","\\gtrsim","\\gnsim","\\grave","\\gt","\\gtrdot","\\gtreqless","\\gtreqqless","\\gtrless","\\hat","\\hbar","\\hbox","\\hdashline","\\hline","\\heartsuit","\\hfil","\\hfill","\\hom","\\hookleftarrow","\\hookrightarrow","\\hphantom","\\href","\\hskip","\\hslash","\\hspace","\\Huge","\\huge","\\iddots","\\idotsint","\\iff","\\iiiint","\\iiint","\\iint","\\int","\\intop","\\Im","\\imath","\\impliedby","\\implies","\\in","\\inf","\\infty","\\injlim","\\intercal","\\iota","\\it","\\jmath","\\Join","\\kappa","\\ker","\\kern","\\Lambda","\\lambda","\\land","\\langle","\\LARGE","\\Large","\\large","\\LaTeX","\\lbrace","\\lbrack","\\lceil","\\ldotp","\\ldots","\\le","\\leq","\\leqq","\\leqslant","\\leadsto","\\left","\\leftarrow","\\Leftarrow","\\leftarrowtail","\\leftharpoondown","\\leftharpoonup","\\leftleftarrows","\\leftrightarrow","\\Leftrightarrow","\\leftrightarrows","\\leftrightharpoons","\\leftrightsquigarrow","\\leftroot","\\leftthreetimes","\\leqalignno","\\lessapprox","\\lessdot","\\lesseqgtr","\\lesseqqgtr","\\lessgtr","\\lesssim","\\lfloor","\\lg","\\lgroup","\\lhd","\\lim","\\liminf","\\limits","\\limsup","\\ll","\\llap","\\llcorner","\\lrcorner","\\Lleftarrow","\\lll","\\llless","\\lmoustache","\\ln","\\lnapprox","\\lneq","\\lneqq","\\lnot","\\lnsim","\\log","\\longleftarrow","\\Longleftarrow","\\longrightarrow","\\Longrightarrow","\\longleftrightarrow","\\Longleftrightarrow","\\longmapsto","\\looparrowleft","\\looparrowright","\\lor","\\lower","\\lozenge","\\Lsh","\\lt","\\ltimes","\\lvert","\\lVert","\\lvertneqq","\\maltese","\\mapsto","\\mathbb","\\mathbf","\\mathbin","\\mathcal","\\mathchoice","\\mathclose","\\mathfrak","\\mathinner","\\mathit","\\mathop","\\mathopen","\\mathord","\\mathpunct","\\mathrel","\\mathring","\\mathrm","\\mathscr","\\mathsf","\\mathstrut","\\mathtt","\\matrix","\\max","\\mbox","\\measuredangle","\\mho","\\mid","\\min","\\mit","\\mod","\\models","\\moveleft","\\moveright","\\mp","\\mskip","\\mspace","\\mu","\\multimap","\\nabla","\\natural","\\ncong","\\ne","\\nearrow","\\neg","\\negthinspace","\\negmedspace","\\negthickspace","\\neq","\\newcommand","\\newenvironment","\\newline","\\nexists","\\ngeq","\\ngeqq","\\ngeqslant","\\ngtr","\\ni","\\nleftarrow","\\nLeftarrow","\\nleftrightarrow","\\nLeftrightarrow","\\nleq","\\nleqq","\\nleqslant","\\nless","\\nmid","\\nobreakspace","\\nolimits","\\normalsize","\\not","\\notag","\\notin","\\nparallel","\\nprec","\\npreceq","\\nrightarrow","\\nRightarrow","\\nshortmid","\\nshortparallel","\\nsim","\\nsubseteq","\\nsubseteqq","\\nsucc","\\nsucceq","\\nsupseteq","\\nsupseteqq","\\ntriangleleft","\\ntrianglelefteq","\\ntriangleright","\\ntrianglerighteq","\\nu","\\nVDash","\\nVdash","\\nvDash","\\nvdash","\\nwarrow","\\odot","\\ominus","\\oplus","\\oslash","\\otimes","\\oint","\\oldstyle","\\omega","\\Omega","\\omicron","\\operatorname","\\over","\\overbrace","\\overleftarrow","\\overrightarrow","\\overleftrightarrow","\\overline","\\overparen","\\overset","\\overwithdelims","\\owns","\\parallel","\\partial","\\perp","\\phantom","\\phi","\\Phi","\\pi","\\Pi","\\pitchfork","\\pm","\\pmatrix","\\pmb","\\pmod","\\pod","\\Pr","\\prec","\\precapprox","\\precnapprox","\\preccurlyeq","\\preceq","\\precneqq","\\precsim","\\precnsim","\\prime","\\prod","\\projlim","\\propto","\\psi","\\Psi","\\quad","\\qquad","\\raise","\\rangle","\\rbrace","\\rbrack","\\rceil","\\Re","\\renewcommand","\\require (non-standard)","\\restriction","\\rfloor","\\rgroup","\\rhd","\\rho","\\right","\\rightarrow","\\Rightarrow","\\rightarrowtail","\\rightharpoondown","\\rightharpoonup","\\rightleftarrows","\\rightleftharpoons","\\rightrightarrows","\\rightsquigarrow","\\rightthreetimes","\\risingdotseq","\\rlap","\\rm","\\rmoustache","\\Rrightarrow","\\Rsh","\\rtimes","\\Rule (non-standard)","\\rvert","\\rVert","\\S","\\scr","\\scriptscriptstyle","\\scriptsize","\\scriptstyle","\\searrow","\\sec","\\setminus","\\sf","\\sharp","\\shortmid","\\shortparallel","\\shoveleft","\\shoveright","\\sideset","\\sigma","\\Sigma","\\sim","\\simeq","\\sin","\\sinh","\\skew","\\small","\\smallfrown","\\smallint","\\smallsetminus","\\smallsmile","\\smash","\\smile","\\space","\\Space (non-standard)","\\spadesuit","\\sphericalangle","\\sqcap","\\sqcup","\\sqrt","\\sqsubset","\\sqsupset","\\sqsubseteq","\\sqsupseteq","\\square","\\stackrel","\\star","\\strut","\\style","\\subset","\\Subset","\\subseteq","\\subsetneq","\\subseteqq","\\subsetneqq","\\substack","\\succ","\\succapprox","\\succnapprox","\\succcurlyeq","\\succeq","\\succneqq","\\succsim","\\succnsim","\\sum","\\sup","\\supset","\\Supset","\\supseteq","\\supsetneq","\\supseteqq","\\supsetneqq","\\surd","\\swarrow","\\tag","\\tan","\\tanh","\\tau","\\tbinom","\\TeX","\\text{\u261A}\u261A","\\textbf{\u261A}\u261A","\\textit{\u261A}\u261A","\\textrm{\u261A}\u261A","\\textsf{\u261A}\u261A","\\texttt{\u261A}\u261A","\\textstyle","\\tfrac{\u261A}{\u261A}\u261A","\\therefore","\\theta","\\Theta","\\thickapprox","\\thicksim","\\thinspace","\\tilde","\\times","\\tiny","\\Tiny","\\to","\\top","\\triangle","\\triangledown","\\triangleleft","\\triangleright","\\trianglelefteq","\\trianglerighteq","\\triangleq","\\tt","\\twoheadleftarrow","\\twoheadrightarrow","\\ulcorner","\\urcorner","\\underbrace","\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\underline","\\underparen","\\underset","\\unicode","\\unlhd","\\unrhd","\\uparrow","\\Uparrow","\\updownarrow","\\Updownarrow","\\upharpoonleft","\\upharpoonright","\\uplus","\\uproot","\\upsilon","\\Upsilon","\\upuparrows","\\varDelta","\\varepsilon","\\varGamma","\\varinjlim","\\varkappa","\\varLambda","\\varlimsup","\\varliminf","\\varnothing","\\varOmega","\\varphi","\\varPhi","\\varpi","\\varPi","\\varprojlim","\\varpropto","\\varPsi","\\varrho","\\varsigma","\\varSigma","\\varsubsetneq","\\varsubsetneqq","\\varsupsetneq","\\varsupsetneqq","\\vartheta","\\varTheta","\\vartriangle","\\vartriangleleft","\\vartriangleright","\\varUpsilon","\\varXi","\\vcenter","\\vdash","\\Vdash","\\vDash","\\vdots","\\vec","\\vee","\\veebar","\\verb","\\vert","\\Vert","\\vphantom","\\Vvdash","\\wedge","\\widehat","\\widetilde","\\wp","\\wr","\\Xi","\\xi","\\xleftarrow","\\xrightarrow","\\yen","\\zeta","\\{%C\\}%C","\\langle %C \\rangle%C"],sre=["align","align*","alignat","alignat*","array","Bmatrix","bmatrix","cases","eqnarray","eqnarray*","equation","equation*","gather","gather*","matrix","pmatrix","smallmatrix","subarray","Vmatrix","vmatrix"];x2=[...ore,...sre.map(are)]});function cre(r){if(RF.has(r))return RF.get(r)??null;let t=null;try{t=(0,E2.renderMath)(r,!0)}catch{t=null}return RF.set(r,t),t}function dre(r){return OF===null&&(OF=new kc(r,{findAllMatches:!0,threshold:.8})),OF}var E2,lre,RF,OF,AT,T2=x(()=>{Ms();wx();E2=require("obsidian");MF();ss();lre=new RegExp(/\\([a-z{}A-Z0-9]*)$/),RF=new Map,OF=null;AT=class extends Er{constructor(e){super(Wr().app,e);this.inputEl=e;this.lastInput="";this.symbols=Object.assign([],x2)}getSuggestions(e){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=e.slice(0,n),o=i.lastIndexOf("\\"),s=i.slice(o),a=lre.exec(s),l=[];a&&(this.lastInput=a[1],l=this.symbols.filter(u=>u.toLowerCase().contains(this.lastInput)));let c=new Set(l);return dre(this.symbols).search(this.lastInput).map(u=>u.item).filter(u=>c.has(u))}renderSuggestion(e,n){if(e){n.setText(e);let i=cre(e);i&&n.append(i.cloneNode(!0))}}selectSuggestion(e){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.lastInput.length,o=this.inputEl.value,s=0,a=e.replace(/\\\\/g,"\\");if(this.inputEl.value=`${o.slice(0,n-i-1)}${a}${o.slice(n)}`,s=n-i+e.length-1,this.inputEl.trigger("input"),this.close(),e.contains("\u261A")){let l=this.inputEl.value.indexOf("\u261A");this.inputEl.value=this.inputEl.value.replace("\u261A",""),this.inputEl.setSelectionRange(l,l)}else this.inputEl.setSelectionRange(s,s)}}});var Si,IT,_2=x(()=>{Si=require("obsidian");ss();MF();T2();rr();IT=class r extends Si.Modal{constructor(){super(Wr().app);this.didSubmit=!1;this.keybindListener=e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&this.submit(),e.key==="Tab"&&(e.preventDefault(),this.cursorToGoTo())};this.submitClickCallback=e=>this.submit();this.cancelClickCallback=e=>this.cancel();this.open(),this.display(),this.waitForClose=new Promise((e,n)=>{this.resolvePromise=e,this.rejectPromise=n}),new AT(this.inputEl),this.inputEl.focus(),this.inputEl.select()}static Prompt(){return new r().waitForClose}display(){this.containerEl.addClass("quickAddModal","qaMathModal"),this.contentEl.empty();let e=this.contentEl.createDiv();e.className="math math-block is-loaded";let n=new Si.TextAreaComponent(this.contentEl);n.inputEl.setCssStyles({width:"100%",height:"10rem"}),this.inputEl=n.inputEl,n.onChange((0,Si.debounce)(async o=>await this.mathjaxLoop(e,o),50)),n.inputEl.addEventListener("keydown",this.keybindListener),this.contentEl.createDiv({text:"Ctrl/Cmd+Enter to submit \xB7 Tab to jump to the cursor marker",cls:"setting-item-description"}).setCssStyles({marginTop:"0.5rem"}),this.createButtonBar(this.contentEl.createDiv())}async onOpen(){super.onOpen(),await(0,Si.loadMathJax)()}async mathjaxLoop(e,n){let i=(0,Si.renderMath)(n,!0);await(0,Si.finishRenderMath)(),e.empty(),e.append(i)}cursorToGoTo(){if(this.inputEl.value.contains("\u261A")){let e=this.inputEl.value.indexOf("\u261A");this.inputEl.value=this.inputEl.value.replace("\u261A",""),this.inputEl.setSelectionRange(e,e)}}createButton(e,n,i){let o=new Si.ButtonComponent(e);return o.setButtonText(n).onClick(i),o}createButtonBar(e){let n=e.createDiv();this.createButton(n,"Ok",this.submitClickCallback).setCta().buttonEl.setCssStyles({marginRight:"0"}),this.createButton(n,"Cancel",this.cancelClickCallback),n.setCssStyles({display:"flex",flexDirection:"row-reverse",justifyContent:"flex-start",marginTop:"1rem",gap:"0.5rem"})}removeInputListeners(){this.inputEl.removeEventListener("keydown",this.keybindListener)}resolveInput(){let e=this.inputEl.value.replace(/\\n/g,"\\\\n").replace(new RegExp("\u261A","g"),"");this.didSubmit?this.resolvePromise(e):this.rejectPromise(on())}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListeners()}}});function PT(r){return r?.triggerContext?.named===!0}function kr(r,t){let e=t?.triggerContext;return e?.named?e.activeFile:r.workspace.getActiveFile()}function DF(r,t){let e=Un(r),n=t?.triggerContext;return n?.named?n.activeFile&&e?.file?.path===n.activeFile.path?e:null:e}function Cf(r,t){return DF(r,t)?.editor.getSelection()??""}var vl=x(()=>{sl()});function yu(r){return r.replace(ure," ").replace(/\s+/g," ").trim()}function k2(r){return!(r.trim()===""||/^( {4,}|\t)/.test(r)||/^ {0,3}#{1,6}[ \t]/.test(r)||/^ {0,3}(`{3,}|~{3,})/.test(r)||/^ {0,3}>/.test(r)||/^ {0,3}([-*+]|\d{1,9}[.)])[ \t]/.test(r)||/^ {0,3}(=+|-+)\s*$/.test(r)||/^ {0,3}([*_-])([ \t]*\1){2,}[ \t]*$/.test(r))}function S2(r,t){return r[t.line]?.trim()===t.heading?t.line+1:t.line}function LF(r){let t=r.map(()=>!1),e=r.map(s=>s.replace(/\r$/,"")),n=0;if(e.length>0&&/^---\s*$/.test(e[0])){let s=1;for(;s=i.length&&(i=null);continue}let a=s.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);if(a&&!(a[1][0]==="`"&&a[2].includes("`"))){t[n]=!0,i={char:a[1][0],length:a[1].length};continue}let l=s.match(/^ {0,3}(%%|\$\$)(.*)$/),c=n>0&&/^\s*([-*+]|\d{1,9}[.)])[ \t]/.test(e[n-1]);if(l&&!(l[1]==="$$"&&c)){let d=l[1],u=l[2];(d==="%%"?u.includes("%%"):u.trimEnd().length>2&&u.trimEnd().endsWith("$$"))||(t[n]=!0,o=d)}}return t}function pre(r,t){return r==="%%"?t.includes("%%"):t.trimEnd().endsWith("$$")}function si(r){let t=[],e=LF(r);for(let n=0;n0){let a=r[n-1],l=t.length>0&&t[t.length-1].line===n-1,c=n<2||e[n-2]||!k2(r[n-2]);!l&&!e[n-1]&&c&&k2(a)&&t.push({heading:a.trim(),level:s[1][0]==="="?1:2,line:n-1});continue}}return t}function mre(r,t){let e=[],n=yu(r[t].heading);n&&e.push(n);let i=r[t].level;for(let o=t-1;o>=0&&i>1;o--)if(r[o].levelu!==e&&yu(d.heading).toLowerCase()===i))return`#${n}`;let s=mre(r,e);if(s.length<2)return null;let a=s.join("#"),l=a.toLowerCase();return fre(r).some((d,u)=>u!==e&&d===l)?null:`#${a}`}function fre(r){let t=new Array(r.length),e=[];for(let n=0;n0&&r[e[e.length-1]].level>=r[n].level;)e.pop();let i=e.length>0?t[e[e.length-1]]:[],o=yu(r[n].heading);t[n]=o?[...i,o]:i,e.push(n)}return t.map(n=>n.join("#").toLowerCase())}var ure,bu=x(()=>{ure=/[!"#$%&()*+,.:;<=>?@^`{|}~/[\]\\\r\n]/g});async function $T(r,t,e,n){return await ix(r,e,n)&&await t.saveSettings?.(),fB(r,e,n)}var VF=x(()=>{nl()});function _y(r,t){let e=t.findIndex(n=>n.id===r.id);if(e!==-1){let n=[...t.slice(e),r].map(i=>i.name).join(" -> ");throw new Error(`${r.type} "${r.name}" calls itself: ${n}`)}return[...t,r]}function A2(){return FT}function I2(r,t){let e=FT;FT=r;try{return t()}finally{FT=e}}var FT,MT=x(()=>{FT=[]});function Dc(r,{logPrefix:t,noticePrefix:e=t,defaultReason:n}){if(!(r instanceof at))return!1;if(P2.has(r))return!0;P2.add(r);let i=typeof r.message=="string"&&r.message.trim().length>0?r.message:n,o=a=>i===a?a:`${a}: ${i}`;return S.logMessage(o(t)),(!(r instanceof et||typeof r.message=="string"&&r.message.toLowerCase().includes("cancelled by user"))||U.getState().showInputCancellationNotification)&&new $2.Notice(o(e)),!0}var $2,P2,ky=x(()=>{$2=require("obsidian");ri();rr();je();ye();P2=new WeakSet});var F2={};cb(F2,{SingleMacroEngine:()=>BF});function gre(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);if(typeof r=="bigint"||typeof r=="symbol")return r.toString();if(r instanceof Error)return r.message;try{return JSON.stringify(r)}catch{return Object.prototype.toString.call(r)}}var hre,BF,M2=x(()=>{ye();er();au();lt();lx();VF();Sy();MT();ky();Gr();ri();hre=new Set(["settings","entry","quickadd"]);BF=class{constructor(t,e,n,i,o){this.app=t;this.plugin=e;this.choices=n;this.emittedConflictNotice=!1;this.choiceExecutor=i,o?(this.variables=o,this.choiceExecutor.variables=o):i.variables?this.variables=i.variables:(this.variables=new Map,this.choiceExecutor.variables=this.variables)}async runAndGetOutput(t,e,n=[]){this.emittedConflictNotice=!1;let{basename:i,memberAccess:o}=Fm(t),s=d=>(d??"").trim(),a=Zt(this.choices).find(d=>d.type==="Macro"&&s(d.name)===s(i));if(!a){let d=p=>s(p).toLowerCase(),u=Zt(this.choices).filter(p=>p.type==="Macro"&&d(p.name)===d(i));if(u.length>1)throw S.logError(`Ambiguous macro reference '${t}'. Multiple choices match when ignoring case.`),new Error(`Ambiguous macro reference '${t}'. Please disambiguate by renaming macros.`);a=u[0]}if(!a)throw S.logError(`macro '${t}' does not exist.`),new Error(`macro '${t}' does not exist.`);let l=new ta(this.app,this.plugin,a,this.choiceExecutor,this.variables,void 0,e?.label,null,_y(a,n));if(o?.length){let d=await this.tryExecuteExport(l,a,o);if(this.ensureNotAborted(),d.executed)return this.formatResult(d.result)}await l.run(),this.ensureNotAborted();let c=l.getOutput();if(o?.length){let d=this.resolveMemberAccess(c,o);d.found||S.logWarning(`Macro '${a.name}' was asked for member '${o.join("::")}', but it has no user script exporting it; the result is empty.`),c=d.value}return typeof c=="function"?c=await c():c&&typeof c=="object"&&(c=JSON.stringify(c)),gre(c)}getVariables(){return this.variables}async tryExecuteExport(t,e,n){let i=Mt(e.macro?.commands);if(!i.length)return{executed:!1};let o=i.map((c,d)=>({command:c,index:d})).filter(c=>Tr(c.command)&&c.command.type==="UserScript");if(o.length===0)return{executed:!1};let s=await this.selectUserScriptCandidate(e,o,n),a=s.candidate.command.id,l=i.slice(0,s.candidate.index);try{l.length&&(await t.runSubset(l),this.ensureNotAborted());let c=e.macro?.commands,d=Lv(c)?c:i,u;a!==void 0?u=d.findIndex(w=>Tr(w)&&w.id===a&&w.type==="UserScript"):u=s.candidate.index;let p=u>=0?d[u]:void 0;if(!p||p.type!=="UserScript")throw new at(`Could not resolve the member-access script for '${e.name}'.`);let m=p;m.settings||(m.settings={});let h=s.candidate.exportsRef!==void 0?s.candidate.exportsRef:await Nv(m,this.app);if(h==null)throw new at(`Macro '${e.name}' could not load '${m.name}' for member access.`);let g=typeof h=="object"||typeof h=="function"?h.settings:void 0;g&&typeof g=="object"&&Pm(m.settings,g);let v=s.candidate.resolvedMember??this.resolveMemberAccess(h,s.memberAccess);if(!v.found)throw new at(`Macro '${e.name}' routes member access to '${m.name}', but that script does not export '${s.memberAccess.join("::")}'.`);let b=d.slice(u+1),y=m.settings;typeof v.value=="function"&&(y=await $T(this.app,this.plugin,m,g&&typeof g=="object"?g:void 0));let C=await this.executeResolvedMember(v.value,t,y);return this.ensureNotAborted(),t.setOutput(C),this.syncVariablesFromParams(t),b.length&&(await t.runSubset(b),this.ensureNotAborted()),{executed:!0,result:C}}catch(c){throw Dc(c,{logPrefix:"Macro execution aborted",noticePrefix:"Macro execution aborted",defaultReason:"Macro execution aborted"})&&this.choiceExecutor.signalAbort?.(c),c}}resolveMemberAccess(t,e){let n=t;for(let i of e){if(n==null||typeof n!="object"&&typeof n!="function")return{found:!1};let o=n;if(!(i in o))return{found:!1};n=o[i]}return{found:!0,value:n}}async executeResolvedMember(t,e,n){return typeof t=="function"?await t(e.params,n):t}async selectUserScriptCandidate(t,e,n){if(e.length===1)return{candidate:{command:e[0].command,index:e[0].index},memberAccess:n};let i=this.resolveScriptSelector(t,e,n);if(i)return{candidate:{command:i.command,index:i.index},memberAccess:i.memberAccess};let o=[];for(let l of e){let c=await Nv(l.command,this.app);o.push({command:l.command,index:l.index,exportsRef:c,resolvedMember:this.resolveMemberAccess(c,n)})}let s=o.filter(l=>l.resolvedMember.found);if(s.length===1)return{candidate:s[0],memberAccess:n};if(s.length===0)throw new at(`Macro '${t.name}' could not find '${n.join("::")}' in any user script.`);if(hre.has(n[0])){let l=s[0];return this.warnReservedKeyConflict(t,n,l,s),{candidate:l,memberAccess:n}}let a=s.map(l=>`'${l.command.name}'`).join(", ");throw new at(`Macro '${t.name}' has multiple user scripts exporting '${n.join("::")}': ${a}. Disambiguate with '{{MACRO:${t.name}::