| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391 |
- /*
- THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
- if you want to view the source, please visit the github repository of this plugin
- */
- var Fj=Object.create;var zf=Object.defineProperty;var Mj=Object.getOwnPropertyDescriptor;var Rj=Object.getOwnPropertyNames;var Dj=Object.getPrototypeOf,Oj=Object.prototype.hasOwnProperty;var rR=r=>{throw TypeError(r)};var Lj=(r,t,e)=>t in r?zf(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 eb=(r,t)=>{for(var e in t)zf(r,e,{get:t[e],enumerable:!0})},nR=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Rj(t))!Oj.call(r,i)&&i!==e&&zf(r,i,{get:()=>t[i],enumerable:!(n=Mj(t,i))||n.enumerable});return r};var Nj=(r,t,e)=>(e=r!=null?Fj(Dj(r)):{},nR(t||!r||!r.__esModule?zf(e,"default",{value:r,enumerable:!0}):e,r)),Vj=r=>nR(zf({},"__esModule",{value:!0}),r);var fe=(r,t,e)=>Lj(r,typeof t!="symbol"?t+"":t,e),ik=(r,t,e)=>t.has(r)||rR("Cannot "+e);var L=(r,t,e)=>(ik(r,t,"read from private field"),e?e.call(r):t.get(r)),qe=(r,t,e)=>t.has(r)?rR("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),De=(r,t,e,n)=>(ik(r,t,"write to private field"),n?n.call(r,e):t.set(r,e),e),tt=(r,t,e)=>(ik(r,t,"access private method"),e);var HD,WD,GD=x(()=>{HD=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},WD=(r=>r?HD(r):HD)});function xh(r){if(r.kind)return r.kind;let t=(r.name??"").toLowerCase(),e=YD(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 jD(r){let t=xh(r);return t==="openai"&&YD(r.endpoint)==="api.openai.com"?"openai-responses":t}function YD(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 aK(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Ub(r,t){let e=aK(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 qb(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=Ub(n.id??n.name,r),e.add(n.id),t=!0}return t}function $l(r,t){return t&&t.name===r?t:void 0}function np(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&&i<o?1:-1:1:t.index-e.index}).map(({model:t})=>t)}function zb(r){return Eh[r].map(t=>({...t}))}var Eh,KD,lK,cK,Hb,fi=x(()=>{Eh={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}]},KD={openai:["gpt-4-32k","gpt-4-1106-preview"],google:["gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"]};lK={id:"openai",name:"OpenAI",endpoint:"https://api.openai.com/v1",kind:"openai",apiKey:"",models:zb("openai"),autoSyncModels:!0,modelSource:"modelsDev"},cK={id:"gemini",name:"Gemini",endpoint:"https://generativelanguage.googleapis.com",kind:"gemini",apiKey:"",models:zb("google"),autoSyncModels:!0,modelSource:"modelsDev"},Hb=[lK,cK]});function QD(r,t){return Object.prototype.hasOwnProperty.call(r,t)?r[t]:void 0}function Th(r,t=ip){let e=r.trim();if(!e)return r;let n=QD(t,e.toLowerCase());if(n)return n;let[i,...o]=e.split(/\s+/),s=QD(t,i.toLowerCase());return s?[s,...o].join(" "):r}function XD(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 lS(r){return Object.entries(r).filter(([t,e])=>t&&e).map(([t,e])=>`${t} = ${e}`).join(`
- `)}function _h(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 Wb(r){return _h(r).map(([t,e])=>`${t}=${e}`).join(", ")}var ip,gd=x(()=>{ip={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 Gb,cS=x(()=>{fi();gd();Gb={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:ip,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:Hb,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 Fl(r,new Map)}function Fl(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(Fl(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(Fl(o,t),Fl(s,t));return i}if(r instanceof Set){let i=new Set;t.set(r,i);for(let o of r.values())i.add(Fl(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(Fl(r.buffer,t),r.byteOffset,r.byteLength);return t.set(r,a),a}let i=r,o=Fl(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:Fl(o,t),writable:!0,enumerable:!0,configurable:!0});return n}var Zr=x(()=>{});var U,je=x(()=>{GD();cS();Zr();U=(()=>{let r=WD((i,o)=>({...ke(Gb)})),{getState:t,setState:e,subscribe:n}=r;return{getState:t,replaceState:i=>e(i,!0),setState:e,subscribe:n}})()});var vd,kh,S,ye=x(()=>{vd=class vd{register(t){return vd.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;vd.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;vd.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;vd.loggers.forEach(o=>o.logMessage(e,n,i))}};vd.loggers=[];kh=vd,S=new kh});var Cr,JD,ZD,Oi,yd,bd,Wo,eO,dS,tO,uS,co,wd,Ml,op,jb,Ts,pS,mS,xt,lr,Mn,Sh,Yb,_s,Kb,Ah,uo,Ih,fS,hS,gS,rO,nO,iO,oO,sO,aO,lO,cO,dO,uO,pO,vS,mO,fO,hO,gO,vO,yO,bO,wO,CO,xO,EO,yS,bS,wS,CS,xS,TO,_O,kO,SO,Qb,Ph,Ta,AO,Ve=x(()=>{Cr="{{value}}",JD="{{name}}",ZD=new RegExp(/^-?[0-9]*$/),Oi="top",yd="bottom",bd="cursor",Wo="ordered",eO=new RegExp(/{{DATE(\+-?[0-9]+)?(?:\|((?:startof|endof):[a-z]+))?(?:\|case:([a-z-]+))?}}/i),dS=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),tO=new RegExp(/{{TIME(?:\|case:([a-z-]+))?}}/i),uS=new RegExp(/{{TIME:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|[]|\|(?!(?:case):[a-z-]+}}))*)(?:\|case:([a-z-]+))?}}/i),co=new RegExp(/{{(?:NAME|VALUE)(?!:)(?:\|[^\n\r}]*)?}}/i),wd=new RegExp(/{{VALUE:([^\n\r}]*)}}/i),Ml="FIELD:",op=new RegExp(/{{FIELD:([^\n\r}|{]*)(\|[^\n\r}{]*)?}}/i),jb=new RegExp(/{{FILE:([^\n\r{}]*)}}/i),Ts=new RegExp(/{{VDATE:([^\n\r},|{]*)(?:,([^\n\r}|{]*))?(?:\|([^\n\r}{]*))?}}/i),pS=new RegExp(/{{LINKCURRENT}}/i),mS=new RegExp(/{{LINKSECTION}}/i),xt=new RegExp(/\.md$/i),lr=new RegExp(/\.canvas$/i),Mn=new RegExp(/\.base$/i),Sh=new RegExp(/\.js$/i),Yb=new RegExp(/{{MACRO:([^\n\r}]*)}}/i),_s=new RegExp(/{{TEMPLATE:([^\n\r}]*\.(?:md|canvas|base))}}/i),Kb=new RegExp(/{{GLOBAL_VAR:([^\n\r}]*)}}/i),Ah=new RegExp(/{{MVALUE}}/i),uo=new RegExp(/{{TITLE}}/i),Ih=new RegExp(/{{PROPERTY}}/i),fS=new RegExp(/{{SELECTED}}/i),hS=new RegExp(/{{CLIPBOARD}}/i),gS=new RegExp(/{{RANDOM:(\d+)}}/i),rO=new RegExp(/\[\[([^\]]*)$/),nO=new RegExp(/#([^ ]*)$/),iO=new RegExp(/{{[D]?[A]?[T]?[E]?[}]?[}]?$/i),oO=new RegExp(/{{[D]?[A]?[T]?[E]?[:]?$|{{DATE:[^\n\r}]*}}$/i),sO=new RegExp(/{{[N]?[A]?[M]?[E]?[}]?[}]?$/i),aO=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[}]?[}]?$/i),lO=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[:]?$|{{VALUE:[^\n\r}]*}}$/i),cO=new RegExp(/{{[V]?[D]?[A]?[T]?[E]?[:]?$|{{VDATE:[^\n\r}]*}}$/i),dO=new RegExp(/{{[L]?[I]?[N]?[K]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),uO=new RegExp(/^\{\{(?:l(?:i(?:n(?:k(?:s(?:e(?:c(?:t(?:i(?:o(?:n(?:\}\}?)?)?)?)?)?)?)?)?)?)?)?)?$/i),pO=new RegExp(/{{[F]?[I]?[L]?[E]?[N]?[A]?[M]?[E]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),vS=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),mO=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[}]?[}]?$/i),fO=new RegExp(/{{[F]?[I]?[L]?[E]?[:]?$/i),hO=new RegExp(/{{[F]?[I]?[E]?[L]?[D]?[:]?$/i),gO=new RegExp(/{{[T]?[E]?[M]?[P]?[L]?[A]?[T]?[E]?[:]?$|{{TEMPLATE:[^\n\r}]*[}]?[}]?$/i),vO=new RegExp(/{{[M]?[A]?[C]?[R]?[O]?[:]?$|{{MACRO:[^\n\r}]*}}$/i),yO=new RegExp(/{{[M]?[V]?[A]?[L]?[U]?[E]?[}]?[}]?/i),bO=new RegExp(/{{[T]?[I]?[T]?[L]?[E]?[}]?[}]?/i),wO=new RegExp(/{{[P]?[R]?[O]?[P]?[E]?[R]?[T]?[Y]?[}]?[}]?$/i),CO=/{{(?:C(?:U(?:R(?:S(?:O(?:R)?)?)?)?)?)?[}]?[}]?$/i,xO=new RegExp(/{{[S]?[E]?[L]?[E]?[C]?[T]?[E]?[D]?[}]?[}]?/i),EO=new RegExp(/{{[C]?[L]?[I]?[P]?[B]?[O]?[A]?[R]?[D]?[}]?[}]?$/i),yS=new RegExp(/{{[D]?[A]?[I]?[L]?[Y]?[}]?[}]?$|{{DAILY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),bS=new RegExp(/{{[W]?[E]?[E]?[K]?[L]?[Y]?[}]?[}]?$|{{WEEKLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),wS=new RegExp(/{{[M]?[O]?[N]?[T]?[H]?[L]?[Y]?[}]?[}]?$|{{MONTHLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),CS=new RegExp(/{{[Q]?[U]?[A]?[R]?[T]?[E]?[R]?[L]?[Y]?[}]?[}]?$|{{QUARTERLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),xS=new RegExp(/{{[Y]?[E]?[A]?[R]?[L]?[Y]?[}]?[}]?$|{{YEARLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),TO=new RegExp(/{{[R]?[A]?[N]?[D]?[O]?[M]?[:]?$|{{RANDOM:[^\n\r}]*}}$/i),_O=new RegExp(/{{[G]?[L]?[O]?[B]?[A]?[L]?[_]?[V]?[A]?[R]?[:]?$|{{GLOBAL_VAR:[^\n\r}]*}}$/i),kO=new RegExp(/{{[T]?[I]?[M]?[E]?[}]?[}]?/i),SO=new RegExp(/{{[T]?[I]?[M]?[E]?[:]?$|{{TIME:[^\n\r}]*}}$/i),Qb="__qa.",Ph=`${Qb}captureTargetFilePath`,Ta=`${Qb}dateOrigin`,AO=new RegExp(/\[\[([^\]]*)\]\]/)});function FO(r){return typeof r=="string"?r:""}function po(r){return FO(r).replace(/^\s+(?=[\\/])/,"").replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"").trimEnd().replace(/\/$/,"").normalize("NFC")}function xr(r){return FO(r).trim().replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"").normalize("NFC")}function ks(r){return((0,_S.normalizePath)(r).split("/").pop()??"").replace(/\.(md|canvas|base)$/i,"")}function Zn(r){let t=(0,_S.normalizePath)(r),e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}var _S,tn=x(()=>{_S=require("obsidian")});function Ss(r){return xt.test(r)||lr.test(r)||Mn.test(r)}function Rn(r,t){let e=xn(t);if(!e)return null;let n=r.vault.getAbstractFileByPath(e);return n instanceof MO.TFile?n:null}function xn(r){let t=xr(r);return t?Ss(t)?t:`${t}.md`:""}function ei(r){if(!Array.isArray(r))return[];let t=new Set,e=[];for(let n of r){if(typeof n!="string")continue;let i=xr(n);!i||t.has(i)||(t.add(i),e.push(i))}return e}function RO(r,t){return t.length===0?!0:t.some(e=>r===e||r.startsWith(`${e}/`))}var MO,tr=x(()=>{MO=require("obsidian");Ve();tn()});function _a(r){return/\{\{[^}]*\}\}/.test(r)}var Fh=x(()=>{});function Li(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 Mh(r){let t=Li(r).defaultView;if(!t)throw new Error("Unable to resolve owner window for DOM node.");return t}function At(r,t){return Li(r).win.createEl(t)}function Cd(r,t){return Li(r).createTextNode(t)}var Go=x(()=>{});var Xb=x(()=>{});var at,ti=x(()=>{at=class extends Error{constructor(t){super(t||"Macro execution aborted"),this.name="MacroAbortError"}}});function rn(){return new et(Dl)}var et,Dl,rr=x(()=>{ti();et=class extends at{},Dl="Input cancelled by user"});function ka(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"&&pK.has(r)}function AS(r){return typeof r=="object"&&r!==null||typeof r=="function"}function hK(r,t){let e=r;for(let n=0;n<fK&&AS(e);n++){let i=SS.get(e);if(i!==void 0&&t-i<mK)return!0;e=e.cause}return!1}function Me(r,t,e="ERROR"){let n=Date.now();if(hK(r,n))return!1;AS(r)&&SS.set(r,n);let i=ka(r,t);switch(e){case"ERROR":S.logError(i);break;case"WARNING":S.logWarning(i);break;case"LOG":S.logMessage(i);break;default:S.logError(i)}return!0}function OO(r){AS(r)&&SS.set(r,Date.now())}function xd(r,t,e="ERROR"){return Be(r)?!1:Me(r,t,e)}function LO(r,t,e="ERROR"){try{return r()}catch(n){Me(n,t,e);return}}function As(r,t){let e=n=>{xd(n,r)};return(...n)=>{try{let i=t(...n);typeof i?.then=="function"&&Promise.resolve(i).catch(e)}catch(i){e(i)}}}function NO(r){let t=r.then(void 0,e=>{throw Be(e)&&t.catch(()=>{}),e});return t}var kS,pK,SS,mK,fK,nt=x(()=>{ye();Xb();rr();kS=100;pK=new Set(["no input given.","No input given.","cancelled"]),SS=new WeakMap,mK=1e4,fK=8});function VO(r,t){return gK.test(r[t])}function vK(r){if(!r.includes("![["))return r;let t="",e=0,n=0,i=0;for(;n<r.length;){if(r.charCodeAt(n)===33&&r.charCodeAt(n+1)===91&&r.charCodeAt(n+2)===91){for(i<n+3&&(i=n+3);i<r.length&&r.charCodeAt(i)!==93;)i++;if(i<r.length&&r.charCodeAt(i+1)===93){t+=r.slice(e,n),n=i+2,e=n;continue}}n++}return t+r.slice(e)}function yK(r){if(!r.includes("[["))return r;let t="",e=0,n=0,i=0,o=0;for(;n<r.length;){if(r.charCodeAt(n)===91&&r.charCodeAt(n+1)===91){for(i<n+2&&(i=n+2);i<r.length;){let s=r.charCodeAt(i);if(s===93||s===124)break;i++}if(i<r.length&&r.charCodeAt(i)===93){if(r.charCodeAt(i+1)===93){t+=r.slice(e,n)+r.slice(n+2,i),n=i+2,e=n;continue}}else if(i<r.length){for(o<i+1&&(o=i+1);o<r.length&&r.charCodeAt(o)!==93;)o++;if(o<r.length&&r.charCodeAt(o+1)===93){t+=r.slice(e,n)+r.slice(i+1,o),n=o+2,e=n;continue}}}n++}return t+r.slice(e)}function bK(r){let t=0;if(r.charCodeAt(0)===35){for(;r.charCodeAt(t)===35;)t++;for(;t<r.length&&VO(r,t);)t++}let e=r.length;if(e>t&&r.charCodeAt(e-1)===35){for(;e>t&&r.charCodeAt(e-1)===35;)e--;for(;e>t&&VO(r,e-1);)e--}return r.slice(t,e)}function wK(r){if(!r.includes("[[")&&!r.includes("]]"))return r;let t="",e=0,n=0;for(;n<r.length;){let i=r.charCodeAt(n);if(i===91&&r.charCodeAt(n+1)===91||i===93&&r.charCodeAt(n+1)===93){t+=r.slice(e,n),n+=2,e=n;continue}n++}return t+r.slice(e)}function IS(r){return wK(bK(yK(vK(r)).replace(CK,""))).trim()}var gK,CK,BO=x(()=>{gK=/^\s$/;CK=/[*_`~]/g});function nn(r){return typeof r=="string"?r:r==null?"":String(r)}function UO(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 ap(r){let t=!1;return e=>{t||(t=!0,S.logWarning(ka(e,r)))}}function Ol(r){return nn(r)}function Ht(r){return r.normalize("NFC").toLowerCase()}function Jb(r){return r.toLowerCase().endsWith(".md")?r.slice(0,-3):r}function Zb(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 qO(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;g<p.length;g++)i.push(m),o.push(h);n+=p,s=h}let a="";for(let u of e)a+=u.toLowerCase();let l=0,c=0,d=n.indexOf(a,c);for(;d!==-1;){let u=Math.max(l,i[d]),p=o[d+a.length-1];if(p>u){u>l&&r.append(Cd(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)}l<t.length&&r.append(Cd(r,t.slice(l)))}function Is(r,t,e,n=0){r.replaceChildren();let i=0;for(let[o,s]of e){let a=Math.max(i,o-n),l=Math.min(t.length,s-n);if(l<=a)continue;a>i&&r.append(Cd(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<t.length&&r.append(Cd(r,t.slice(i)))}function Sa(r,t=!1){let e=Object.assign(new Event("input",{bubbles:!0}),{fromCompletion:!0,...t?{keepOpen:!0}:{}});r.dispatchEvent(e)}var on=x(()=>{ye();Go();nt();BO()});function TK(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+Dh+e>i.top;return o&&s}function _K(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(EK,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-Dh,m=e.top-Dh-u,h=s.height<=p,v=s.height<=m?!h||TK(r,e,s.height):!h&&m>p,b=Math.min(s.height,v?m:p),y=v?e.top-Dh-b:e.bottom+Dh,C=Math.max(i.offsetLeft,Math.min(e.left,i.offsetLeft+i.width-o));t.setCssStyles({maxHeight:b<s.height?`${b}px`:"",left:`${C-s.left}px`,top:`${y-s.top}px`})}function kK(r){let t=Array.from(r.childNodes).flatMap(e=>e.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 ew,xK,Dh,EK,SK,PS,Rh,Er,Ps=x(()=>{ew=require("obsidian");ye();Go();on();xK=(r,t)=>(r%t+t)%t,Dh=4,EK=300;SK=0,PS=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),kK(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=xK(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}},Rh=new WeakMap,Er=class{constructor(t,e,n){this.currentRequestId=0;this.isOpen=!1;this.destroyed=!1;this.currentQuery="";this.listQuery=null;this.renderMatch=qO;let i=this.constructor.name,o=Rh.get(e);o||(o=new Map,Rh.set(e,o));let s=o.get(i);s&&s.destroy(),Rh.set(e,o),o.set(i,this),this.app=t,this.inputEl=e,this.scope=new ew.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-${++SK}`,a.id=this.listboxId,a.setAttribute("role","listbox"),a.setAttribute("aria-label","Suggestions"),this.suggest=new PS(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,ew.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=Li(e);if((Li(t)===i?t:i.body).appendChild(this.suggestEl),this.reposition(),!n)return;let a=Mh(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(){_K(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=Li(this.inputEl),e=Mh(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=Rh.get(this.inputEl);e&&(e.delete(t),e.size===0&&Rh.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 Oh=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 jo=x(()=>{});function tw(r){return Ee(r)&&r.type==="Multi"}function Ee(r){return typeof r=="object"&&r!==null}function Le(r){return tw(r)?Array.isArray(r.choices)?r.choices:[]:[]}function Aa(r){return tw(r)&&Array.isArray(r.choices)}function lp(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 pr(r){return Array.isArray(r)?r:[]}function mo(r){return tw(r)?Wt(r.choices):!1}function cp(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 Ed(r){return(typeof r.icon=="string"?r.icon.trim():"")||cp(r.type)}function Jt(r){let t=[],e=n=>{Ee(n)&&(t.push(n),Le(n).forEach(e))};return pr(r).forEach(e),t}function zO(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),tw(s)&&Array.isArray(s.choices)&&(s={...s,choices:e(s.choices)}),i.push(s)}return i};return e(r)}function rw(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 HO(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(Aa(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 Td(r,t=[],e=0,n=null){let i=[];for(let o of pr(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(...Td(Le(o),s,e+1,o.id))}return i}var lt=x(()=>{Oh();jo();Oh()});function $S(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 Ll(r,t,e,n){let i=r.trim();if(!i)return t.slice(0,n.limit).map(a=>({item:a,matches:[]}));let o=(0,QO.prepareFuzzySearch)(i),s=[];for(let a of t){let l=e(a),c=$S(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 QO,dp=x(()=>{QO=require("obsidian")});function jK(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 YK(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 Lh(r,t={}){let e=t.passThroughUntilUsed??!1,n=!e,i=()=>{n=!e},o=()=>{n=!0},s=l=>{if(l.key!=="Tab"){GK.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;YK(r,jK(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 nw(r){return{destroy:Lh(r,{passThroughUntilUsed:!0})}}var GK,Nh=x(()=>{GK=new Set(["Shift","Control","Alt","Meta"])});function Dn(r){return r.replace(/\{\{CURSOR\}\}/gi,"")}function up(r){let t=/\{\{CURSOR\}\}/i.exec(r);return r=Dn(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 Ia(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 Nl(r,t,e){return{content:t,cursor:r.cursor.kind==="none"||e===null?{kind:"none"}:{...r.cursor,value:e}}}var Pa=x(()=>{});function nQ(r){return eQ.test(r.trim())}function iQ(r){let t=r.replace(tQ,"");return t===r?!1:!rQ.test(t)}function iw(r,t){return JK.has(r)?iQ(t):nQ(t)}function ow(r){return r==="noteTitle"||r==="captureTarget"||r==="propertyName"||r==="propertyValue"||r==="folder"||r==="templatePath"||r==="lineTarget"||r==="filePath"}function sw(r){return r!=="templatePath"&&r!=="generic"}function aw(r,t){if(r==="generic")return{};let e=ZK[r];return t?{title:e.ask,placeholder:e.hint}:{placeholder:e.partOf}}function oQ(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=`${XO}/${n}`;return s.length<r.length?s:r}let o=`${e[0]}/${XO}/${n}`;return o.length<r.length?o:r}function pp(r,t,e){if(!r)return;let n=[],i=r.choiceName?.trim();i&&i!==t?.trim()&&n.push(i);let o=e?.showDestination===!1?void 0:r.destination?.trim();if(o){let s=e?.elide===!1?o:oQ(o);n.push(`\u2192 ${r.destinationKind==="folder"?`${s}/`:s}`)}return n.length?n.join(" "):void 0}var JK,ZK,eQ,tQ,rQ,XO,mp=x(()=>{Ve();JK=new Set(["captureText"]),ZK={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"}},eQ=new RegExp(`^(?:${co.source})$`,"i"),tQ=new RegExp(co.source,"gi"),rQ=/\{\{[^}\n\r]*\}\}/;XO="\u2026"});function Vh(r){let e=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(r);return e?[0,e[0].length]:null}function Bh(r,t,e,n){let[i,o]=n??[Number.NaN,Number.NaN];if(!(n!==null&&t>=i&&t<o))return{isInYaml:!1,isQuoted:!1,lineStart:0,lineEnd:0,baseIndent:"",isKeyValuePosition:!1,isListItemPosition:!1};let a=r.lastIndexOf(`
- `,t-1)+1,l=r.indexOf(`
- `,Math.max(t,e)),c=l===-1?r.length:l,d=r.slice(a,t),u=r.slice(e,c),p=(d.match(/^\s*/)||[""])[0],m=r[t-1]==='"'&&r[e]==='"'||r[t-1]==="'"&&r[e]==="'",h=d.replace(/["']$/,""),v=u.replace(/^["']/,"").replace(/\s+#.*$/,"").trim().length===0,b=/:\s*$/.test(h)&&v,y=/^\s*-\s*$/.test(h)&&v;return{isInYaml:!0,isQuoted:m,lineStart:a,lineEnd:c,baseIndent:p,isKeyValuePosition:b,isListItemPosition:y}}var FS=x(()=>{});function $s(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 lQ(r){return r!==null&&sQ.has(r.toLowerCase())}function JO(r,t){return aQ.has(t.toLowerCase())||lQ($s(r,t))}var sQ,aQ,fp=x(()=>{sQ=new Set(["aliases","list","multitext","tags"]),aQ=new Set(["aliases","cssclasses","tags"])});function cQ(r,t=","){let e=[],n="",i=[],o=null;for(let a=0;a<r.length;a++){let l=r[a];if(o){if(n+=l,l===o){let c=0;for(let d=a-1;d>=0&&r[d]==="\\";d--)c++;c%2===0&&(o=null)}continue}if(l==='"'){o=l,n+=l;continue}if(l in ZO){i.push(ZO[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 dQ(r){return r.includes(`
- `)?r.replace(/\r?\n/g,`
- `):r.includes("\\n")?r.replace(/\\n/g,`
- `):r}function uQ(r){if(!r)return!1;let t=r.toLowerCase();return t==="list"||t==="tags"||t==="multitext"}function e0(r,t){let e=r.trim();if(!e)return;let n=dQ(e),i=t?.propertyType??$s(t?.app,t?.propertyKey),o=uQ(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=cQ(n);if(d.length>1)return d}}var ZO,t0=x(()=>{fp();ZO={"[":"]","(":")","{":"}","<":">"}});function hp(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 MS(r){return typeof r!="string"&&(Array.isArray(r)||typeof r=="object"&&r!==null||typeof r=="number"||typeof r=="boolean"||r===null)}function r0(r){return Array.isArray(r)||typeof r=="object"&&r!==null}function n0(r){if(MS(r))return Array.isArray(r)?"[]":r===null?"null":typeof r=="object"?"{}":String(r)}var gp=x(()=>{});var i0,Ni,Uh=x(()=>{FS();t0();gp();fp();i0="\0",Ni=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=Vh(e),d=Bh(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=e0(o,this.buildParseOptions(b));w!==void 0&&(y=w)}if(!MS(y)||Array.isArray(y)&&y.length===0||!l&&!r0(y))return;let C=v.join(i0);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(m<s&&(o.unshift(u[2].trim()),s=m,s===0))break}i=l-2}return o.length>0?o:null}resolvePropertyType(t){if(!this.app)return null;if(this.propertyTypeCache.has(t))return this.propertyTypeCache.get(t)??null;let e=$s(this.app,t);return this.propertyTypeCache.set(t,e),e}};Ni.PATH_SEPARATOR=i0});function kd(r){return pQ.has(r.toUpperCase())}function RS(r){if(r.length===0||r==="."||r===".."||r.startsWith(".")||qh.test(r)||zh.test(r)||Hh.test(r))return!1;let t=r.split(".")[0]??"";return t.length===0||!kd(t)}var qh,zh,Hh,pQ,Wh=x(()=>{qh=new RegExp("[\0-]","u"),zh=/[\\/:*?"<>|]/u,Hh=/[. ]$/u,pQ=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 o0(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 dw(r){return o0(r)!==null}function DS(r){if(!r)return r;let t=r.toLowerCase();return t.slice(0,1).toUpperCase()+t.slice(1)}function OS(r){return/\p{L}/u.test(r)?/\p{Lu}/u.test(r)&&!/\p{Ll}/u.test(r):!1}function lw(r){return/\p{Lu}/u.test(r)&&/\p{Ll}/u.test(r)}function mQ(r){return/^\p{Ll}/u.test(r)&&lw(r)}function fQ(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 hQ(r){return r.split(/[^\p{L}\p{N}\p{M}]+/gu).filter(Boolean).flatMap(fQ).filter(Boolean)}function Gh(r,t){let e=o0(t);if(!e)return r;if(e==="lower")return r.toLowerCase();if(e==="upper")return r.toUpperCase();let n=hQ(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?mQ(i)?i:i.toLowerCase():"",a=o.map(l=>OS(l)||lw(l)?l:DS(l));return[s,...a].join("")}case"pascal":return n.map(i=>OS(i)||lw(i)?i:DS(i)).join("");case"title":return n.map(i=>OS(i)||lw(i)?i:DS(i)).join(" ");case"slug":{let i=n.map(o=>o.toLowerCase()).join("-");return kd(i)?`${i}-`:i}default:return r}}var cw,uw=x(()=>{Wh();cw=["kebab","snake","camel","pascal","title","lower","upper","slug"]});function s0(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(gQ,t=>`\\x${t.charCodeAt(0).toString(16).padStart(2,"0")}`)}function jh(r){return`"${s0(r)}"`}function LS(r,t,e){let n=Bh(r,t,e,Vh(r));return!n.isInYaml||!n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}function Sd(r,t,e,n){return LS(r,t,e)?r[t-1]==='"'?s0(n):n.replace(/'/g,"''"):n}function NS(r,t,e){let n=Bh(r,t,e,Vh(r));return!n.isInYaml||n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}var gQ,pw=x(()=>{FS();gQ=new RegExp("[\0-\x7F]","g")});function mw(r,t,e){let n=r.trim().toLowerCase();if(vQ.has(n))return n;e?.(`QuickAdd: Unsupported multi-select format "${r}" in "${t}". Supported formats: auto, inline, spaced, yaml, markdown.`)}function yQ(r,t){let e=r.lastIndexOf(`
- `,t-1)+1;return r.slice(e,t).match(/^\s*/)?.[0]??""}function a0(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 bQ(r){return`- ${r.replace(/\r\n?|\n/g,`
- `)}`}function l0(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(jh).join(", ")}]`;case"markdown":{if(o.length===0)return"";let s=yQ(t,e);return o.map(bQ).join(`
- ${s}`)}default:return i}}var vQ,fw=x(()=>{pw();vQ=new Set(["auto","inline","spaced","yaml","markdown"])});function hw(r){let t=r.trim();return t&&(/^\[\[.*\]\]$/.test(t)?t:`[[${t}]]`)}var VS=x(()=>{});function ho(r){return r.split("|")}function c0(r){return r.startsWith("|")?r.slice(1):r}function go(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 Vl(r){if(!r)return!0;let t=r.trim().toLowerCase();return!["false","no","0","off"].includes(t)}function Yo(r,t){let e=!1;return{remaining:r.filter(i=>i.trim().toLowerCase()===t?(e=!0,!1):!0),found:e}}var Bl=x(()=>{});function BS(r){let{remaining:t,found:e}=Yo(r,"optional"),{remaining:n,found:i}=Yo(t,"trim");return{remaining:n,optional:e,trim:i}}function US(r,t,e,n,i){let o=r.map(u=>{let p=u.trim();return{raw:p,option:go(p)}}),s=e?CQ:d0,a=o.some(({option:u})=>u?.key==="type"&&["number","slider"].includes(u.value.toLowerCase())),l=u=>s.has(u)||a&&wQ.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=Vl(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=Vl(h);break;case"trim":d.trimExplicit=Vl(h);break;case"multi":d.multiSelect=!0,d.multiEmit=h.trim().toLowerCase()==="linklist"?"linklist":"text";break;case"format":d.multiFormat=mw(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 wQ,d0,CQ,u0=x(()=>{Bl();fw();wQ=new Set(["min","max","step"]),d0=new Set(["label","default","custom","type","case","text","optional","trim","multi","format"]),CQ=new Set([...d0,"name"])});var vp,Yh,Kh=x(()=>{ye();vp=r=>{S.logWarning(r)},Yh=()=>{}});function yp(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 xQ(r){return r.minRaw!==void 0||r.maxRaw!==void 0||r.stepRaw!==void 0}function p0(r,t,e){let n=yp(r.minRaw),i=yp(r.maxRaw),o=yp(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.max<s.min&&(e(`QuickAdd: Ignoring invalid numeric range in VALUE token "${t}"; max must be greater than or equal to min.`),delete s.min,delete s.max),r.stepRaw!==void 0&&(o===void 0||o<=0?e(`QuickAdd: Ignoring invalid step in VALUE token "${t}"; step must be greater than 0.`):s.step=o),Object.keys(s).length>0?s:void 0}function qS(r,t,e,n){if(e!=="number"&&e!=="slider")return xQ(r)&&n(`QuickAdd: Ignoring numeric range options in "${t}" because type is not number or slider.`),{inputTypeOverride:e};if(e!=="slider"){let c=p0(r,t,n);return{inputTypeOverride:e,numericConfig:c}}let i=yp(r.minRaw),o=yp(r.maxRaw),s=r.stepRaw===void 0?1:yp(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:p0(r,t,Yh)};let l={min:i,max:o,step:s};return{inputTypeOverride:e,numericConfig:l,sliderConfig:l}}function m0(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 EQ(r,t){return String(Number(r.toFixed(t)))}function vo(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(m0(a),m0(t.step));return EQ(s,c)}return String(s)}function bp(r,t){return vo(r,t)||String(t.min)}var zS=x(()=>{Kh()});function gw(r){return r!==void 0&&TQ.has(r)}function Ad(r){let t=[],e="",n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(n){if(gw(o)){if(gw(r[i+1])){e+='"',i++;continue}let s=i+1;for(;s<r.length&&_Q.test(r[s]);)s++;if(s>=r.length||r[s]===","){n=!1,i=s-1;continue}return r.split(",")}e+=o;continue}if(o===","){t.push(e),e="";continue}if(gw(o)&&e.trim()===""){n=!0,e="";continue}e+=o}return n?r.split(","):(t.push(e),t)}function Qh(r){let t=r.trim();if(!gw(t[0]))return r;let e=Ad(t);return e.length===1&&e[0]!==t?e[0].trim():r}var TQ,_Q,HS=x(()=>{TQ=new Set(['"',"\u201C","\u201D"]);_Q=/[^\S\r\n]/});function AQ(r,t,e){return e&&t?`${r}${WS}${t}`:r}function GS(r){let t=r.indexOf(WS);return t===-1?r:r.slice(0,t)}function IQ(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 Ul(r,t){if(!t)return null;let e=[t],n=GS(t);n!==t&&e.push(n);for(let i of e){if(r.has(i)&&r.get(i)!==void 0)return i;let o=IQ(r,i);if(o)return o}return null}function f0(r,t,e){if(r&&!dw(r)){e(`QuickAdd: Unsupported |case style "${r}" in token "${t}". Supported styles: ${cw.join(", ")}.`);return}return r}function h0(r,{tokenDisplay:t,hasOptions:e,allowCustomInput:n},i){if(!r)return;let o=r.trim().toLowerCase(),s=o==="boolean"?"checkbox":o;if(!kQ.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 Id(r,t){if(!r)return null;let e=t?.warn??vp,n=ho(r),i=(n.shift()??"").trim();if(!i)return null;let o=Ad(i).map(N=>N.trim()).filter(Boolean),s=o.length>1,{remaining:a,optional:l,trim:c}=BS(n),d=`{{VALUE:${r}}}`,u=US(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=Qh(h));let T=h0(u.inputTypeOverride,{tokenDisplay:d,hasOptions:s,allowCustomInput:g},e),P=qS(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(_=Ad(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(WS)&&(e(`QuickAdd: |name in "${d}" contains a reserved control character and was ignored.`),I=void 0),I&&SQ.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=f0(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 O=I||AQ(i,p,s);return{raw:r,variableName:i,aliasName:I,variableKey:O,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 Xh(r,t){let e=t?.warn??vp,n=c0(r),i=ho(n).map(g=>g.trim()).filter(Boolean),{remaining:o,optional:s,trim:a}=BS(i);if(o.length===0)return{defaultValue:"",optional:s,trim:a};let l=`{{VALUE${r}}}`,c=US(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=f0(u,l,e);let m=h0(c.inputTypeOverride,{tokenDisplay:l,hasOptions:!1,allowCustomInput:c.allowCustomInput},e),h=qS(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 WS,kQ,SQ,yo=x(()=>{u0();zS();HS();zS();HS();Bl();uw();Kh();WS="",kQ=new Set(["multiline","number","slider","checkbox","text"]),SQ=new Set(["value","title"])});function Fs(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 ql(r){return PQ.includes(r)}function y0(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 b0(r){if(!ql(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 g0.has(e)?!0:v0.has(e)?!1:!!t}default:return t}}function jS(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(g0.has(e))return!0;if(v0.has(e))return!1}return!!r;default:return r==null?"":Fs(r)}}function $Q(r){if(!ql(r.operator))return"";let t=r.expectedValue??"";return t.length===0?"(empty)":r.valueType==="string"?`"${t}"`:t}function FQ(r){let t=r.variableName?`$${r.variableName}`:"(missing variable)",e=RQ(r.operator),n=ql(r.operator)?` ${$Q(r)}`:"";return`${t} ${e}${n}`.trim()}function MQ(r){let t=r.exportName?`::${r.exportName}`:"";return`script ${r.scriptPath}${t}`}function zl(r){return r.mode==="variable"?FQ(r):MQ(r)}function RQ(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 PQ,g0,v0,Hl=x(()=>{PQ=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],g0=new Set(["true","1","yes","on"]),v0=new Set(["false","0","no","off"])});var DQ,vw,YS=x(()=>{Ve();mp();ye();Uh();uw();gp();pw();fw();VS();yo();Kh();Hl();DQ=new Set(["number","slider","checkbox"]),vw=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 Ni(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 Fs(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=iw(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?dw(e)?Gh(t,e):(this.warn(`QuickAdd: Unsupported |case style "${e}" in token "${n}". Supported styles: ${cw.join(", ")}.`),t):t}async resolveValue(t){if(this.valuePromptContext=this.getValuePromptContext(t),this.hasConcreteVariable("value")){let e=this.variables.get("value");this.value=Fs(e)}return this.value===void 0&&(this.value=await this.promptForValue()),this.value}async replaceValueInString(t){let e=t;if(!co.test(e))return e;await this.resolveValue(e);let n=new RegExp(co.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(Sd(a,s,s+o.length,this.value));let d=l.slice(c),u=Xh(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!==""&&NS(a,s,s+o.length)?this.userText(jh(m)):this.userText(Sd(a,s,s+o.length,m))}),e}applyValueTextOptions(t,e){let n=String(t??""),i=e.trim?n.trim():n;return Gh(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(co.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=Xh(l,{warn:Yh});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)&&a0({...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=l0({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=n0(e);if(n!==void 0)return n;if(Array.isArray(t.rawValue))return Sd(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=Ul(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(hw):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(wd.source,"gi"),n=[],i;for(;(i=e.exec(t))!==null;){if(!i[1])continue;let a;try{a=Id(i[1],{warn:Yh})}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(wd.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=Id(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!==""&&NS(e,o.index,o.index+o[0].length)?p=jh(v):DQ.has(s.inputTypeOverride??"")&&LS(e,o.index,o.index+o[0].length)?(m=!0,p=v):p=Sd(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 yw(r){let t=r.trim().toLowerCase(),e=OQ[t];if(!e)throw new Error(`Unknown date unit "${r.trim()}". Valid units: ${LQ}.`);return e}function w0(r){let t=go(r);return t?t.key==="startof"?{boundary:"start",unit:yw(t.value)}:t.key==="endof"?{boundary:"end",unit:yw(t.value)}:null:null}function wp(r,t){return t?t.boundary==="start"?r.startOf(t.unit):r.endOf(t.unit):r}var OQ,LQ,Jh=x(()=>{Bl();OQ={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"},LQ="year, quarter, month, week, isoweek, day"});function NQ(r){return r===void 0?window.moment():window.moment(r)}function VQ(r){let t=NQ(r?.now);return r?.origin?window.moment(r.origin).hour(t.hour()).minute(t.minute()).second(t.second()).millisecond(t.millisecond()):t}function $a(r){let t;return r?.offset!==null&&r?.offset!==void 0&&typeof r.offset=="number"&&(t=window.moment.duration(r.offset,"days")),wp(VQ(r).add(t),r?.snap).format(r?.format??"YYYY-MM-DD")}var bw=x(()=>{Jh()});function Zh(r){if(!r)return{optional:!1,withTime:!1};let{remaining:t,found:e}=Yo(ho(r),"optional"),{remaining:n,found:i}=Yo(t,"time"),{remaining:o,found:s}=Yo(n,"datetime"),a,l=!1,c,d,u,p=[];for(let h of o){let g=go(h.trim());if(g?.key==="optional"){a=Vl(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:yw(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 ww(r){try{return{options:Zh(r)}}catch(t){return{options:{optional:!1,withTime:!1},error:t instanceof Error?t.message:String(t)}}}var eg=x(()=>{Bl();Jh()});function C0(r,t,e){return r.replace(t,()=>e)}function tg(r){return r?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"}function KS(r,t,e,n=!1){let i=Cp.get(r);i||(i=new Map,Cp.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 Cw(r,t){let e=Cp.get(r)?.get(t);return e&&e.answer===r.get(t)?e.dateFormat:void 0}function rg(r,t){let e=Cw(r,t);if(e!==void 0)return e;let n=t.toLowerCase(),i=[...Cp.get(r)?.keys()??[]].filter(o=>o.toLowerCase()===n);return i.length===1?Cw(r,i[0]):void 0}function x0(r){return new Map(Cp.get(r))}function ng(r,t){Cp.set(r,new Map(t))}function ig(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(Th(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:wp(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:Fs(i)}:{text:""}}function E0(r,t){let e=r;for(let n of[eO,dS]){let i=n===dS;for(;n.test(e);){let o=n.exec(e);if(i&&!o)throw _0("date",e,n);let s=o?.[i?2:1]?.replace("+","").trim(),a=s&&ZD.test(s)?parseInt(s):void 0,l=o?.[i?3:2],c=t.clocks(),d=$a({...i?{format:o?.[1]}:{},offset:a,snap:l?w0(l)??void 0:void 0,origin:c?.date,now:c?.now});e=C0(e,n,t.applyCase(d,o?.[i?4:3],o?.[0]??"{{DATE}}"))}}return e}function T0(r,t){let e=r;for(let n of[tO,uS]){let i=n===uS;for(;n.test(e);){let o=n.exec(e);if(!o)throw _0("time",e,n);let s=$a({format:i?o[1]:"HH:mm",now:t.clocks()?.now});e=C0(e,n,t.applyCase(s,o[i?2:1],o[0]))}}return e}function _0(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 k0(r,t){let e=new RegExp(Ts.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}=Zh(o[3]),m=o[2]?.trim()||tg(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=Th(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=ig(t.variables.get(s),m,d,t.dateParser);g?.normalized!==void 0&&t.variables.set(s,g.normalized),KS(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 Cp,Pd=x(()=>{Ve();bw();je();gd();Jh();eg();Hl();Cp=new WeakMap});function sg(r,t=0){let e=r.length,n=t;for(;n<e;){let i=r.indexOf("`",n);if(i===-1)break;let o=i;for(;o<e&&r[o]==="`";)o++;if(o-i<3||!r.startsWith(og,o)){n=o;continue}let s=o+og.length,a=s;for(;a<e;){let l=r.indexOf("`",a);if(l===-1)break;let c=l;for(;c<e&&r[c]==="`";)c++;if(c-l>=3)return{start:i,end:c,code:r.slice(s,l).trim()};a=c}break}}function bo(r){let t=[],e=sg(r);for(;e;)t.push(e),e=sg(r,e.end);return t}function S0(r,t){let e=Math.max(3,t-og.length+1);for(let n=e;n<t;n++)if(r.startsWith("```",n-3)&&r.startsWith(og,n)){let i=n-3;for(;i>0&&r[i-1]==="`";)i--;return i}return t}function QS(r){let t=bo(r),e=r.length,n=t.length>0?t[t.length-1].end:0;for(;n<e;){let i=r.indexOf("`",n);if(i===-1)return!1;let o=i;for(;o<e&&r[o]==="`";)o++;if(o-i>=3&&r.startsWith(og,o))return!0;n=o}return!1}function xw(r){return bo(r).map(({code:t})=>t).filter(t=>t!=="")}var og,Wl=x(()=>{og="js quickadd"});function A0(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 I0=x(()=>{ye()});function BQ(r,t){let e=Math.min(r.length,t.length),n=0;for(;n<e&&r[n]===t[n];)n++;return n}function P0(r,t,e){if(r===t)return 0;if(Math.abs(r.length-t.length)>e||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,d<a&&(a=d)}if(a>e)return e+1;n=i,i=o}return i[t.length]}function $0(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:P0(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:BQ(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:P0(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 F0=x(()=>{});function Tw(r,t){return r.length<=t?r:`${r.slice(0,t)}\u2026`}function qQ(r){let t=r.map(e=>`"${e}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`}function M0(r,t){let e=Tw(r,32),n=`{{FIELD:${Tw(t,48)}}}`,i=UQ.get(r);if(i)return`Unknown FIELD filter "${e}" - ${i}. Ignored in ${n}.`;let o=$0(r,Ew);return o.length>0?`Unknown FIELD filter "${e}" - did you mean ${qQ(o)}? Ignored in ${n}.`:`Unknown FIELD filter "${e}" in ${n} was ignored. Supported filters: ${Ew.join(", ")}.`}function zQ(r,t){let e=Tw(r,32);return`FIELD filter "${e}" needs a value - write "${e}:value". Ignored in {{FIELD:${Tw(t,48)}}}.`}function HQ(r,t,e){(e.warn??vp)(M0(r,t))}var Ew,UQ,On,Fa=x(()=>{Kh();Bl();F0();fw();Ew=["folder","tag","inline","inline-code-blocks","exclude-folder","exclude-tag","exclude-file","default","default-from","default-empty","default-always","case-sensitive","multi","format","label"],UQ=new Map([["case-insensitive",'matching is already case-insensitive; use "case-sensitive:true" to match exactly']]);On=class{static parse(t,e){let n=ho(t).map(d=>d.trim()),i=n[0],o={},s=!1,a="auto",l=!1,c;for(let d=1;d<n.length;d++){let u=n[d];if(u.toLowerCase()==="multi"){s=!0;continue}let p=go(u);if(!p){let g=u.toLowerCase();e?.warnUnknown&&g&&(e.warn??vp)(Ew.includes(g)?zQ(g,t):M0(g,t));continue}let m=p.key,h=p.value;if(!Ew.includes(m)){e?.warnUnknown&&HQ(m,t,e);continue}switch(m){case"label":c=h||void 0;break;case"multi":s=Vl(h);break;case"format":l=!0,a=mw(h,`{{FIELD:${t}}}`,e?.warn)??"auto";break;case"folder":o.folders??(o.folders=[]),o.folders.push(h),o.folder||(o.folder=h);break;case"tag":{o.tags??(o.tags=[]);let g=h.startsWith("#")?h.substring(1):h;o.tags.push(g);break}case"inline":o.inline=h.toLowerCase()==="true";break;case"inline-code-blocks":o.inlineCodeBlocks??(o.inlineCodeBlocks=[]),o.inlineCodeBlocks.push(...h.split(",").map(g=>g.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 jQ(r){return r.split(",").map(t=>t.trim().toLowerCase().replace(/^\./,"")).filter(Boolean)}function YQ(r){if(r.length!==0)return r.includes("any")?"any":new Set(r.flatMap(t=>GQ.get(t)??[t]))}function XS(r){return r.replace(/^\/+|\/+$/g,"")}function xp(r,t=e=>e){return JSON.stringify([...r].map(t).sort())}function D0(r,t,e){let n=[`folder=${XS(r)}`];return e&&n.push(`types=${e==="any"?"any":xp([...e])}`),t.folders?.length&&n.push(`folders=${xp(t.folders,XS)}`),t.tags?.length&&n.push(`tags=${xp(t.tags)}`),t.excludeFolders?.length&&n.push(`xfolder=${xp(t.excludeFolders,XS)}`),t.excludeTags?.length&&n.push(`xtag=${xp(t.excludeTags)}`),t.excludeFiles?.length&&n.push(`xfile=${xp(t.excludeFiles)}`),n.join("|")}function KQ(r){let{folderPath:t,mode:e,label:n,optional:i,allowCustomInput:o,multiSelect:s,filter:a,extensions:l}=r,c=[D0(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 _w(r,t){if(!r)return null;let e=ho(r),n=(e.shift()??"").trim();if(!n)return null;let i=e,o=Yo(i,"optional");i=o.remaining;let s=o.found,a=Yo(i,"custom");i=a.remaining;let l=a.found,c=Yo(i,"multi");i=c.remaining;let d=c.found,u="name",p=[];for(let P of i){let _=P.trim().toLowerCase();if(WQ.has(_)){u=_;continue}p.push(P)}let m,h,g=[];for(let P of p){let _=go(P);if(_){if(_.key==="label"&&_.value)m=_.value;else if(_.key==="name"&&_.value)h=_.value;else if(_.key==="type")for(let I of jQ(_.value))g.includes(I)||g.push(I)}}let v=YQ(g),b=On.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?`${ag}name=${h}|${D0(n,w,v)}${y?"|multi":""}`:`${ag}${KQ({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 O0(r,t){if(!r)return r;for(let e of t)if(r===e)return r;return`${Ko}${r}`}function $d(r){return typeof r!="string"||r===""?{kind:"empty"}:r.startsWith(Ko)?{kind:"custom",text:r.slice(Ko.length)}:r.startsWith(Gl)?{kind:"file",path:r.slice(Gl.length)}:{kind:"raw",value:r}}function Ep(r){return(r.split("/").pop()??r).replace(/\.(md|canvas|base)$/i,"")}function Tp(r){return(r.split("/").pop()??r).replace(/\.md$/i,"")}function L0(r){return typeof r=="string"&&r.trim().length>0?r.trim():void 0}function QQ(r){if(!r)return;let t=Object.entries(r).find(([e])=>e.toLowerCase()==="title");return t?L0(t[1]):void 0}function XQ(r){let t=r?.headings?.find(e=>e.level===1);return L0(t?.heading)}function JQ(r){let t=r.parent?.path;return t&&t!=="/"?t:r.path.includes("/")?r.path.slice(0,r.path.lastIndexOf("/")):"vault root"}function ZQ(r){return r.extension&&r.extension!=="md"?r.name:r.basename||Tp(r.path)}function Fd(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 Ms(r,t){let e=r.map(i=>{let o=t?.(i)??null,s=ZQ(i),a=QQ(o?.frontmatter)??XQ(o)??s,l=a===s?s:`${a} (${s})`,c=(0,R0.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} - ${JQ(i)}`;return{primary:o,secondary:i.path,label:l,aliases:a}})}var R0,ag,Gl,Ko,WQ,GQ,Ln=x(()=>{R0=require("obsidian");Fa();Bl();ag="FILE:",Gl="@file:",Ko="@filecustom:",WQ=new Set(["name","link","path"]),GQ=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"]]])});function V0(r,t,e){return Array.isArray(r)?r.map(n=>N0(n,t,e)):N0(r,t,e)}function N0(r,t,e){if(t==="link")return e(r);let n=$d(r);switch(n.kind){case"empty":return"";case"file":return t==="path"?n.path:Tp(n.path);case"custom":case"raw":return n.kind==="custom"?n.text:n.value}}var B0=x(()=>{Ln()});function kw(r){return new Promise(t=>window.setTimeout(t,r))}function jl(r){return r.split(`
- `)}var _p=x(()=>{});var Sw,lg,wo,JS=x(()=>{Sw=class{isResolved(){return!this.hasConflicts}isConflicted(){return this.hasConflicts}},lg=class r extends Sw{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)})}},wo=class r extends Sw{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 Ma,ZS,kp,eA,tA,Rs,cg,Aw,Iw=x(()=>{Ma=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 eA(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 Aw(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(o<n||s<i)return t;{let[a,l,c,d]=this.findPrevChange(n,i,o-1,s-1),[u,p]=this.findNextChange(o+1,s+1),m=this.appendChangeRange(t.changeRanges,a,l,c,d);return new Aw(u,p,m)}}findNextChange(t=0,e=0){let n=this.left.slice(t)||[],i=this.right.slice(e)||[],o=this.mismatchOffset(n,i);return[t+o,e+o]}findPrevChange(t,e,n,i){if(t>n||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;i<n;i++)if(t[i]!==e[i])return i;return Math.min(t.length,e.length)}identifyUniquePositions(){let t=this.findUnique(this.left),e=this.findUnique(this.right),n=new Set(...t.keys()),i=new Set(...e.keys()),s=[...new Set([...n].filter(a=>i.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 ZS(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 cg(Rs.change,e+1,n+1,i+1,o+1)):e<=n?t.push(new cg(Rs.remove,e+1,n+1,i+1,i)):i<=o&&t.push(new cg(Rs.add,e+1,e,i+1,o+1)),t}},ZS=class{constructor(t,e){this.pos=t,this.unique=e}},kp=class{constructor(t,e){this.text=t,this.low=e}},eA=class{constructor(t,e,n){this.oldTextArray=t,this.newTextArray=e,this.chunks=n,this.oldText=[],this.newText=[]}convertToTypedOutput(){let t=new tA(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<t.leftLo-1;)this.oldText.push(new kp(this.oldTextArray[e+i],n+i)),i+=1;let o=0;for(;n+o<t.rightLo-1;)this.newText.push(new kp(this.newTextArray[n+o],e+o)),o+=1;return[i,o]}appendChanges(t,e,n){for(;e<=t.leftHi-1;)this.oldText.push(this.oldTextArray[e]),e+=1;for(;n<=t.rightHi-1;)this.newText.push(this.newTextArray[n]),n+=1;return[e,n]}setTheRemainingTextNodeIndexes(t,e){let n=0;for(;t+n<this.oldTextArray.length;)this.oldText.push(new kp(this.oldTextArray[t+n],e+n)),n+=1;for(;e+n<this.newTextArray.length;)this.newText.push(new kp(this.newTextArray[e+n],t+n)),n+=1}},tA=class{constructor(t,e){this.oldIndex=t,this.newIndex=e}};(function(r){r.change="change",r.add="add",r.remove="remove"})(Rs||(Rs={}));cg=class{constructor(t,e,n,i,o){this.action=t,this.leftLo=e,this.leftHi=n,this.rightLo=i,this.rightHi=o}},Aw=class{constructor(t,e,n){this.leftChangePos=t,this.rightChangePos=e,this.changeRanges=n}}});var Pw,Sp,rA,Ra,Or,$w,nA=x(()=>{Iw();Pw=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)}},Sp=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=Ma.diff(this.base,this.left).map(n=>Pw.fromChangeRange(n)),e=Ma.diff(this.base,this.right).map(n=>Pw.fromChangeRange(n));return this.collapseDifferences(new $w(t,e))}collapseDifferences(t,e=[]){if(t.isFinished())return e;{let n=new $w,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),e<i.baseHi?(t.switchSides(),this.buildResultQueue(t,i.baseHi,n)):this.buildResultQueue(t,e,n)}}queueIsFinished(t,e){return t.length===0||t[0].baseLo>e+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(Or.left),i,s),[c,d]=this.diffableEndpoints(t.get(Or.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 rA(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(Or.left)?Ra.chooseRight:t.isEmpty(Or.right)?Ra.chooseLeft:e.every((i,o)=>n[o]===i)?Ra.noConflictFound:Ra.possibleConflict}},rA=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"})(Ra||(Ra={}));(function(r){r.left="left",r.right="right"})(Or||(Or={}));$w=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(Or.left)&&this.isEmpty(Or.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===Or.left?Or.right:Or.left}chooseSide(){return this.isEmpty(Or.left)?this.currentSide=Or.right:this.isEmpty(Or.right)?this.currentSide=Or.left:this.currentSide=this.get(Or.left)[0].baseLo<=this.get(Or.right)[0].baseLo?Or.left:Or.right,this.currentSide}}});var dg,iA,U0=x(()=>{JS();nA();Iw();dg=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 iA(t,n,e)}executeThreeWayMerge(){let t=Sp.executeDiff(this.text3.left,this.text3.base,this.text3.right),e=1;t.forEach(i=>{let o=[];for(let s=e;s<i.baseLo;s++)o.push(this.text3.base[s-1]);o.length&&this.result.push(new wo(o)),this.interpretChunk(i),e=i.baseHi+1});let n=this.accumulateLines(e,this.text3.base.length,this.text3.base);n.length&&this.result.push(new wo(n))}setConflict(t){let e=lg.create({left:this.accumulateLines(t.leftLo,t.leftHi,this.text3.left),base:this.accumulateLines(t.baseLo,t.baseHi,this.text3.base),right:this.accumulateLines(t.rightLo,t.rightHi,this.text3.right)});this.result.push(e)}determineConflict(t,e,n){let i=1;t.forEach(s=>{for(let l=i;l<=s.leftLo;l++)this.result.push(new wo(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 wo(o))}determineOutcome(t,e,n){return t.action===Rs.change?lg.create({left:this.accumulateLines(t.rightLo,t.rightHi,e),right:this.accumulateLines(t.leftLo,t.leftHi,n),base:[]}):t.action===Rs.add?new wo(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=Ma.diff(e,n);(this._assocRange(i,Rs.change)||this._assocRange(i,Rs.remove))&&t.baseLo<=t.baseHi?this.setConflict(t):this.determineConflict(i,n,e)}interpretChunk(t){if(t.changeType==Ra.chooseLeft){let e=this.accumulateLines(t.leftLo,t.leftHi,this.text3.left);e.length&&this.result.push(new wo(e))}else if(t.changeType!==Ra.possibleConflict){let e=this.accumulateLines(t.rightLo,t.rightHi,this.text3.right);e.length&&this.result.push(new wo(e))}else this._conflictRange(t)}_assocRange(t,e){for(let n=0;n<t.length;n++){let i=t[n];if(i.action===e)return i}return null}accumulateLines(t,e,n){let i=[];for(let o=t;o<=e;o++)n[o-1]&&i.push(n[o-1]);return i}},iA=class{constructor(t,e,n){this.left=t,this.right=e,this.base=n}}});var Md,q0=x(()=>{Md=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 ug,z0=x(()=>{JS();q0();ug=class r{static collateMerge(t,e,n){return t.length?(t=r.combineNonConflicts(t),t.length===1&&t[0].isResolved()?new Md(t,e):new Md(t,e,{conflict:!0,conflictHandler:n})):new Md([new wo([])],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 H0(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 W0=x(()=>{});function oA(r,t,e,n={}){n=Object.assign({},r3,n);let[i,o,s]=[r,t,e].map(c=>n.splitFunction.call(n,c)),a=dg.merge(i,o,s);return ug.collateMerge(a,n.joinFunction,n.conflictFunction)}var G0,e3,t3,r3,j0=x(()=>{U0();z0();W0();G0=r=>r.join(""),e3=r=>r.split(/\b/),t3=H0("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",G0),r3={splitFunction:e3,joinFunction:G0,conflictFunction:t3}});var Y0,K0=x(()=>{j0();nA();Iw();Y0=oA});function Lr(r,t){if(!r)throw new Error(typeof t=="function"?t():t)}var Rd=x(()=>{});function aA(r,t){let e=i=>i instanceof sA.MarkdownView&&i.file===t&&!!i.editor&&i.getMode()==="source",n=r.workspace.getActiveViewOfType(sA.MarkdownView);return e(n)?n:r.workspace.getLeavesOfType("markdown").map(i=>i.view).find(e)??null}async function Q0(r,t){let e=aA(r,t);e&&await lA(e)}async function Od(r,t){return await Q0(r,t),r.vault.read(t)}async function Co(r,t,e){let n=aA(r,t);if(n){await lA(n);let i=await r.vault.read(t),{editor:o}=n,s=o.getValue();if(aA(r,t)===n&&s===Dd(i)){let a=Dd(e(s)),l=i3(s,a);return l&&(o.transaction({changes:[{from:o.offsetToPos(l.from),to:o.offsetToPos(l.to),text:l.text}]}),await lA(n).catch(c=>S.logWarning(`Could not save '${t.path}' yet: ${String(c)}`))),a}}return r.vault.process(t,e)}async function X0(r,t,e,n){let i=!1;return{content:await Co(r,t,s=>{if(Dd(s)===Dd(e))return n;let a=Y0(Dd(s),Dd(e),Dd(n));return Lr(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 Yl(r,t,e){await Q0(r,t),await r.fileManager.processFrontMatter(t,e)}async function lA(r){await r.save();let t=()=>r.saving===!0;for(let e=0;t();e+=10){if(e>=n3)throw new Error(`Obsidian is still saving '${r.file?.path}'. Try again once it has saved.`);await kw(10)}}function i3(r,t){if(r===t)return null;let e=Math.min(r.length,t.length),n=0;for(;n<e&&r.charCodeAt(n)===t.charCodeAt(n);)n++;let i=0;for(;i<e-n&&r.charCodeAt(r.length-1-i)===t.charCodeAt(t.length-1-i);)i++;return{from:n,to:r.length-i,text:t.slice(n,t.length-i)}}function Dd(r){return r.includes("\r")?r.replace(/\r\n?/g,`
- `):r}var sA,n3,Ds=x(()=>{sA=require("obsidian");_p();K0();Rd();ye();n3=1e4});function Ap(r){return o3.has(r)}function Da(r){return r==="inFrontmatter"}function Fw(r){return s3.has(r)}function a3(r,t,e){return r==="embed"&&e.type==="activeFile"&&Ap(t)?"embed":"link"}function l3(r,t,e,n){return r==="selection"&&e.type==="activeFile"&&Fw(t)&&n==="link"?"selection":"none"}function c3(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 Kl(r){if(d3(r)){let t=r.placement??"replaceSelection",e=c3(r.destination),n=a3(r.linkType,t,e);return{enabled:r.enabled,placement:t,requireActiveFile:r.requireActiveFile??!0,linkType:n,displayText:l3(r.displayText,t,e,n),destination:e,frontmatterProperty:r.frontmatterProperty,frontmatterHandling:Da(t)?r.frontmatterHandling??Ld:r.frontmatterHandling}}return{enabled:r,placement:"replaceSelection",requireActiveFile:!!r,linkType:"link",displayText:"none",destination:{type:"activeFile"}}}var Ld,o3,s3,Ql=x(()=>{Ld="alwaysAppend",o3=new Set(["replaceSelection","afterSelection","endOfLine","newLine"]);s3=new Set(["replaceSelection","afterSelection"])});function cA(r){return r.vault.getConfig?.("useMarkdownLinks")===!0}function u3(r,t){let e=t.replace(/\s+/g,n=>/[\r\n]/.test(n)?" ":n).trim();if(e){if(cA(r))return e.replace(/\\/g,"\\\\").replace(/\[/g,"\\[").replace(/\]/g,"\\]");if(!(e.includes("]]")||e.includes("[[")||e.endsWith("]")))return e}}function p3(r){return`[[${r.path.replace(/\.md$/i,"")}]]`}function Mw(r,t,e={}){let n=e.sourcePath??"";if(e.linkType==="embed"&&(!e.placement||Ap(e.placement)))return`![[${r.metadataCache.fileToLinktext(t,n)}]]`;let o=e.alias===void 0?void 0:u3(r,e.alias);return o===void 0?r.fileManager.generateMarkdownLink(t,n):r.fileManager.generateMarkdownLink(t,n,void 0,o)}function dA(r){let t=r.trim().replace(/^\/+/,"");return t?/\.md$/i.test(t)?t:`${t}.md`:""}function mg(r,t){if(t.type!=="specifiedFile")return null;let e=dA(t.path);if(!e)return null;let n=r.vault.getAbstractFileByPath(e);return!(n instanceof pg.TFile)||n.extension!=="md"?null:n}function m3(r,t){return r.length===0?t:r.endsWith(`
- `)?`${r}${t}`:`${r}
- ${t}`}async function Z0(r,t,e,n){let i=e.destination;if(i?.type!=="specifiedFile")return!1;let o=mg(r,i);if(!o)throw new Error(`Append link target file not found or is not a Markdown file: ${i.path}`);let s=Mw(r,t,{sourcePath:o.path,linkType:"link"}),a;return await Co(r,o,l=>{let c=m3(l,s);return a={filePath:o.path,before:l,after:c,edits:[{from:l.length,to:l.length,text:c.slice(l.length)}]},c}),a&&n?.(a),!0}async function f3(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 eL(r){let t=p3(r);return await f3(t)?(new pg.Notice(`Copied link to '${r.basename}' to clipboard.`,J0),!0):(new pg.Notice(`Created '${r.basename}', but QuickAdd could not copy its link to the clipboard.`,J0),!1)}var pg,J0,Ip=x(()=>{pg=require("obsidian");Ds();ye();Ql();J0=4e3});function Pp(r){return r&&typeof r=="object"?r:void 0}function uA(r){return typeof r=="string"?r.trim():""}function tL(r){return r.replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"")}function rL(r){return`{{${r.toUpperCase()}}}`}function nL(r,t,e){return{source:r,folder:tL(uA(e.folder)),format:uA(e.format)||h3[t],template:tL(uA(e.template))}}function Dw(r,t){let e=Pp(Pp(r?.plugins?.plugins?.["periodic-notes"])?.settings);if(e&&"calendarSets"in e)throw new Error(`${rL(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=Pp(e?.[t]);if(n?.enabled===!0)return nL("periodic-notes",t,n);if(t!=="daily")throw new Error(`${rL(t)} needs the Periodic Notes plugin with ${t} notes turned on.`);let i=Pp(r?.internalPlugins?.plugins?.["daily-notes"]);if(i?.enabled===!0)return nL("daily-notes",t,Pp(Pp(i.instance)?.options)??{});throw new Error("{{DAILY}} needs the Daily notes core plugin, or Periodic Notes with daily notes, turned on.")}function iL(r,t){return t.clone().startOf(g3[r])}function oL(r,t,e){let n=iL(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 sL(r,t,e){let n=r.vault.getAbstractFileByPath(`${t}.md`);if(n instanceof Rw.TFile)return r.fileManager.generateMarkdownLink(n,e);if(!cA(r))return`[[${t}]]`;let i=encodeURI(`${t}.md`).replace(/\(/g,"%28").replace(/\)/g,"%29");return`[${(t.split("/").pop()??t).replace(/[\\[\]]/g,"\\$&")}](${i})`}async function aL(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 Rw.TFile?i:r.vault.getAbstractFileByPath(`${n}.md`);if(!(o instanceof Rw.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 pA(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 lL(r,t,e,n,i){let{format:o}=t,s=iL(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 pA(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 pA(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 pA(r,s,i,o).replace(/{{\s*date\s*}}/gi,a).replace(/{{\s*time\s*}}/gi,l).replace(/{{\s*title\s*}}/gi,a)}var Rw,mA,h3,g3,fA=x(()=>{Rw=require("obsidian");Ip();mA=/{{(DAILY|WEEKLY|MONTHLY|QUARTERLY|YEARLY)(\|link)?}}/i,h3={daily:"YYYY-MM-DD",weekly:"gggg-[W]ww",monthly:"YYYY-MM",quarterly:"YYYY-[Q]Q",yearly:"YYYY"},g3={daily:"day",weekly:"week",monthly:"month",quarterly:"quarter",yearly:"year"}});function cL(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 dL=x(()=>{});function pL(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 mL(r){return Ih.test(r)}function fL(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 gL(r){return hL.map(t=>({key:t,present:r.has(t),value:r.get(t)}))}function vL(r,t){for(let e of t)e.present?r.set(e.key,e.value):r.delete(e.key)}function yL(r,t,e){for(let i of hL)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=v3(e,t)),r.set("propertyKey",t),r.set("propertyValue",n),r.set("list",Array.isArray(n)?[...n]:[])}function v3(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 fg(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 bL(r){return r.split(/\r?\n/).map(t=>t.trim()).filter(t=>t!=="")}function wL(r){return typeof r=="string"?bL(r).length===0:Array.isArray(r)&&r.length===0}function uL(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 CL(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 xL(r){if(r.action==="addToList")return!0;let t=CL(r.registeredType,r.key);return t==="list"||t===null&&Array.isArray(r.existing)}function Ow(r){return Array.isArray(r)?"list":typeof r=="boolean"?"checkbox":typeof r=="number"?"number":"text"}function y3(r,t,e){let n=Ow(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 EL(r){let{frontmatter:t,config:e}=r,n=fg(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=uL(r.value,n),a=o==null?null:uL(o,n),l=CL(r.registeredType,n)??(a===null?null:Ow(a)),c=typeof s=="string"?bL(s):null;if(e.action==="addToList"){if(a!==null&&!Array.isArray(a))throw new Error(`Property '${n}' is ${Ow(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 ${Ow(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&&y3(d,l,n),Array.isArray(d)?[...new Set(d)]:d}function TL(r){let t=(0,Nd.getFrontMatterInfo)(r);if(!t.exists||!t.frontmatter.trim())return{};let e=(0,Nd.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 _L(r,t){let e=(0,Nd.getFrontMatterInfo)(r),n=e.exists?r.slice(e.contentStart):r;return`---
- ${(0,Nd.stringifyYaml)(t)}---
- ${n}`}var Nd,hL,hA=x(()=>{Nd=require("obsidian");Ve();hL=["propertyKey","propertyValue","list"]});var kL,Lw,Xl,$p=x(()=>{YS();Pd();Pd();Wl();I0();kL=require("obsidian");Ve();Ln();B0();fA();ye();pw();Fa();dL();hA();YS();Wl();Lw=10,Xl=class extends vw{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=E0(e,{clocks:()=>this.runClocks(),applyCase:(i,o,s)=>this.applyCaseOption(i,o,s)});return mA.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(mA.source,"gi");return e.replace(o,(s,a,l)=>{let c=a.toLowerCase(),d=oL(Dw(this.app,c),c,i);return l&&this.app?sL(this.app,d,this.getLinkSourcePath()??""):(this.promptScope==="captureTarget"&&(this.outermostIncluder().periodicNoteTarget={path:d,period:c}),d)})}replaceTimeInString(e){return T0(e,{clocks:()=>this.runClocks(),applyCase:(n,i,o)=>this.applyCaseOption(n,i,o)})}async replaceSelectedInString(e){if(!fS.test(e))return e;let n=await this.getSelectedText(),i=new RegExp(fS.source,"gi"),o=this.userText(n);return e.replace(i,()=>o)}async replaceClipboardInString(e){if(!hS.test(e))return e;let n=await this.getClipboardContent(),i=new RegExp(hS.source,"gi"),o=this.userText(n);return e.replace(i,()=>o)}async replaceLinkToCurrentFileInString(e){if(!pS.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(pS.source,"gi");return e.replace(i,()=>n??"")}replaceLinkToCurrentSectionInString(e){if(!mS.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(mS.source,"gi");return e.replace(i,()=>n??"")}replaceCurrentFileLinksInString(e){return this.replaceCurrentFileTokensInString(e,{links:!0})}replaceCurrentFileTokensInString(e,n){return A0(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(op.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=On.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=Sd(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`${Ml}${e}`}async replaceFileInString(e){let n=new RegExp(jb.source,"gi"),i="",o=0,s;for(;(s=n.exec(e))!==null;){i+=e.slice(o,s.index);let a=_w(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=V0(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=$d(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 kL.TFile?this.app?.fileManager.generateMarkdownLink(o,this.getLinkSourcePath()??"")??`[[${Tp(i)}]]`:`[[${Tp(i)}]]`}getLinkSourcePath(){return null}async replaceMathValueInString(e){let n=new RegExp(Ah.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(Yb.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]?cL(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 k0(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=Cw(this.variables,e)??tg(!1);return ig(n,i,void 0,this.dateParser)?.text??""}return super.getValueTokenText(e)}async replaceTemplateInString(e){let n=e;for(;_s.test(n);){let i=_s.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,_s,a);continue}if(this.templateInclusion.depth>=Lw){let a=`[QuickAdd: max template inclusion depth (${Lw}) exceeded at "${o}"]`;this.reportProblem(a),n=this.replacer(n,_s,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,_s,s)}return n}replaceLinebreakInString(e){let n="";for(let i=0;i<e.length;i++){let o=e[i],s=e[i+1];o=="\\"?s=="n"?(n+=`
- `,i++):s=="\\"?(n+="\\",i++):n+="\\":n+=o}return n}expandLinebreakEscapesOutsideTokens(e){let n=bo(e),i="",o=0,s=0;for(;o<e.length;){for(;s<n.length&&n[s].end<=o;)s++;let a=n[s];if(a&&a.start===o){i+=e.slice(a.start,a.end),o=a.end;continue}if(e[o]==="{"&&e[o+1]==="{"){let d=e.indexOf("}}",o+2),u=!1;if(d!==-1){let p=d+2;for(let m=s;m<n.length;m++){let h=n[m];if(h.start>=p)break;if(p<h.end&&p>h.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(;gS.test(n);){let i=gS.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;l<o;l++)a+=s.charAt(Math.floor(Math.random()*s.length));n=n.replace(i[0],a)}return n}replaceTitleInString(e){return this.replaceCurrentFileTokensInString(e,{title:!0})}consumePropertyTokenExpanded(){let e=this.propertyTokenExpanded;return this.propertyTokenExpanded=!1,e}replacePropertyInString(e){if(!Ih.test(e))return e;if(this.promptScope!=="propertyValue")throw new Error("{{PROPERTY}} can only be used in a property Capture format.");this.propertyTokenExpanded=!0;let n=this.variables.get("propertyValue");/^{{PROPERTY}}$/i.test(e.trim())&&e.trim()===e&&this.retainSingleTokenValue(e,0,e.length,n===void 0?"":n);let i=this.userText(fL(n));return e.replace(new RegExp(Ih.source,"gi"),()=>i)}}});function AL(r){return r<=31||r===127||r===8232||r===8233}function C3(r){let t="",e=0;for(;e<r.length;){let n=e;for(;n<r.length&&r.charCodeAt(n)===32;)n++;if(n<r.length&&AL(r.charCodeAt(n))){for(;n<r.length&&AL(r.charCodeAt(n));)n++;for(;n<r.length&&r.charCodeAt(n)===32;)n++;t+=" ",e=n;continue}t+=r.slice(e,Math.min(n+1,r.length)),e=n+1}return t}function IL(r,t){let e=r.length;for(;e>0&&t.includes(r[e-1]);)e--;return r.slice(0,e)}function Vd(r){return x3.filter(t=>r.includes(t))}function $L(r){return`A file or folder name cannot contain ${RL(r)}, so this choice would fail at run time. ${ML}`}function FL(r,t){return`Cannot create "${t}": a file or folder name cannot contain ${RL(r)}. ${ML}`}function RL(r){return r.map(t=>`"${t}"`).join(", ")}function Nr(r,t="File path"){let{path:e,problems:n}=OL(r,t);if(n.length>0)throw new Error(n[0]);return e}function DL(r,t="File path"){return OL(r,t)}function OL(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):E3(o,t,e)).join("/"),problems:e}}function E3(r,t,e){if(r.length===0)return r;let n=b3.test(r),i=w3.test(r),o=C3(r);n&&(o=o.replace(/^ /u,"")),i&&(o=o.replace(/ $/u,""));let s=IL(o," ");return s==="."||s===".."?(e.push(`${t} cannot contain "." or ".." path segments.`),s):(o=IL(o,". "),o||e.push(`${t} contains an empty path segment after formatting.`),o)}var PL,b3,w3,x3,ML,Qo=x(()=>{PL="\0-\x7F\u2028\u2029",b3=new RegExp(`^ *[${PL}]`,"u"),w3=new RegExp(`[${PL}] *$`,"u");x3=[":"];ML="Check your own text and tokens like {{TIME}}, which is HH:mm."});function Rp(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 gg(r){return r==null?[]:(Array.isArray(r)?r:typeof r=="string"?r.split(/,|\s+/):[r]).map(Rp).filter(Boolean)}var yA=x(()=>{});var Os,Nw=x(()=>{yA();Os=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(Rp).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(...gg(t.frontmatter.tags)),t.frontmatter?.tag&&e.push(...gg(t.frontmatter.tag)),t.tags&&e.push(...t.tags.map(n=>Rp(n.tag))),e.filter(Boolean)}static normalizePath(t){return t.replace(/^\/+|\/+$/g,"")}}});function La(r){return r.vault.getAllLoadedFiles().filter(t=>t instanceof bA.TFolder).map(t=>t.path)}function vg(r,t){let e=r.vault.getAbstractFileByPath(t);return!!e&&e instanceof bA.TFolder}function Xo(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 S3(r){return Object.entries(r.frontmatter??{}).filter(([t])=>["tag","tags"].includes(t.toLowerCase())).flatMap(([,t])=>gg(t)).filter(Boolean)}function A3(r,t){let e=r.metadataCache.getFileCache(t);if(!e)return[];let n=[];return e.frontmatter&&n.push(...S3(e)),e.tags&&Array.isArray(e.tags)&&n.push(...e.tags.map(i=>Rp(i.tag))),n}function GL(r,t){let e=t.replace(/^#/,"");return r.vault.getMarkdownFiles().filter(n=>A3(r,n).includes(e))}function Vw(r,t){return Os.filterFiles(r.vault.getMarkdownFiles(),t,e=>r.metadataCache.getFileCache(e))}function I3(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 Bw(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:I3(c[1],e):!1});return n&&(n.folder||n.tags?.length||n.excludeFolders?.length||n.excludeTags?.length||n.excludeFiles?.length)&&(o=Os.filterFiles(o,n,a=>r.metadataCache.getFileCache(a))),o}function Dp(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 Os.filterFiles(n,t.filter,i=>r.metadataCache.getFileCache(i))}var bA,gi=x(()=>{bA=require("obsidian");Nw();yA()});function Zl(r,t){let e=r,n=new RegExp(Kb.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"?l:""});return e}var yg=x(()=>{Ve()});var dt,Lt,Vi,Na=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"})(Vi||(Vi={}))});function Jo(r,t){r.assign("day",t.getDate()),r.assign("month",t.getMonth()+1),r.assign("year",t.getFullYear())}function Uw(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 Va(r,t){r.imply("day",t.getDate()),r.imply("month",t.getMonth()+1),r.imply("year",t.getFullYear())}function bg(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 Bd=x(()=>{Na()});function ec(r,t,e,n,i=0){let o=0,s=0;for(;s<n;)o++,new Date(r,t-1,o).getDay()===e&&s++;return new Date(r,t-1,o,i)}function jL(r,t,e,n=0){let i=e===0?7:e,o=new Date(r,t-1+1,1,12),s=o.getDay()===0?7:o.getDay(),a;return s===i?a=7:s<i?a=7+s-i:a=s-i,o.setDate(o.getDate()-a),new Date(r,t-1,o.getDate(),n)}function qw(r,t,e={}){if(r==null)return null;if(typeof r=="number")return r;let n=e[r]??$3[r];return n==null?null:typeof n=="number"?n:t==null?null:t>n.dstStart(t.getFullYear())&&!(t>n.dstEnd(t.getFullYear()))?n.timezoneOffsetDuringDst:n.timezoneOffsetNonDst}var $3,wA=x(()=>{Na();$3={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=>jL(r,Vi.MARCH,Lt.SUNDAY,2),dstEnd:r=>jL(r,Vi.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=>ec(r,Vi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>ec(r,Vi.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=>ec(r,Vi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>ec(r,Vi.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=>ec(r,Vi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>ec(r,Vi.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=>ec(r,Vi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>ec(r,Vi.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 an(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 tc(r){let t={};for(let e in r)t[e]=-r[e];return t}var YL,Ba=x(()=>{YL={day:0,second:0,millisecond:0}});var rc,mt,Ua,Zo=x(()=>{Bd();wA();Ba();rc=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=qw(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=YL){let n=an(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"),Uw(i,n),Jo(i,n),i.assign("timezoneOffset",t.getTimezoneOffset())):(bg(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=an(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}},Ua=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 CA(r,t,e="\\s{0,5},?\\s{0,5}"){let n=t.replace(/\((?!\?)/g,"(?:");return`${r}${n}(?:${e}${n}){0,10}`}function F3(r){let t;return r instanceof Array?t=[...r]:r instanceof Map?t=Array.from(r.keys()):t=Object.keys(r),t}function Vr(r){return`(?:${F3(r).sort((e,n)=>n.length-e.length).join("|").replace(/\./g,"\\.")})`}var qa=x(()=>{});function zw(r){return r<100&&(r>50?r=r+1900:r=r+2e3),r}function nc(r,t,e){let n=new Date(r);n.setMonth(e-1),n.setDate(t);let i=an(n,{year:1}),o=an(n,{year:-1});return Math.abs(i.getTime()-r.getTime())<Math.abs(n.getTime()-r.getTime())?n=i:Math.abs(o.getTime()-r.getTime())<Math.abs(n.getTime()-r.getTime())&&(n=o),n.getFullYear()}var Lp=x(()=>{Ba()});function M3(r){let t=r.toLowerCase();return xA[t]!==void 0?xA[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 Vp(r){let t=r.toLowerCase();return EA[t]!==void 0?EA[t]:(t=t.replace(/(?:st|nd|rd|th)$/i,""),parseInt(t))}function Ls(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 zw(t)}function xo(r){let t={},e=r,n=KL.exec(e);for(;n;)D3(t,n),e=e.substring(n[0].length).trim(),n=KL.exec(e);return Object.keys(t).length==0?null:t}function D3(r,t){if(t[0].match(/^[a-zA-Z]+$/))return;let e=M3(t[1]),n=wg[t[2].toLowerCase()];r[n]=e}var Hw,TA,ni,xA,EA,QL,wg,XL,Np,ic,JL,KL,R3,ZL,za,oc,mr=x(()=>{qa();Lp();Hw={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},TA={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},ni={...TA,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},xA={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},EA={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},QL={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"},wg={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",...QL},XL=`(?:${Vr(xA)}|[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)?)`;Np=`(?:${Vr(EA)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;ic="(?:[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)))";JL=`(${XL})\\s{0,3}(${Vr(wg)})`,KL=new RegExp(JL,"i"),R3=`(${XL})\\s{0,3}(${Vr(QL)})`,ZL="\\s{0,5},?(?:\\s*and)?\\s{0,5}",za=CA("(?:(?:about|around)\\s{0,3})?",JL,ZL),oc=CA("(?:(?:about|around)\\s{0,3})?",R3,ZL)});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<e.length;i++)e[i-1]=e[i];return this.innerExtract(t,e)}}});var O3,L3,N3,Cg,eN=x(()=>{mr();Zo();Nn();O3=new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${za})(?=\\W|$)`,"i"),L3=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${za})(?=\\W|$)`,"i"),N3=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${oc})(?=\\W|$)`,"i"),Cg=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(e){return this.strictMode?N3:e.option.forwardDate?O3:L3}innerExtract(e,n){if(n[0].match(/^for\s*the\s*\w+/))return null;let i=xo(n[1]);return i?mt.createRelativeFromReference(e.reference,i):null}}});var V3,tN,rN,B3,nN,xg,iN=x(()=>{Lp();mr();mr();mr();qa();Nn();V3=new RegExp(`(?:on\\s{0,3})?(${Np})(?:\\s{0,3}(?:to|\\-|\\\u2013|until|through|till)\\s{0,3}(${Np}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${Vr(ni)})(?:(?:-|/|,?\\s{0,3})(${ic}(?!\\w)))?(?=\\W|$)`,"i"),tN=1,rN=2,B3=3,nN=4,xg=class extends yt{innerPattern(){return V3}innerExtract(t,e){let n=t.createParsingResult(e.index,e[0]),i=ni[e[B3].toLowerCase()],o=Vp(e[tN]);if(o>31)return e.index=e.index+e[tN].length,null;if(n.start.assign("month",i),n.start.assign("day",o),e[nN]){let s=Ls(e[nN]);n.start.assign("year",s)}else{let s=nc(t.refDate,o,i);n.start.imply("year",s)}if(e[rN]){let s=Vp(e[rN]);n.end=n.start.clone(),n.end.assign("day",s)}return n}}});var U3,q3,oN,_A,kA,Eg,sN=x(()=>{Lp();mr();mr();mr();qa();Nn();U3=new RegExp(`(${Vr(ni)})(?:-|/|\\s*,?\\s*)(${Np})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${Np})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${ic}))?(?=\\W|$)(?!\\:\\d)`,"i"),q3=1,oN=2,_A=3,kA=4,Eg=class extends yt{constructor(e){super();fe(this,"shouldSkipYearLikeDate");this.shouldSkipYearLikeDate=e}innerPattern(){return U3}innerExtract(e,n){let i=ni[n[q3].toLowerCase()],o=Vp(n[oN]);if(o>31||this.shouldSkipYearLikeDate&&!n[_A]&&!n[kA]&&n[oN].match(/^\d{2}$/))return null;let s=e.createParsingComponents({day:o,month:i}).addTag("parser/ENMonthNameMiddleEndianParser");if(n[kA]){let c=Ls(n[kA]);s.assign("year",c)}else{let c=nc(e.refDate,o,i);s.imply("year",c)}if(!n[_A])return s;let a=Vp(n[_A]),l=e.createParsingResult(n.index,n[0]);return l.start=s,l.end=s.clone(),l.end.assign("day",a),l}}});var z3,H3,W3,aN,Tg,lN=x(()=>{mr();Lp();qa();mr();Nn();z3=new RegExp(`((?:in)\\s*)?(${Vr(ni)})\\s*(?:(?:,|-|of)?\\s*(${ic})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),H3=1,W3=2,aN=3,Tg=class extends yt{innerPattern(){return z3}innerExtract(t,e){let n=e[W3].toLowerCase();if(e[0].length<=3&&!TA[n])return null;let i=t.createParsingResult(e.index+(e[H3]||"").length,e.index+e[0].length);i.start.imply("day",1),i.start.addTag("parser/ENMonthNameParser");let o=ni[n];if(i.start.assign("month",o),e[aN]){let s=Ls(e[aN]);i.start.assign("year",s)}else{let s=nc(t.refDate,1,o);i.start.imply("year",s)}return i}}});var G3,j3,Y3,cN,K3,_g,dN=x(()=>{mr();qa();Nn();G3=new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${Vr(ni)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),j3=1,Y3=2,cN=3,K3=4,_g=class extends yt{constructor(e){super();fe(this,"strictMonthDateOrder");this.strictMonthDateOrder=e}innerPattern(){return G3}innerExtract(e,n){let i=parseInt(n[j3]),o=parseInt(n[K3]),s=n[cN]?parseInt(n[cN]):ni[n[Y3].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 Q3,X3,J3,Z3,kg,uN=x(()=>{mr();qa();mr();Nn();Q3="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-9][0-9]{3})",X3=new RegExp(`(${Q3})(?:\\s*[-.\\/,]?\\s*|\\s+of\\s+)(${Vr(ni)})(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),J3=1,Z3=2,kg=class extends yt{innerPattern(){return X3}innerExtract(t,e){let n=Ls(e[J3]),i=e[Z3].toLowerCase(),o=ni[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 e4,t4,r4,Sg,pN=x(()=>{Nn();e4=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),t4=1,r4=2,Sg=class extends yt{innerPattern(){return e4}innerExtract(t,e){let n=parseInt(e[r4]),i=parseInt(e[t4]);return t.createParsingComponents().imply("day",1).assign("month",i).assign("year",n)}}});function n4(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 i4(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 SA,Ud,Ww,Gw,Bp,jw,mN=x(()=>{Na();SA=2,Ud=3,Ww=4,Gw=5,Bp=6,jw=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[SA]);if(a>100){if(e[SA].length==4&&e[Ud]==null&&!e[Bp]||this.strictMode||e[Ud]!=null)return null;o=a%100,a=Math.floor(a/100)}if(a>24)return null;if(e[Ud]!=null){if(e[Ud].length==1&&!e[Bp])return null;o=parseInt(e[Ud])}if(o>=60)return null;if(a>12&&(s=dt.PM),e[Bp]!=null){if(a>12)return null;let l=e[Bp][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[Gw]!=null){let l=parseInt(e[Gw].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(e[Ww]!=null){let l=parseInt(e[Ww]);if(l>=60)return null;i.assign("second",l)}return i}extractFollowingTimeComponents(t,e,n){let i=t.createParsingComponents();if(e[Gw]!=null){let l=parseInt(e[Gw].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(e[Ww]!=null){let l=parseInt(e[Ww]);if(l>=60)return null;i.assign("second",l)}let o=parseInt(e[SA]),s=0,a=-1;if(e[Ud]!=null?s=parseInt(e[Ud]):o>100&&(s=o%100,o=Math.floor(o/100)),s>=60||o>24)return null;if(o>=12&&(a=dt.PM),e[Bp]!=null){if(o>12)return null;let l=e[Bp][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()<n.start.date().getTime()&&i.imply("day",i.get("day")+1),i}checkAndReturnWithoutFollowingPattern(t){if(t.text.match(/^\d$/)||t.text.match(/^\d\d\d+$/)||t.text.match(/\d[apAP]$/))return null;let e=t.text.match(/[^\d:.](\d[\d.]+)$/);if(e){let n=e[1];if(this.strictMode||n.includes(".")&&!n.match(/\d(\.\d{2})+$/)||parseInt(n)>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=n4(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=i4(t,e),this.cachedFollowingPhase=t,this.cachedFollowingSuffix=e,this.cachedFollowingTimePatten)}}});var Ag,fN=x(()=>{Na();mN();Ag=class extends jw{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 o4,s4,Ig,hN=x(()=>{mr();Zo();Nn();Ba();o4=new RegExp(`(${za})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),s4=new RegExp(`(${oc})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),Ig=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(){return this.strictMode?s4:o4}innerExtract(e,n){let i=xo(n[1]);return i?mt.createRelativeFromReference(e.reference,tc(i)):null}}});var a4,l4,c4,Pg,gN=x(()=>{mr();Zo();Nn();a4=new RegExp(`(${za})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`,"i"),l4=new RegExp(`(${oc})\\s{0,5}(later|after|from now)(?=\\W|$)`,"i"),c4=1,Pg=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(){return this.strictMode?l4:a4}innerExtract(e,n){let i=xo(n[c4]);return i?mt.createRelativeFromReference(e.reference,i):null}}});var Up,Eo,sc=x(()=>{Up=class{refine(t,e){return e.filter(n=>this.isValid(t,n))}},Eo=class{refine(t,e){if(e.length<2)return e;let n=[],i=e[0],o=null;for(let s=1;s<e.length;s++){o=e[s];let a=t.text.substring(i.index+i.text.length,o.index);if(!this.shouldMergeResults(a,i,o,t))n.push(i),i=o;else{let l=i,c=o,d=this.mergeResults(a,l,c,t);t.debug(()=>{console.log(`${this.constructor.name} merged ${l} and ${c} into ${d}`)}),i=d}}return i!=null&&n.push(i),n}}});var $g,vN=x(()=>{sc();Ba();$g=class extends Eo{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()&&an(s,{day:7})>o?(s=an(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()&&an(o,{day:-7})<s?(o=an(o,{day:-7}),e.start.imply("day",o.getDate()),e.start.imply("month",o.getMonth()+1),e.start.imply("year",o.getFullYear())):n.start.isDateWithUnknownYear()&&an(s,{year:1})>o?(s=an(s,{year:1}),n.start.imply("year",s.getFullYear())):e.start.isDateWithUnknownYear()&&an(o,{year:-1})<s?(o=an(o,{year:-1}),e.start.imply("year",o.getFullYear())):[n,e]=[e,n]}let i=e.clone();return i.start=e.start,i.end=n.start,i.index=Math.min(e.index,n.index),e.index<n.index?i.text=e.text+t+n.text:i.text=n.text+t+e.text,i}}});var Fg,yN=x(()=>{vN();Fg=class extends $g{patternBetween(){return/^\s*(to|-|–|until|through|till)\s*$/i}}});function AA(r,t){let e=r.clone(),n=r.start,i=t.start;if(e.start=bN(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=bN(o,s);if(r.end==null&&a.date().getTime()<e.start.date().getTime()){let l=new Date(a.date().getTime());l.setDate(l.getDate()+1),a.isCertain("day")?Jo(a,l):Va(a,l)}e.end=a}return e}function bN(r,t){let e=r.clone();t.isCertain("hour")?(e.assign("hour",t.get("hour")),e.assign("minute",t.get("minute")),t.isCertain("second")?(e.assign("second",t.get("second")),t.isCertain("millisecond")?e.assign("millisecond",t.get("millisecond")):e.imply("millisecond",t.get("millisecond"))):(e.imply("second",t.get("second")),e.imply("millisecond",t.get("millisecond")))):(e.imply("hour",t.get("hour")),e.imply("minute",t.get("minute")),e.imply("second",t.get("second")),e.imply("millisecond",t.get("millisecond"))),t.isCertain("timezoneOffset")&&e.assign("timezoneOffset",t.get("timezoneOffset"));let n=r.get("meridiem")!=null&&(r.isCertain("meridiem")||Array.from(r.tags()).some(i=>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 wN=x(()=>{Na();Bd()});var Mg,CN=x(()=>{sc();wN();Mg=class extends Eo{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()?AA(e,n):AA(n,e);return i.index=e.index,i.text=e.text+t+n.text,i}}});var qp,xN=x(()=>{CN();qp=class extends Mg{patternBetween(){return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|\u2219|:)?\\s*$")}}});var d4,Rg,EN=x(()=>{wA();d4=new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)","i"),Rg=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=d4.exec(o);if(!s)return;let a=s[1].toUpperCase(),l=i.start.date()??i.refDate??new Date,c={...this.timezoneOverrides,...n},d=qw(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 u4,p4,m4,f4,Dg,TN=x(()=>{u4=new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?","i"),p4=1,m4=2,f4=3,Dg=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=u4.exec(i);if(!o)return;t.debug(()=>{console.log(`Extracting timezone: '${o[0]}' into : ${n}`)});let s=parseInt(o[m4]),a=parseInt(o[f4]||"0"),l=s*60+a;l>840||(o[p4]==="-"&&(l=-l),n.end!=null&&n.end.assign("timezoneOffset",l),n.start.assign("timezoneOffset",l),n.text+=o[0])}),e}}});var ac,IA=x(()=>{ac=class{refine(t,e){if(e.length<2)return e;let n=[],i=e[0];for(let o=1;o<e.length;o++){let s=e[o];if(s.index>=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 _N(r,t,e){let n=r.getDateWithAdjustedTimezone(),i=h4(n,t,e),o=new mt(r);return o=o.addDurationAsImplied({day:i}),o.assign("weekday",t),o}function h4(r,t,e){let n=r.getDay();switch(e){case"this":return qd(r,t);case"last":return kN(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<n&&t!=Lt.SUNDAY?qd(r,t):qd(r,t)+7}return g4(r,t)}function g4(r,t){let e=kN(r,t),n=qd(r,t);return n<-e?n:e}function qd(r,t){let e=r.getDay(),n=t-e;return n<0&&(n+=7),n}function kN(r,t){let e=r.getDay(),n=t-e;return n>=0&&(n-=7),n}var PA=x(()=>{Na();Zo()});var Og,SN=x(()=>{Bd();Bd();Ba();PA();Og=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),Va(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()&&(Va(n.end,s),n.start.date()>n.end.date()&&(s.setDate(s.getDate()+1),Va(n.end,s)))}if(n.start.isOnlyWeekdayComponent()&&i>n.start.date()){let o=qd(i,n.start.get("weekday"))||7,s=an(i,{day:o});if(Va(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=qd(i,n.start.get("weekday"))||7,l=an(i,{day:a});Va(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 Lg,AN=x(()=>{sc();Lg=class extends Up{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 v4,y4,b4,w4,IN,C4,PN,$N,x4,FN,MN,Ng,RN=x(()=>{Nn();v4=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"),y4=1,b4=2,w4=3,IN=4,C4=5,PN=6,$N=7,x4=8,FN=9,MN=10,Ng=class extends yt{innerPattern(){return v4}innerExtract(t,e){let n=t.createParsingComponents({year:parseInt(e[y4]),month:parseInt(e[b4]),day:parseInt(e[w4])});if(e[IN]!=null&&(n.assign("hour",parseInt(e[IN])),n.assign("minute",parseInt(e[C4])),e[PN]!=null&&n.assign("second",parseInt(e[PN])),e[$N]!=null&&n.assign("millisecond",parseInt(e[$N])),e[x4]!=null)){let i=0;if(e[FN]){let o=parseInt(e[FN]),s=0;e[MN]!=null&&(s=parseInt(e[MN])),i=o*60,i<0?i-=s:i+=s}n.assign("timezoneOffset",i)}return n.addTag("parser/ISOFormatParser")}}});var Vg,DN=x(()=>{sc();Vg=class extends Eo{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 ON(r,t=!1){return r.parsers.unshift(new Ng),r.refiners.unshift(new Vg),r.refiners.unshift(new Dg),r.refiners.unshift(new ac),r.refiners.push(new Rg),r.refiners.push(new ac),r.refiners.push(new Og),r.refiners.push(new Lg(t)),r}var LN=x(()=>{EN();TN();IA();SN();AN();RN();DN()});function NN(r){let t=r.getDateWithAdjustedTimezone(),e=new mt(r,{});return Jo(e,t),Uw(e,t),e.assign("timezoneOffset",r.getTimezoneOffset()),e.addTag("casualReference/now"),e}function VN(r){let t=r.getDateWithAdjustedTimezone(),e=new mt(r,{});return Jo(e,t),bg(e,t),e.delete("meridiem"),e.addTag("casualReference/today"),e}function BN(r){return E4(r,1).addTag("casualReference/yesterday")}function UN(r){return Yw(r,1).addTag("casualReference/tomorrow")}function E4(r,t){return Yw(r,-t)}function Yw(r,t){let e=r.getDateWithAdjustedTimezone(),n=new mt(r,{}),i=new Date(e.getTime());return i.setDate(i.getDate()+t),Jo(n,i),bg(n,i),n.delete("meridiem"),n}function qN(r,t=22){let e=r.getDateWithAdjustedTimezone(),n=new mt(r,{});return Jo(n,e),n.imply("hour",t),n.imply("meridiem",dt.PM),n.addTag("casualReference/tonight"),n}function zN(r,t=20){let e=new mt(r,{});return e.imply("meridiem",dt.PM),e.imply("hour",t),e.addTag("casualReference/evening"),e}function HN(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 WN(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 GN(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 jN(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 $A=x(()=>{Zo();Bd();Na()});var T4,Bg,KN=x(()=>{Nn();Bd();$A();T4=/(now|today|tonight|tomorrow|overmorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i,Bg=class extends yt{innerPattern(t){return T4}innerExtract(t,e){let n=t.refDate,i=e[0].toLowerCase(),o=t.createParsingComponents();switch(i){case"now":o=NN(t.reference);break;case"today":o=VN(t.reference);break;case"yesterday":o=BN(t.reference);break;case"tomorrow":case"tmr":case"tmrw":o=UN(t.reference);break;case"tonight":o=qN(t.reference);break;case"overmorrow":o=Yw(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}Jo(o,n),o.imply("hour",0)}break}return o.addTag("parser/ENCasualDateParser"),o}}});var _4,Ug,QN=x(()=>{Nn();$A();_4=/(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i,Ug=class extends yt{innerPattern(){return _4}innerExtract(t,e){let n=null;switch(e[1].toLowerCase()){case"afternoon":n=GN(t.reference);break;case"evening":case"night":n=zN(t.reference);break;case"midnight":n=HN(t.reference);break;case"morning":n=WN(t.reference);break;case"noon":case"midday":n=jN(t.reference);break}return n&&n.addTag("parser/ENCasualTimeParser"),n}}});var k4,S4,A4,I4,qg,XN=x(()=>{mr();qa();Nn();PA();Na();k4=new RegExp(`(?:(?:\\,|\\(|\\\uFF08)\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${Vr(Hw)}|weekend|weekday)(?:\\s*(?:\\,|\\)|\\\uFF09))?(?:\\s*(?:of\\s*)?(this|last|past|next)\\s*week)?(?=\\W|$)`,"i"),S4=1,A4=2,I4=3,qg=class extends yt{innerPattern(){return k4}innerExtract(t,e){let n=e[S4],i=e[I4],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[A4].toLowerCase(),l;if(Hw[a]!==void 0)l=Hw[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 _N(t.reference,l,s)}}});var P4,$4,F4,zg,JN=x(()=>{mr();Zo();Nn();qa();P4=new RegExp(`(this|last|past|next|after\\s*this)\\s*(${Vr(wg)})(?=\\s*)(?=\\W|$)`,"i"),$4=1,F4=2,zg=class extends yt{innerPattern(){return P4}innerExtract(t,e){let n=e[$4].toLowerCase(),i=e[F4].toLowerCase(),o=wg[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 M4,R4,D4,ZN,e1,FA,Hg,t1=x(()=>{Lp();M4=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"),R4=1,D4=5,ZN=2,e1=3,FA=4,Hg=class{constructor(t){fe(this,"groupNumberMonth");fe(this,"groupNumberDay");this.groupNumberMonth=t?e1:ZN,this.groupNumberDay=t?ZN:e1}pattern(){return M4}extract(t,e){let n=e.index+e[R4].length,i=e.index+e[0].length-e[D4].length;if(n>0&&t.text.substring(0,n).match("\\d/?$")||i<t.text.length&&t.text.substring(i).match("^/?\\d"))return;let o=t.text.substring(n,i);if(o.match(/^\d\.\d$/)||o.match(/^\d\.\d{1,2}\.\d{1,2}\s*$/)||!e[FA]&&o.indexOf("/")<0)return;let s=t.createParsingResult(n,o),a=parseInt(e[this.groupNumberMonth]),l=parseInt(e[this.groupNumberDay]);if((a<1||a>12)&&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[FA]){let c=parseInt(e[FA]),d=zw(c);s.start.assign("year",d)}else{let c=nc(t.refDate,l,a);s.start.imply("year",c)}return s.addTag("parser/SlashDateFormatParser")}}});var O4,L4,Wg,r1=x(()=>{mr();Zo();Nn();Ba();O4=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${za})(?=\\W|$)`,"i"),L4=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${oc})(?=\\W|$)`,"i"),Wg=class extends yt{constructor(e=!0){super();fe(this,"allowAbbreviations");this.allowAbbreviations=e}innerPattern(){return this.allowAbbreviations?O4:L4}innerExtract(e,n){let i=n[1].toLowerCase(),o=xo(n[2]);if(!o)return null;switch(i){case"last":case"past":case"-":o=tc(o);break}return mt.createRelativeFromReference(e.reference,o)}}});function N4(r){return r.text.match(/^[+-]/i)!=null}function n1(r){return r.text.match(/^-/i)!=null}var Gg,i1=x(()=>{sc();Zo();mr();Ba();Gg=class extends Eo{shouldMergeResults(t,e,n){return t.match(/^\s*$/i)?N4(n)||n1(n):!1}mergeResults(t,e,n,i){let o=xo(n.text);n1(n)&&(o=tc(o));let s=mt.createRelativeFromReference(rc.fromDate(e.start.date()),o);return new Ua(e.reference,e.index,`${e.text}${t}${n.text}`,s)}}});function o1(r){return r.text.match(/\s+(before|from)$/i)!=null}function V4(r){return r.text.match(/\s+(after|since)$/i)!=null}var jg,s1=x(()=>{sc();Zo();mr();Ba();jg=class extends Eo{patternBetween(){return/^\s*$/i}shouldMergeResults(t,e,n){return!t.match(this.patternBetween())||!o1(e)&&!V4(e)?!1:!!n.start.get("day")&&!!n.start.get("month")&&!!n.start.get("year")}mergeResults(t,e,n){let i=xo(e.text);o1(e)&&(i=tc(i));let o=mt.createRelativeFromReference(rc.fromDate(n.start.date()),i);return new Ua(n.reference,e.index,`${e.text}${t}${n.text}`,o)}}});var B4,U4,Yg,a1=x(()=>{mr();B4=new RegExp(`^\\s*(${ic})`,"i"),U4=1,Yg=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=B4.exec(i);if(!o||o[0].trim().length<=3)return;t.debug(()=>{console.log(`Extracting year: '${o[0]}' into : ${n}`)});let s=Ls(o[U4]);n.end!=null&&n.end.assign("year",s),n.start.assign("year",s),n.text+=o[0]}),e}}});var Kg,l1=x(()=>{sc();Kg=class extends Up{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 zd,MA=x(()=>{eN();iN();sN();lN();dN();uN();pN();fN();hN();gN();yN();xN();LN();KN();QN();XN();JN();t1();r1();i1();s1();IA();a1();l1();zd=class{createCasualConfiguration(t=!1){let e=this.createConfiguration(!1,t);return e.parsers.push(new Bg),e.parsers.push(new Ug),e.parsers.push(new Tg),e.parsers.push(new zg),e.parsers.push(new Wg),e.refiners.push(new Kg),e}createConfiguration(t=!0,e=!1){let n=ON({parsers:[new Hg(e),new Cg(t),new xg,new Eg(e),new qg,new Sg,new Ag(t),new Ig(t),new Pg(t),new kg],refiners:[new qp]},t);return n.parsers.unshift(new _g(t)),n.refiners.unshift(new jg),n.refiners.unshift(new Gg),n.refiners.unshift(new ac),n.refiners.push(new qp),n.refiners.push(new Yg),n.refiners.push(new Fg),n}}});var zp,RA,c1=x(()=>{Zo();MA();zp=class r{constructor(t){fe(this,"parsers");fe(this,"refiners");fe(this,"defaultConfig",new zd);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 RA(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 Ua?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}},RA=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=rc.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 Ua(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 DA,d1,q4,NAe,u1=x(()=>{c1();MA();DA=new zd,d1=new zp(DA.createCasualConfiguration(!1)),q4=new zp(DA.createConfiguration(!0,!1)),NAe=new zp(DA.createCasualConfiguration(!0))});function p1(r,t,e){return H4.parseDate(r,t,e)}var H4,m1=x(()=>{u1();H4=d1});function Y4(r){return!G4.test(r)}var G4,j4,OA,To,Hd=x(()=>{m1();G4=/\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,j4=/\bprevious\b/gi;OA=class{getParsedDate(t,e=new Date){let n=t.replace(j4,"last");return p1(n,e,{forwardDate:Y4(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}}},To=new OA});function rv(r){return typeof r=="string"&&tv.includes(r)}function Ha(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)||!rv(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 tv,jp=x(()=>{tv=["days","weeks","months","years"]});function iC(r){return o6.has(r)}function Wa(r){if(!r||r.kind==="now")return"today";if(r.kind==="ask")return"ask";if(r.kind==="variable")return"variable";for(let t of NA)if(r.offset===t.offset&&r.unit===t.unit)return t.id;return"custom"}function oC(r){let{preset:t,previous:e}=r;if(t!=="today"){if(t==="ask")return e?.kind==="ask"?e:v1(Wa(e));if(t==="variable")return e?.kind==="variable"?e:{kind:"variable",name:""};if(t==="custom")return e?.kind==="relative"&&Wa(e)==="custom"?e:{kind:"relative",offset:-2,unit:"days"};for(let n of NA)if(n.id===t)return{kind:"relative",offset:n.offset,unit:n.unit}}}function v1(r){for(let t of nC)if(t.id===r&&t.defaultValue)return{kind:"ask",defaultValue:t.defaultValue};return{kind:"ask"}}function ov(r){let t=(r??"").trim().toLowerCase();for(let e of nC)if(e.aliases.some(n=>n===t))return e.id;return"kept"}function sC(r){let t=nC.map(e=>({value:e.id,label:e.label}));if(ov(r)==="kept"){let e=r?.trim();e&&t.push({value:"kept",label:e})}return t}function aC(r,t){if(r==="kept"){let e=t?.trim();return e||void 0}for(let e of nC)if(e.id===r)return e.defaultValue}function y1(r){return typeof r=="string"&&r.trim().toLowerCase()==="ask"}function Yp(r){return r?.kind==="ask"?r:v1(Wa(r))}var i6,Qw,Xw,Jw,Zw,nv,eC,iv,tC,NA,rC,nC,o6,lc=x(()=>{i6=["today","ask","yesterday","last-week","next-week","last-month","custom","variable"],Qw="Which day",Xw="The day {{DATE}} writes. The clock stays now. Hold Shift in the QuickAdd menu to pick a different day.",Jw="Picker starts on",Zw="The date the picker suggests first. You can still pick a different day.",nv="How far from today",eC="How many days, weeks, months, or years from today. Negative is the past.",iv="Variable name",tC="A VDATE or script value that already has the day.",NA=[{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"}],rC=[{value:"today",label:"Today"},{value:"ask",label:"Ask each time"},...NA.map(r=>({value:r.id,label:r.label})),{value:"custom",label:"Custom\u2026"},{value:"variable",label:"A variable\u2026"}],nC=[{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"]}],o6=new Set(i6)});function C6(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 C1(r){let t=On.parse(`__capture_scope|${r}`);return{filter:t.filters,multiSelect:t.multiSelect??!1}}function x6(r){return!!(r.folder||r.folders?.length||r.tags?.length||r.excludeFolders?.length||r.excludeTags?.length||r.excludeFiles?.length)}function Qp(r){let t=r.trim();if(!t)return null;if(t.startsWith("#")){let o=ho(t),s=(o.shift()??"").replace(/^#/,"").replace(/\.md$/i,"").trim();if(!s)return null;let a=o.length>0?C1(o.join("|")):{filter:{},multiSelect:!1};return{filter:{...a.filter,tags:C6(s,a.filter.tags)},multiSelect:a.multiSelect}}let e=ho(t)[0]??"",n=go(e);if(!n||!w6.has(n.key))return null;let i=C1(t);return x6(i.filter)?i:null}var w6,pC=x(()=>{Fa();Bl();w6=new Set(["folder","tag","exclude-folder","exclude-tag","exclude-file"])});function Xp(r){let t=r.trim();if(!x1.test(t))return null;let e=t.replace(x1,""),{fieldName:n,filters:i}=On.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 x1,mC=x(()=>{Fa();x1=/^property:/i});function B1(r){let t=yC.find(e=>e.id===(r===void 0?"open":r));if(!t)throw new Error(`Unknown existing-note action: ${String(r)}`);return t}function bC(r){return B1(r).id}function uc(r){return B1(r).verb}function nm(r){let t=J6.get(r);if(!t)throw new Error(`Unknown file exists mode: ${r}`);return t}function U1(r){return XA.filter(t=>t.category===r)}function q1(r){return nm(r).category}function z1(){return[...XA]}function H1(r){return r.kind==="prompt"?"prompt":q1(r.mode)}function W1(r,t){return r==="prompt"?{kind:"prompt"}:t?.kind==="apply"&&q1(t.mode)===r?t:{kind:"apply",mode:Z6[r]}}function G1(r){return typeof r!="string"||!Object.prototype.hasOwnProperty.call(N1,r)?null:N1[r]??null}async function j1(r,t,e){return await eX[t](r,e)}async function tX(r,t){let e=r;for(;await t(e);){let{basename:n,extension:i}=Y1(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 rX(r,t){let e=r;for(;await t(e);){let{basename:n,extension:i}=Y1(e),o=n.match(/^(.*) \((\d+)\)$/);e=`${o?`${o[1]} (${String(BigInt(o[2])+1n)})`:`${n} (1)`}${i}`}return e}function Y1(r){return lr.test(r)?{basename:r.replace(lr,""),extension:".canvas"}:Mn.test(r)?{basename:r.replace(Mn,""),extension:".base"}:{basename:r.replace(xt,""),extension:".md"}}var V1,XA,yC,J6,Z6,N1,eX,ja=x(()=>{Ve();V1=[{id:"prompt",label:"Ask every time"},{id:"update",label:"Update existing file"},{id:"create",label:"Create another file"},{id:"keep",label:"Keep existing file"}],XA=[{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"}],yC=[{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"}];J6=new Map(XA.map(r=>[r.id,r])),Z6={update:"appendBottom",create:"duplicateSuffix",keep:"doNothing"},N1={"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"},eX={increment:tX,duplicateSuffix:rX}});function xI(r,t){if(!r.fileNameFormat?.enabled)return!0;let e=t.trim().toLowerCase();return e===Cr.toLowerCase()||e===JD.toLowerCase()}function EI(r,t){return r.discoverExistingNotesBeforeCreate===!0&&xI(r,t)}function bc(r,t,e){return!(!EI(r,t)||e!=null)}var Jd=x(()=>{Ve()});function wi(r,{title:t,message:e,action:n,destructive:i=!0}){return new Promise(o=>{let s=!1,a=new OV.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(UC),a.setCloseCallback(()=>o(s)),a.open()})}function UC(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 OV,Ka=x(()=>{OV=require("obsidian")});function LV(r){kI=r}function zr(){if(!kI)throw new Error("QuickAdd plugin instance accessed before it was initialised.");return kI}var kI,rs=x(()=>{});var jt,Zt=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 qs(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=q5.exec(c);if(n){if(u&&u[1].length>=i&&u[2].trim().length===0)return BV(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?BV(r.slice(o),s):{code:null,error:z5}}function BV(r,t){return r.trim().length===0?{code:"",error:H5}:{code:`
- `.repeat(t)+r}}var q5,z5,H5,Cm=x(()=>{q5=/^ {0,3}(`{3,})(.*)$/,z5="No ```js (or ```javascript) code block found in the note.",H5="The ```js code block is empty."});function ns(r,t){let e=t;for(;e<r.length;){let n=r[e],i=r[e+1];if(/\s/.test(n)){e+=1;continue}if(n==="/"&&i==="/"){let o=r.indexOf(`
- `,e+2);e=o===-1?r.length:o+1;continue}if(n==="/"&&i==="*"){let o=r.indexOf("*/",e+2);e=o===-1?r.length:o+2;continue}return e}return e}function Av(r,t){let e=r[t];if(e!=='"'&&e!=="'"&&e!=="`")return null;let n="";for(let i=t+1;i<r.length;i++){let o=r[i];if(o==="\\"){let s=r[i+1];if(s===void 0)return null;n+=s,i+=1;continue}if(o===e)return{value:n,end:i+1};n+=o}return null}function UV(r,t){let e=/^[A-Za-z_$][\w$]*/.exec(r.slice(t));return e?{value:e[0],end:t+e[0].length}:null}function zC(r,t,e,n){let i=0;for(let o=t;o<r.length;o++){let s=r[o],a=r[o+1];if(s==='"'||s==="'"||s==="`"){let l=Av(r,o);if(!l)return-1;o=l.end-1;continue}if(s==="/"&&a==="/"){let l=r.indexOf(`
- `,o+2);o=l===-1?r.length:l;continue}if(s==="/"&&a==="*"){let l=r.indexOf("*/",o+2);if(l===-1)return-1;o=l+1;continue}if(s===e){i+=1;continue}if(s===n&&(i-=1,i===0))return o}return-1}function qV(r){let t=new Map,e=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(["'`])/g,n;for(;(n=e.exec(r))!==null;){let i=Av(r,e.lastIndex-1);i&&(t.set(n[1],i.value),e.lastIndex=i.end)}return t}function G5(r){let t=[],e=qV(r),n=0;for(;n<r.length;){n=ns(r,n);let i=r[n];if(i==='"'||i==="'"||i==="`"){let a=Av(r,n);n=a?a.end:n+1;continue}let o=$I(r,n,e);if(!o){n+=1;continue}if(n=ns(r,o.end),r[n]!==":"){n=o.end;continue}if(n=ns(r,n+1),o.name!=="options"||r[n]!=="{")continue;let s=zC(r,n,"{","}");if(s===-1)break;t.push({start:n+1,end:s}),n=s+1}return t}function $I(r,t,e){if(r[t]==='"'||r[t]==="'"||r[t]==="`"){let i=Av(r,t);return i?{name:i.value,end:i.end}:null}if(r[t]==="["){let i=ns(r,t+1),o=UV(r,i),s=zC(r,t,"[","]");if(s===-1)return null;let a=o?ns(r,o.end):i;return{name:o&&a===s?e.get(o.value)??null:null,end:s+1}}let n=UV(r,t);return n?{name:n.value,end:n.end}:null}function j5(r){let t=new Map,e=0;for(;e<r.length;){if(e=ns(r,e),r[e]===","){e+=1;continue}if(e>=r.length)break;let n=$I(r,e,new Map);if(!n?.name){e+=1;continue}if(e=ns(r,n.end),r[e]!==":"){e+=1;continue}if(e=ns(r,e+1),r[e]==='"'||r[e]==="'"||r[e]==="`"){let o=Av(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=zC(r,e,i,i==="{"?"}":"]");if(o===-1)break;e=o+1;continue}for(;e<r.length&&r[e]!==",";)e+=1}return t}function Y5(r){let t=j5(r),e=t.get("type"),n=t.get("secret");return e==="secret"||(e==="text"||e==="input")&&n===!0}function Iv(r,t){let e=t&&W5.test(t)?qs(r).code??"":r,n=new Set,i=!1,o=qV(e);for(let{start:s,end:a}of G5(e)){let l=s;for(;l<a;){if(l=ns(e,l),e[l]===","){l+=1;continue}if(l>=a)break;let c=$I(e,l,o);if(!c){l+=1;continue}if(l=ns(e,c.end),e[l]!==":"){l+=1;continue}if(l=ns(e,l+1),e[l]!=="{"){l+=1;continue}let d=zC(e,l,"{","}");if(d===-1||d>a)break;let u=e.slice(l+1,d);Y5(u)&&(i=!0,c.name&&n.add(c.name)),l=d+1}}return{names:n,foundSecretOptions:i}}var W5,zV=x(()=>{Cm();W5=/\.md$/i});function Tr(r){return typeof r=="object"&&r!==null}function Qa(r){return Tr(r)&&!Array.isArray(r)}function K5(r){return Qa(r)?!1:Array.isArray(r)?r.length>0:Wt(r)}function dr(r){return Qa(r)?r.commands:K5(r)?r:void 0}function Mt(r){return Array.isArray(r)?r:[]}function xm(r){return Array.isArray(r)?r:[]}function Pv(r){return Array.isArray(r)}function FI(r){let t=Mt(r),e=new Set,n=!1,i=[];for(let o of t){if(Array.isArray(o)){let l=FI(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 HV(r){WV(r,new Set)}function WV(r,t){Tr(r)&&(t.has(r)||(t.add(r),Qa(r)&&(r.id=Vt()),HC(dr(r),t)))}function HC(r,t){if(Pv(r))for(let e of r){if(Array.isArray(e)){HC(e,t);continue}if(!Tr(e)||t.has(e))continue;t.add(e),e.id=Vt();let n=e;HC(n.thenCommands,t),HC(n.elseCommands,t),GV(n.choice,t)}}function GV(r,t){if(!Tr(r)||t.has(r))return;t.add(r);let e=r;if(e.id=Vt(),e.type==="Macro"&&WV(e.macro,t),e.type==="Multi"&&Array.isArray(e.choices))for(let n of e.choices)GV(n,t)}var Hr=x(()=>{Oh();jo();Oh()});function Tm(r){return r!==null&&typeof r=="object"}function KC(r){return r?.secretStorage}function GC(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"setting"}function X5(r){let t=5381;for(let e=0;e<r.length;e+=1)t=t*33^r.charCodeAt(e);return(t>>>0).toString(36).slice(0,Q5)}function YV(r,t){return r.length<=t?r:r.slice(0,t).replace(/-+$/g,"")||"setting"}function QV(r,t){let e=t?.id;return typeof e=="string"&&e.trim().length>0?e:r}function MI(r,t,e){let i=(e?[WC,r,t,e]:[WC,r,t]).join("-");if(i.length<=jV)return i;let o=X5([r,t,e].filter(Boolean).join(":")),s=e?4:3,a=jV-WC.length-o.length-(e?.length??0)-s,l=Math.max(8,Math.floor(a*.6)),c=Math.max(8,a-l);return[WC,YV(r,l),YV(t,c),...e?[e]:[],o].join("-")}function RI(r){return r?.message??String(r)}function _m(r){return Tm(r)?r.type==="secret"||(r.type==="text"||r.type==="input")&&r.secret===!0:!1}function Em(r){return Tm(r)&&r[KV]===!0&&typeof r.secretRef=="string"&&r.secretRef.trim().length>0}function jC(r){return{[KV]:!0,secretRef:r}}function J5(r,t,e){let n=r.id?.trim()||r.path||r.name||"script";return MI(GC(n),GC(QV(t,e)))}function Z5(r){let t=r?.options;return t?Object.entries(t).filter(([,e])=>_m(e)).map(([e])=>e):[]}function e8(r){let t=r?.options;return t?Object.entries(t).filter(([,e])=>_m(e)):[]}function t8(r){return typeof r.id=="string"&&r.id.trim().length>0}async function DI(r,t){let e=KC(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}": ${RI(n)}`),null}}async function r8(r,t,e){let n=KC(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}": ${RI(i)}`),!1}}async function n8(r,t,e,n,i){let o=t.id?.trim()||t.path||t.name||"script",s=GC(o),a=GC(QV(e,i)),l=MI(s,a),c=1;for(;;){let d=await DI(r,l);if(!d||d===n)return l;c+=1,l=MI(s,a,String(c))}}async function OI(r,t,e,n,i,o){if(n.length===0)return null;let s=i?.trim()||await n8(r,t,e,n,o);return await r8(r,s,n)?s:null}async function LI(r,t){let e=t?.trim();if(!e)return!0;let n=KC(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}": ${RI(o)}`)}return!1}async function XV(r,t,e){let n=t.settings??{},i={...n},o=new Set(Z5(e));for(let[s,a]of Object.entries(n)){if(Em(a)){let l=await DI(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 QC(r,t,e){let n=e8(e);if(n.length===0)return!1;let i=KC(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(Em(l))continue;if(typeof l!="string"||l.length===0){if(!t8(a))continue;let d=J5(t,s,a);if(!await DI(r,d))continue;t.settings[s]=jC(d);for(let[p,m]of Object.entries(t.settings))p!==s&&Em(m)&&m.secretRef===d&&delete t.settings[p];o=!0;continue}let c=await OI(r,t,s,l,void 0,a);c&&(t.settings[s]=jC(c),o=!0)}return o}function XC(r,t){let e=r.settings?.[t];return Em(e)?e.secretRef:void 0}async function i8(r,t){if(!Tm(t))return!0;let e=Object.values(t).filter(Em).map(i=>i.secretRef);return(await Promise.all(e.map(i=>LI(r,i)))).every(Boolean)}function*NI(r){if(Tm(r)&&(r.type==="Macro"&&(yield*YC(dr(r.macro))),r.type==="Multi"&&Array.isArray(r.choices)))for(let t of r.choices)yield*NI(t)}function*VI(r){Tm(r)&&(r.type==="UserScript"&&(yield r),yield*YC(r.thenCommands),yield*YC(r.elseCommands),yield*NI(r.choice))}function*YC(r){if(Array.isArray(r))for(let t of r)yield*Array.isArray(t)?YC(t):VI(t)}async function o8(r,t){let e=!0;for(let n of t)e=await i8(r,n.settings)&&e;return e}async function JC(r,t){return o8(r,VI(t))}function s8(r,t){let e=r.path;if(typeof e=="string")return t?.secretOptionNamesByPath?.get(e)}function a8(r,t,e){if(Tm(r))for(let[n,i]of Object.entries(r)){if(Em(i)){delete r[n];continue}typeof i=="string"&&(t===null||t?.has(n)||t===void 0&&e?.stripUnknownStringSettings===!0)&&delete r[n]}}function JV(r,t){for(let e of r)a8(e.settings,s8(e,t),t)}function ZV(r,t){JV(VI(r),t)}function ZC(r,t){JV(NI(r),t)}var WC,KV,jV,Q5,Xa=x(()=>{ye();zV();Hr();WC="quickadd-user-script",KV="__quickaddSecret",jV=64,Q5=8});function km(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&&!_m(t.options[e])&&(r[e]=t.options[e].defaultValue)}}var ex=x(()=>{Xa()});function ix(r){return r instanceof rx}function d8(r){return r.charCodeAt(0)===65279?r.slice(1):r}function u8(r){return d8(r).trimStart().slice(0,c8).toLowerCase()}function p8(r){return/^<(?:!doctype\s+html|html\b|head\b|body\b|script\b|meta\b|title\b|div\b)/.test(u8(r))}function Sm(r,t){let e=new rx(r);throw t.reportLoadErrors!==!1&&Me(e),e}function m8(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 f8(r){return`QuickAdd could not find ${r}. If you moved or renamed the script, update its path in the macro.`}function h8(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 g8(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 v8(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 y8(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 b8(r,t){if(r.startsWith("#!"))return;let e=window.require?.("vm");try{e?.compileFunction(r,rB,{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 w8(r){return nB(r)?(r instanceof Error?r.message:String(r)).match(/Cannot find module ['"]([^'"]+)['"]/)?.[1]:void 0}function nB(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 BI(r){return r!==null&&typeof r=="object"}function C8(r){return typeof r.entry=="function"?!0:Object.entries(r).some(([t,e])=>t!=="settings"&&t!=="quickadd"&&typeof e=="function")}function x8(r){return typeof r=="function"?!0:BI(r)?C8(r):!1}function Am(r){let t=r.split("::").map(e=>e.trim()).filter(Boolean);return{basename:t[0],memberAccess:t.slice(1)}}function ox(r){let t=r.path??r.id;if(t===void 0)return;let{memberAccess:e}=Am(r.name??"");return e&&e.length>0?`${t}::${e.join("::")}`:t}function tB(r){if(!BI(r)&&typeof r!="function")return;let t=r.settings;return BI(t)?t:void 0}function E8(r,t){let e=r,n=tB(e);for(let i of t)e=e[i],n=tB(e)??n;return{script:e,settings:n}}async function $v(r,t,e={}){return(await Zd(r,t,e))?.script}async function Zd(r,t,e={}){let n=t.vault.getAbstractFileByPath(r.path);if(n||Sm(f8(r.path),e),n instanceof nx.TFile){let i=xt.test(n.path);!i&&!Sh.test(n.path)&&Sm(m8(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}=qs(l);if(g===null||g.length===0){e.reportLoadErrors!==!1&&new nx.Notice(`QuickAdd: ${v} (${r.path})`);return}c=g}p8(c)&&Sm(h8(r.path),e);let d;try{d=new Function(...rB,c)}catch(g){throw g instanceof SyntaxError&&Sm(y8(r.path,g.message,b8(c,g.message)),e),g}try{d(o,a,s)}catch(g){throw nB(g)&&Sm(v8(r.path,w8(g)),e),g}let u=s.default||a.exports;if(!u)return;let p=!!s.default,m=Am(r.name).memberAccess??[],h=E8(u,m);return p&&m.length===0&&!x8(h.script)&&Sm(g8(r.path),e),h}}var nx,c8,rx,rB,eu=x(()=>{nx=require("obsidian");Ve();Cm();nt();c8=1024,rx=class extends Error{constructor(t){super(t),this.name="UserScriptLoadError"}};rB=["require","module","exports"]});function Cc(r){return Array.isArray?Array.isArray(r):pB(r)==="[object Array]"}function S8(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 zI(r){return r==null?"":S8(r)}function Vn(r){return typeof r=="string"}function lx(r){return typeof r=="number"}function A8(r){return r===!0||r===!1||I8(r)&&pB(r)=="[object Boolean]"}function uB(r){return typeof r=="object"}function I8(r){return uB(r)&&r!==null}function zi(r){return r!=null}function ax(r){return!r.trim().length}function pB(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}function mB(r){let t=null,e=null,n=null,i=1,o=null;if(Vn(r)||Cc(r))n=r,t=oB(r),e=cx(r);else{if(!iB.call(r,"name"))throw new Error(M8("name"));let s=r.name;if(n=s,iB.call(r,"weight")&&r.weight!==void 0&&(i=r.weight,i<=0))throw new Error(R8(cx(s)));t=oB(s),e=cx(s),o=r.getFn??null}return{path:t,id:e,weight:i,src:n,getFn:o}}function oB(r){return Cc(r)?r:r.split(".")}function cx(r){return Cc(r)?r.join("."):r}function L8(r,t){let e=[],n=!1,i=(o,s,a,l)=>{if(zi(o))if(!s[a])e.push(l!==void 0?{v:o,i:l}:o);else{let c=o[s[a]];if(!zi(c))return;if(a===s.length-1&&(Vn(c)||lx(c)||A8(c)||typeof c=="bigint"))e.push(l!==void 0?{v:zI(c),i:l}:zI(c));else if(Cc(c)){n=!0;for(let d=0,u=c.length;d<u;d+=1)i(c[d],s,a+1,d)}else s.length&&i(c,s,a+1,l)}};return i(r,Vn(t)?t.split("."):t,0),n?e:e[0]}function q8(r){return r>=9&&r<=13||r===32||r===160}function z8(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<i.length;l++)q8(i.charCodeAt(l))?s=!1:s||(o++,s=!0);if(o===0&&(o=1),e.has(o))return e.get(o);let a=Math.round(n/Math.pow(o,.5*r))/n;return e.set(o,a),a},clear(){e.clear()}}}function fB(r,t,{getFn:e=Ue.getFn,fieldNormWeight:n=Ue.fieldNormWeight}={}){let i=new XI({getFn:e,fieldNormWeight:n});return i.setKeys(r.map(mB)),i.setSources(t),i.create(),i}function H8(r,{getFn:t=Ue.getFn,fieldNormWeight:e=Ue.fieldNormWeight}={}){let{keys:n,records:i}=r,o=new XI({getFn:t,fieldNormWeight:e});return o.setKeys(n),o.setIndexRecords(i),o}function W8(r=[],t=Ue.minMatchCharLength){let e=[],n=-1,i=-1,o=0;for(let s=r.length;o<s;o+=1){let a=r[o];a&&n===-1?n=o:!a&&n!==-1&&(i=o-1,i-n+1>=t&&e.push([n,i]),n=-1)}return r[o-1]&&o-n>=t&&e.push([n,o-1]),e}function G8(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(F8(32));let d=t.length,u=r.length,p=Math.max(0,Math.min(n,u)),m=o,h=p,g=(O,N)=>{let K=O/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 O=g(0,y);if(m=Math.min(O,m),h=y+d,v){let N=0;for(;N<d;)b[y+N]=1,N+=1}}h=-1;let C=[],w=1,T=0,P=d+u,_=1<<d-1;for(let O=0;O<d;O+=1){let N=0,K=P;for(;N<K;)g(O,p+K)<=m?N=K:P=K,K=Math.floor((P-N)/2+N);P=K;let ne=Math.max(1,p-K+1),H=s?u:Math.min(p+K,u)+d,D=Array(H+2);D[H+1]=(1<<O)-1;for(let G=H;G>=ne;G-=1){let V=G-1,M=e[r[V]];if(D[G]=(D[G+1]<<1|1)&M,O&&(D[G]|=(C[G+1]|C[G])<<1|1|C[G+1]),D[G]&_&&(w=g(O,V),w<=m)){if(m=w,h=V,T=O,h<=p)break;ne=Math.max(1,2*p-h)}}if(g(O+1,p)>m)break;C=D}if(v&&h>=0){let O=Math.min(u-1,h+d-1+T);for(let N=h;N<=O;N+=1)e[r[N]]&&(b[N]=1)}let I={isMatch:h>=0,score:Math.max(.001,w)};if(v){let O=W8(b,a);O.length?l&&(I.indices=O):I.isMatch=!1}return I}function j8(r){let t={};for(let e=0,n=r.length;e<n;e+=1){let i=r.charAt(e);t[i]=(t[i]||0)|1<<n-e-1}return t}function JI(r){if(r.length<=1)return r;r.sort((e,n)=>e[0]-n[0]||e[1]-n[1]);let t=[r[0]];for(let e=1,n=r.length;e<n;e+=1){let i=t[t.length-1],o=r[e];o[0]<=i[1]+1?i[1]=Math.max(i[1],o[1]):t.push(o)}return t}function Q8(r){return r.startsWith("inverse")}function Z8(r){let t=[],e=r.length,n=0;for(;n<e;){for(;n<e&&r[n]===" ";)n++;if(n>=e)break;let i=n;for(;i<e&&r[i]!==" "&&r[i]!=='"';)i++;if(i<e&&r[i]==='"'){for(i++;i<e;){if(r[i]==='"'){let o=i+1;if(o>=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<e&&r[i]!==" ";)i++;t.push(r.substring(n,i)),n=i}}return t}function aB(r,t){let e=r.match(t);return e?e[1]:null}function e9(r,t={}){return r.replace(/\\\|/g,X8).split(J8).map(e=>{let n=Z8(e.replace(/\u0000/g,"|").trim()).filter(o=>o&&!!o.trim()),i=[];for(let o=0,s=n.length;o<s;o+=1){let a=n[o],l=!1,c=-1;for(;!l&&++c<sB;){let d=WI[c],u=aB(a,d.multiRegex);u&&(i.push(d.create(u,t)),l=!0)}if(!l)for(c=-1;++c<sB;){let d=WI[c],u=aB(a,d.singleRegex);if(u){i.push(d.create(u,t));break}}}return i})}function eP(...r){GI.push(...r)}function dx(r,t){for(let e=0,n=GI.length;e<n;e+=1){let i=GI[e];if(i.condition(r,t))return new i(r,t)}return new ZI(r,t)}function gB(r,t,{auto:e=!0}={}){let n=i=>{if(Vn(i)){let l={keyId:null,pattern:i};return e&&(l.searcher=dx(i,t)),l}let o=Object.keys(i),s=r9(i);if(!s&&o.length>1&&!YI(i))return n(lB(i));if(n9(i)){let l=s?i[jI.PATH]:o[0],c=s?i[jI.PATTERN]:i[l];if(!Vn(c))throw new Error($8(l));let d={keyId:cx(l),pattern:c};return e&&(d.searcher=dx(c,t)),d}let a={children:[],operator:o[0]};return o.forEach(l=>{let c=i[l];Cc(c)&&c.forEach(d=>{a.children.push(n(d))})}),a};return YI(r)||(r=lB(r)),n(r)}function KI(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 i9(r,{ignoreFieldNorm:t=Ue.ignoreFieldNorm}){r.forEach(e=>{e.score=KI(e.matches,{ignoreFieldNorm:t})})}function s9(r){let t=[];return r.matches.forEach(e=>{if(!zi(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 a9(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=s9(i)),n&&(s.score=i.score),s})}function c9(r){cB.has(r)||(cB.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 d9(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||c9(r),t=>t.match(r)||[]):t=>t.match(l9)||[]}function QI({isCaseSensitive:r=!1,ignoreDiacritics:t=!1,tokenize:e}={}){let n=d9(e);return{tokenize(i){return r||(i=i.toLowerCase()),t&&(i=Fv(i)),n(i)}}}function qI(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 vB(r,t,e,n){let{i,v:o,$:s}=t;if(o!==void 0){qI(r,o,i,n);return}if(s)for(let a=0;a<e;a++){let l=s[a];if(l)if(Array.isArray(l))for(let c of l)qI(r,c.v,i,n);else qI(r,l.v,i,n)}}function p9(r,t,e){let n={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of r)vB(n,i,t,e);return n}function m9(r,t,e,n){vB(r,t,e,n)}function f9(r,t){let e=r.docFieldCount.get(t);if(e===void 0)return;r.fieldCount-=e,r.docFieldCount.delete(t);let n=r.docTermFieldHits.get(t);if(n){for(let[i,o]of n){let s=(r.df.get(i)||0)-o;s<=0?r.df.delete(i):r.df.set(i,s)}r.docTermFieldHits.delete(t)}}function dB(r,t){if(t.length===0)return;let e=Array.from(new Set(t)).sort((a,l)=>a-l);for(let a of e)f9(r,a);let n=a=>{let l=0,c=e.length;for(;l<c;){let d=l+c>>>1;e[d]<a?l=d+1:c=d}return a-l},i=e[0],o=new Map;for(let[a,l]of r.docFieldCount)o.set(a>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 P8,HI,$8,F8,M8,R8,D8,iB,O8,N8,V8,B8,U8,Ue,XI,hB,Y8,Fv,ZI,K8,WI,sB,X8,J8,t9,GI,ux,jI,YI,r9,n9,lB,o9,l9,cB,u9,xc,Ec,px=x(()=>{P8="Incorrect 'index' type",HI="Invalid doc index: must be a non-negative integer within the bounds of the docs array",$8=r=>`Invalid value for key ${r}`,F8=r=>`Pattern length exceeds max of ${r}.`,M8=r=>`Missing ${r} property in key`,R8=r=>`Property 'weight' in key '${r}' must be a positive integer`,D8="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.",iB=Object.prototype.hasOwnProperty,O8=class{constructor(r){this._keys=[],this._keyMap={};let t=0;r.forEach(e=>{let n=mB(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)}};N8={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},V8={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(r,t)=>r.score===t.score?r.idx<t.idx?-1:1:r.score<t.score?-1:1},B8={location:0,threshold:.6,distance:100},U8={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:L8,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},Ue=Object.freeze({...V8,...N8,...B8,...U8});XI=class{constructor({getFn:r=Ue.getFn,fieldNormWeight:t=Ue.fieldNormWeight}={}){this.norm=z8(t,3),this.getFn=r,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(r=[]){this.docs=r}setIndexRecords(r=[]){this.records=r}setKeys(r=[]){this.keys=r,this._keysMap={},r.forEach((t,e)=>{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;e<r;e++){let n=this._createStringRecord(this.docs[e],e);n&&(this.records[t++]=n)}else for(let e=0;e<r;e++)this.records[t++]=this._createObjectRecord(this.docs[e],e);this.records.length=t,this.norm.clear()}add(r,t){if(!Number.isInteger(t)||t<0)throw new Error(HI);if(Vn(r)){let n=this._createStringRecord(r,t);return n&&this.records.push(n),n}let e=this._createObjectRecord(r,t);return this.records.push(e),e}removeAt(r){if(!Number.isInteger(r)||r<0)throw new Error(HI);for(let t=0,e=this.records.length;t<e;t+=1)if(this.records[t].i===r){this.records.splice(t,1);break}for(let t=0,e=this.records.length;t<e;t+=1)this.records[t].i>r&&(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<o;){let s=i+o>>>1;e[s]<n.i?i=s+1:o=s}n.i-=i}}getValueForItemAtKeyId(r,t){return r[this._keysMap[t]]}size(){return this.records.length}_createStringRecord(r,t){return!zi(r)||ax(r)?null:{v:r,i:t,n:this.norm.get(r)}}_createObjectRecord(r,t){let e={i:t,$:{}};for(let n=0,i=this.keys.length;n<i;n++){let o=this.keys[n],s=o.getFn?o.getFn(r):this.getFn(r,o.path);if(zi(s)){if(Cc(s)){let a=[];for(let l=0,c=s.length;l<c;l+=1){let d=s[l];if(zi(d)){if(Vn(d)){if(!ax(d)){let u={v:d,i:l,n:this.norm.get(d)};a.push(u)}}else if(zi(d.v)){let u=Vn(d.v)?d.v:zI(d.v);if(!ax(u)){let p={v:u,i:d.i,n:this.norm.get(u)};a.push(p)}}}}e.$[n]=a}else if(Vn(s)&&!ax(s)){let a={v:s,n:this.norm.get(s)};e.$[n]=a}}}return e}toJSON(){return{keys:this.keys.map(({getFn:r,...t})=>t),records:this.records}}};hB={\u0142:"l",\u0141:"L",\u0111:"d",\u0110:"D",\u00F8:"o",\u00D8:"O",\u0127:"h",\u0126:"H",\u0167:"t",\u0166:"T",\u0131:"i",\u00DF:"ss"},Y8=new RegExp("["+Object.keys(hB).join("")+"]","g"),Fv=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(Y8,t=>hB[t]):r=>r,ZI=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?Fv(r):r,this.pattern=r,this.chunks=[],!this.pattern.length)return;let d=(p,m)=>{this.chunks.push({pattern:p,alphabet:j8(p),startIndex:m})},u=this.pattern.length;if(u>32){let p=0,m=u%32,h=u-m;for(;p<h;)d(this.pattern.substr(p,32),p),p+=32;if(m){let g=u-32;d(this.pattern.substr(g),g)}}else d(this.pattern,0)}searchIn(r){let{isCaseSensitive:t,ignoreDiacritics:e,includeMatches:n}=this.options;if(r=t?r:r.toLowerCase(),r=e?Fv(r):r,this.pattern===r){if(r.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let h={isMatch:!0,score:0};return n&&(h.indices=[[0,r.length-1]]),h}let{location:i,distance:o,threshold:s,findAllMatches:a,minMatchCharLength:l,ignoreLocation:c}=this.options,d=[],u=0,p=!1;this.chunks.forEach(({pattern:h,alphabet:g,startIndex:v})=>{let{isMatch:b,score:y,indices:C}=G8(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=JI(d)),m}},K8=new Set(["fuzzy","include"]);WI=[{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 ZI(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)}}}}],sB=WI.length,X8="\0",J8="|";t9=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?Fv(r):r,this.pattern=r,this.query=e9(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?Fv(r):r;let o=0,s=[],a=0,l=!1;for(let c=0,d=t.length;c<d;c+=1){let u=t[c];s.length=0,o=0,l=!1;for(let p=0,m=u.length;p<m;p+=1){let h=u[p],{isMatch:g,indices:v,score:b}=h.search(r);if(g)o+=1,a+=b,Q8(h.type)&&(l=!0),e&&(K8.has(h.type)?s.push(...v):s.push(v));else{a=0,o=0,s.length=0,l=!1;break}}if(o){let p={isMatch:!0,score:a/o};return l&&(p.hasInverse=!0),e&&(p.indices=JI(s)),p}}return{isMatch:!1,score:1}}},GI=[];ux={AND:"$and",OR:"$or"},jI={PATH:"$path",PATTERN:"$val"},YI=r=>!!(r[ux.AND]||r[ux.OR]),r9=r=>!!r[jI.PATH],n9=r=>!Cc(r)&&uB(r)&&!YI(r),lB=r=>({[ux.AND]:Object.keys(r).map(t=>({[t]:r[t]}))});o9=class{constructor(r,t){this.limit=r,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(r){this.size<this.limit?(this.heap.push(r),this._bubbleUp(this.size-1)):this.comparator(r,this.heap[0])<0&&(this.heap[0]=r,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(r){let t=this.heap;for(;r>0;){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(i<e&&this.comparator(t[i],t[n])>0&&(n=i),o<e&&this.comparator(t[o],t[n])>0&&(n=o),n!==r){let s=t[r];t[r]=t[n],t[n]=s}}while(n!==r)}};l9=/[\p{L}\p{M}\p{N}_]+/gu,cB=new WeakSet;u9=class{static condition(r,t){return t.useTokenSearch}constructor(r,t){this.options=t,this.analyzer=QI({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 ZI(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;c<this.termSearchers.length;c++){let d=this.termSearchers[c].searchIn(r),u=this.idfWeights[c];n+=u,d.isMatch&&(i++,e+=u*(1-d.score),d.indices&&t.push(...d.indices),this.combineAll&&(this.useMask?o|=1<<c:s.add(c)))}if(i===0)return{isMatch:!1,score:1};let a=n>0?1-e/n:0,l={isMatch:!0,score:Math.max(.001,a)};return this.options.includeMatches&&t.length&&(l.indices=JI(t)),this.combineAll&&(this.useMask?l.matchedMask=o:l.matchedTerms=s,l.termCount=this.numTerms),l}};xc=class{constructor(r,t,e){this.options={...Ue,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new O8(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=dx(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 XI))throw new Error(P8);if(this._myIndex=t||fB(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=QI({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=p9(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(r){if(!zi(r))return;this._docs.push(r);let t=this._myIndex.add(r,this._docs.length-1);if(this._invertedIndex&&t){let e=QI({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});m9(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<i;n+=1)r(this._docs[n],n)&&(t.push(this._docs[n]),e.push(n));if(e.length){this._invertedIndex&&dB(this._invertedIndex,e);let n=new Set(e);this._docs=this._docs.filter((i,o)=>!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(HI);this._invertedIndex&&dB(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 lx(e)&&e>-1&&(p=p.slice(0,e)),p}let l=o&&lx(e)&&e>0&&Vn(r),c=s,d=(p,m)=>c(p,m)||p.idx-m.idx,u;if(l){let p=new o9(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),i9(u,{ignoreFieldNorm:a}),o&&u.sort(Vn(r)?d:c),lx(e)&&e>-1&&(u=u.slice(0,e));return a9(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(!zi(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=KI(m.matches,{ignoreFieldNorm:e}),t.insert(m)):s.push(m)}}}),s}_searchLogical(r){let t=gB(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<h;m+=1){let g=d[m],v=n(g,l,c);if(v.length)p.push(...v);else if(u===ux.AND)return[]}return p},i=this._myIndex.records,o=new Map,s=[];return i.forEach(({$:a,i:l})=>{if(zi(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(!zi(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=KI(m.matches,{ignoreFieldNorm:e}),t.insert(m)):a.push(m)}}),a}_findMatches({key:r,value:t,searcher:e}){if(!zi(t))return[];let n=[];if(Cc(t))t.forEach(({v:i,i:o,n:s})=>{if(!zi(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;i<r.length;i++)n|=r[i].matchedMask||0;return n===2**t-1}let e=new Set;for(let n=0;n<r.length;n++){let i=r[n].matchedTerms;if(i)for(let o of i)e.add(o)}return e.size===t}};xc.version="7.5.0";xc.createIndex=fB;xc.parseIndex=H8;xc.config=Ue;xc.match=function(r,t,e){if(e&&e.useTokenSearch)throw new Error(D8);return dx(r,{...Ue,...e}).searchIn(t)};xc.parseQuery=gB;eP(t9);eP(u9);xc.use=function(...r){r.forEach(t=>eP(t))};Ec=xc});function h9(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 yB(r,t,e){let n=r.metadataCache.getFileCache(t),i=n?.frontmatter,o=h9(i),s=o.map(d=>Ht(d)),a=(n?.headings??[]).map(d=>IS(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 bB=x(()=>{on()});function wB(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)/864e5<i.thresholds.recencyDays&&(a+=i.boosts.recency),e.currentFile&&o){let m=r.tags.filter(h=>o.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 mx,tP=x(()=>{on();mx={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 Mv,rP,g9,v9,CB,Im,nP=x(()=>{Mv=require("obsidian");px();bB();tP();tP();on();rP=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()}},g9=20,v9=100,CB=/\w/,Im=class r{constructor(t,e){this.fileMap=new Map;this.recentFiles=new rP;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=mx;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 Ec([],{...n,threshold:.2}),this.fuseRelaxed=new Ec([],{...n,threshold:.4}),this.setupEventListeners(),this.effectiveWeights=mx}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 Mv.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 Mv.TFile&&t.extension==="md"&&this.addFile(t)})),this.plugin.registerEvent(this.app.vault.on("delete",t=>{t instanceof Mv.TFile&&this.removeFile(t)})),this.plugin.registerEvent(this.app.vault.on("rename",(t,e)=>{t instanceof Mv.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;a<o.length;a+=s){let l=o.slice(a,a+s);for(let c of l){let d=this.createIndexedFile(c);n.set(c.path,d)}await new Promise(c=>window.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 yB(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()},v9)}processPendingFuseUpdates(){if(this.pendingFuseUpdates.size!==0){if(this.isIndexing){this.pendingFuseUpdates.clear();return}if(this.pendingFuseUpdates.size>g9){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&&!CB.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 wB(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&&!CB.test(u.basenameNormalized[p-1])&&c(u,i.substringBasename,"fuzzy",u.basename)}let d=this.fuseStrict.search(s,{limit:n*2});d.length<this.effectiveWeights.thresholds.fuzzyRelaxCount&&(d=this.fuseRelaxed.search(s,{limit:n*2}));for(let u of d){if(!u||!u.item||!u.item.path||a.has(u.item.path))continue;let p=(u.matches??[]).find(v=>v.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 y9(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 fx,Pm,iP=x(()=>{Ps();fx=require("obsidian");Ve();nP();on();rs();Go();Pm=class extends Er{constructor(e,n,i){super(e,n);this.app=e;this.inputEl=n;this.lastInput="";this.sourcePathOverride=i?.sourcePath,this.fileIndex=Im.getInstance(e,zr()),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=rO.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=y9(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=Li(this.inputEl),o=()=>this.hideTooltip();i.addEventListener("scroll",o,{passive:!0}),this.scrollListener=o,this.scrollListenerDocument=i}}hideTooltip(){let e=Li(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=Li(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 fx.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 fx.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 fx.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 xB,hx,EB=x(()=>{px();xB={threshold:.4,includeScore:!0,keys:[""]},hx=class r{constructor(t,e){this.sortedTags=[];this.fuse=new Ec([],xB);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 Ec(this.sortedTags,xB)}getSortedTags(){return this.sortedTags}search(t){return this.fuse.search(t)}}});function b9(r,t){let e=r.slice(0,t),n=e.lastIndexOf("[[");return n===-1?!1:e.lastIndexOf("]]")<n}var $m,oP=x(()=>{Ve();Ps();on();rs();EB();$m=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=hx.getInstance(e,zr()),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=nO.exec(i);if(!o)return[];if(o.index===void 0)return[];if(b9(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}`;Zb(n,i,o,s,{fromCompletion:!0}),this.close()}}});var Bn,Fm=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 gx,TB=x(()=>{je();Fm();gx=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 vx(r,t){if(r.focus(),t?.cursorAtEnd){let e=r.value.length;r.setSelectionRange(e,e);return}r.select()}var sP=x(()=>{});function _B(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 kB=x(()=>{});function SB(r){return(r??"").trim().replace(/\\/g,"/")}function w9(r){return r.startsWith("/")||/^[a-zA-Z]:/.test(r)}function C9(r){return r.split("/").some(t=>/^\.\.[. ]*$/u.test(t))}function Ut(r){let t=SB(r);return t?w9(t)||C9(t):!1}function yx(r){let t=SB(r);return!t||Ut(t)?!1:!t.split("/").some(e=>e.startsWith(".")&&!e.startsWith("..%"))}var Hi=x(()=>{});function Za(r){return Object.hasOwn(Ja,r)}function AB(r){let t=r.toLowerCase();return t==="jpeg"||Object.values(Ja).includes(t)}function x9(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 T9(r){return r.replace(E9,"").replace(/\s+/g," ").replace(/[. ]+$/g,"").trim()}function bx(r){if(r.nameAfterNoteTitle){let t=T9(Ep(r.sourcePath));if(t.length>0&&RS(t))return`${t}.${r.extension}`}return`Clipboard image ${x9(r.now)}.${r.extension}`}function IB(r,t){if(!Za(r))throw new Error(`Unsupported clipboard image type: ${r}`);return bx({extension:Ja[r],sourcePath:"",now:t,nameAfterNoteTitle:!1})}function PB(r){let t=r.split(/[\\/]/u).at(-1)??"",e=t.lastIndexOf("."),n=e>=0?t.slice(0,e):t;return RS(n)?n:null}async function aP(r,t,e,n,i){if(!Za(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 wx(r,t,e,n,i){if(!Za(e))throw new Error(`Unsupported clipboard image type: ${e}`);let o=i?.nameAfterNoteTitle??U.getState().namePastedImagesAfterNoteTitle;return aP(r,t,e,n,bx({extension:Ja[e],sourcePath:n,now:i?.now??new Date,nameAfterNoteTitle:o}))}function Cx(r,t,e){let n=r.fileManager.generateMarkdownLink(t,e);return n.startsWith("!")?n:`!${n}`}var Ja,E9,xx=x(()=>{je();Ln();Wh();Hi();Ja=Object.assign(Object.create(null),{"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"});E9=/[/\\:*?"<>|#^[\]]/g});function _9(){let r=Ex.filter(e=>e.inputEl.isConnected);return r.find(e=>document.activeElement!==null&&e.inputEl.contains(document.activeElement))??r.at(-1)??null}function _x(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 Rv.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 Tx(C)}},d=b=>{let y=b.clipboardData;if(!y||s)return;let C=new Date;c("paste",b,$B("paste",y,r),C)},u=b=>{if(s)return;let y=b.dataTransfer;!y||!MB(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||!MB(y))return;let C=new Date;c("drop",b,$B("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(),O=I9(P,y,n);_=await P9(()=>aP(r,I,P.mimeType,n,O));break}default:return Tx(P)}w.push(Cx(r,_,n))}}catch(P){S.logError(`Failed to save image: ${P instanceof Error?P.message:String(P)}`),new Rv.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 $9(t,T),T}catch(P){return S.logError(`Failed to insert image link: ${P instanceof Error?P.message:String(P)}`),new Rv.Notice("QuickAdd: saved the image but could not insert its link."),""}}async function g(b){let y=new Date,C=A9(b);if(C.length===0)return S.logMessage("QuickAdd: image ingest skipped (no-images)."),"";if(i)return new Rv.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=Ex.findIndex(y=>y.handle===v);b>=0&&Ex.splice(b,1)}};return Ex.push({handle:v,inputEl:t}),v}async function DB(r){let t=_9();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 $B(r,t,e){switch(r){case"paste":{if(t.getData("text/plain").length>0)return{kind:"stand-down"};let n=FB(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=k9(t,e);if(n.length>0)return{kind:"take",images:n};let i=FB(t).map(o=>({origin:"bytes",...o,naming:OB(o)}));return i.length>0?{kind:"take",images:i}:{kind:"stand-down"}}default:return Tx(r)}}function k9(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);S9(o)&&e.push({origin:"vault",file:o})}return e}function S9(r){return r!==null&&"extension"in r&&typeof r.extension=="string"&&AB(r.extension)}function FB(r){let t=[],e=0;for(let o of Array.from(r.items??[])){if(o.kind!=="file"||(e++,!Za(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??[]))Za(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(!Za(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 A9(r){return r.flatMap(t=>{if(!Za(t.type))return[];let e={file:t,mimeType:t.type};return[{origin:"bytes",...e,naming:OB(e)}]})}function OB(r){let t=PB(r.file.name);return t===null?{kind:"clipboard-stamp"}:{kind:"original-stem",stem:t}}function I9(r,t,e){switch(r.naming.kind){case"clipboard-stamp":return IB(r.mimeType,t);case"paste-name":return bx({extension:Ja[r.mimeType],sourcePath:e,now:t,nameAfterNoteTitle:U.getState().namePastedImagesAfterNoteTitle});case"original-stem":return`${r.naming.stem}.${Ja[r.mimeType]}`;default:return Tx(r.naming)}}function MB(r){return Array.from(r.types??[]).some(t=>t==="Files"||Za(t))}function Tx(r){throw new Error(`Unexpected image intake value: ${String(r)}`)}function P9(r){let t=RB.then(r,r);return RB=t.catch(()=>{}),t}function $9(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 Rv,Ex,RB,kx=x(()=>{Rv=require("obsidian");ye();xx();je();Hi();Ex=[];RB=Promise.resolve()});function mn(r){let t=r.workspace.getActiveViewOfType(LB.MarkdownView);return t?.editor?t:null}function el(r){return mn(r)?.editor.getSelection()??""}var LB,is=x(()=>{LB=require("obsidian")});function NB(r,t){return!r.isComposing&&r.key.toLowerCase()===t.toLowerCase()&&r.shiftKey&&(r.ctrlKey||r.metaKey)}function VB(r){return NB(r,"Enter")}function UB(r){return NB(r,Dv)}function qB(r){return r?`Look at the note without losing this draft. ${BB}`:"Look at the note without losing this draft."}function zB(){return`${BB} returns to the prompt`}var Dv,BB,Ov=x(()=>{Dv="E",BB="Ctrl/Cmd+Shift+E"});function HB(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 WB(r,t=42){let e=r.slice(0,t*4),n=e.replace(/\s+/g," ").trim();return n.length<=t?e.length<r.length?`${n}\u2026`:n:`${n.slice(0,Math.max(0,t-1))}\u2026`}var lP=x(()=>{});function dP(r){cP.add(r)}function uP(r){cP.delete(r)}function GB(){return cP.size>0}var cP,pP=x(()=>{cP=new Set});function F9(r,t){let e=new Set([t]);return r.workspace.iterateAllLeaves?.(i=>{let o=i.view?.containerEl?.ownerDocument;o&&e.add(o)}),[...e]}var _n,os,tl,Sx=x(()=>{_n=require("obsidian");is();Go();Ov();lP();pP();os=class os{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 os.active!==null}static getActive(){return os.active}static activate(t,e){let n=os.active;if(n){let o=n.handle.title;n.cancel(),new _n.Notice(`QuickAdd: cancelled the peeked prompt "${o}".`)}let i=new os(t,e);return os.active=i,i.mount(),i}static discard(){os.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=el(this.app);if(!t){this.resume();return}let e=this.handle;this.destroy(),e.insertSelectionAndResume(t)}canReturnNow(){return GB()?(new _n.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=_n.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,_n.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 _n.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 _n.ButtonComponent(l).setButtonText("Return").setTooltip("Go back to the prompt without inserting").onClick(()=>this.resume());let c=new _n.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,_n.setIcon)(d,"x"),c.buttonEl.replaceChildren(d)}else c.setButtonText("Cancel");_n.Platform.isMobile||i.createEl("p",{cls:"qa-peek-chip-keys",text:zB()}),this.chipEl=i,this.refreshInsertButton(),this.listenForSelection(),this.listenForChipEscape(),this.pushReturnShortcut()}listenForSelection(){let t=(0,_n.debounce)(()=>this.refreshInsertButton(),100,!0);this.selectionListener=t,this.selectionDocuments=F9(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=el(this.app),n=e.length>0,i=n&&!this.compactChrome?WB(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 _n.Scope(this.app.scope),this.returnScope.register(["Mod","Shift"],Dv,()=>(this.resume(),!1)),this.app.keymap.pushScope(this.returnScope)}destroy(){if(os.active===this&&(os.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}};os.active=null;tl=os});function M9(r){mn(r)?.editor?.focus?.()}var jB,Mm,mP=x(()=>{is();Sx();lP();pP();jB="qa-prompt-peek-hidden",Mm=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=tl.activate(this.host.app,{title:this.host.title,resume:()=>this.resume(),cancel:()=>this.cancel(),insertSelectionAndResume:e=>this.insertSelectionAndResume(e)})}onHostOpened(){dP(this.host)}onHostClosed(){uP(this.host),this.peeking&&(this.peeking=!1,this.session?.discard(),this.session=null)}hideModal(){uP(this.host),this.host.containerEl.addClass(jB),this.host.app.keymap.popScope(this.host.scope),M9(this.host.app)}showModal(){this.host.app.keymap.pushScope(this.host.scope),this.host.containerEl.removeClass(jB),dP(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=HB(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 YB(r){return Lv.Platform.isPhone||(r?.innerWidth??Number.POSITIVE_INFINITY)<=540}function Ax(r){let t=YB(r.ownerDocument.defaultView);return r.classList.toggle("qa-prompt-compact",t),t}function Ix(r){let t=YB(r.buttonEl.ownerDocument.defaultView);r.setButtonText(t?D9:R9),r.setTooltip(qB(!Lv.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,Lv.setIcon)(e,"eye"),r.buttonEl.prepend(e),r}var Lv,R9,D9,fP=x(()=>{Lv=require("obsidian");Go();Ov();R9="Peek at note",D9="Peek"});var Px,Rm,hP=x(()=>{Px=require("obsidian");iP();oP();TB();sP();kB();kx();rr();mP();Ov();fP();Rm=class extends Px.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()&&UB(e)){e.preventDefault(),this.peek.peek();return}if(this.isOptionalPrompt&&VB(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 gx({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 Mm({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"),Ax(this.containerEl),this.contentEl.empty(),this.titleEl.textContent=this.header,_B(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=_x(this.app,e.inputEl,this.options.imagePaste)),e}disposeInput(){}createButton(e,n,i){let o=new Px.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"});Ix(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(rn())}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 Pm(this.app,this.inputComponent.inputEl,{sourcePath:this.options?.linkSourcePath}),this.tagSuggester=new $m(this.app,this.inputComponent.inputEl)}removeInputListener(){this.inputComponent.inputEl.removeEventListener("keydown",this.submitEnterCallback),this.disposeInput(),this.imagePasteHandle?.detach()}onOpen(){super.onOpen(),this.peek.onHostOpened(),vx(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 KB,ir,zs=x(()=>{KB=require("obsidian");hP();ir=class r extends Rm{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 KB.TextComponent(t);return i.inputEl.setCssStyles({width:"100%"}),this.configureInput(i,e,n)}shouldSubmit(t){return!t.isComposing&&t.key==="Enter"}}});function Ci(r){if(r.length===0)return 0;let t=new TextEncoder().encode(r).length,e=!1;for(let i=0;i<r.length;i++)if(r.charCodeAt(i)>127){e=!0;break}return Math.max(1,Math.ceil(t/(e?3:4)))}function QB(r){return!Number.isFinite(r)||r<=0?1:Math.max(1,Math.floor(r*.45))}var Nv=x(()=>{});function eU(){return U.getState().ai.providers.flatMap(t=>t.models).map(t=>t.name)}function vP(){return U.getState().ai.providers}function XB(r,t){for(let e of r){let n=e.models.find(i=>i.name===t);if(n)return{provider:e,model:n}}}function gP(r){let t=vP();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 ZB(r,t){JB.has(r)||(JB.add(r),S.logWarning(t))}function tu(r,t){let e=vP(),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=XB(e,r.name);return l?(n||ZB(`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=XB(e,r);if(i){let s=gP(r);return s.length>1&&!n&&ZB(`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 tU(r.slice(0,o),r.slice(o+1))}function tU(r,t){let e=vP(),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 Vv(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?tU(r.provider,t):tu(t);if(!e){let n=t.includes("/")?t.slice(t.indexOf("/")+1):t,i=[...gP(t),...n!==t?gP(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 JB,Dm=x(()=>{ye();je();JB=new Set});var Rx=x(()=>{});var Wi=x(()=>{});var fn,rl=x(()=>{jo();fn=class{constructor(t,e){this.name=t,this.type=e,this.id=Vt()}}});var ht,ss=x(()=>{Zt();rl();is();ye();ht=class extends fn{constructor(t){super(t,"EditorCommand"),this.editorCommandType=t}static getSelectedText(t){return this.getActiveMarkdownView(t).editor.getSelection()}static getActiveMarkdownView(t){let e=mn(t);if(!e)throw S.logError("no active markdown editor."),new Error("no active markdown editor.");return e}}});var Lm,CP=x(()=>{Wi();ss();Lm=class extends ht{constructor(){super("Copy")}static async run(t){let e=ht.getSelectedText(t);await navigator.clipboard.writeText(e)}}});var Nm,xP=x(()=>{Wi();ss();ye();Nm=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 Vm,EP=x(()=>{Wi();ye();ss();Vm=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 sU,Bm,TP=x(()=>{sU=require("obsidian");ye();ss();Wi();Bm=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,sU.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 Um,_P=x(()=>{Wi();ss();Um=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 qm,kP=x(()=>{ss();Wi();Ve();ye();qm=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=AO.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 zm,SP=x(()=>{ss();Wi();zm=class extends ht{constructor(){super("Move cursor to file start")}static run(t){ht.getActiveMarkdownView(t).editor.setCursor({line:0,ch:0})}}});var Hm,AP=x(()=>{ss();Wi();Hm=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 Wm,IP=x(()=>{ss();Wi();Wm=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 Gm,PP=x(()=>{ss();Wi();Gm=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 js,jm,MP=x(()=>{js=require("obsidian");ye();on();rr();dp();jm=class extends js.FuzzySuggestModal{constructor(e,n,i,o,s){super(e);this.indexByItem=new Map;this.aliasByMatch=new WeakMap;this.warnedOnEmptyDisplay=!1;this.warnRenderItemFailure=ap("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=>nn(a)),this.promise=new Promise((a,l)=>{this.resolvePromise=a,this.rejectPromise=l}),s?.skippable&&UO(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 nn(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 nn(i??e)}getItems(){return this.items}getSuggestions(e){let n=Ol(e);if(!this.aliases||!n.trim())return super.getSuggestions(n);let i=(0,js.prepareFuzzySearch)(n.trim()),o=[];return this.items.forEach((s,a)=>{let l=$S(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,js.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,js.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,js.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(rn())}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 uU,gr,nl=x(()=>{uU=require("obsidian");on();MP();gr=class r extends jm{constructor(e,n,i,o={}){super(e,n,i,o.renderItem,o);this.warnCustomValueFailure=ap("Custom create-row rendering threw an error; falling back to default rendering");this.allowCustomValue=!0;this.searchItems=o.searchItems?.map(s=>nn(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)=>nn(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 nn(i??e)}getSuggestions(e){let n=super.getSuggestions(e);if(!this.allowCustomValue)return n;let i=Ol(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,uU.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,Gi=x(()=>{MP();It=class r extends jm{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 Un(r){return r.type==="Template"}function sl(r){return r.type==="Capture"}function ji(r){return r.type==="Macro"}function iu(r){return r.type==="Multi"}var al=x(()=>{});function zU(r){let t=[],e=new RegExp(Z7.source,"gi"),n=0;for(;n<r.length;){e.lastIndex=n;let i=e.exec(r);if(!i)break;let o=i.index,s=o+qU.length,a=s;for(;a<r.length;){let d=r[a];if(d==="}"||d===`
- `||d==="\r")break;a++}let l=r.slice(s,a);r[a]==="}"&&r[a+1]==="}"&&eJ.test(l)?(t.push({start:o,end:a+2,path:xr(l)}),n=a+2):n=a}return t}function _c(r){let t=new Set;if(!r)return t;for(let e of zU(r))e.path&&t.add(e.path);return t}function aE(r,t){if(!r||t.size===0)return r;let e=zU(r);if(e.length===0)return r;let n="",i=0;for(let o of e){let s=t.get(o.path);s&&(n+=r.slice(i,o.start),n+=`${qU}${s}}}`,i=o.end)}return i===0?r:n+r.slice(i)}var qU,Z7,eJ,ou=x(()=>{tn();qU="{{TEMPLATE:",Z7=/{{TEMPLATE:/gi,eJ=/\.(?:md|canvas|base)$/i});function uq(r){try{let t=window.require;return t?t(r):null}catch{return null}}async function of(r,t){let e=r.vault.adapter;if(typeof n$.FileSystemAdapter!="function"||!(e instanceof n$.FileSystemAdapter))return;let n=uq("fs"),i=uq("path");if(!n?.promises||!i)return;let o=await n.promises.realpath(e.getBasePath()),a=e.getFullPath(t);for(;!EJ(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 jv(`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 jv(`Refusing to write to "${t}": it resolves (via a symlink) outside the vault.`);if(c.split(i.sep).some(p=>p.startsWith(".")))throw new jv(`Refusing to write to "${t}": it resolves (via a symlink) into a config/hidden directory.`)}function EJ(r,t){try{return r.lstatSync(t),!0}catch{return!1}}var n$,jv,i$=x(()=>{n$=require("obsidian"),jv=class extends Error{constructor(t){super(t),this.name="VaultWriteEscapeError"}}});function N$(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 aee){let o=e[i];o!==void 0&&n.push(...N$(o,t))}return n}function qE(r){return Number(r.replace(/,/g,""))}function lee(r){let t=r.match(/context (?:length|window)(?:\s+is)?(?:\s+of)?\s*(\d[\d,]*)/i);return t?qE(t[1]):null}function cee(r){let t=r.match(/(\d[\d,]*)\s*(?:tokens?\s+)?in the completion\b/i);if(t){let n=qE(t[1]),i=lee(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 ty(r){let t=N$(r).join(" "),e=cee(t);return e==="output"?"output_budget":e==="input"?"input_context":see.some(n=>n.test(t))?"output_budget":oee.some(n=>n.test(t))?"input_context":"other"}function jq(r){return ty(r)==="input_context"}function Yq(r){return dee.test(N$(r).join(" "))}function zE(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 oee,see,aee,dee,df=x(()=>{oee=[/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],see=[/max_tokens/i,/max_completion_tokens/i,/max(?:imum)? output tokens/i,/output token limit/i],aee=["message","code","type","status","statusText","providerCode","error","response","json","cause"];dee=/tool_choice:\s*type\s*"tool"\s*and\s*"any"\s*are not supported/i});function Cee(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function xee(r){let t=r.name?.trim()||"provider";return`${wee}-${Cee(t)}`}async function Jq(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 So(r,t){let e=t.apiKeyRef?.trim();if(e){let n=await Jq(r,e);if(n)return n}return t.apiKey??""}async function Zq(r,t,e){let n=e?.trim();if(!n||!r?.secretStorage?.getSecret||!r.secretStorage?.setSecret)return null;let i=xee(t),o=i,s=1;for(;;){let a=await Jq(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 wee,kc=x(()=>{ye();wee="quickadd-ai"});async function oy(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 sy(r,t){return{[r]:t,[`${r}-quoted`]:("> "+t).replace(/\n/g,`
- > `)}}var W$=x(()=>{});var ue,kn=x(()=>{ti();ue=class extends at{}});function pf(r){return G$.filter(t=>typeof r[t]=="number")}function iT(r){let t={...r};for(let e of G$)delete t[e];return t}function j$(r,t){return r.supportsTemperature===!1&&pf(t).length>0?iT(t):t}function gz(r,t){return t.length===0?!1:Nee.some(e=>e.test(r))}function Y$(r){let t=r.map(e=>Lee[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 ay(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 G$,Lee,nT,Nee,oT=x(()=>{G$=["temperature","top_p","frequency_penalty","presence_penalty"],Lee={temperature:"Temperature",top_p:"Top P",frequency_penalty:"Frequency penalty",presence_penalty:"Presence penalty"};nT=G$.join("|"),Nee=[new RegExp(`unsupported (?:parameter|value)[^.]{0,40}['\`"]?(?:${nT})['\`"]?`,"i"),new RegExp(`['\`"]?(?:${nT})['\`"]?[^.]{0,40}(?:is deprecated|is not supported|not supported|does not support)`,"i"),new RegExp(`unrecognized request argument[^.]{0,40}(?:${nT})`,"i"),new RegExp(`(?:${nT})[^.]{0,40}extra inputs are not permitted`,"i")]});function K$(r){return{...r,modelOptions:{...r.modelOptions},usage:r.usage?{...r.usage}:void 0}}function Q$(r){let t=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,e=Date.now();return Io.push({...r,modelOptions:{...r.modelOptions??{}},id:t,createdAt:e,status:"pending"}),yz(),t}function ly(r,t){let e=Io.find(n=>n.id===r);e&&(e.status=t.status,e.durationMs=t.durationMs,e.usage=t.usage,e.errorMessage=t.errorMessage,yz())}function vz(r=10){Number.isFinite(r)||(r=10);let t=Math.floor(r);return t<=0?[]:Io.slice(-t).map(K$).reverse()}function yz(){if(Io.length<=25)return;let r=Io.length-25;for(;r>0;){let t=Io.findIndex(e=>e.status!=="pending");if(t===-1)break;Io.splice(t,1),r-=1}}function bz(r){let t=Io.find(e=>e.id===r);return t?K$(t):null}function wz(){let r=Io[Io.length-1];return r?K$(r):null}function Cz(){Io.splice(0,Io.length)}var Io,X$=x(()=>{Io=[]});function sT(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 J$=x(()=>{});function au(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]=au(o);t.properties=n}return t.items&&!Array.isArray(t.items)&&(t.items=au(t.items)),e&&(t.additionalProperties=!1,t.required=t.properties?Object.keys(t.properties):[]),t}function Vee(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 Bee(r){return r.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.strict?au(t.parameters):t.parameters,...t.strict?{strict:!0}:{}}}))}function Uee(r){return typeof r=="string"?r:{type:"function",function:{name:r.name}}}function zee(r,t){let e={model:r,...t.modelParams??{},messages:Vee(t.messages)};return t.tools&&t.tools.length>0&&(e.tools=Bee(t.tools),t.toolChoice&&(e.tool_choice=Uee(t.toolChoice)),t.disableParallel&&(e.parallel_tool_calls=!1)),t.maxOutputTokens!==void 0&&(qee.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?au(t.responseFormat.schema):t.responseFormat.schema}}:{type:"json_object"}),e}function Hee(r){let t=r.choices?.[0]??{},e=t.message??{},i=(e.tool_calls??[]).map(d=>Ez(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 xz(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function Ez(r){let t=r.function.arguments;if(typeof t=="string")try{let n=xz(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=xz(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 Wee(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 Gee(r){return typeof r=="string"?r:{type:"function",name:r.name}}function jee(r,t){let{reasoning_effort:e,max_tokens:n,max_completion_tokens:i,...o}=t.modelParams??{},s={model:r,...o,input:Wee(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?au(l.parameters):l.parameters,strict:l.strict===!0})),t.toolChoice&&(s.tool_choice=Gee(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?au(t.responseFormat.schema):t.responseFormat.schema}:{type:"json_object"}}}return s}function Yee(r){let t=r.output??[],e=t.filter(d=>d.type==="function_call").map(d=>Ez({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 Kee(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,ay("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=Qee(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:au(t.responseFormat.schema)}}),o}function Qee(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 Xee(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 Jee(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=Zee(t.toolChoice)));let o=ay("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 Zee(r){return typeof r=="string"?{functionCallingConfig:{mode:r==="required"?"ANY":r==="none"?"NONE":"AUTO"}}:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[r.name]}}}function ete(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 Z$(r,t,e,n=8192){switch(r){case"anthropic":return Kee(t,e,n);case"gemini":return Jee(t,e);case"openai-responses":return jee(t,e);default:return zee(t,e)}}function Tz(r,t){switch(r){case"anthropic":return Xee(t);case"gemini":return ete(t);case"openai-responses":return Yee(t);default:return Hee(t)}}var qee,_z=x(()=>{oT();qee=/^(?:o[1-9]|gpt-(?:[5-9]|\d\d))/i});async function cy({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,kz.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 zE(e.name,c);return c.json}function tte(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 rte(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 dy(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 nte(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=ay(r,n);return r==="anthropic"?{model:t.name,max_tokens:dy(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 Sz({kind:r,systemPrompt:t,params:e,prompt:n,...i}){let o=nte(r,i.model,t,e,n),s={...i,kind:r,body:o};switch(r){case"anthropic":return rte(await cy(s));case"gemini":return ite(await cy(s));default:return tte(await cy(s))}}function ite(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 kz,eF=x(()=>{kz=require("obsidian");df();oT()});function uy(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=Ci(l)+Ci(i),d=Date.now(),u=Q$({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=sT(r),m=xh(n),h=C=>Sz({kind:m,apiKey:t,model:e,provider:n,systemPrompt:i,params:C,prompt:l,afterRequest:p}),g=j$(e,o),v=pf(g);v.length===0&&pf(o).length>0&&S.logMessage(`[AI Request ${u}] ${e.name} uses fixed sampling; not sending ${Y$(pf(o))}.`);let b=await Iz(()=>h(g),()=>h(iT(g)),{sentKeys:v,model:e,provider:n,logPrefix:`AI Request ${u}`,advancedSettings:!0}),y=Date.now()-d;return ly(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;ly(u,{status:"error",durationMs:h,errorMessage:m}),S.logMessage(`[AI Request ${u}] Failed in ${h}ms: ${m}`);let g=ty(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 tF(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=jD(n),l={...i,modelParams:j$(e,i.modelParams??{})},c=pf(l.modelParams??{}),d=Z$(a,e.name,l,dy(e)),u=i.messages.find(g=>g.role==="system"),p=[...i.messages].reverse().find(g=>g.role==="user"),m=Date.now(),h=Q$({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=>cy({kind:a,apiKey:t,provider:n,model:e,body:w,afterRequest:o}),v=async w=>{try{return await g(w)}catch(T){let P=ste(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 Iz(()=>v(d),()=>v(Z$(a,e.name,{...l,modelParams:iT(l.modelParams??{})},dy(e))),{sentKeys:c,model:e,provider:n,logPrefix:`AI Chat ${h}`}),y=Tz(a,b),C=Date.now()-m;return ly(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;ly(h,{status:"error",durationMs:b,errorMessage:v});let y=Yq(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 ste(r,t,e){return r!=="openai"||!Array.isArray(t.tools)||t.tools.length===0||t.reasoning_effort!==void 0||!ote.test(e)?null:{...t,reasoning_effort:"none"}}async function Iz(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(!gz(i,o))throw n;let d=Y$(o),u=o.length>1?"them":"it";return S.logMessage(`[${l}] ${a.name} rejected ${d}; retrying without sampling parameters.`),new Az.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 Az,ote,aT=x(()=>{Az=require("obsidian");oT();je();X$();J$();nt();fi();_z();ye();Nv();df();eF();eF();ote=/function tools with reasoning_effort are not supported[\s\S]*reasoning_effort to 'none'/i});function lu(r){if(r){let t=new Pz.Notice(rF("starting",""),1e6);return{setMessage:(e,n)=>{t.setMessage(rF(e,n))},hide:()=>t.hide(),fail:e=>{if(Be(e)){t.hide();return}t.setMessage(rF("dead",e?.message??String(e))),OO(e),window.setTimeout(()=>t.hide(),5e3)}}}return{setMessage:()=>{},hide:()=>{},fail:()=>{}}}var Pz,rF,lT=x(()=>{Pz=require("obsidian");nt();rF=(r,t)=>`${r==="dead"?"AI request failed.":`Assistant is ${r}.`}${t?`
- ${t}`:""}`});function lte(){return Array.from(new Set([nF,...["kebab","snake","camel","pascal","title","lower","upper","slug"].map(r=>Gh(nF,r))])).filter(Boolean)}function Fz(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);m<i&&(i=m,n=p)}}if(n>0&&n<r.length)return[r.slice(0,n),r.slice(n)];let o=t,s=r.charCodeAt(o);return s>=56320&&s<=57343&&(o+=1),o<=0||o>=r.length?null:[r.slice(0,o),r.slice(o)]}function cte(r){let t=new RegExp(wd.source,"gi"),e;for(;(e=t.exec(r))!==null;)if(e[1].split("|")[0].trim().toLowerCase()==="chunk")return!0;return!1}function dte(r){return _s.test(r)||Yb.test(r)||Kb.test(r)||bo(r).length>0}function ute(r){return $z.some(t=>r.includes(t))}function pte(r){return $z.slice().sort((t,e)=>e.length-t.length).reduce((t,e)=>t.split(e).join(" "),r)}function Mz(r){if(r>dT)throw new Error(`This chunked AI request would split into more than ${dT} prompts, which exceeds the safety limit. Increase the chunk size, use a larger chunk separator, or reduce the input text.`)}function mte(r,t,e){let n=Math.max(1,Math.floor(t)),i=[r],o=0;for(;i.length>0;){let s=i.pop(),l=Ci(s)<=n?null:Fz(s);if(!l){e.push(s),o+=1,Mz(o);continue}i.push(l[1],l[0])}}function fte(r){let t=r.flags.replace(/[gy]/g,"");return new RegExp(r.source+"|",t).exec("").length-1}function gte(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(fte(t)>0||hte.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<n.length;s++)s%2===0?i.push(n[s]):o.push(n[s]);return{chunks:i,separators:o}}function vte(r,t,e,n){let i=[];if(r.forEach((l,c)=>{let d=[];mte(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=Ci(l.text)+Math.max(1,Ci(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 yte(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 iF(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=lu(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}=gte(d,p),g=await e(c,{chunk:nF});if(!(cte(c)||dte(c)&&ute(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=QB(b),C=pte(g),w=Ci(l)+Ci(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}=yte(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=vte(m,h,T,_);Mz(I.length);let O=uy(r,i,o,s,l,u,!t.showAssistantMessages),N=["prompting",`${I.length} prompts being sent.`];n.setMessage(N[0],N[1]);let K=new cT(5,1e3*30),ne=!1,H=0,D=Promise.resolve(),G=W=>{let Z=D.then(()=>{if(ne)throw new Error("Chunked prompt stopped after an earlier failure.");return e(c,{chunk:W})});return D=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>dT)throw new Error(`Chunked AI request exceeded the safety limit of ${dT} provider requests.`);return O(se)})).content]}catch(ce){let $e=Fz(W);if(Z>=ate||!$e||!jq(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 oy(M,n,N)).flat().join(t.resultJoiner);return window.setTimeout(()=>n.hide(),5e3),sy(a,te)}catch(i){throw n.fail(i),i}}var cT,ate,dT,nF,$z,hte,Rz=x(()=>{je();aT();df();lT();Nv();ye();Ve();Wl();uw();W$();cT=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.intervalMs),this.startTimes.length>=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()}},ate=12,dT=500,nF="quickadd_chunk_probe_123456789";$z=lte();hte=/(?:^|[^\\])(?:\\\\)*\\[1-9]/});async function bte(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 ue("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.")}Lr(o,"Prompt template does not exist");let s=o.path,a=r.vault.getAbstractFileByPath(s);Lr(a instanceof Dz.TFile,`${s} is not a file`);let l=await r.vault.cachedRead(a);return[o.basename,l]}async function Oz(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=lu(t.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,promptTemplate:l,systemPrompt:c,promptTemplateFolder:d}=t,u=Xo(r,d),[p,m]=await bte(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=uy(r,i,o,s,c,t.modelOptions,!t.showAssistantMessages)(h),C=(await oy(b,n,g)).content;return window.setTimeout(()=>n.hide(),5e3),sy(a,C)}catch(i){throw n.fail(i),Be(i)?new et("Input cancelled by user"):i}}async function Lz(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=lu(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=uy(r,i,o,s,l,d,!t.showAssistantMessages)(u),v=(await oy(h,n,p)).content;return window.setTimeout(()=>n.hide(),5e3),sy(a,v)}catch(i){throw n.fail(i),i}}var Dz,oF=x(()=>{W$();Dz=require("obsidian");rr();kn();Gi();je();gi();Rd();nt();aT();lT();X$();Rz()});function Nz(r){return r.replace(wte,t=>t+"\uFDD0")}function Sn(r){return r.includes("\uFDD0")?r.replace(Cte,"$1"):r}function py(r,t){if(!r.includes("\uFDD0"))return{content:r,offsets:t};let e=n=>Sn(r.slice(0,n)).length;return{content:Sn(r),offsets:typeof t=="number"?e(t):t.map(e)}}function uT(r){let{cursor:t}=r,e=py(r.content,t.kind==="offset"?t.value:0);return{content:e.content,cursor:t.kind==="offset"?{...t,value:e.offsets}:t}}var wte,Cte,mf=x(()=>{wte=/\{(?=\{)|<(?=%)|%(?=>)/g,Cte=/([{<%])\uFDD0(?=[{%>])/g});var Vz,Sc,sF=x(()=>{Vz=require("obsidian");hP();Nh();Sc=class r extends Rm{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 Vz.TextAreaComponent(t);return i.inputEl.classList.add("wideInputPromptInputEl"),i.inputEl.setAttribute("dir","auto"),this.disposeIndent=Lh(i.inputEl),this.configureInput(i,e,n)}shouldSubmit(t){return(t.ctrlKey||t.metaKey)&&t.key==="Enter"}disposeInput(){this.disposeIndent?.()}}});var my,Bz=x(()=>{zs();yo();my=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?"":vo(t,this.options.numeric):t}}});var aF,fy,Uz=x(()=>{zs();yo();aF={min:0,max:100,step:1},fy=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??aF,o=this.isOptionalPrompt&&!n,s=bp(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=vo(t,this.options?.slider??aF);e!==""&&(this.sliderEl.value=e),this.onInputChanged(t)}transformInputOnSubmit(t){return t===""&&this.isOptionalPrompt?"":bp(t,this.options?.slider??aF)}}});var cu,lF=x(()=>{sF();zs();Bz();Uz();rs();cu=class{factory(t){return t==="multiline"?Sc:t==="number"?my:t==="slider"?fy:zr().settings.inputPrompt==="multi-line"?Sc:ir}}});function cF(r){return r.normalize("NFKD").toLowerCase()}var zz,qz,xte,du,dF=x(()=>{zz=require("obsidian"),qz=200,xte=0;du=class{constructor(t,e){this.options=e;this.instanceId=++xte;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<=qz)return t;let e=[],n=[];for(let i of t)(this.options.isSelected(i.item)?e:n).push(i);return[...e,...n].slice(0,qz)}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,zz.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 Ac,Ic,uF=x(()=>{Ac=require("obsidian");on();rr();Ln();dF();Ic=class r extends Ac.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 du(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 Ac.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 Ac.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:nn(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 Ac.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 Ac.Notice(`"${e}" is already added.`),!1):(this.selectValue(n),this.draft="",this.render(),this.focusCustomInput(),!0)}typedValue(e){return Fd(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(rn())}}});var pT,Pc,Ete,Tte,_te,Wz,pF,hy,mF,Hz,mT,fT,fF=x(()=>{pT=require("obsidian");je();Pc=r=>r.toString().padStart(2,"0"),Ete=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},Tte=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))},_te=(r,t)=>new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(r,t,1)),Wz=(r,t,e)=>`${r}-${Pc(t+1)}-${Pc(e)}`,pF=r=>Wz(r.getFullYear(),r.getMonth(),r.getDate()),hy=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},mF=(r,t,e,n)=>{let i=Wz(r,t,e);return n?`${i}T${Pc(n.hour)}:${Pc(n.minute)}:00`:i},Hz=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}},mT=r=>{let t=Ete(r.weekStartsOn),e=Tte(t),n=hy(r.initialIso)??new Date,i=n.getFullYear(),o=n.getMonth(),s=r.initialIso,a=r.withTime===!0,l=a?Hz(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,pT.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,pT.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 O=h.createDiv({cls:"qa-date-picker__weekday"});O.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=`${Pc(l.hour)}:${Pc(l.minute)}`)}let w=I=>{o+=I,o>11?(o=0,i+=1):o<0&&(o=11,i-=1),_()},T=(I,O)=>{s=I,r.onSelect(I,O),_()},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,O=mF(I.getFullYear(),I.getMonth(),I.getDate(),l);i=I.getFullYear(),o=I.getMonth(),T(O,"action")}),y.addEventListener("click",()=>P("action")),C&&C.addEventListener("change",()=>{if(C.value.trim()==="")l={hour:0,minute:0};else{let[I,O]=C.value.split(":").map(N=>Number.parseInt(N,10));if(Number.isNaN(I)||Number.isNaN(O))return;l={hour:I,minute:O}}if(s){let I=hy(s);I&&T(mF(I.getFullYear(),I.getMonth(),I.getDate(),l),"picker")}});let _=()=>{p.textContent=_te(i,o),g.empty();let O=(new Date(i,o,1).getDay()-t+7)%7,N=new Date(i,o,1-O),K=pF(new Date),ne=s?hy(s):null,H=ne?pF(ne):void 0,D=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=pF(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",D.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=mF(V.getFullYear(),V.getMonth(),V.getDate(),l);T(Z,"picker")})}};return _(),{setSelectedIso:(I,{updateView:O}={})=>{if(s=I,I&&O!==!1){let N=hy(I);N&&(i=N.getFullYear(),o=N.getMonth())}if(a&&I){let N=Hz(I);N&&(l=N,C&&(C.value=`${Pc(N.hour)}:${Pc(N.minute)}`))}_()},setViewFromIso:I=>{let O=hy(I);O&&(i=O.getFullYear(),o=O.getMonth(),_())},destroy:()=>{c.remove()}}},fT=(r,t)=>{let e=r.createEl("button",{cls:"qa-date-field__calendar clickable-icon"});e.type="button",e.tabIndex=-1,(0,pT.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 $c(r,t,e=To,n){if(!r||!r.trim())return{isValid:!1,error:"Empty input"};try{let i=n??U.getState().dateAliases,o=Th(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 Po(r,t){if(!window.moment)return null;try{let e=window.moment(r);if(e.isValid())return e.format(t)}catch{}return null}var uu=x(()=>{Hd();je();gd()});var hf,ff,ll,hT=x(()=>{hf=require("obsidian");zs();fF();uu();sP();je();gd();ff=class ff 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&&Po(c,this.dateFormat)!==null&&(this.applyPickerSelection(c,!1),vx(this.inputComponent.inputEl,a))}this.updatePreviewDebounced=(0,hf.debounce)(this.updatePreview.bind(this),250,!0),this.updatePreview()}supportsPeek(){return!1}static Prompt(e,n,i,o,s,a,l){return new ff(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 hf.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=mT({container:this.pickerHostEl,initialIso:this.selectedIso,withTime:this.withTime,onSelect:e=>{e?this.applyPickerSelection(e):this.clearPickerSelection()}}),this.unsubscribeCalendarToggle=fT(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=ff.PREVIEW_PLACEHOLDER;let i=_h(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=Wb(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":ff.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=Po(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=$c(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=$c(this.defaultValue,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`}if(n){let i=$c(n,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`;new hf.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()}};ff.PREVIEW_PLACEHOLDER="Preview will appear here";ll=ff});async function Gz(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=sw(r.scope),s=pp(r.runContext,i,{showDestination:o}),a=pp(r.runContext,i,{elide:!1,showDestination:o});return e?.type==="VDATE"?await ll.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 cu().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 jz(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 gr.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 Yz(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 Ic.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 Kz=x(()=>{mp();lF();nl();Gi();uF();hT();rr();nt()});var cl,gT=x(()=>{cl=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 vT,Qz=x(()=>{vT=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 Qs,hF=x(()=>{Ve();Qz();Qs=class{static processValues(t,e){let n=t.size,i=Array.from(t).filter(l=>!this.isUnresolvedFieldToken(l)),o=vT.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[]}};Qs.unresolvedFieldTokenRegex=new RegExp(`^${op.source}$`,"i")});function Xz(r){if(!r.includes(",")){let o=r.trim();return o?[o]:[]}let t=[],e="",n=!1;for(let o=0;o<r.length;o++){let s=r[o],a=r[o+1];if(s==="["&&a==="["){n=!0,e+=s;continue}if(s==="]"&&a==="]"){n=!1,e+=s;continue}if(s===","&&!n){let l=e.trim();l&&t.push(l),e="";continue}e+=s}let i=e.trim();return i&&t.push(i),t}var Jz=x(()=>{});var dl,gf,gF=x(()=>{Jz();dl=class dl{static parseInlineFields(t,e){let n=new Map,i=this.removeCodeBlocksAndFrontmatter(t,e),o;for(;(o=dl.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 Xz(a))n.get(s)?.add(l)}}return dl.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<s.lines.length;d++)o.push(s.lines[d]);s=null}else s.lines.push(a)}if(s)for(let a of s.lines)o.push(a);return o.join(`
- `)}static matchFenceOpen(t){let e=this.FENCE_OPEN_REGEX.exec(this.stripTrailingCarriage(t));return e?{length:e[1].length,info:e[2]}:null}static matchFenceClose(t,e){let n=this.FENCE_CLOSE_REGEX.exec(this.stripTrailingCarriage(t));return n!==null&&n[1].length>=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}};dl.INLINE_FIELD_REGEX=/(?:^|[\n\r])(?![ \t]*[-*+][ \t]+\[[ xX]\])([^:\n\r]+?)::[ \t]*(.*)$/gmu,dl.FRONTMATTER_REGEX=/^---\r?\n[\s\S]*?\r?\n---\r?\n/,dl.INLINE_CODE_SPAN_REGEX=/`[^`]*`/g,dl.FENCE_OPEN_REGEX=/^[ \t]*(`{3,})([^`]*)$/,dl.FENCE_CLOSE_REGEX=/^[ \t]*(`{3,})[ \t]*$/;gf=dl});function vF(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 Zz(r,t,e){return(await yF(r,t,e)).values}async function yF(r,t,e){let n=await kte(r,t,e),i=Qs.processValues(n,e);return{values:i.values,hasDefaultValue:i.hasDefaultValue}}async function kte(r,t,e){let n=cl.getInstance(),i=vF(e),o=n.get(t,i);if(o)return o;let s=n.getRevision(),a=await bF(r,t,e);return n.setIfRevision(t,a,i,s),a}async function bF(r,t,e){let n=t.trim().toLowerCase();if(n==="tags"||n==="tag"){let i=await Ste(r,e);if(i.size>0)return i}return await Pte(r,t,e)}async function Ste(r,t){if(!(!!t.folder||!!t.folders?.length||!!t.tags?.length||!!t.excludeFolders?.length||!!t.excludeTags?.length||!!t.excludeFiles?.length)){let n=Ate(r);if(n.size>0)return n}return await Ite(r,t)}function Ate(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 gy(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 e2(r,t,e){let n=new Set,i=Os.filterFiles(r.vault.getMarkdownFiles(),t,o=>r.metadataCache.getFileCache(o));for(let o=0;o<i.length;o+=50){let s=await Promise.all(i.slice(o,o+50).map(async a=>{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 Ite(r,t){return e2(r,t,(e,n)=>{let i=r.metadataCache.getFileCache(e);gy(n,i?.frontmatter?.tags),gy(n,i?.frontmatter?.tag);for(let o of i?.tags??[]){let s=String(o.tag??"").trim().replace(/^#/,"");s&&n.add(s)}})}async function Pte(r,t,e){return e2(r,e,async(n,i)=>{let o=r.metadataCache.getFileCache(n)?.frontmatter?.[t];if(Array.isArray(o)?o.forEach(s=>gy(i,[s])):typeof o!="object"&&gy(i,o),e.inline){let s=await r.vault.cachedRead(n);gy(i,[...gf.getFieldValues(s,t,{includeCodeBlocks:e.inlineCodeBlocks})])}})}var yT=x(()=>{Nw();gT();hF();gF()});function $te(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=t2(o);s!==null&&i.push(s)}return i.length>0?i:null}return t2(n)}function bT(r,t,e){if(!t||t.extension!=="md")return null;let n=r.metadataCache.getFileCache(t)?.frontmatter;return $te(n,e)}function t2(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 wF=x(()=>{});async function r2({app:r,executor:t,getSourcePath:e},n){let i=t?.promptProvider;try{let{fieldName:o,filters:s,multiSelect:a,label:l}=On.parse(n),c=s.defaultFrom==="active"?bT(r,t?.triggerContext?.activeFile??null,o):null,{values:d,hasDefaultValue:u}=await yF(r,o,s),p=d,m=u,h=s.defaultValue;!a&&typeof c=="string"?(p=Qs.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=Qs.getSmartDefaults(o,[]);C.length>0&&(b=C)}let y=c===null?void 0:(Array.isArray(c)?c:[c]).map(C=>Qs.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 Ic.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=Qs.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 gr.Suggest(r,p,p,{placeholder:v})}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}async function n2({app:r,executor:t,getSourcePath:e},n){let i=t?.promptProvider;try{let o=Dp(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?[`${Ko}${m}`]:[]:m?`${Ko}${m}`:""}let a=Ms(o,p=>r.metadataCache.getFileCache(p)),l=a.map(p=>p.label),c=a.map(p=>p.aliases),d=o.map(p=>`${Gl}${p.path}`);if(n.multiSelect)return(i?(await i.suggesterMulti(l,d,{placeholder:s,allowCustomInput:n.allowCustomInput})).map(m=>d.includes(m)?m:Fd(d,c,m)??m):await Ic.Suggest(r,l,d,{placeholder:s,allowCustomValue:n.allowCustomInput,aliases:c,...n.optional?{skippable:!0}:{}})).map(m=>d.includes(m)?m:`${Ko}${m}`);if(i){let p=String(await i.suggester(l,d,s,n.allowCustomInput));return p?d.includes(p)?p:Fd(d,c,p)??`${Ko}${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 gr.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:`${Ko}${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 i2=x(()=>{zs();nl();uF();Gi();Fa();yT();hF();wF();Ln();rr();nt();ye();gi()});function Rte(r){return`\\begin{${r}}
- \u261A
- \\end{${r}}\u261A`}var Fte,Mte,o2,CF=x(()=>{Fte=["\\!","\\,","\\:","\\>","\\;","\\#","\\$","\\%","\\&","\\","_","{ }","|","^{\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"],Mte=["align","align*","alignat","alignat*","array","Bmatrix","bmatrix","cases","eqnarray","eqnarray*","equation","equation*","gather","gather*","matrix","pmatrix","smallmatrix","subarray","Vmatrix","vmatrix"];o2=[...Fte,...Mte.map(Rte)]});function Ote(r){if(xF.has(r))return xF.get(r)??null;let t=null;try{t=(0,s2.renderMath)(r,!0)}catch{t=null}return xF.set(r,t),t}function Lte(r){return EF===null&&(EF=new Ec(r,{findAllMatches:!0,threshold:.8})),EF}var s2,Dte,xF,EF,wT,a2=x(()=>{Ps();px();s2=require("obsidian");CF();rs();Dte=new RegExp(/\\([a-z{}A-Z0-9]*)$/),xF=new Map,EF=null;wT=class extends Er{constructor(e){super(zr().app,e);this.inputEl=e;this.lastInput="";this.symbols=Object.assign([],o2)}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=Dte.exec(s),l=[];a&&(this.lastInput=a[1],l=this.symbols.filter(u=>u.toLowerCase().contains(this.lastInput)));let c=new Set(l);return Lte(this.symbols).search(this.lastInput).map(u=>u.item).filter(u=>c.has(u))}renderSuggestion(e,n){if(e){n.setText(e);let i=Ote(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 Ti,CT,l2=x(()=>{Ti=require("obsidian");rs();CF();a2();rr();CT=class r extends Ti.Modal{constructor(){super(zr().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 wT(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 Ti.TextAreaComponent(this.contentEl);n.inputEl.setCssStyles({width:"100%",height:"10rem"}),this.inputEl=n.inputEl,n.onChange((0,Ti.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,Ti.loadMathJax)()}async mathjaxLoop(e,n){let i=(0,Ti.renderMath)(n,!0);await(0,Ti.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 Ti.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(rn())}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListeners()}}});function pu(r){return r.replace(Nte," ").replace(/\s+/g," ").trim()}function c2(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 d2(r,t){return r[t.line]?.trim()===t.heading?t.line+1:t.line}function TF(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<e.length&&!/^---\s*$/.test(e[s]);)s++;if(s<e.length){for(let a=0;a<=s;a++)t[a]=!0;n=s+1}}let i=null,o=null;for(;n<e.length;n++){let s=e[n];if(o){t[n]=!0,Vte(o,s)&&(o=null);continue}if(i){t[n]=!0;let d=s.match(/^ {0,3}(`{3,}|~{3,})\s*$/);d&&d[1][0]===i.char&&d[1].length>=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 Vte(r,t){return r==="%%"?t.includes("%%"):t.trimEnd().endsWith("$$")}function oi(r){let t=[],e=TF(r);for(let n=0;n<r.length;n++){let i=r[n].replace(/\r$/,"");if(e[n])continue;let o=i.match(/^ {0,3}(#{1,6})[ \t]+(.*)$/);if(o){t.push({heading:o[2],level:o[1].length,line:n});continue}let s=i.match(/^ {0,3}(=+|-+)\s*$/);if(s&&n>0){let a=r[n-1],l=t.length>0&&t[t.length-1].line===n-1,c=n<2||e[n-2]||!c2(r[n-2]);!l&&!e[n-1]&&c&&c2(a)&&t.push({heading:a.trim(),level:s[1][0]==="="?1:2,line:n-1});continue}}return t}function Bte(r,t){let e=[],n=pu(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].level<i){i=r[o].level;let s=pu(r[o].heading);s&&e.unshift(s)}return e}function _F(r,t){if(r.length===0)return null;let e=-1;for(let d=0;d<r.length&&r[d].line<=t;d++)e=d;if(e===-1)return null;let n=pu(r[e].heading);if(!n)return null;let i=n.toLowerCase();if(!r.some((d,u)=>u!==e&&pu(d.heading).toLowerCase()===i))return`#${n}`;let s=Bte(r,e);if(s.length<2)return null;let a=s.join("#"),l=a.toLowerCase();return Ute(r).some((d,u)=>u!==e&&d===l)?null:`#${a}`}function Ute(r){let t=new Array(r.length),e=[];for(let n=0;n<r.length;n++){for(;e.length>0&&r[e[e.length-1]].level>=r[n].level;)e.pop();let i=e.length>0?t[e[e.length-1]]:[],o=pu(r[n].heading);t[n]=o?[...i,o]:i,e.push(n)}return t.map(n=>n.join("#").toLowerCase())}var Nte,mu=x(()=>{Nte=/[!"#$%&()*+,.:;<=>?@^`{|}~/[\]\\\r\n]/g});async function xT(r,t,e,n){return await QC(r,e,n)&&await t.saveSettings?.(),XV(r,e,n)}var kF=x(()=>{Xa()});function vy(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 u2(){return ET}function p2(r,t){let e=ET;ET=r;try{return t()}finally{ET=e}}var ET,TT=x(()=>{ET=[]});function Mc(r,{logPrefix:t,noticePrefix:e=t,defaultReason:n}){if(!(r instanceof at))return!1;if(m2.has(r))return!0;m2.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 f2.Notice(o(e)),!0}var f2,m2,yy=x(()=>{f2=require("obsidian");ti();rr();je();ye();m2=new WeakSet});var h2={};eb(h2,{SingleMacroEngine:()=>SF});function zte(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 qte,SF,g2=x(()=>{ye();Zt();eu();lt();ex();kF();by();TT();yy();Hr();ti();qte=new Set(["settings","entry","quickadd"]);SF=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}=Am(t),s=d=>(d??"").trim(),a=Jt(this.choices).find(d=>d.type==="Macro"&&s(d.name)===s(i));if(!a){let d=p=>s(p).toLowerCase(),u=Jt(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 Xs(this.app,this.plugin,a,this.choiceExecutor,this.variables,void 0,e?.label,null,vy(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)),zte(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=Pv(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 $v(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"&&km(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 xT(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 Mc(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 $v(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(qte.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}::<Script Name>::${n.join("::")}}}'.`)}warnReservedKeyConflict(t,e,n,i){if(this.emittedConflictNotice)return;this.emittedConflictNotice=!0;let o=i.map(s=>`'${s.command.name}'`).join(", ");S.logWarning(`Macro '${t.name}': multiple user scripts export '${e.join("::")}' (${o}); using '${n.command.name}'. Disambiguate with '{{MACRO:${t.name}::<Script Name>::${e.join("::")}}}'.`)}resolveScriptSelector(t,e,n){if(n.length<2)return null;let i=n[0]?.trim(),o=e.filter(s=>s.command.name.trim()===i);if(o.length===0)return null;if(o.length>1)throw new at(`Macro '${t.name}' has multiple user scripts named '${i}'. Rename one of them before using '{{MACRO:${t.name}::${i}::${n.slice(1).join("::")}}}'.`);return{command:o[0].command,index:o[0].index,memberAccess:n.slice(1)}}syncVariablesFromParams(t){Object.keys(t.params.variables).forEach(e=>{this.choiceExecutor.variables.set(e,t.params.variables[e])})}formatResult(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(typeof t=="object")try{return JSON.stringify(t)}catch{return Object.prototype.toString.call(t)}return String(t)}ensureNotAborted(){let t=this.choiceExecutor.consumeAbortSignal?.();if(t)throw t}}});function AF(r,t){let e=r.replace(/\n$/,"").split(`
- `).pop()??"",n=t.split(`
- `,1)[0];return y2.test(e)&&y2.test(n)?`
- `:""}function ul(r){let t=(0,b2.getFrontMatterInfo)(r);return t.exists?t.contentStart:0}function Wte(r,t){let e=ul(r);if(e===0)return 0;if(v2.test(t))return e;let n=v2.exec(r.slice(e));return n?e+n[0].length:e}function fu(r,t,{separateBlockquotes:e=!1}={}){if(t.length===0)return{content:r,insertedStartOffset:null,insertedEndOffset:null};let n=Wte(r,t),i=r.slice(0,n),o=r.slice(n),s=i.length>0&&!i.endsWith(`
- `)&&!Hte.test(t)?`
- `:"",a=o.length>0&&!t.endsWith(`
- `)?`
- `:"",l=e?AF(t,o):"",c=i.length+s.length,d=c+t.length;return{content:`${i}${s}${t}${a}${l}${o}`,insertedStartOffset:c,insertedEndOffset:d}}function w2(r,t){return fu(r,t).content}var b2,v2,Hte,y2,Rc=x(()=>{b2=require("obsidian"),v2=/^[^\S\r\n]*\r?\n/,Hte=/^\r?\n/,y2=/^ {0,3}>/});function _T(r){let t=ul(r),e=/\{\{CURSOR\}\}/i.exec(r.slice(t));return{content:Dn(r),offsets:e?[Dn(r.slice(0,t)).length+e.index]:[]}}function IF(r,t){if(r.content===t)return r;r.content.includes("\r")&&!t.includes("\r")&&(r=Gte(r));let e=ul(r.content),n=ul(t);return r.offsets.some(i=>i<e)||r.content.slice(e)!==t.slice(n)?null:{content:t,offsets:r.offsets.map(i=>i+n-e)}}function Gte(r){let t=e=>e.replace(/\r\n?/g,`
- `);return{content:t(r.content),offsets:r.offsets.map(e=>t(r.content.slice(0,e)).length)}}var PF=x(()=>{Pa();Rc()});function kT(r){for(let t of r.workspace.getLeavesOfType("markdown")){let e=t.view;if(!(!e.containerEl||!e.file||e.file.extension!=="md"))try{let n=Li(e.containerEl).activeElement;if(!n||!e.containerEl.contains(n)||!n.closest(".metadata-property-value")||n.matches(jte))continue;let o=n.closest(".metadata-property")?.getAttribute("data-property-key");if(!o)continue;return{file:e.file,key:o}}catch{continue}}return null}function Yte(r,t,e){let n=T2(r,t),i=r[n];if(Array.isArray(i)){i.push(e);return}if(i==null||i===""){r[n]=e;return}if(typeof i=="string"){r[n]=`${i} ${e}`;return}throw new Error(`Cannot append link to frontmatter property '${n}' because it contains a ${typeof i} value.`)}function E2(r,t,e,n=Ld){let i=T2(r,t),o=r[i];if(Array.isArray(o)){o.push(e);return}if(o===null||o===""){r[i]=[e];return}if(o===void 0){if(n==="error")throw new Error(`Cannot append link to frontmatter property '${i}' because it does not exist.`);r[i]=[e];return}if(typeof o=="object")throw new Error(`Cannot append link to frontmatter property '${i}' because it contains an object value.`);if(n!=="alwaysAppend")throw new Error(`Cannot append link to frontmatter property '${i}' because it is not a list and the link-handling mode is '${C2[n]}'. Choose '${C2.alwaysAppend}' to convert it into a list and append.`);r[i]=[o,e]}function T2(r,t){if(t=t.trim(),!t)throw new Error("Cannot append link to an empty frontmatter property key.");let e=x2(t),n=Object.keys(r).filter(i=>x2(i)===e);if(n.length>1)throw new Error(`Cannot append link to frontmatter property '${t}' because the note has multiple properties that normalize to that key.`);return n[0]??t}function x2(r){return r.trim().toLowerCase()}async function _2(r,t,e){let n=r.fileManager.generateMarkdownLink(e,t.file.path);try{return await Yl(r,t.file,i=>{Yte(i,t.key,n)}),!0}catch(i){return S.logError(`QuickAdd: created the file but could not append the link to frontmatter property '${t.key}' in '${t.file.path}': ${i instanceof Error?i.message:String(i)}`),!1}}var C2,jte,wy=x(()=>{Ds();ye();Ql();Go();C2={alwaysAppend:"Create or convert",createProperty:"Create if missing",error:"Require list"},jte=['input[type="number"]','input[type="date"]','input[type="datetime-local"]','input[type="time"]','input[type="month"]','input[type="checkbox"]'].join(", ")});function k2(r,t,e,n){let i=Js(t,e);return i?$F(r,i.editor,n):null}function $F(r,t,e){if(r.cursor.kind==="none")return null;let n=r.content.replace(/\r\n?/g,`
- `),i=r.content.slice(0,r.cursor.value).replace(/\r\n?/g,`
- `).length,o=u=>t.posToOffset(u),s=t.getCursor(),a;if(e==="currentLine")a=t.listSelections().map(({anchor:u,head:p})=>({from:o(u)<=o(p)?u:p,to:o(u)<=o(p)?p:u,text:n,cursor:i}));else if(e==="newLineAbove"||e==="newLineBelow"){let u=e==="newLineAbove";a=[{from:{line:s.line,ch:u?0:t.getLine(s.line).length},text:u?n+`
- `:`
- `+n,cursor:i+(u?0:1)}]}else return null;let l=[],c=[],d=0;a.sort((u,p)=>o(u.from)-o(p.from));for(let u of a)l.push(o(u.from)+d+u.cursor),c.push(o(u.from)+d+u.text.length-(e==="newLineAbove"?1:0)),d+=u.text.length-(o(u.to??u.from)-o(u.from));return t.transaction({changes:a.map(({from:u,to:p,text:m})=>({from:u,to:p,text:m}))}),t.setSelections(c.map(u=>({anchor:t.offsetToPos(u)}))),{offsets:l,content:t.getValue()}}function Js(r,t){let e=mn(r);return e?.file?.path===t.path?e:null}function S2(r,t){try{let e=mn(t);return e?(e.editor.replaceSelection(r),!0):(S.logError(`unable to append '${r}' to current line.`),!1)}catch{return S.logError(`unable to append '${r}' to current line.`),!1}}function A2(r,t,e){try{let n=mn(e);if(!n)return S.logError(`unable to insert '${r}' on new line ${t}.`),!1;let i=n.editor,s=i.getCursor().line,a=r.split(`
- `),l=a.length,c=a[l-1]?.length??0;if(t==="above")i.replaceRange(r+`
- `,{line:s,ch:0}),i.setCursor({line:s+l-1,ch:c});else{let d=i.getLine(s);i.replaceRange(`
- `+r,{line:s,ch:d.length}),i.setCursor({line:s+l,ch:c})}return!0}catch{return S.logError(`unable to insert '${r}' on new line ${t}.`),!1}}function I2(r,t){return A2(r,"above",t)}function P2(r,t){return A2(r,"below",t)}function Kte(r,t,e,n,i){let o=c=>r.posToOffset(c),s=t.map(c=>{let[d,u]=o(c.anchor)<=o(c.head)?[c.anchor,c.head]:[c.head,c.anchor];return{from:d,to:u,text:n(r.getRange(d,u))}}).sort((c,d)=>o(c.from)-o(d.from)),a=s.map(({from:c,to:d,text:u})=>e==="replaceSelection"?{from:c,to:d,text:u}:{from:d,text:u}),l=[];if(e==="replaceSelection"){let c=0;for(let{from:d,to:u,text:p}of s)l.push(o(d)+c+p.length),c+=p.length-(o(u)-o(d))}i(a,()=>r.transaction({changes:a})),e==="replaceSelection"&&r.setSelections(l.map(c=>({anchor:r.offsetToPos(c)})))}async function Qte(r,t,e="replaceSelection",n={}){let{requireActiveView:i=!0,frontmatterProperty:o,frontmatterHandling:s=Ld,textForSelection:a,onEditorTextMutation:l}=n,c=r.workspace.getActiveViewOfType(ST.MarkdownView);if(!c){let g="Cannot append link because no active Markdown view is available.";if(i)throw new Error(g);S.logMessage(g);return}if(e==="inFrontmatter"){let g=c.file;if(!g)throw new Error("Cannot append link because the active Markdown view has no file.");await Yl(r,g,v=>{E2(v,o??"",t,s)});return}let d=c.editor;if(!d){let g="Cannot append link because the active Markdown view has no editor.";if(i)throw new Error(g);S.logMessage(g);return}let u=(g,v)=>{if(!l){v();return}let b=d.getValue(),y=g.map(C=>({from:d.posToOffset(C.from),to:d.posToOffset(C.to??C.from),text:C.text}));v(),l({filePath:c.file?.path??null,before:b,after:d.getValue(),edits:y})},p=d.listSelections().map(g=>({anchor:{...g.anchor},head:{...g.head}}));if(a&&p.length>0&&(e==="replaceSelection"||e==="afterSelection")){Kte(d,p,e,a,u);return}if(e==="replaceSelection"){let g=p.map(({anchor:v,head:b})=>({from:d.posToOffset(v)<=d.posToOffset(b)?v:b,to:d.posToOffset(v)<=d.posToOffset(b)?b:v,text:t}));u(g,()=>d.replaceSelection(t));return}let m=({line:g,ch:v})=>d.posToOffset({line:g,ch:v}),h=p.sort((g,v)=>m(v.head)-m(g.head));for(let g of h){let v=m(g.anchor)>m(g.head)?g.anchor:g.head;switch(e){case"afterSelection":{u([{from:v,text:t}],()=>d.replaceRange(t,v));break}case"endOfLine":case"newLine":{let b=d.getLine(v.line).length,y=e==="newLine"&&b>0?`
- `:"",C={line:v.line,ch:b};u([{from:C,text:y+t}],()=>d.replaceRange(y+t,C));break}}}}async function FF(r,t,e,n){if(!e?.enabled)return!1;let i=Kl(e),o=r.workspace.getActiveViewOfType(ST.MarkdownView),s=i.placement!=="inFrontmatter";if(!o||!o.file||s&&!o.editor){if(e.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}let a=o.file.path,l=Mw(r,t,{sourcePath:a,linkType:i.linkType,placement:i.placement}),c=i.displayText==="selection"?d=>Mw(r,t,{sourcePath:a,linkType:i.linkType,placement:i.placement,alias:d}):void 0;return await Qte(r,l,i.placement,{requireActiveView:!1,frontmatterProperty:i.frontmatterProperty,frontmatterHandling:i.frontmatterHandling,textForSelection:c,onEditorTextMutation:n}),!0}function $2(r,t,e,n){return Cy(r,t,[e],n)}function Cy(r,t,e,n){try{if(t.extension!=="md"||!e.length||e.some(c=>!Number.isSafeInteger(c)||c<0||c>n.length))return!1;let i=r.workspace.getActiveViewOfType(ST.MarkdownView);if(!i||i.file?.path!==t.path||i.getMode()==="preview")return!1;let o=i.editor;if(!o)return!1;let s=o.getValue(),a=e;if(s!==n){if(s!==n.replace(/\r\n?/g,`
- `))return!1;a=e.map(c=>n.slice(0,c).replace(/\r\n?/g,`
- `).length)}a.length===1?o.setCursor(o.offsetToPos(a[0])):o.setSelections(a.map(c=>({anchor:o.offsetToPos(c)})));let l=i.containerEl?.ownerDocument;return l&&l.activeElement===l.body&&o.focus(),!0}catch{return S.logMessage(`Unable to place cursor after capture in '${t.path}'.`),!1}}var ST,hu=x(()=>{ST=require("obsidian");is();ye();Ql();Ip();wy();Ds()});function IT(r,t){try{let e=r.workspace.getActiveViewOfType(PT.MarkdownView);if(!e||e.file?.path!==t.path)return{cursor:null,value:null};let n=e.editor,i=n?.getCursor?.(),o=i&&typeof i.line=="number"&&typeof i.ch=="number"?{line:i.line,ch:i.ch}:null,s=typeof n?.getValue=="function"?n.getValue():null;return{cursor:o,value:s}}catch{return{cursor:null,value:null}}}function Jte(r,t){return r!==null&&t!==null&&(r.line!==t.line||r.ch!==t.ch)}function F2(r){return typeof r!="string"?null:[...r.matchAll(Xte)].length}function D2(r,t){let e=F2(r),n=F2(t);return e!==null&&n!==null&&e>n}function M2(r,t){return Jte(r.cursor,t.cursor)||D2(r.value,t.value)}async function RF(r,t,e=500){try{let n=r.vault.adapter;if(!("stat"in n)||typeof n.stat!="function")return;let i=await n.stat(t.path);if(!i)return;let o=i.mtime,s=Date.now(),a=30;for(;Date.now()-s<e;){await Ey(a);let l=await n.stat(t.path);if(!l||l.mtime===o)return;o=l.mtime,a=Math.min(a*2,200)}}catch(n){S.logWarning(`waitForFileSettle: fallback due to adapter/stat failure \u2013 ${n.message}`)}}function OF(r){return r.plugins.plugins["templater-obsidian"]}function vu(r){let t=OF(r);return t||null}function Ty(r){let t=vu(r);if(!t)return!1;let e=t.settings?.trigger_on_file_creation;if(typeof e=="boolean")return e;let n=r.loadLocalStorage?.("templater-local-settings");return typeof n=="object"&&n!==null&&!Array.isArray(n)&&"trigger_on_file_creation"in n&&n.trigger_on_file_creation===!0}function Ey(r){return new Promise(t=>window.setTimeout(t,r))}function Zte(r,t){if(Dc)return;let e=function(...n){let i=t.apply(this,n),o=n[n.length-1]?.path;return typeof o=="string"&&gu.has(o)&&gu.set(o,Promise.resolve(i)),i};r.on_file_creation=e,Dc={owner:r,original:t,wrapper:e}}function ere(){!Dc||gu.size>0||(Dc.owner.on_file_creation===Dc.wrapper&&(Dc.owner.on_file_creation=Dc.original),Dc=null)}async function LF(r,t,e){let n=(0,PT.normalizePath)(t),i,o;try{i=Ty(r)?vu(r)?.templater?.constructor:void 0,o=i?.on_file_creation}catch{i=void 0}if(!(!!i&&typeof o=="function"&&!gu.has(n))){let d=await e();return await R2(r,d),d}gu.set(n,null),Zte(i,o);let a,l;try{a=await e()}finally{l=gu.get(n)??null,gu.delete(n),ere()}if(!l||a.path!==n)return await R2(r,a),a;let c;try{await Promise.race([l,new Promise(d=>{c=window.setTimeout(d,tre)})])}catch(d){S.logWarning(`Templater failed on new note ${a.path}: ${d.message}`)}finally{window.clearTimeout(c)}return a}async function R2(r,t,e={}){if(t.extension!=="md"||!Ty(r))return;let i=vu(r)?.templater?.files_with_pending_templates;if(!(i instanceof Set)){await ire(r,t,{timeoutMs:e.timeoutMs??5e3,gracePeriodMs:e.appearTimeoutMs??2500,quietPeriodMs:200});return}let{timeoutMs:o=5e3,appearTimeoutMs:s=2500}=e,a=Date.now();for(;Date.now()-a<s&&!i.has(t.path);)await Ey(50);for(;Date.now()-a<o&&i.has(t.path);)await Ey(50);await RF(r,t,800)}async function nre(r,t,e){if(!(DF>0)&&e.size===0){if(xy){await xy;return}xy=(async()=>{try{r.workspace.trigger("templater:all-templates-executed"),await t.templater?.functions_generator?.teardown?.()}catch(n){S.logWarning(`withTemplaterFileCreationSuppressed: teardown failed \u2013 ${n.message}`)}})();try{await xy}finally{xy=null}}}async function O2(r,t,e){let n=vu(r),i=n?.templater?.files_with_pending_templates;if(!n||!Ty(r)||!(i instanceof Set))return await e();DF++;let o=MF.get(t);o||(o={count:0,hadPathInitially:i.has(t)},MF.set(t,o),o.hadPathInitially||i.add(t)),o.count++;let s=!1;try{let a=await e();return s=!0,a}finally{o.count--,DF--,o.count<=0&&(MF.delete(t),o.hadPathInitially||(s&&await Ey(rre),i.delete(t),await nre(r,n,i)))}}async function ire(r,t,e={}){let{timeoutMs:n=2e3,quietPeriodMs:i=150,gracePeriodMs:o=800}=e;try{let s=r.vault.adapter;if(!("stat"in s)||typeof s.stat!="function")return;let a=await s.stat(t.path);if(!a)return;let l=a.mtime,c=Date.now(),d=!1,u=c,p=50;for(;Date.now()-u<n;){await Ey(p);let m=await s.stat(t.path);if(!m)return;let h=Date.now();if(m.mtime!==l){d=!0,l=m.mtime,c=h,p=50;continue}if(d){if(h-c>=i)return}else if(h-u>=o)return;p=Math.min(Math.floor(p*1.5),200)}}catch(s){S.logWarning(`waitForFileToStopChanging: fallback due to adapter/stat failure \u2013 ${s.message}`)}}async function ore(r,t){let e=AT.get(r)??Promise.resolve(),n,i=new Promise(s=>{n=()=>s()}),o=e.catch(()=>{}).then(()=>i);AT.set(r,o),o.finally(()=>{AT.get(r)===o&&AT.delete(r)}).catch(()=>{}),await e.catch(()=>{});try{return await t()}finally{n()}}async function yu(r,t,e={}){if(t.extension!=="md")return!1;let n=vu(r),i=n?.templater,o=i?.overwrite_file_commands;if(!n||!i||typeof o!="function")return!1;let{skipIfNoTags:s=!0,postWait:a=!0}=e;return await ore(t.path,async()=>{await RF(r,t);let l;try{l=await r.vault.read(t)}catch(u){return Me(u,`overwriteTemplaterOnce: failed to read ${t.path} before render`),!1}if(s&&!l.includes("<%"))return!1;let c=null,d=r.workspace.on("templater:overwrite-file",u=>{u.file.path===t.path&&(c=u.content)});try{await o.call(i,t);let u=D2(c,IT(r,t).value);return a&&await RF(r,t,800),u}catch(u){return Me(u,`Templater failed on ${t.path}`),!1}finally{r.workspace.offref(d)}})}async function Oc(r,t,e){if(e.extension!=="md")return t;let n=vu(r),i=n?.templater,o=i?.parse_template;if(!n||!i||typeof o!="function")return t;let s=i.create_running_config,a=typeof s=="function"?s.call(i,void 0,e,4):{target_file:e,run_mode:4,frontmatter:{}};return await o.call(i,a,t)}async function bu(r,t){if(t.extension!=="md"||r.workspace.getActiveFile()?.path!==t.path)return!1;let e=vu(r),n=!!e?.settings?.auto_jump_to_cursor,i=e?.editor_handler,o=i?.jump_to_next_cursor_location;if(!n)return!1;let s=IT(r,t);if(typeof o=="function")try{return await o.call(i,t,!0),M2(s,IT(r,t))}catch(a){S.logWarning(`jumpToNextTemplaterCursorIfPossible: API failed \u2013 ${a.message}`)}try{return!r.commands.executeCommandById?.("templater-obsidian:jump-to-next-cursor-location")?!1:M2(s,IT(r,t))}catch{}return!1}var PT,Xte,gu,Dc,tre,MF,DF,xy,rre,AT,Lc=x(()=>{PT=require("obsidian");ye();nt();Xte=/<%\s*tp\.file\.cursor\((?:-?[0-9]+(?:\.[0-9]+)?)?\)\s*%>/g;gu=new Map,Dc=null;tre=5e3;MF=new Map,DF=0,xy=null,rre=350;AT=new Map});var _y,vf,NF=x(()=>{_y=require("obsidian");Ve();ye();Lc();Hi();vf=class{constructor(t){this.app=t}async createFolder(t){await this.app.vault.adapter.exists(t)||await this.app.vault.createFolder(t)}stripLeadingSlash(t){return t.replace(/^\/+/,"")}normalizeMarkdownFilePath(t,e){let n=this.stripLeadingSlash(t),i=n?`${n}/`:"",o=this.stripLeadingSlash(e).replace(xt,"");return`${i}${o}.md`}async fileExists(t){return await this.app.vault.adapter.exists(t)}getFileByPath(t){let e=this.app.vault.getAbstractFileByPath(t);if(!e)throw S.logError(`${t} not found`),new Error(`${t} not found`);if(e instanceof _y.TFolder)throw S.logError(`${t} found but it's a folder`),new Error(`${t} found but it's a folder`);if(!(e instanceof _y.TFile))throw new Error(`${t} is not a file`);return e}async createFileWithInput(t,e,n={}){if(Ut(t))throw new Error(`Refusing to create a file outside the vault: "${t}".`);let i=t.match(/(.*)[/\\]/),o="";i&&(o=i[1]);let s=this.app.vault.getAbstractFileByPath(o);(!s||!(s instanceof _y.TFolder))&&await this.createFolder(o);let a=()=>this.app.vault.create(t,e);return n.suppressTemplaterOnCreate&&t.toLowerCase().endsWith(".md")?await O2(this.app,t,a):await a()}}});async function Ki(r,t){try{return r.promptProvider?await t.remote(r.promptProvider):r.interactive===!1?await t.headless():await t.app()}catch(e){throw Be(e)?new et("Input cancelled by user"):e}}var wu=x(()=>{rr();nt()});async function Qi(r,t){let e=t.items.map((s,a)=>`${sre}${a}`),n=await r.suggester(t.items.map(s=>s.title),e,t.placeholder,t.allowCustomInput??!1),i=n==null?"":String(n),o=e.indexOf(i);if(o!==-1)return t.items[o].value;if(i==="")throw new et("Input cancelled by user");if(t.allowCustomInput)return i;throw new Error(`A reply to ${t.what} has to be one of the offered options, and "${i.slice(0,60)}" is not. Reply with the item's \`value\` token exactly as it was sent, or \`{"cancelled": true}\` to dismiss it.`)}var sre,Cu=x(()=>{rr();sre="\0qa-eng:"});function VF(r){let t=r.map(n=>n||"/");return`Folder must be under: ${t.length>3?`${t.slice(0,3).join(", ")}...`:t.join(", ")}`}var $T,are,Zs,FT,L2=x(()=>{$T=require("obsidian");NF();Gi();nl();Wh();tn();ti();kn();wu();Cu();are=3,Zs=class extends Error{constructor(t){super(t),this.name="InvalidFolderPathError"}},FT=class extends vf{async getOrCreateFolder(t,e){let n=this.buildFolderSelectionContext(t,{...e,topItems:t.length>0?[]:e.topItems??[]});if(!this.shouldPromptForFolder(n))return await this.handleSingleSelection(n);let i=this.buildFolderSelectionContext(t,e),o=await this.promptUntilAllowed(i,e.executor);return o.isEmpty?"":o.normalized}buildFolderSelectionContext(t,e){let n=e.allowCreate??!1,i=e.allowedRoots?.map(s=>po(s))??[];return{...this.buildFolderSuggestions(t,e.topItems??[],i.length>0?i:void 0),allowCreate:n,allowedRoots:i,placeholder:e.placeholder}}shouldPromptForFolder(t){return t.items.length>1||t.allowCreate&&t.items.length===0}async promptForFolder(t,e){let n=t.placeholder??"Choose a folder or type to create one";return String(await Ki(e,{remote:i=>Qi(i,{items:t.items.map((o,s)=>({value:o,title:t.displayItems[s]??o})),placeholder:n,allowCustomInput:t.allowCreate,what:"the folder chooser"}),headless:()=>{throw new ue("This choice needs to ask which folder to create the note in, but this run is non-interactive. Configure a single target folder, or re-run with the ui flag.")},app:()=>t.allowCreate?gr.Suggest(this.app,t.displayItems,t.items,{placeholder:n,renderItem:(i,o)=>{this.renderFolderSuggestion(i,o,t.canonicalByNormalized,t.displayByNormalized)}}):It.Suggest(this.app,t.displayItems,t.items,t.placeholder)}))}async resolveSelection(t,e){let n=xr(t),i=n.length===0,o=e.canonicalByNormalized.get(n)??po(t),s=i?!1:e.canonicalByNormalized.has(n)||await this.app.vault.adapter.exists(o),a=e.allowedRoots.length===0?!0:this.isPathAllowed(o,e.allowedRoots);return{raw:t,normalized:o,exists:s,isAllowed:a,isEmpty:i}}async promptUntilAllowed(t,e){let n=e.promptProvider?are:0,i=null;for(;;){if(e.promptProvider&&n--<=0)throw new ue(i??VF(t.allowedRoots));let o=await this.promptForFolder(t,e),s=await this.resolveSelection(o,t);if(!s.isAllowed){i=VF(t.allowedRoots),this.showFolderNotAllowedNotice(t.allowedRoots);continue}if(s.isEmpty)return s;try{this.validateFolderPath(s.normalized)}catch(a){if(a instanceof Zs){i=a.message,new $T.Notice(a.message);continue}throw a}return await this.ensureFolderExists(s),s}}async ensureFolderExists(t){t.isEmpty||t.exists||await this.createFolder(t.normalized)}async handleSingleSelection(t){let e=t.items[0]??"",n=await this.resolveSelection(e,t);if(n.isEmpty)return"";if(!n.isAllowed)throw this.showFolderNotAllowedNotice(t.allowedRoots),new at("Selected folder not allowed.");try{this.validateFolderPath(n.normalized)}catch(i){if(i instanceof Zs)return new $T.Notice(i.message),"";throw i}return await this.ensureFolderExists(n),n.normalized}validateFolderPath(t){if(!t)return;let e=t.split("/");for(let n of e)this.validateFolderSegment(n)}validateFolderSegment(t){if(!t)throw new Zs("Folder name cannot be empty.");if(t==="."||t==="..")throw new Zs("Folder name cannot be '.' or '..'.");if(qh.test(t))throw new Zs("Folder name cannot contain control characters.");if(zh.test(t))throw new Zs('Folder name cannot contain any of the following characters: \\ / : * ? " < > |');if(Hh.test(t))throw new Zs("Folder name cannot end with a space or a period.");let e=t.split(".")[0]??"";if(e&&kd(e))throw new Zs("Folder name cannot be a reserved name like CON, PRN, AUX, NUL, COM1-9, or LPT1-9.")}isPathAllowed(t,e){let n=po(t);for(let i of e)if(!i||n===i||n.startsWith(`${i}/`))return!0;return!1}showFolderNotAllowedNotice(t){new $T.Notice(VF(t))}canonicalFolderPath(t){return po(t)}buildFolderSuggestions(t,e,n){let i=[],o=[],s=new Map,a=new Map,l=(c,d)=>{let u=xr(c);s.has(u)||n&&n.length>0&&!this.isPathAllowed(c,n)||(i.push(c),o.push(d??c),s.set(u,this.canonicalFolderPath(c)),d&&a.set(u,d))};for(let c of e)l(c.path,c.label);for(let c of t)l(c);return{items:i,displayItems:o,canonicalByNormalized:s,displayByNormalized:a}}renderFolderSuggestion(t,e,n,i){e.empty(),e.classList.add("mod-complex");let o=xr(t),s=i.get(o),a=t||"/",l=n.has(o),c="";s==="<current folder>"?c="Current folder":l||(c="Create folder"),e.createDiv("suggestion-content").createDiv("suggestion-title").createSpan({text:a}),c&&e.createDiv("suggestion-aux").createEl("kbd",{cls:"suggestion-hotkey",text:c})}}});function cre(r){let t=[],e=[];for(let[n,i]of r){let o=UF(n,i,new Set,0);t.push(...o.warnings),e.push(...o.errors)}return{isValid:e.length===0,warnings:t,errors:e}}function UF(r,t,e,n){let i=[],o=[];if(typeof t=="function")return o.push(`Variable "${r}" contains a function, which cannot be serialized to YAML`),{warnings:i,errors:o};if(typeof t=="symbol")return o.push(`Variable "${r}" contains a symbol, which cannot be serialized to YAML`),{warnings:i,errors:o};if(typeof t=="bigint")return i.push(`Variable "${r}" contains a BigInt, which will be converted to a string`),{warnings:i,errors:o};if(t==null)return{warnings:i,errors:o};if(typeof t!="object")return{warnings:i,errors:o};if(e.has(t))return o.push(`Variable "${r}" contains a circular reference`),{warnings:i,errors:o};if(n>=BF.MAX_NESTING_DEPTH)return o.push(`Variable "${r}" exceeds maximum nesting depth of ${BF.MAX_NESTING_DEPTH}`),{warnings:i,errors:o};e.add(t);try{if(Array.isArray(t))for(let s=0;s<t.length;s++){let a=UF(`${r}[${s}]`,t[s],e,n+1);i.push(...a.warnings),o.push(...a.errors)}else for(let[s,a]of Object.entries(t)){let l=UF(`${r}.${s}`,a,e,n+1);i.push(...l.warnings),o.push(...l.errors)}}finally{e.delete(t)}return{warnings:i,errors:o}}function yf(r,t){return lre.includes(r.extension)&&t.size>0}async function bf(r,t,e){let n=cre(e);if(n.warnings.length>0)for(let i of n.warnings)S.logWarning(`Structured variable validation warning: ${i}`);if(!n.isValid){let i=n.errors.join("; ");S.logError(`Cannot post-process front matter for file ${t.path} due to validation errors: ${i}. The file was created successfully, but some structured variables may not be properly formatted. Please check the variable values and ensure they don't contain circular references, exceed nesting depth of ${BF.MAX_NESTING_DEPTH}, or contain unsupported types (functions, symbols).`);return}try{S.logMessage(`Post-processing front matter for ${t.path} with ${e.size} structured variables`),S.logMessage(`Variable types: ${Array.from(e.entries()).map(([i,o])=>`${i}:${typeof o}`).join(", ")}`),await Yl(r,t,i=>{for(let[o,s]of e){let a=o.includes(Ni.PATH_SEPARATOR)?o.split(Ni.PATH_SEPARATOR):[o],l=hp(s);ky(i,a,l)}}),S.logMessage(`Successfully post-processed front matter for ${t.path}`)}catch(i){S.logError(`Failed to post-process front matter for file ${t.path}: ${i}. The file was created successfully, but structured variables may not be properly formatted. This usually happens when variable values contain unexpected types or when Obsidian's YAML processor encounters an issue. Check the console for more details about which variables caused the problem.`)}}function qF(r){return r.some((t,e)=>t==="__proto__"?!0:!(e===r.length-1)&&dre.has(t))}function ky(r,t,e){if(t.length===0)return;if(qF(t)){S.logWarning(`Skipping front matter assignment for unsafe key path "${t.join(".")}" to avoid prototype pollution.`);return}let n=r;for(let i=0;i<t.length-1;i++){let o=t[i],s=n[o];(typeof s!="object"||s===null||Array.isArray(s))&&(n[o]={}),n=n[o]}n[t[t.length-1]]=e}var BF,lre,dre,MT=x(()=>{Ds();ye();gp();Uh();BF={MAX_NESTING_DEPTH:10},lre=["md"];dre=new Set(["prototype","constructor"])});function Sy(r){let t=Vd(r);if(t.length!==0)throw new ue(FL(t,r))}function N2(r){return Vd(r).length===0}var RT=x(()=>{kn();Qo()});function zF(r){return r instanceof at||!!r&&typeof r=="object"&&"name"in r&&r.name==="MacroAbortError"}var V2,Nc,DT=x(()=>{PF();Pa();Rc();hu();Ds();L2();MT();xu();V2=require("obsidian");tr();Lc();Ve();nt();Qo();Hi();tn();ti();ye();RT();mf();Nc=class extends FT{constructor(e,n,i,o){super(e);this.plugin=n;this.cursorPlacement=null;this.templaterCursorHandled=!1;this.lastTemplateFileFailure=null;this.templater=OF(e),this.formatter=new _i(e,n,i),o&&this.formatter.setTemplateInclusionState(o)}hasTemplaterHandledCursor(){return this.templaterCursorHandled}async finishTemplateContent(e){if(this.cursorPlacement=null,e.extension!=="md")return;let n=null;await Co(this.app,e,i=>{let o=_T(i);return n=py(o.content,o.offsets),n.content}),this.cursorPlacement=n,this.cursorPlacement?.offsets.length===0&&(this.cursorPlacement=null)}getCursorPlacement(){return this.cursorPlacement}placeCursor(e,n){let i=Js(this.app,e)?.editor;if(this.cursorPlacement&&i)for(let o of[this.cursorPlacement,n]){if(!o)continue;let s=IF(o,i.getValue())??o;if(Cy(this.app,e,s.offsets,s.content))return}}async rebaseCursorAfterFileChanges(e){if(this.cursorPlacement)try{this.cursorPlacement=IF(this.cursorPlacement,await this.app.vault.read(e))}catch{this.cursorPlacement=null,S.logMessage(`Unable to verify cursor position in '${e.path}'.`)}}stripDuplicateFolderPrefix(e,n){let i=this.stripLeadingSlash(n),o=this.stripLeadingSlash(e);return i?o.startsWith(`${i}/`)?{fileName:o.slice(i.length+1),strippedPrefix:!0}:{fileName:o,strippedPrefix:!1}:{fileName:o,strippedPrefix:!1}}shouldTreatFormattedNameAsVaultRelativePath(e,n,i){if(i||n)return!1;let o=e.trim();if(!o.includes("/")||o.startsWith("./"))return!1;if(o.startsWith("/"))return!0;let[s]=this.stripLeadingSlash(o).split("/");return s?this.app.vault.getAbstractFileByPath(s)instanceof V2.TFolder:!1}getTemplateExtension(e){return e=xn(e),lr.test(e)?".canvas":Mn.test(e)?".base":".md"}normalizeTemplateFilePath(e,n,i){let o=this.stripLeadingSlash(e),s=o?`${o}/`:"",a=this.getTemplateExtension(i),l=Nr(this.stripLeadingSlash(n),"File name"),c=Nr(l.replace(xt,"").replace(lr,"").replace(Mn,""),"File name");if(!c.slice(c.lastIndexOf("/")+1).trim())throw new Error("File name is empty after formatting. Make sure the tokens in the file name format produce a value (an optional token left empty can cause this).");let u=`${s}${c}${a}`;if(Ut(u))throw new Error(`Refusing to build a file path outside the vault: "${u}".`);return u}noteTemplateFileFailure(e,n){this.lastTemplateFileFailure=e instanceof Error&&e.message?e.message:n}setTemplateDestination(e,n){this.formatter.setTitle(n),this.formatter.setTargetFolderPath(Zn(e)),this.formatter.setPromptRunContext({destination:e,destinationKind:"file"})}async prepareTemplateBody(e,n,i,o){this.setTemplateDestination(n,i);let s=n.toLowerCase().endsWith(".md"),a=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",e,()=>s?this.formatter.withUserTextProtected(()=>this.formatter.formatTemplateContent(e)):this.formatter.formatFileContent(e))),l=this.formatter.getAndClearTemplatePropertyVars();S.logMessage(`TemplateEngine.${o}: Collected ${l.size} template property variables for ${n}`),l.size>0&&S.logMessage(`Variables: ${Array.from(l.keys()).join(", ")}`),this.cursorPlacement=null,this.templaterCursorHandled=!1;let c=ul(a);return{content:n.toLowerCase().endsWith(".md")?Dn(a.slice(0,c))+a.slice(c):Dn(a),variables:l}}async createFileWithTemplate(e,n){this.lastTemplateFileFailure=null,Sy(e);try{let i=await this.getTemplateContent(n),{content:o,variables:s}=await this.prepareTemplateBody(i,e,ks(e),"createFileWithTemplate"),a=e.toLowerCase().endsWith(".md"),l=await this.createFileWithInput(e,o,{suppressTemplaterOnCreate:a}),c=!1;try{yf(l,s)&&await bf(this.app,l,s),this.templaterCursorHandled=await yu(this.app,l),c=!0}finally{await this.finishTemplateContent(l).catch(d=>{if(c)throw d;S.logWarning(`Unable to clean cursor markers in '${l.path}': ${String(d)}`)})}return l}catch(i){if(zF(i))throw i;return this.noteTemplateFileFailure(i,`Could not create file with template at ${e}`),Me(i,`Could not create file with template at ${e}`),null}}setLinkToCurrentFileBehavior(e){this.formatter.setLinkToCurrentFileBehavior(e)}setTargetFolderPath(e){this.formatter.setTargetFolderPath(e)}setPromptRunContext(e){this.formatter.setPromptRunContext(e)}get choiceChain(){return this.formatter.choiceChain}set choiceChain(e){this.formatter.choiceChain=e}async resolveTemplateSourcePath(e){return this.formatter.formatTemplateFilePath(e)}async overwriteFileWithTemplate(e,n){this.lastTemplateFileFailure=null;try{let i=await this.getTemplateContent(n),{content:o,variables:s}=await this.prepareTemplateBody(i,e.path,e.basename,"overwriteFileWithTemplate");await Co(this.app,e,()=>o);let a=!1;try{yf(e,s)&&await bf(this.app,e,s),this.templaterCursorHandled=await yu(this.app,e),a=!0}finally{await this.finishTemplateContent(e).catch(l=>{if(a)throw l;S.logWarning(`Unable to clean cursor markers in '${e.path}': ${String(l)}`)})}return e}catch(i){if(zF(i))throw i;return this.noteTemplateFileFailure(i,"Could not overwrite file with template"),Me(i,"Could not overwrite file with template"),null}}async appendToFileWithTemplate(e,n,i){this.lastTemplateFileFailure=null;try{let o=await this.getTemplateContent(n);this.setTemplateDestination(e.path,e.basename);let s=await this.formatter.withPromptScope("noteBody",o,()=>this.formatter.withUserTextProtected(()=>this.formatter.formatFileContent(o)));e.extension==="md"&&(s=await Oc(this.app,s,e)),s=Sn(s);let a=await this.app.vault.cachedRead(e),l=i==="top"?`${s}
- ${a}`:`${a}
- ${s}`;return await this.app.vault.modify(e,l),e}catch(o){if(zF(o))throw o;return this.noteTemplateFileFailure(o,"Could not append to file with template"),Me(o,"Could not append to file with template"),null}}async getTemplateContent(e){let n=Rn(this.app,e);if(!n)throw new Error(`Template file not found at path "${e}".`);return await this.app.vault.cachedRead(n)}}});var B2={};eb(B2,{SingleTemplateEngine:()=>wf});var wf,HF=x(()=>{DT();ye();tn();wf=class extends Nc{constructor(e,n,i,o,s){super(e,n,o,s);this.templatePath=i;this.promptScope="noteBody";this.preserveCursorMarkers=!1;this.keepUserTextProtected=!1}setPreserveCursorMarkers(e){this.preserveCursorMarkers=e}setKeepUserTextProtected(e){this.keepUserTextProtected=e}setPromptScope(e){this.promptScope=e}setDestinationPath(e){this.formatter.setTitle(ks(e)),this.formatter.setTargetFolderPath(Zn(e))}async run(){let e=await this.resolveTemplateSourcePath(this.templatePath),n=await this.getTemplateContent(e);n||S.logError(`Template ${e} not found.`);let i=()=>this.preserveCursorMarkers?this.formatter.formatTemplateContent(n):this.formatter.formatFileContent(n);return n=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope(this.promptScope,n,()=>this.keepUserTextProtected?this.formatter.withUserTextProtected(i):i())),n}getAndClearTemplatePropertyVars(){return this.formatter.getAndClearTemplatePropertyVars()}}});var U2={};eb(U2,{SingleInlineScriptEngine:()=>WF});var WF,q2=x(()=>{by();WF=class extends Xs{constructor(t,e,n,i,o){super(t,e,null,n,i,void 0,void 0,null,o)}async runAndGetOutput(t){let e=Object.getPrototypeOf(async function(){}).constructor;return await new e(t).bind(this.params,this).call()}}});var z2,_i,xu=x(()=>{Pa();mf();Kz();i2();yg();Wl();z2=require("obsidian");Ve();Pd();Gi();lF();l2();Hd();Fa();Ln();yo();yT();is();$p();mp();mu();rr();kn();nt();_i=class extends Xl{constructor(e,n,i,o){super(e);this.app=e;this.plugin=n;this.choiceExecutor=i;this.contentValuePromptsAcceptImagePaste=!1;this.preserveTemplateCursorMarkers=!1;this.keepUserTextProtected=!1;this.choiceChain=[];this.skipPropertyExpansion=!1;this.includingText=null;this.dateParser=o||To,i&&(this.variables=i?.variables)}userText(e){return Nz(e)}async withUserTextProtected(e){let n=this.keepUserTextProtected;this.keepUserTextProtected=!0;try{return await e()}finally{this.keepUserTextProtected=n}}runClocks(){return this.choiceExecutor?.clocks??this.clocks}async format(e){return this.formatScalarTokens(await this.expandCodeAndIncludes(e))}async expandCodeAndIncludes(e){let n=e;n=await this.replaceInlineJavascriptInString(n),n=await this.replaceMacrosInString(n);let i=this.includingText;this.includingText=await this.replaceGlobalVarInString(n);try{n=await this.replaceTemplateInString(n)}finally{this.includingText=i}return this.replaceGlobalVarInString(n)}async formatScalarTokens(e){let n=e;return n=this.replaceDateInString(n),n=this.replaceTimeInString(n),n=await this.replaceValueInString(n),n=await this.replaceSelectedInString(n),n=await this.replaceClipboardInString(n),n=await this.replaceDateVariableInString(n),n=await this.replaceVariableInString(n),n=await this.replaceFieldVarInString(n),n=await this.replaceFileInString(n),n=await this.replaceMathValueInString(n),n=this.replaceRandomInString(n),this.defersPropertyExpansion()||(n=this.replacePropertyInString(n)),this.promptScope==="captureText"||this.promptScope==="noteBody"&&this.preserveTemplateCursorMarkers?n:Dn(n)}async replaceGlobalVarInString(e){return Zl(e,this.plugin?.settings?.globalVariables)}async formatFileName(e,n="generic"){if(uo.test(e))throw new Error("{{title}} cannot be used in file names as it would create a circular dependency. The title is derived from the filename itself.");let i=await this.withPromptScope(n,e,()=>this.format(e));if(uo.test(i))throw new Error("{{title}} cannot be used in file names as it would create a circular dependency. The title is derived from the filename itself.");return i=this.replaceCurrentFileTokensInString(i,{fileName:!0,folder:!0,activeFolder:"path"}),Sn(i)}get includer(){return this.templateInclusion?.includer}async resolveIncludingTextDate(e){if(!(!this.includer||rg(this.variables,e)!==void 0))for(let n=this.includer;n;n=n.includer){let i=[...(n.includingText??"").matchAll(new RegExp(Ts.source,"gi"))].filter(o=>o[1]?.trim().toLowerCase()===e.toLowerCase());if(i.length>0){await n.replaceDateVariableInString(i.map(o=>o[0]).join(""));return}}}defersPropertyExpansion(){return this.includer?.defersPropertyExpansion()??this.skipPropertyExpansion}writesListPicksAsLines(){return this.includer?.writesListPicksAsLines()??super.writesListPicksAsLines()}async formatPropertyName(e){return await this.withPromptScope("propertyName",e,async()=>Sn(this.replaceCurrentFileTokensInString(await this.format(e),{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0})))}async formatPropertyValue(e,n={}){let i=await this.preserveSingleTokenValue(e,()=>this.withPromptScope("propertyValue",e,async()=>{this.skipPropertyExpansion=!0,this.listPicksAsLines=n.listItems??!1;let o;try{o=await this.format(e)}finally{this.skipPropertyExpansion=!1,this.listPicksAsLines=!1}return o=this.replaceCurrentFileTokensInString(o,{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0}),this.replacePropertyInString(o)}));return typeof i=="string"?Sn(Dn(i)):i}async formatTemplateContent(e){return this.formatContentWithCursorMarkers(e,!0)}async formatFileContent(e){return this.formatContentWithCursorMarkers(e,!1)}async formatContentWithCursorMarkers(e,n){let i=e,o=this.preserveTemplateCursorMarkers;this.preserveTemplateCursorMarkers=n;let s=this.contentValuePromptsAcceptImagePaste;this.contentValuePromptsAcceptImagePaste=!ow(this.promptScope);try{i=await this.format(i)}finally{this.contentValuePromptsAcceptImagePaste=s,this.preserveTemplateCursorMarkers=o}return i=this.replaceCurrentFileTokensInString(i,{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0}),this.keepUserTextProtected||this.includer?i:Sn(i)}async formatFolderPath(e){if(uo.test(e))throw new Error("{{title}} cannot be used in folder paths as it would create a circular dependency. The title is derived from the filename itself.");let n=await this.withPromptScope("folder",e,()=>this.format(e));if(uo.test(n))throw new Error("{{title}} cannot be used in folder paths as it would create a circular dependency. The title is derived from the filename itself.");let i=this.replaceCurrentFileTokensInString(n,{folder:!0,activeFolder:"path"});return Sn(i).replace(/^\/+/,"")}async formatTemplateFilePath(e){if(uo.test(e))throw new Error("{{title}} cannot be used in a template path \u2014 the title is derived from the created file, not the source template.");let n=e;if(n=await this.replaceGlobalVarInString(n),uo.test(n))throw new Error("{{title}} cannot be used in a template path \u2014 the title is derived from the created file, not the source template.");return n=await this.withPromptScope("templatePath",e,()=>this.formatScalarTokens(n)),Sn(n).trim()}async formatLocationString(e){let n=await this.withPromptScope("lineTarget",e,()=>this.format(e));return n=this.replaceCurrentFileTokensInString(n,{links:!0,fileName:!0,title:!0}),Sn(n)}getLinkSourcePath(){return this.includer?.getLinkSourcePath()??null}getCurrentFileLink(){if(this.includer)return this.includer.getCurrentFileLink();let e=this.app.workspace.getActiveFile();return e?this.app.fileManager.generateMarkdownLink(e,""):null}getCurrentFileName(){let e=this.app.workspace.getActiveFile();return e?e.basename:null}getCurrentFolderPath(){let e=this.app.workspace.getActiveFile();if(!e)return null;let n=e.parent?.path??"";return n==="/"?"":n}getCurrentFileLinkToSection(){let e=this.app.workspace.getActiveFile();if(!e)return null;let n=this.getLinkSourcePath()??"",i=null;try{i=this.getActiveHeadingSubpath(e)}catch{i=null}return i?this.app.fileManager.generateMarkdownLink(e,n,i):this.app.fileManager.generateMarkdownLink(e,n)}getActiveHeadingSubpath(e){let n=this.app.workspace.getActiveViewOfType(z2.MarkdownView);if(!n||n.file?.path!==e.path||n.getMode()==="preview")return null;let i=n.editor,o=i?.getCursor();if(!i||!o)return null;let s=i.getValue(),a=oi(s.split(/\r?\n/)),c=n.data.replace(/\r\n/g,`
- `)===s?this.app.metadataCache.getFileCache(e):null,d=(c?.headings??[]).map(y=>({heading:y.heading,level:y.level,line:y.position.start.line})),u=y=>`${y.level}:${pu(y.heading)}`,p=new Map(a.map(y=>[y.line,u(y)]));if(!(c&&d.every(y=>p.get(y.line)===u(y))))return _F(a,o.line);let h=new Set(d.map(y=>y.line)),g=(c.sections??[]).filter(y=>y.type==="html"||y.type==="comment"||y.type==="math"),v=a.filter(y=>!h.has(y.line)&&!g.some(C=>C.position.start.line<=y.line&&y.line<=C.position.end.line)),b=[...d,...v].sort((y,C)=>y.line-C.line);return _F(b,o.line)}getVariableValue(e){return this.variables.get(e)??""}shouldUseSelectionForValue(){return this.includer?.shouldUseSelectionForValue()??!0}async getSelectedTextForValue(){return this.includer?await this.includer.getSelectedTextForValue():await this.getSelectedText()}assertInteractivePrompt(e){if(this.choiceExecutor?.interactive===!1)throw new ue(`This run is non-interactive but a value for ${e} was not provided up front. Pass it (e.g. a value- flag) or re-run with the ui flag.`)}describeAnonymousValuePrompt(){let e=aw(this.promptScope,this.promptScopeSoleValue),n=this.valuePromptContext?.label??e.title??(this.promptRunContext?.choiceName?.trim()||"Enter value"),i=sw(this.promptScope);return{title:n,placeholder:e.placeholder,contextLine:pp(this.promptRunContext,n,{showDestination:i}),contextLineFull:pp(this.promptRunContext,n,{elide:!1,showDestination:i})}}async promptForValue(e){if(this.value===void 0){if(this.shouldUseSelectionForValue()){let o=await this.getSelectedTextForValue();if(o){let s=this.normalizeSelectedTextForPrompt(o);if(s!==void 0)return this.value=s,this.value}}if(this.assertInteractivePrompt("{{VALUE}}"),this.valuePromptContext?.inputTypeOverride==="checkbox"){let o=this.choiceExecutor?.promptProvider;if(o)return this.value=String(await o.suggester(["true","false"],["true","false"],this.describeAnonymousValuePrompt().title,!1)),this.value;try{return this.value=await It.Suggest(this.app,["true","false"],["true","false"],this.describeAnonymousValuePrompt().title,void 0,this.valuePromptContext.optional?{skippable:!0}:void 0),this.value}catch(s){throw Be(s)?new et("Input cancelled by user"):s}}let n=this.describeAnonymousValuePrompt(),i=this.choiceExecutor?.promptProvider;if(i)return this.value=await i.inputPrompt(n.contextLine?`${n.title} (${n.contextLine})`:n.title,this.valuePromptContext?.placeholder??n.placeholder,this.valuePromptContext?.defaultValue),this.value;try{let o=this.getLinkSourcePath(),s=new cu().factory(this.valuePromptContext?.inputTypeOverride??this.defaultValueInputType),a=this.valuePromptContext?.defaultValue,l=this.buildInputPromptOptions(this.valuePromptContext,n.contextLine,n.contextLineFull),c=this.valuePromptContext?.placeholder??n.placeholder;this.value=await s.Prompt(this.app,n.title,c,a,void 0,{...l,linkSourcePath:o||void 0})}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}return this.value}normalizeSelectedTextForPrompt(e){let n=this.valuePromptContext;if(n?.inputTypeOverride==="checkbox"){let s=e.trim().toLowerCase();return s==="true"||s==="false"?s:void 0}if(n?.inputTypeOverride!=="number"&&n?.inputTypeOverride!=="slider")return e;let i=n.sliderConfig??n.numericConfig,o=vo(e,i);return o===""?void 0:o}buildInputPromptOptions(e,n,i){let o=this.contentValuePromptsAcceptImagePaste&&e?.inputTypeOverride!=="number"&&e?.inputTypeOverride!=="slider"?{sourcePath:this.getLinkSourcePath()??""}:void 0,s=this.promptRunContext?.draftScopeId;return{optional:e?.optional,numeric:e?.numericConfig,slider:e?.sliderConfig,imagePaste:o,contextLine:n,contextLineFull:i,draftScopeId:s,allowPeek:!0}}promptRuntime(){return{app:this.app,executor:this.choiceExecutor,scope:this.promptScope,runContext:this.promptRunContext,assertInteractivePrompt:e=>this.assertInteractivePrompt(e),buildInputPromptOptions:(e,n,i)=>this.buildInputPromptOptions(e,n,i)}}async promptForVariable(e,n){return Gz(this.promptRuntime(),e,n)}async promptForMathValue(){let e=this.choiceExecutor?.promptProvider;if(e)return await e.inputPrompt("Enter a math expression");this.assertInteractivePrompt("a {{MVALUE}} math expression");try{return await CT.Prompt()}catch(n){throw Be(n)?new et("Input cancelled by user"):n}}async suggestForValue(e,n=!1,i){return jz(this.promptRuntime(),e,n,i)}async suggestForValueMulti(e,n=!1,i){return Yz(this.promptRuntime(),e,n,i)}async suggestForField(e){return this.assertInteractivePrompt(`{{FIELD:${e}}}`),r2({app:this.app,executor:this.choiceExecutor,getSourcePath:()=>this.getLinkSourcePath()},e)}generateCacheKey(e){return vF(e)}async suggestForFile(e){return this.assertInteractivePrompt(`{{FILE}} (pick a file from ${e.folderPath})`),n2({app:this.app,executor:this.choiceExecutor,getSourcePath:()=>this.getLinkSourcePath()},e)}async getMacroValue(e,n){let{SingleMacroEngine:i}=await Promise.resolve().then(()=>(g2(),h2)),o=new i(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),s=await o.runAndGetOutput(e,n,this.choiceChain)??"";return o.getVariables().forEach((a,l)=>{this.variables.set(l,a)}),s}async getTemplateContent(e){let{SingleTemplateEngine:n}=await Promise.resolve().then(()=>(HF(),B2));this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0});let i={visited:this.templateInclusion.visited,depth:this.templateInclusion.depth+1,includer:this},o=new n(this.app,this.plugin,e,this.choiceExecutor,i);o.setTargetFolderPath(this.targetFolderPath),o.choiceChain=this.choiceChain,this.preserveTemplateCursorMarkers&&this.promptScope==="noteBody"&&o.setPreserveCursorMarkers(!0),this.promptScope!=="generic"&&o.setPromptScope(this.promptScope),this.promptRunContext&&o.setPromptRunContext({...this.promptRunContext,draftScopeId:`${this.promptRunContext.draftScopeId??""}#${e}`});let s=await o.run();return this.mergeTemplatePropertyVars(o.getAndClearTemplatePropertyVars()),s}async getSelectedText(){let e=mn(this.app);return e?e.editor.getSelection():""}async getClipboardContent(){if(this.includer)return this.includer.getClipboardContent();try{return await navigator.clipboard.readText()}catch{return""}}isTemplatePropertyTypesEnabled(){return this.plugin.settings.enableTemplatePropertyTypes}async replaceInlineJavascriptInString(e){let n=e,i=sg(n);for(;i;){let{start:o,end:s,code:a}=i,l="";if(a){let{SingleInlineScriptEngine:c}=await Promise.resolve().then(()=>(q2(),U2)),d=new c(this.app,this.plugin,this.choiceExecutor,this.variables,this.choiceChain),u=await d.runAndGetOutput(a);for(let p in d.params.variables)this.variables.set(p,d.params.variables[p]);typeof u=="string"?l=u:(typeof u=="number"||typeof u=="boolean"||Array.isArray(u))&&(l=this.renderCollectedOrArrayValue({input:n,matchStart:o,matchEnd:s,rawValue:u,fallbackKey:"inlineScript",heuristicEnabled:this.isTemplatePropertyTypesEnabled()})??String(u))}n=n.slice(0,o)+l+n.slice(s),i=sg(n,S0(n,o))}return n}async collectValuesManually(e,n){return await bF(this.app,e,n)}}});async function H2(r,t,e,n,i,o){if(U.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let s=U.getState().ai,a;if(i.model==="Ask me")a=await o();else if(a=tu($l(i.model,i.modelRef)??i.model),!a)throw new Error(`Model ${i.model} not found with any provider.`);let{model:l,provider:c}=a,d=new _i(r,zr(),e);d.setPromptRunContext({choiceName:t?.name,draftScopeId:`${t?.id??"macro"}#aiAssistant:${i.id}`}),d.choiceChain=n;let u=await So(r,c),p=await Oz(r,{apiKey:u,model:l,provider:c,outputVariableName:i.outputVariableName,promptTemplate:i.promptTemplate,promptTemplateFolder:s.promptTemplatesFolderPath,systemPrompt:i.systemPrompt,showAssistantMessages:s.showAssistant,modelOptions:i.modelParameters,interactive:e.interactive,promptProvider:e.promptProvider},async m=>d.formatFileContent(m));for(let m in p)e.variables.set(m,p[m])}async function W2(r,t){let n=U.getState().ai.providers.flatMap(o=>np(o.models).map(s=>({label:`${s.name} (${o.name}${s.deprecated?", retired":""})`,qualified:`${o.id??o.name}/${s.name}`,resolved:{provider:o,model:s}})));if(n.length===0)throw new Error("No AI models are configured. Add a provider with models in the AI Assistant settings.");let i=t.promptProvider;if(i){let o=String(await i.suggester(n.map(a=>a.label),n.map(a=>a.qualified),"Select a model")),s=n.find(a=>a.qualified===o);if(!s)throw new Error(`Model ${o} not found with any provider.`);return s.resolved}if(t.interactive===!1)throw new ue('This AI command is set to "Ask me" for the model, but this run is non-interactive. Pick a specific model in the command, or re-run with the ui flag.');try{return await It.Suggest(r,n.map(o=>o.label),n.map(o=>o.resolved),"Select a model")}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}var G2=x(()=>{oF();kc();je();xu();rs();Dm();fi();nt();kn();rr();Gi()});function Vc(r,t){try{return r.getChoiceById(t)}catch{return null}}var OT=x(()=>{});function LT(r,t){j2.has(r)||(j2.add(r),S.logWarning(t))}function pre(r,t){return r.type==="NestedChoice"?r.choice??null:r.type==="Choice"?t(r.choiceId):null}function Y2(r,t,e){if(!r||t.type!=="Obsidian"||t.commandId!==ure)return null;let n=pre(r,e);return n&&(n.type==="Template"||n.type==="Capture")?n.name:null}var ure,j2,GF=x(()=>{ye();Zt();ure="templater-obsidian:replace-in-file-templater",j2=new Set});function J2(r){return Ay.some(t=>t.id===r)}function K2(r){let t=(0,NT.getFrontMatterInfo)(r);return t.exists?{frontmatterYaml:t.frontmatter,body:r.slice(t.contentStart)}:{frontmatterYaml:null,body:r}}function hre(r,t,e){if(e==="bottom"){let n=r.replace(mre,""),i=n.trim()?`${n}
- `:"",o=i+t;return{content:o,insertedStartOffset:i.length,insertedEndOffset:o.length}}return fu(r,`${t}
- `)}function gre(r){return r==null||r===""||Array.isArray(r)&&r.length===0}function Q2(r){return typeof r=="string"?r.length>0?[r]:[]:!Array.isArray(r)||!r.every(t=>typeof t=="string")?null:r}function X2(r,t){let e=Q2(r),n=Q2(t);if(e===null||n===null)return;let i=[],o=new Set(e);for(let s of n)s.length===0||o.has(s)||(o.add(s),i.push(s));if(i.length!==0)return[...e,...i]}var NT,Ay,mre,fre,Cf,VT=x(()=>{NT=require("obsidian");ye();hu();Lc();MT();Rd();Uh();gp();tn();Rc();Ds();PF();DT();Qo();fp();mf();Ay=[{id:"cursor",label:"Insert at cursor",description:"Inserts the template at the cursor position in the editor."},{id:"top",label:"Insert at top",description:"Inserts the template below the note's frontmatter, or at the very top."},{id:"bottom",label:"Append to bottom",description:"Adds the template content to the end of the note."},{id:"replace",label:"Replace note content",description:"Replaces the entire note content with the template."}];mre=/(?:\r?\n[^\S\r\n]*)+$/,fre=/^(?:[^\S\r\n]*\r?\n)+/;Cf=class extends Nc{constructor(e,n,i,o,s,a,l){super(e,n,a);this.targetFile=i;this.templatePath=o;this.mode=s;this.cursorView=null;this.resolvedTemplatePath=l??null}placeCursor(e){this.mode==="cursor"&&Js(this.app,e)!==this.cursorView||super.placeCursor(e)}async run(){await this.apply()}async getResolvedTemplatePath(){return this.resolvedTemplatePath===null&&(this.resolvedTemplatePath=await this.resolveTemplateSourcePath(this.templatePath)),this.resolvedTemplatePath}async apply(){switch(this.cursorPlacement=null,Lr(this.templatePath,"Cannot apply template: no template path given."),this.mode){case"replace":return await this.overwriteFileWithTemplate(this.targetFile,await this.getResolvedTemplatePath());case"top":case"bottom":return await this.insertTemplateIntoFile(this.mode);case"cursor":return await this.insertTemplateAtCursor()}}async computeChoiceTargetPath(e){let n=e.folder,i;if(this.formatter.setTargetFolderPath(null),n?.enabled){if(n.chooseWhenCreatingNote)return null;if(n.createInSameFolderAsActiveFile)i=this.targetFile.parent?.path??"";else{if(n.chooseFromSubfolders)return null;if(n.folders.length===1)i=await this.formatter.formatFolderPath(n.folders[0]);else return null}}else i=this.targetFile.parent?.path??"";i==="/"&&(i="");let o=this.targetFile.basename,s=!1;if(e.fileNameFormat?.enabled&&e.fileNameFormat.format){this.formatter.setTargetFolderPath(i);let a=await this.formatter.formatFileName(e.fileNameFormat.format,"generic"),l=Nr(a,"File name"),c=this.stripDuplicateFolderPrefix(l,i);o=c.fileName,s=this.shouldTreatFormattedNameAsVaultRelativePath(l,c.strippedPrefix,n?.enabled??!1)}return o.slice(o.lastIndexOf("/")+1).trim()?this.normalizeTemplateFilePath(s?"":i,o,await this.getResolvedTemplatePath()):null}async insertTemplateIntoFile(e){let{formatted:n,templatePropertyVars:i}=await this.formatTemplateForTargetFile(),o=K2(n),{frontmatterYaml:s}=o,a=e==="bottom"?o.body.replace(fre,""):o.body,l=this.cursorPlacement;return(a.trim().length>0||l)&&await Co(this.app,this.targetFile,c=>{let d=hre(c,a,e);if(l&&d.insertedStartOffset!==null){let u=d.insertedStartOffset,p=u-(n.length-a.length);this.cursorPlacement={content:d.content,offsets:l.offsets.map(m=>Math.max(u,p+m))}}return d.content}),await this.mergeFrontmatterProperties(s,i),await this.rebaseCursorAfterFileChanges(this.targetFile),this.targetFile}async insertTemplateAtCursor(){let e=Js(this.app,this.targetFile);Lr(e,"Cannot insert at cursor: the note is not open in the active editor."),this.cursorView=e;let n=e.editor,{formatted:i,templatePropertyVars:o}=await this.formatTemplateForTargetFile();Lr(e.file===this.targetFile&&e.editor===n&&this.app.workspace.getLeavesOfType("markdown").some(c=>c.view===e),"Cannot insert at cursor: the original editor was closed or changed notes.");let{frontmatterYaml:s,body:a}=K2(i),l=this.cursorPlacement?.offsets[0];return l!==void 0?this.cursorPlacement=$F({content:a,cursor:{kind:"offset",value:l-(i.length-a.length),source:"marker"}},n,"currentLine"):a.trim().length>0&&n.replaceSelection(a),this.cursorPlacement&&s&&await e.save(),await this.mergeFrontmatterProperties(s,o),s&&await this.rebaseCursorAfterFileChanges(this.targetFile),this.targetFile}async formatTemplateForTargetFile(){let e=await this.getTemplateContent(await this.getResolvedTemplatePath());this.formatter.setTitle(this.targetFile.basename),this.formatter.setTargetFolderPath(Zn(this.targetFile.path));let n=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",e,()=>this.formatter.withUserTextProtected(()=>this.targetFile.extension==="md"?this.formatter.formatTemplateContent(e):this.formatter.formatFileContent(e)))),i=this.formatter.getAndClearTemplatePropertyVars();this.targetFile.extension==="md"&&(n=await Oc(this.app,n,this.targetFile));let o=_T(n),s=py(o.content,o.offsets);return this.cursorPlacement=this.targetFile.extension==="md"&&s.offsets.length>0?s:null,{formatted:s.content,templatePropertyVars:i}}async mergeFrontmatterProperties(e,n){if(!e||this.targetFile.extension!=="md")return;let i;try{i=(0,NT.parseYaml)(e)}catch(o){S.logWarning(`Could not parse template frontmatter for merging: ${o}`);return}if(!(!i||typeof i!="object"||Array.isArray(i))){if(n&&n.size>0)for(let[o,s]of n){let a=o.includes(Ni.PATH_SEPARATOR)?o.split(Ni.PATH_SEPARATOR):[o];ky(i,a,hp(s))}await Yl(this.app,this.targetFile,o=>{for(let[s,a]of Object.entries(i)){if(qF([s])){S.logWarning(`Skipping front matter merge for unsafe key "${s}" to avoid prototype pollution.`);continue}let l=Object.hasOwn(o,s)?o[s]:void 0,c=JO(this.app,s);if(gre(l)){c&&Array.isArray(a)?o[s]=X2([],a)??[]:o[s]=a;continue}if(c){let d=X2(l,a);d!==void 0&&(o[s]=d)}}})}}}});function vre(r){return r.trim().length===0}function Bc(r){return r=xn(r),!lr.test(r)&&!Mn.test(r)}function yre(r){return r.kind==="choice"?`Choice: ${r.choice.name}`:`Template: ${r.path}`}function bre(r){return xn(r).toLowerCase()}function wre(r){return r.toLowerCase()}function Cre(r,t){let e=Jt(r).filter(o=>o.type==="Template"&&!!o.templatePath&&Bc(o.templatePath)),n=new Set(e.map(o=>bre(o.templatePath))),i=e.map(o=>({kind:"choice",choice:o}));for(let o of t)Bc(o)&&(n.has(wre(o))||i.push({kind:"file",path:o}));return i}async function Iy(r,t,e){let n=e.file??r.workspace.getActiveFile();if(!n||n.extension!=="md")return new xf.Notice("QuickAdd: No active markdown note to apply a template to."),null;let i=e.choiceExecutor.triggerContext;i==null&&(e.choiceExecutor.triggerContext={activeFile:n});try{let o=!e.templatePath,s;if(e.templatePath)s={kind:"file",path:e.templatePath};else{let h=await xre(r,t);if(!h)return null;s=h}let a=s.kind==="choice"?s.choice.templatePath:s.path;if(!Bc(a))return new xf.Notice("QuickAdd: Only markdown templates can be applied to a note. Canvas and base templates create their own file types."),null;let l=await Od(r,n),c=vre(l),d;if(e.mode)d=e.mode;else if(c)d="replace";else if(!o)d="bottom";else{let h=await Ere(r,n);if(!h)return null;d=h}e.choiceExecutor.variables.has("value")||e.choiceExecutor.variables.set("value",n.basename);let u=new Cf(r,t,n,a,d,e.choiceExecutor);e.chain&&(u.choiceChain=e.chain),u.setPromptRunContext({choiceName:s.kind==="choice"?s.choice.name:void 0,draftScopeId:s.kind==="choice"?s.choice.id:`template-insert#${a}`,destination:n.path,destinationKind:"file"});let p=await u.getResolvedTemplatePath();return Bc(p)?await u.apply()?(o&&s.kind==="choice"&&(u.setPromptRunContext({destination:void 0,destinationKind:void 0}),await Tre(r,u,s.choice,n)),!u.hasTemplaterHandledCursor()&&!await bu(r,n)&&u.placeCursor(n),new xf.Notice(`Applied template to '${n.basename}'.`),n):null:(new xf.Notice("QuickAdd: Only markdown templates can be applied to a note. Canvas and base templates create their own file types."),null)}catch(o){return Be(o)||Z2(o)||Me(o,"Error applying template to note"),null}finally{e.choiceExecutor.triggerContext=i}}function Z2(r){return!!r&&typeof r=="object"&&r.name==="MacroAbortError"}async function xre(r,t){let e=Cre(t.settings.choices,t.getTemplateFiles().map(n=>n.path));if(e.length===0)return new xf.Notice("QuickAdd: No Template choices or template files found. Create a Template choice or set the template folder path in settings."),null;try{return await It.Suggest(r,e.map(yre),e,"Apply template to note")}catch(n){if(Be(n))return null;throw n}}async function Ere(r,t){let e=!!Js(r,t),n=Ay.filter(i=>i.id!=="cursor"||e);try{return await It.Suggest(r,n.map(i=>i.label),n.map(i=>i.id),"How should the template be applied?")}catch(i){if(Be(i))return null;throw i}}async function Tre(r,t,e,n){try{let i=await t.computeChoiceTargetPath(e);if(!i||i===n.path||await r.vault.adapter.exists(i)||!N2(i)||!await wi(r,{title:"Move note to match choice settings?",message:`'${e.name}' creates notes at '${i}'. Move '${n.path}' there? Links to the note will be updated.`,action:"Move",destructive:!1}))return;let s=i.lastIndexOf("/"),a=s===-1?"":i.slice(0,s);a&&!await r.vault.adapter.exists(a)&&await r.vault.createFolder(a),await r.fileManager.renameFile(n,i)}catch(i){if(Be(i)||Z2(i))return;S.logWarning(`Could not move note to match choice settings: ${i}`)}}var xf,BT=x(()=>{tr();xf=require("obsidian");Ve();Gi();Ka();ye();hu();Lc();lt();RT();nt();Ds();VT()});function _re(r,t,e){return window.moment(r).add(t,e).startOf("day").toDate()}function Py(r){if(r instanceof Date&&!Number.isNaN(r.getTime()))return r;if(typeof r!="string")return;let t=r.trim();if(!t)return;if(t.toLowerCase().startsWith("@date:")){let n=t.slice(6),i=window.moment(n);return i.isValid()?i.toDate():void 0}let e=$c(t,void 0,To);if(e.isValid&&e.isoString){let n=window.moment(e.isoString);return n.isValid()?n.toDate():void 0}}function UT(r){if(r.clocks?.date)return{status:"inherit"};if(r.reservedSeed!==void 0){let o=Py(r.reservedSeed);return o?{status:"set",date:o}:{status:"error",message:"Could not parse the seeded date origin."}}let t=r.setting;if(!t||t.kind==="now")return{status:"inherit"};if(t.kind==="ask")return{status:"ask",defaultValue:t.defaultValue};if(t.kind==="relative"){let o=r.clocks?.now??new Date;return{status:"set",date:_re(o,t.offset,t.unit)}}let e=r.variables;if(!e)return{status:"error",message:`Date origin variable "${t.name}" is not available.`};let n=Ul(e,t.name);if(!n)return{status:"error",message:`Date origin variable "${t.name}" is not set.`};let i=Py(e.get(n));return i?{status:"set",date:i}:{status:"error",message:`Date origin variable "${t.name}" is not a date.`}}function Ef(r,t){if(t==null||typeof t=="string"&&!t.trim())return!0;if(y1(t))return r.pickDate=!0,!0;let e=Py(t);return e?(r.clocks={now:r.clocks?.now??new Date,date:e},!0):!1}var Tf=x(()=>{Hd();lc();uu();yo()});var $y,Fy,eH=x(()=>{$y=require("obsidian");Ka();Fy=class r extends $y.Modal{constructor(e,n,i){super(e);this.header=n;this.text=i;this.input=null;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Ask(e,n,i){return new r(e,n,i).waitForClose}display(){this.containerEl.addClass("quickAddModal","qaYesNoPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.header,this.contentEl.createEl("p",{text:this.text});let e=this.contentEl.createDiv({cls:"yesNoPromptButtonContainer"}),n=new $y.ButtonComponent(e).setButtonText("No").onClick(()=>this.submit(!1));UC(n.buttonEl);let i=new $y.ButtonComponent(e).setButtonText("Yes").onClick(()=>this.submit(!0)).setDestructive();UC(i.buttonEl),i.buttonEl.focus(),qC([n.buttonEl,i.buttonEl])}submit(e){this.input=e,this.close()}onClose(){super.onClose(),this.resolvePromise(this.input)}}});var qT,My,tH=x(()=>{qT=require("obsidian"),My=class r extends qT.Modal{constructor(e,n,i){super(e);this.header=n;this.text=i;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Show(e,n,i){return new r(e,n,i).waitForClose}display(){this.contentEl.empty(),this.titleEl.textContent=this.header,String.isString(this.text)?this.contentEl.createEl("p",{text:this.text}):Array.isArray(this.text)&&this.text.forEach(i=>this.contentEl.createEl("p",{text:i}));let e=this.contentEl.createDiv(),n=new qT.ButtonComponent(e).setButtonText("OK").onClick(()=>this.close());Object.assign(e.style,{display:"flex",justifyContent:"flex-end"}),n.buttonEl.focus()}onClose(){super.onClose(),this.resolvePromise()}}});var Ry,_f,rH=x(()=>{Ry=require("obsidian");rr();dF();_f=class r extends Ry.Modal{constructor(e,n,i=[],o){super(e);this.items=n;this.selectedItems=i;this.header=o;this._selectedItems=[...i],this.promise=new Promise((s,a)=>{this.resolvePromise=s,this.rejectPromise=a}),this.display(),this.open(),this.picker.focusSearchOnOpen()}static Open(e,n,i,o){return new r(e,n,i,o).promise}onEscapeKey(e){if(this.picker.clearSearch()){e.preventDefault();return}super.onEscapeKey(e)}display(){this.contentEl.empty(),this.containerEl.addClass("quickAddModal","qaSearchableMultiSelectModal","checkboxPrompt"),this.header&&(this.titleEl.textContent=this.header),this.addSearchableOptions(),this.addSubmitButton()}onClose(){super.onClose(),this.resolved||this.rejectPromise(rn())}addSearchableOptions(){this.picker=new du(this.contentEl,{items:this.items.map(e=>({key:e,value:e,label:e})),isSelected:({value:e})=>this._selectedItems.includes(e),onToggle:({value:e},n)=>{if(n){this._selectedItems.includes(e)||this._selectedItems.push(e);return}this._selectedItems=this._selectedItems.filter(i=>i!==e)},getSelectedCount:()=>new Set(this._selectedItems).size})}addSubmitButton(){let e=this.contentEl.createDiv("submitButtonContainer");new Ry.ButtonComponent(e).setButtonText("Cancel").onClick(()=>{this.close()}),new Ry.ButtonComponent(e).setButtonText("Submit").setCta().onClick(()=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}}});function ea(r){throw r instanceof at?r:Be(r)?new et(Dl):r}var ta,jF=x(()=>{zs();sF();eH();tH();Gi();rH();nl();hT();on();ti();rr();nt();uu();ta=class{static async inputPrompt(t,e,n,i,o){try{return await ir.Prompt(t,e,n,i,void 0,{allowPeek:!0,...o})}catch(s){ea(s)}}static async datePrompt(t,e,n){try{let i=await ll.Prompt(t,e,n?.placeholder,n?.defaultValue,n?.dateFormat);if(i&&i.startsWith("@date:")){let o=i.slice(6);return(n?.dateFormat?Po(o,n.dateFormat):null)??o}return i}catch(i){ea(i)}}static async wideInputPrompt(t,e,n,i,o){try{return await Sc.Prompt(t,e,n,i,void 0,{allowPeek:!0,...o})}catch(s){ea(s)}}static async yesNoPrompt(t,e,n){let i;try{i=await Fy.Ask(t,e,n)}catch(o){ea(o)}if(i===null)throw new et(Dl);return i}static async infoDialog(t,e,n){try{return await My.Show(t,e,n)}catch(i){ea(i)}}static async suggester(t,e,n,i,o=!1,s){try{let a;return typeof e=="function"?a=n.map((l,c,d)=>nn(e(l,c,d))):a=e.map(l=>nn(l)),o?await gr.Suggest(t,a,n,{...i?{placeholder:i}:{},...s?.renderItem?{renderItem:s.renderItem}:{}}):await It.Suggest(t,a,n,i,s?.renderItem)}catch(a){ea(a)}}static async checkboxPrompt(t,e,n,i){try{return await(i===void 0?_f.Open(t,e,n):_f.Open(t,e,n,i))}catch(o){ea(o)}}}});var kre,zT,nH=x(()=>{Fa();yT();dp();Ps();on();kre=200,zT=class extends Er{constructor(e,n,i){super(e,n);this.matchesByItem=new Map;this.lookupSequence=0;this.dropValues=()=>{this.values=void 0};this.fieldInput=i;let o=On.parse(i);this.fieldName=o.fieldName,this.filters=o.filters,n.addEventListener("blur",this.dropValues)}destroy(){this.inputEl.removeEventListener("blur",this.dropValues),super.destroy()}async getSuggestions(e){let n=++this.lookupSequence;this.values??(this.values=Zz(this.app,this.fieldName,this.filters));let i=await this.values;if(n!==this.lookupSequence)return[];let o=Ll(e,i,s=>s,{limit:kre});return this.matchesByItem=new Map(o.map(({item:s,matches:a})=>[s,a])),o.map(({item:s})=>s)}renderSuggestion(e,n){Is(n,e,this.matchesByItem.get(e)??[])}selectSuggestion(e){this.inputEl.value=e,Sa(this.inputEl),this.close()}}});var YF,iH,HT,oH=x(()=>{YF=require("obsidian");dp();Ps();on();Ln();iH=200,HT=class extends Er{constructor(e,n,i,o,s,a,l,c){super(e,n);this.getOptions=i;this.isSelected=o;this.onSelect=s;this.multiSelect=a;this.allowCustomInput=l;this.newNoteExists=c;this.matchesByOption=new Map;this.aliasByOption=new Map;this.namesByOption=new WeakMap;a&&n.setAttribute("aria-multiselectable","true")}getSuggestions(e){let n=e.trim(),i=this.getOptions().filter(d=>!this.isSelected(d.value)),o=Ll(n,i,d=>`${d.label} ${d.path}`,{limit:iH,aliases:d=>d.aliases});this.matchesByOption=new Map(o.map(({item:d,matches:u})=>[d,u])),this.aliasByOption=new Map(o.flatMap(({item:d,alias:u})=>u!==void 0?[[d,u]]:[]));let s=o.map(({item:d})=>d);if(!n||!this.allowCustomInput)return s;let a=n.toLocaleLowerCase(),l=this.getOptions().some(d=>this.namesOf(d).includes(a)),c=this.isSelected(n);return l||c||this.newNoteExists?.(n)?s:[this.newNoteExists?{value:n,label:`Create new note: ${n}`,path:"",isCustom:!0}:{value:n,label:`Use \u201C${n}\u201D`,path:"Custom value",isCustom:!0},...s].slice(0,iH)}namesOf(e){let n=this.namesByOption.get(e);return n||(n=[e.label,e.path,...e.isCustom?[]:[Ep(e.path)],...e.aliases??[]].map(i=>i.toLocaleLowerCase()),this.namesByOption.set(e,n)),n}renderSuggestion(e,n){n.addClass("qa-onepage-file-suggestion");let i=n.createDiv({cls:"qa-onepage-file-suggestion__text"}),o=i.createDiv({cls:"qa-onepage-file-suggestion__label"});if(e.isCustom&&this.newNoteExists){o.setText(`Create new note: ${e.value}`),n.addClass("mod-complex"),i.addClass("suggestion-content"),(0,YF.setIcon)(n.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"}),"file-plus");return}let s=i.createDiv({cls:"qa-onepage-file-suggestion__path"});if(e.isCustom){o.setText(e.label),s.setText(e.path);return}let a=this.matchesByOption.get(e)??[],l=this.aliasByOption.get(e);if(l!==void 0){Is(o,l,a),s.setText(e.label),n.addClass("mod-complex"),i.addClass("suggestion-content");let c=n.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"});c.setAttribute("aria-label","Alias"),(0,YF.setIcon)(c,"forward");return}Is(o,e.label,a),Is(s,e.path,a,e.label.length+1)}selectSuggestion(e){if(this.onSelect(e),this.inputEl.value="",!this.multiSelect){this.close();return}Sa(this.inputEl,!0),this.inputEl.focus()}}});var Sre,WT,sH=x(()=>{dp();Ps();on();Sre=200,WT=class extends Er{constructor(e,n,i,o=!1,s=!1,a){super(e,n);this.matchesByItem=new Map;this.options=i.map(l=>nn(l)),this.caseSensitive=o,this.multiSelect=s,this.onSelect=a,this.multiSelect&&this.inputEl.setAttribute("aria-multiselectable","true")}parseMultiSelectInput(e){if(!this.multiSelect)return{alreadySelected:[],activeTerm:e};let n=e.split(",").map(i=>i.trim());return{alreadySelected:n.slice(0,-1).filter(Boolean),activeTerm:n[n.length-1]||""}}getRemainingOptions(e){return this.options.filter(n=>!e.includes(n))}getSuggestions(e){let n=Ol(e),{alreadySelected:i,activeTerm:o}=this.parseMultiSelectInput(n),s=this.getRemainingOptions(i),a=Ll(o,s,l=>l,{limit:Sre,caseSensitive:this.caseSensitive});return this.matchesByItem=new Map(a.map(({item:l,matches:c})=>[l,c])),a.map(({item:l})=>l)}renderSuggestion(e,n){Is(n,e,this.matchesByItem.get(e)??[])}selectSuggestion(e){this.multiSelect?this.selectMultipleItem(e):this.selectSingleItem(e)}selectSingleItem(e){this.inputEl.value=e,Sa(this.inputEl),this.close()}selectMultipleItem(e){let{alreadySelected:n}=this.parseMultiSelectInput(this.inputEl.value);n.push(e),this.onSelect?.(e);let i=this.getRemainingOptions(n).length>0;this.inputEl.value=i?n.join(", ")+", ":n.join(", "),this.inputEl.setSelectionRange(this.inputEl.value.length,this.inputEl.value.length),Sa(this.inputEl,i),i?this.inputEl.focus():this.close()}}});function aH(r,t,e){return e?t.get(r)??r:r}function lH(r,t){return t.length===0?r:r===""?t[0]??"":t.includes(r)?r:t[0]??""}var cH=x(()=>{});function dH(r){return`qa-onepage-label-${encodeURIComponent(r.id)}`}var si,GT,uH=x(()=>{si=require("obsidian");Ve();fF();nH();oH();sH();uu();gd();je();yo();Ln();Qo();cH();GT=class{constructor(t,e,n){this.app=t;this.contentEl=e;this.host=n}setting(t,e=!0){let n=new si.Setting(this.contentEl).setName(this.host.decorateLabel(t));return n.nameEl.id=dH(t),e&&t.description&&n.setDesc(t.description),this.fieldSetting=n,n}labelControls(t){this.fieldSetting?.controlEl.querySelectorAll("input:not([aria-label]), textarea:not([aria-label]), select:not([aria-label])").forEach(e=>e.setAttribute("aria-labelledby",dH(t))),this.fieldSetting=void 0}render(t){let e=this.host.controlFor(t),n=(o,s)=>{e.value=s,this.host.publish(e),this.host.updatePreview()},i=this.host.initialValue(t.id)??t.defaultValue??"";switch(e.value=i,t.type){case"textarea":case"text":{let o=this.setting(t),s=t.type==="textarea"?new si.TextAreaComponent(o.controlEl):new si.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(a=>n(t.id,a)),t.type==="textarea"&&s.inputEl.addClass("qa-onepage-textarea"),this.host.attachFreeText(t,s.inputEl);break}case"number":{let o=this.setting(t),s=new si.TextComponent(o.controlEl);s.inputEl.type="number",s.inputEl.inputMode="decimal",t.numericConfig?.min!==void 0&&(s.inputEl.min=String(t.numericConfig.min)),t.numericConfig?.max!==void 0&&(s.inputEl.max=String(t.numericConfig.max)),s.inputEl.step=t.numericConfig?.step!==void 0?String(t.numericConfig.step):"any";let a=t.numericConfig?vo(i,t.numericConfig):i;s.setPlaceholder(t.placeholder??"").setValue(a).onChange(l=>n(t.id,t.numericConfig?vo(l,t.numericConfig):l)),n(t.id,a);break}case"slider":{let o=this.setting(t);o.controlEl.parentElement?.addClass("qa-onepage-slider-setting");let s=t.sliderConfig??{min:0,max:100,step:1},a=t.optional&&i==="",l=bp(i,s),c=o.controlEl.createDiv({cls:"qa-onepage-slider"}),d=c.createEl("input");d.type="range",d.min=String(s.min),d.max=String(s.max),d.step=String(s.step),d.value=l;let u=new si.TextComponent(c);u.inputEl.type="number",u.inputEl.inputMode="decimal",u.inputEl.min=String(s.min),u.inputEl.max=String(s.max),u.inputEl.step=String(s.step),u.setValue(a?"":l),n(t.id,a?"":l),d.addEventListener("input",()=>{u.inputEl.value=d.value,n(t.id,d.value)}),u.onChange(p=>{if(p===""&&t.optional){n(t.id,"");return}let m=vo(p,s);m!==""&&(d.value=m,u.inputEl.value=m,n(t.id,m))});break}case"dropdown":{let o=this.setting(t),s=new si.DropdownComponent(o.controlEl),a=t.options??[],l=t.displayOptions??a;if(a.length>0){t.optional&&s.addOption("","Skip (leave empty)"),a.forEach((d,u)=>{let p=l[u]??d;s.addOption(d,p)});let c=lH(i,a);s.setValue(c),n(t.id,c),s.onChange(d=>n(t.id,d))}else s.setDisabled(!0),o.controlEl.createDiv({text:t.placeholder||"No options available"}).addClass("qa-onepage-dropdown-note");break}case"date":{let o=this.setting(t);o.settingEl.addClass("qa-onepage-date-setting");let s=o.controlEl.createDiv({cls:"qa-date-input"}),a=s.createDiv({cls:"qa-date-field"}),l=new si.TextComponent(a),c="Enter a date (e.g., 'today', 'next friday', '2025-12-25')",d,u=i;i?.startsWith("@date:")&&(d=i.slice(6),u=(t.dateFormat?Po(d,t.dateFormat):void 0)??(d.length>=10?d.slice(0,10):d)),l.setPlaceholder(c).setValue(u??"");let p=s.createDiv();p.addClass("qa-date-preview-text");let m=s.createDiv({cls:"qa-date-picker-container"}),h=mT({container:m,initialIso:d,withTime:t.withTime===!0,onSelect:_=>{_?C(_):w()}});e.dispose.push(()=>h.destroy()),e.dispose.push(fT(a,m));let g=_h(U.getState().dateAliases);if(g.length>0){let _=s.createEl("details");_.addClass("qa-date-alias-details"),_.createEl("summary",{text:`Aliases (${g.length})`}).addClass("qa-date-alias-summary");let O=_.createDiv();O.textContent=Wb(U.getState().dateAliases),O.addClass("qa-date-alias-list")}let v=_=>{if(t.dateFormat){let I=Po(_,t.dateFormat);if(I)return I}return _.length>=10?_.slice(0,10):_},b=(_,I)=>{p.setText(_),p.toggleClass("is-error",I)},y=_=>{h.setSelectedIso(_)},C=_=>{e.dateParseError=!1;let I=v(_);l.inputEl.value=I,n(t.id,`@date:${_}`),b(I,!1),y(_)},w=()=>{l.inputEl.value="",P("")},T=_=>{let I=$c(_,t.dateFormat),O=I.isValid?I.isoString:void 0;e.dateParseError=!O,n(t.id,O?`@date:${O}`:""),y(O),b(O?I.formatted??v(O):I.error||"Unable to parse date",!O)},P=_=>{let I=(_??"").trim();if(!I&&t.defaultValue&&!t.optional){T(t.defaultValue);return}if(!I){e.dateParseError=!1,n(t.id,""),y(),b(t.optional?"Will be left empty":"Preview will appear here",!1);return}if(I.startsWith("@date:")){let O=I.slice(6).trim();if(O){C(O);return}}T(I)};l.onChange(_=>P(_)),d?C(d):P(u??"");break}case"field-suggest":{let o=this.setting(t),s=new si.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(l=>n(t.id,l));let a=t.id.startsWith(Ml)?t.id.slice(Ml.length):t.id;try{e.suggesters.push(new zT(this.app,s.inputEl,a))}catch{}break}case"suggester":{let o=this.setting(t),s=t.options??[],a=t.displayOptions??s,l=new Map,c=new Map;s.forEach((p,m)=>{let h=a[m]??p;l.set(h,p),c.has(p)||c.set(p,h)});let d=c.get(i)??i,u=new si.TextComponent(o.controlEl);if(u.setPlaceholder(t.placeholder??"Type to search...").setValue(d).onChange(p=>n(t.id,p)),u.inputEl.addEventListener("input",p=>{let m=!!p.fromCompletion,h=u.inputEl.value,g=aH(h,l,m);(g!==h||m)&&n(t.id,g)}),a.length>0)try{let p=t.suggesterConfig?.caseSensitive??!1,m=t.suggesterConfig?.multiSelect??!1;e.suggesters.push(new WT(this.app,u.inputEl,a,p,m,m?h=>{let g=e.multiSelections??[];g.push(h),e.multiSelections=g,this.host.publish(e)}:void 0))}catch{}break}case"file-picker":{this.renderFilePickerField(t,i,n);break}default:{let o=this.setting(t,!1),s=new si.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(a=>n(t.id,a)),this.host.attachFreeText(t,s.inputEl)}}this.labelControls(t),this.host.publish(e)}noteNameExists(t,e){let n=t==="vault"?this.app.vault.getMarkdownFiles().map(o=>o.path):e,i=new Set(n.map(o=>Ep(o).toLowerCase()));return o=>{let s;try{s=Nr(o,"Capture target file path")}catch{return!1}let a=s.replace(/\.(md|canvas)$/i,"");return i.has(a.slice(a.lastIndexOf("/")+1).toLowerCase())?!0:t==="vault"&&[s,`${a}.md`,`${a}.canvas`].some(l=>!!this.app.vault.getAbstractFileByPath(l))}}renderFilePickerField(t,e,n){let i=this.setting(t);i.settingEl.addClass("qa-onepage-file-picker-setting");let o=t.options??[],s=t.displayOptions??o,a=o.map((w,T)=>{let P=$d(w);return{value:w,label:s[T]??w,path:P.kind==="file"?P.path:w,aliases:t.optionAliases?.[T]}}),l=new Map(a.map(w=>[w.value,w])),c=t.suggesterConfig?.multiSelect??!1,d=t.suggesterConfig?.allowCustomInput??!1,u=new Set,p=new Map,m=w=>{let T=p.get(w);if(T)return T;let P={value:w,label:w,path:t.newNoteName?"New note":"Custom value",isCustom:!0};return p.set(w,P),P};if(e&&l.has(e))u.add(e);else if(e&&d){let w=$d(e),T=w.kind==="custom"?w.text:e;m(T),u.add(T)}let h=i.controlEl.createDiv({cls:"qa-onepage-file-picker"}),g=h.createDiv({cls:"qa-onepage-file-picker__selection"});g.setAttribute("aria-live","polite");let v=new si.TextComponent(h);v.inputEl.addClass("qa-onepage-file-picker__input"),v.setPlaceholder(t.placeholder??(c?"Search and add files...":"Search files...")),v.inputEl.setAttribute("aria-label",c?`Add files for ${t.label}`:`Choose file for ${t.label}`);let b=()=>{let w=a.filter(T=>u.has(T.value));for(let T of p.values())u.has(T.value)&&w.push(T);return w},y=()=>{let w=b(),T=w.map(P=>P.value);this.host.controlFor(t).fileSelections=T,n(t.id,c?T.join(", "):T[0]??""),g.empty(),g.toggleClass("qa-hidden",w.length===0);for(let P of w){let _=g.createDiv({cls:"qa-onepage-file-picker__chip"});_.setAttribute("title",P.path),_.createSpan({cls:"qa-onepage-file-picker__chip-label",text:P.label});let I=_.createEl("button",{cls:"qa-onepage-file-picker__remove",text:"\xD7"});I.type="button",I.setAttribute("aria-label",`Remove ${P.label}`),I.addEventListener("click",()=>{u.delete(P.value),y(),v.inputEl.focus()})}},C=w=>{let T=w.isCustom?m(w.value):w;c||u.clear(),u.add(T.value),y()};v.inputEl.addEventListener("keydown",w=>{if(w.key==="Backspace"&&v.inputEl.value===""&&u.size>0){let T=b().at(-1);if(!T)return;w.preventDefault(),u.delete(T.value),y()}});try{let w=new HT(this.app,v.inputEl,()=>[...a,...p.values()],T=>u.has(T),C,c,d,t.newNoteName?this.noteNameExists(t.newNoteName,a.map(T=>T.path)):void 0);this.host.controlFor(t).suggesters.push(w)}catch{v.setDisabled(!0)}y()}}});function pH(r,t){r.empty(),r.toggleClass("qa-hidden",t.length===0);for(let e of t){let n=e.diagnostics.filter(l=>l.severity==="error"),o=n.some(l=>l.kind!=="path")?"Unresolved":n.length>0?"Won't be created":e.label,s=r.createDiv({cls:"qa-onepage-preview-row"});s.createDiv({text:`${o}:`,cls:"qa-preview-key"}),s.createDiv({text:e.text,cls:"qa-preview-val"}).setAttribute("title",e.text);for(let l of e.diagnostics){let c=r.createDiv({cls:"qa-preview-issue"});c.toggleClass("qa-preview-issue--error",l.severity==="error"),c.createSpan({cls:"qa-visually-hidden",text:l.severity==="error"?"Error: ":"Warning: "}),c.appendText(l.message),c.setAttribute("title",l.message)}}}var mH=x(()=>{});function jT(r,t={}){let{openedAtOf:e,recentRankOf:n,isExcluded:i}=t;return r.map(o=>({file:o,name:o.basename||o.path,excluded:i?.(o.path)??!1,openedAt:e?.(o.path),recentRank:n?.(o.path)})).sort((o,s)=>{if(o.excluded!==s.excluded)return o.excluded?1:-1;let a=o.openedAt!=null,l=s.openedAt!=null;if(a!==l)return a?-1:1;if(a&&l&&o.openedAt!==s.openedAt)return s.openedAt-o.openedAt;let c=o.recentRank??Number.POSITIVE_INFINITY,d=s.recentRank??Number.POSITIVE_INFINITY;return c!==d?c-d:o.name.localeCompare(s.name)}).map(o=>o.file)}var KF=x(()=>{});function YT(r){let t=r.workspace?.getLastOpenFiles?.(),e=Array.isArray(t)?t:[],n=new Map;e.forEach((s,a)=>{n.has(s)||n.set(s,a)});let i;try{i=Im.getInstanceIfExists()}catch{i=void 0}let o=r.metadataCache;return{openedAtOf:s=>i?.getLastOpenedAt(s),recentRankOf:s=>n.get(s),isExcluded:s=>o?.isUserIgnored?.(s)??!1}}var QF=x(()=>{nP()});function Are(r){return`${XF}${r}`}function Ire(r){return`${JF}${r}`}function Pre(r){return r.startsWith(XF)}function $re(r){return r.startsWith(JF)}function Fre(r){return r.slice(XF.length)}function Mre(r){return r.slice(JF.length)}function Xi(r){return r.trim().replace(/\.md$/i,"").toLowerCase()}function Rre(r){return r.trim().replace(/^\/+/,"")}function Dre(r){return r.trim().length>0&&!r.includes("{{")}function Ore(r){return Dre(r.templatePath)?new Set([xn(r.templatePath).toLowerCase()]):new Set}function Lre(r,t,e){let n=t.replace(/\.md$/i,"");r.add(Xi(t)),r.add(Xi(n)),r.add(Xi(e))}function Nre(r,t){let e=r.metadataCache.getFileCache(t)?.frontmatter;if(!e)return[];let n=[];for(let[i,o]of Object.entries(e)){let s=i.toLowerCase();s!=="alias"&&s!=="aliases"||(typeof o=="string"?n.push(...o.split(",").map(a=>a.trim()).filter(Boolean)):Array.isArray(o)&&n.push(...o.filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean)))}return n}function Vre(r){let n=((r.split("|")[0]?.trim()??"").split("#")[0]?.trim()??"").replace(/\.md$/i,"").trim();return!n||n==="/"||Ut(n)?null:n}function Bre(r){let t=r.metadataCache.unresolvedLinks??{},e=new Map;for(let n of Object.values(t))for(let i of Object.keys(n)){let o=Vre(i);if(!o)continue;let s=Xi(o);e.has(s)||e.set(s,o)}return[...e.values()].sort((n,i)=>n.localeCompare(i))}function KT(r,t){let e=new Set,n=Ore(t),i=jT(r.vault.getMarkdownFiles(),YT(r)),o=[];for(let s of i){if(n.has(Rre(s.path).toLowerCase()))continue;Lre(e,s.path,s.basename);let a=Nre(r,s);for(let c of a)e.add(Xi(c));let l=[s.basename,s.path,...a].join(" ");o.push({item:Are(s.path),exactKeys:[s.basename,s.path,...a].map(Xi),display:l,title:a[0]?`${s.basename} (${s.path})`:s.path,renderPath:s.path,renderAlias:a[0]})}for(let s of Bre(r)){let a=Xi(s);e.has(a)||o.push({item:Ire(s),exactKeys:[Xi(s)],display:s,title:`${s} (unresolved link)`,unresolvedTitle:s})}return{candidates:o,existingKeys:e}}function Dy(r){return Pre(r)?{kind:"existing",path:Fre(r)}:ra($re(r)?Mre(r):r)}function ra(r){let t=Nr(r,"Note title");return{kind:"create",title:t,...t.includes("/")?{vaultRelativePath:t}:{}}}function ZF(r,t){let e=Dy(t);return Oy(r,e),e}function Oy(r,t){if(t.kind==="existing"){let n=r.vault.getAbstractFileByPath(t.path);if(!(n instanceof fH.TFile))throw new Error("Selected note no longer exists. Please run QuickAdd again.");if(n.extension.toLowerCase()!=="md")throw new Error("Select a Markdown note to use with this Template choice.");return{kind:"existing",file:n}}let e=Nr(t.title,"Note title");return{kind:"create",title:e,...e.includes("/")?{vaultRelativePath:e}:{}}}var fH,XF,JF,kf=x(()=>{fH=require("obsidian");KF();QF();Qo();Hi();tr();XF="@quickadd-existing-note:",JF="@quickadd-unresolved-note:"});var XT,QT,hH=x(()=>{XT=require("obsidian");ja();kf();Ps();QT=class extends Er{constructor(e,n,i,o,s){let{candidates:a,existingKeys:l}=KT(e,i);super(e,n,s);this.obsidianApp=e;this.onSelect=o;this.existingKeys=l;let c=uc(i.existingNoteAction);this.options=a.map(d=>({item:d.item,exactKeys:d.exactKeys,label:d.renderPath?`${c==="Open"?"":`${c}: `}${d.renderPath.split("/").at(-1)?.replace(/\.md$/i,"")}`:d.unresolvedTitle??d.title,detail:d.renderPath??"Unresolved link",search:d.display}))}getSuggestions(e){let n=e.trim();if(!n)return this.options.slice(0,100);let i=Xi(n),o=(0,XT.prepareFuzzySearch)(n),s=this.options.map(a=>({option:a,match:o(a.search)})).filter(a=>a.match!==null).sort((a,l)=>Number(l.option.exactKeys.includes(i))-Number(a.option.exactKeys.includes(i))||(l.match?.score??0)-(a.match?.score??0)).slice(0,99).map(({option:a})=>a);return!this.existingKeys.has(i)&&!this.options.some(a=>a.exactKeys.includes(i))&&s.unshift({item:n,exactKeys:[i],label:`Create new note: ${n}`,detail:"",search:n}),s}resolveInput(e){let n=Xi(e),i=this.options.find(o=>o.exactKeys.includes(n));return i?ZF(this.obsidianApp,i.item):ra(e)}renderSuggestion(e,n){n.addClass("qa-onepage-file-suggestion");let i=n.createDiv({cls:"qa-onepage-file-suggestion__text"});i.createDiv({cls:"qa-onepage-file-suggestion__label",text:e.label}),e.detail&&i.createDiv({cls:"qa-onepage-file-suggestion__path",text:e.detail})}selectSuggestion(e){try{let n=this.options.includes(e)?ZF(this.obsidianApp,e.item):ra(e.item);this.inputEl.value="",this.close(),this.onSelect(n)}catch(n){new XT.Notice(n instanceof Error?n.message:"Could not select this note."),this.inputEl.focus()}}}});function JT(r=null){return{collect:{kind:"none"},opaque:null,deferred:r}}function eM(r){return{collect:{kind:"none"},opaque:r,deferred:r}}function vH(r,t=null){return JT(t)}function gH(r){if(!r)return JT("unresolvableChoice");switch(r.type){case"Template":case"Capture":return Un(r)||sl(r)?{collect:{kind:"scanChoice",choice:r},opaque:null,deferred:null}:JT("unresolvableChoice");case"Macro":return eM("nestedMacroGroup");case"Multi":return eM("interactivePicker");default:return vH(r.type,"unresolvableChoice")}}function Sf(r,t){switch(r.type){case"NestedChoice":return gH(r.choice??null);case"Choice":return gH(t(r.choiceId));case"UserScript":return{collect:{kind:"scriptInputs",command:r},opaque:"runsUserCode",deferred:null};case"AIAssistant":return{collect:{kind:"none"},opaque:"runsUserCode",deferred:null};case"Conditional":return eM("conditionalBranch");case"Obsidian":case"EditorCommand":case"Wait":case"OpenFile":return JT();default:return vH(r.type)}}var ZT=x(()=>{al();Zt()});function tM(r,t){return r.onePageInput==="never"&&Un(r)&&bc(r,r.fileNameFormat.enabled?r.fileNameFormat.format:Cr,t)}function Ure(r){return{id:r.id,label:r.name}}function qre(r){return{id:r.id,label:r.name}}function Ly(r,t,e){let n=[],i=[],o=!1,s=!1;for(let a of Mt(t.macro?.commands)){if(!Tr(a))continue;let l=Sf(a,r);if(s){i.push({label:a.name,reason:"afterOpaqueStep"});continue}if(l.collect.kind==="scanChoice"){let c=l.collect.choice;s=tM(c,e),c.onePageInput==="never"?i.push({label:c.name,reason:"choiceOptedOut"}):o?i.push({label:c.name,reason:"afterOpaqueStep"}):n.push({kind:"choice",occurrenceId:a.id,choice:c,group:Ure(c)})}else l.collect.kind==="scriptInputs"?n.push({kind:"script",occurrenceId:a.id,command:l.collect.command,group:qre(l.collect.command)}):l.deferred&&i.push({label:a.name,reason:l.deferred});l.opaque&&(o=!0)}return{members:n,deferred:i}}var e_=x(()=>{Hr();Ve();Jd();al();ZT()});function t_(r,t){switch(t.kind){case"filter":return Vw(r,t.filter);case"property":return Bw(r,t.field,t.value,t.filter);case"tag":return GL(r,t.tag);case"folder":return Xo(r,t.folderPathSlash)}}function r_(r,t){let e=jT(t,YT(r)),n=e.map(l=>l.path),i=Ms(e,l=>r.metadataCache.getFileCache(l)),o=i.map(l=>l.label),s=i.map(l=>l.aliases),a=n.map((l,c)=>`${i[c]?.primary??l} ${l}`);return{paths:n,labels:o,aliases:s,search:a}}var rM=x(()=>{gi();KF();QF();Ln()});function Hre(r){return typeof r=="string"&&zre.includes(r)}function yH(r){if(!r||typeof r!="object")return null;let t=r,e=t.id,n=t.type;if(typeof e!="string"||!Hre(n))return null;let i=Wre(t.numericConfig),o=Gre(t.sliderConfig),s=n==="slider"&&!o?"number":n;return{id:e,label:typeof t.label=="string"?t.label:e,type:s,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,defaultValue:typeof t.defaultValue=="string"?t.defaultValue:void 0,numericConfig:o??i,sliderConfig:o,options:Array.isArray(t.options)?t.options.filter(a=>typeof a=="string"):void 0,dateFormat:typeof t.dateFormat=="string"?t.dateFormat:void 0,description:typeof t.description=="string"?t.description:void 0,optional:typeof t.optional=="boolean"?t.optional:void 0,source:"script"}}function Wre(r){if(!r||typeof r!="object")return;let t=r,e=typeof t.min=="number"&&Number.isFinite(t.min)?t.min:void 0,n=typeof t.max=="number"&&Number.isFinite(t.max)?t.max:void 0,i=typeof t.step=="number"&&Number.isFinite(t.step)&&t.step>0?t.step:void 0;if(e!==void 0&&n!==void 0&&n<e)return i===void 0?void 0:{step:i};let o={};return e!==void 0&&(o.min=e),n!==void 0&&(o.max=n),i!==void 0&&(o.step=i),Object.keys(o).length>0?o:void 0}function Gre(r){if(!r||typeof r!="object")return;let t=r,e=typeof t.min=="number"?t.min:void 0,n=typeof t.max=="number"?t.max:void 0,i=t.step===void 0?1:typeof t.step=="number"?t.step:void 0;if(!(e===void 0||n===void 0||i===void 0||!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(i)||n<=e||i<=0))return{min:e,max:n,step:i}}function bH(r){if(!r||typeof r!="object"&&typeof r!="function")return[];let t=r.quickadd;if(!t||typeof t!="object")return[];let e=t.inputs;return Array.isArray(e)?e:[]}var zre,wH=x(()=>{zre=["text","number","textarea","dropdown","slider","date","field-suggest","file-picker","suggester"]});function n_(r){return`${r.replace(/^\/+/,"").replace(xt,"")}.md`}function i_(r,t,e){if(e)return null;let n=(t??"").trim().replace(/^\/+/,"");if(_a(n))return null;let i=Xp(n),o=!!i&&!!i.field,s=o?null:Qp(n),a=!!s&&!s.multiSelect,l=!o&&!s&&n.startsWith("#"),c=n.endsWith("/"),d=!l&&!o&&!a&&!c&&(xt.test(n)||lr.test(n)||Mn.test(n)),u=n.replace(/\/+$/,""),p=!l&&!o&&!a&&!d&&(n===""||r.isFolder(u)&&!r.markdownFileExists(u)),m=!o&&!a&&c;if(o&&i)return{kind:"property",field:i.field,value:i.value,filter:i.filter};if(a&&s)return{kind:"filter",filter:s.filter};if(l)return{kind:"tag",tag:n};if(p||m){let h=u;return{kind:"folder",folderPathSlash:h===""?"":`${h}/`}}return null}var nM=x(()=>{Ve();Fh();mC();pC()});function iM(r){let t=/^\{\{VALUE:([^{}]+)\}\}$/i.exec(r);if(t){let i=Id(t[1]);return i&&!i.inputTypeOverride&&!i.hasOptions&&!i.caseStyle?i.variableKey:null}let e=/^\{\{(?:VALUE|NAME)(\|[^{}]+)?\}\}$/i.exec(r);if(!e)return null;let n=Xh(e[1]??"");return!n.inputTypeOverride&&!n.caseStyle?"value":null}function o_(r,t){let e=t==="boolean"?"checkbox":t;return e!=="number"&&e!=="checkbox"||iM(r)===null?r:`${r.slice(0,-2)}|type:${e}}}`}var oM=x(()=>{yo()});var Ny,CH=x(()=>{yg();tn();Ve();$p();mp();Hd();yo();eg();Fa();wF();Ln();gi();Ny=class extends Xl{constructor(e,n,i){super(e);this.app=e;this.plugin=n;this.choiceExecutor=i;this.requirements=new Map;this.templatesToScan=new Set;this.scannedTemplateRefDepths=new Map;this.scanningPathContext=!1;this.scanningScope="generic";this.valueTakesLines=!1;this.scanningSoleValue=!1;this.scanPositions=new Map;this.dateParser=To,i&&(this.variables=new Map(i.variables))}warn(){}reportProblem(){}async scanString(e,n=!1,i="generic"){let o=this.scanningPathContext,s=this.scanningScope,a=this.scanningSoleValue;this.scanningPathContext=n,this.scanningScope=i,this.scanningSoleValue=iw(i,e);let l=new Set(this.requirements.keys());this.scanPositions=new Map;try{let c=await this.replaceGlobalVarInString(e);if(this.scanDateTokens(c),this.scanVariableTokens(c),this.scanFileTokens(c),n){if(new RegExp(co.source,"i").test(c)){let d=this.requirements.get("value");d&&(d.pathContext=!0)}if(new RegExp(Ah.source,"i").test(c)){let d=this.requirements.get("mvalue");d&&(d.pathContext=!0)}}await this.format(c),this.orderNewFieldsByPosition(l,c)}finally{this.scanningPathContext=o,this.scanningScope=s,this.scanningSoleValue=a}}orderNewFieldsByPosition(e,n){this.notePosition("value",n.search(co)),this.notePosition("mvalue",n.search(Ah));let i=new RegExp(op.source,"gi");for(let a of n.matchAll(i))this.notePosition(`${Ml}${a[1]}${a[2]??""}`,a.index);let o=[...this.requirements].filter(([a])=>!e.has(a)),s=a=>this.scanPositions.get(a)??Number.MAX_SAFE_INTEGER;o.sort(([a],[l])=>s(a)-s(l));for(let[a]of o)this.requirements.delete(a);for(let[a,l]of o)this.requirements.set(a,l)}notePosition(e,n){if(n<0)return;let i=this.scanPositions.get(e);(i===void 0||n<i)&&this.scanPositions.set(e,n)}markScanContext(e){this.scanningPathContext&&(e.pathContext=!0)}async format(e){let n=e;n=await this.replaceGlobalVarInString(n),n=this.replaceDateInString(n),n=this.replaceTimeInString(n),n=await this.replaceValueInString(n),n=await this.replaceSelectedInString(n),n=await this.replaceClipboardInString(n),n=await this.replaceDateVariableInString(n),n=await this.replaceVariableInString(n),n=await this.replaceFieldVarInString(n),n=await this.replaceFileInString(n),n=await this.replaceMathValueInString(n),n=this.replaceRandomInString(n);{let i=new RegExp(_s.source,"gi"),o;for(;(o=i.exec(n))!==null;){let s=o[1];s&&this.templatesToScan.add(xr(s))}}return n}async replaceGlobalVarInString(e){return Zl(e,this.plugin?.settings?.globalVariables)}scanVariableTokens(e){let n=new RegExp(wd.source,"gi"),i;for(;(i=n.exec(e))!==null;){let o=(i[1]??"").trim();if(!o)continue;let s=Id(o,{warn:this.warnSink});if(!s)continue;let{variableName:a,variableKey:l,label:c,defaultValue:d,displayValues:u,hasOptions:p}=s;if(!a)continue;let m=c??a,h=l,g=this.findRequirementIgnoringCase(h,"date");if(this.notePosition(g?.id??h,i.index),g){this.markScanContext(g);continue}if(this.requirements.has(h)){let v=this.requirements.get(h);if(this.markScanContext(v),p&&!this.hasOptionList(v)&&(v.type=this.optionFieldType(s),v.label=m,this.applyOptionFields(v,s),v.defaultValue!==void 0&&!s.allowCustomInput)){let b=Qh(v.defaultValue);v.defaultValue=s.suggestedValues.includes(b)?b:void 0}d&&v.defaultValue===void 0&&(v.defaultValue=d),!v.displayOptions&&u&&(v.displayOptions=u),v.optional=(v.optional??!1)&&s.optional}else{let v=this.inputFieldType(s),b={id:h,label:m,type:p?this.optionFieldType(s):v,optional:s.optional};p?this.applyOptionFields(b,s):v==="dropdown"?b.options=["true","false"]:v==="number"?b.numericConfig=s.numericConfig:v==="slider"&&(b.numericConfig=s.numericConfig,b.sliderConfig=s.sliderConfig),d&&(b.defaultValue=d),this.markScanContext(b),this.requirements.set(h,b)}}}findRequirementIgnoringCase(e,n){let i=this.requirements.get(e);if(i)return i.type===n?i:void 0;let o=e.toLowerCase(),s=[...this.requirements.values()].filter(a=>a.id.toLowerCase()===o);return s.length===1&&s[0].type===n?s[0]:void 0}inputFieldType(e){switch(e?.inputTypeOverride){case"checkbox":return"dropdown";case"number":return"number";case"slider":return"slider";case"multiline":return"textarea";default:return this.plugin.settings.inputPrompt==="multi-line"?"textarea":"text"}}optionFieldType(e){return e.allowCustomInput||e.multiSelect?"suggester":"dropdown"}hasOptionList(e){return Array.isArray(e.options)&&e.options.length>0}applyOptionFields(e,n){e.options=n.suggestedValues,n.displayValues&&(e.displayOptions=n.displayValues),n.multiSelect?e.multiEmit=n.multiEmit??"text":delete e.multiEmit,n.allowCustomInput||n.multiSelect?e.suggesterConfig={allowCustomInput:n.allowCustomInput,caseSensitive:!1,multiSelect:n.multiSelect??!1}:delete e.suggesterConfig}scanDateTokens(e){let n=new RegExp(Ts.source,"gi"),i;for(;(i=n.exec(e))!==null;){let o=i[1]?.trim();if(!o)continue;this.notePosition(o,i.index);let{defaultValue:s,optional:a,withTime:l,label:c}=Zh(i[3]),d=i[2]?.trim()||(l?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"),u=this.requirements.get(o);u?((u.type==="text"||u.type==="textarea")&&!this.hasOptionList(u)&&(u.type="date",u.dateFormat=d,u.withTime=l,c&&(u.label=c)),u.type==="date"&&s&&u.defaultValue===void 0&&(u.defaultValue=s),u.optional=(u.optional??!1)&&a,u.type==="date"&&l&&!u.withTime&&(u.withTime=!0,i[2]?.trim()||(u.dateFormat="YYYY-MM-DD HH:mm"))):this.requirements.set(o,{id:o,label:c??o,type:"date",defaultValue:s,dateFormat:d,withTime:l,optional:a,source:"collected"})}}async promptForValue(e){let n="value";if(!this.requirements.has(n)){let i=this.valueTakesLines&&!this.valuePromptContext?.inputTypeOverride?"textarea":this.inputFieldType(this.valuePromptContext),o=aw(this.scanningScope,this.scanningSoleValue);this.requirements.set(n,{id:n,label:this.valuePromptContext?.label||o.title||e||"Enter value",type:i,placeholder:o.placeholder,defaultValue:this.valuePromptContext?.defaultValue,numericConfig:this.valuePromptContext?.numericConfig,sliderConfig:this.valuePromptContext?.sliderConfig,options:i==="dropdown"?["true","false"]:void 0,source:"collected",optional:this.valuePromptContext?.optional})}return this.markScanContext(this.requirements.get(n)),""}async promptForVariable(e,n){if(!e)return"";let i=n?.variableKey??e;if(n?.type==="VDATE")return n.defaultValue??"@date:1970-01-01T00:00:00.000Z";if(!this.requirements.has(i)){let o=Ad(e).map(c=>c.trim()).filter(Boolean),s=o.length>1,a=s?"dropdown":this.inputFieldType(n),l={id:i,label:n?.label??e,type:a,numericConfig:n?.numericConfig,sliderConfig:n?.sliderConfig,source:"collected"};s?l.options=o:a==="dropdown"&&(l.options=["true","false"]),n?.defaultValue&&(l.defaultValue=n.defaultValue),this.requirements.set(i,l)}return this.markScanContext(this.requirements.get(i)),n?.defaultValue??""}async promptForMathValue(){let e="mvalue";return this.requirements.has(e)||this.requirements.set(e,{id:e,label:"Math expression",type:"text",placeholder:"e.g., 2+2*3"}),this.markScanContext(this.requirements.get(e)),""}async suggestForField(e){let n=On.parse(e),i=`${Ml}${e}`;if(!this.requirements.has(i)){let o={id:i,label:n.label??(n.fieldName||e),type:"field-suggest",source:"collected",runtimeOnly:n.multiSelect};if(!n.multiSelect&&n.filters.defaultFrom==="active"){let s=bT(this.app,this.choiceExecutor?.triggerContext?.activeFile??null,n.fieldName),a=(typeof s=="string"?s:void 0)??n.filters.defaultValue;a!==void 0&&(o.defaultValue=a)}this.requirements.set(i,o)}return""}scanFileTokens(e){let n=new RegExp(jb.source,"gi"),i;for(;(i=n.exec(e))!==null;){let o=_w(i[1]??"");o&&(this.notePosition(o.variableKey,i.index),this.recordFileRequirement(o))}}recordFileRequirement(e){let n=e.variableKey,i=this.requirements.get(n);if(i){i.optional=(i.optional??!1)&&e.optional,i.type="file-picker",i.suggesterConfig={allowCustomInput:(i.suggesterConfig?.allowCustomInput??!1)||e.allowCustomInput,caseSensitive:!1,multiSelect:(i.suggesterConfig?.multiSelect??!1)||e.multiSelect};return}let o=Dp(this.app,e),s=o.map(p=>`${Gl}${p.path}`),a=Ms(o,p=>this.app.metadataCache.getFileCache(p)),l=a.map(p=>p.label),c=e.allowCustomInput||s.length===0,d=[...e.types];e.mode!=="name"&&d.push(e.mode);let u=d.length?`File from ${e.folderPath} (${d.join(", ")})`:`File from ${e.folderPath}`;this.requirements.set(n,{id:n,label:e.label??u,type:"file-picker",source:"collected",options:s,displayOptions:l,optionAliases:a.map(p=>p.aliases),optional:e.optional,suggesterConfig:{allowCustomInput:c,caseSensitive:!1,multiSelect:e.multiSelect}})}suggestForFile(e){return""}async suggestForValue(e,n,i){return""}getVariableValue(e){return""}async getTemplateContent(e){return""}async getSelectedText(){return""}async getClipboardContent(){return""}getCurrentFileLink(){return null}getCurrentFileName(){return null}async getMacroValue(e,n){return""}isTemplatePropertyTypesEnabled(){return!1}}});function aM(r){return`${sM}${r}`}function Af(r){return r.startsWith(sM)&&r.length>sM.length}function lM(r){return r===Ph||Af(r)}function xH(r,t){let e=Ul(r,t);return e?r.get(e)==null?null:e:null}function jre(r){let t=0;for(let e of r.keys())Af(e)&&t++;return t}function EH(r,t){if(!r)return;let e=r.get(aM(t));if(typeof e=="string"&&e.length>0)return e;if(jre(r)>1)return;let n=r.get(Ph);if(typeof n=="string"&&n.length>0)return n}function TH(r,t){return lM(t)?xH(r,t):null}function _H(r,t,e){return e!==1||!Af(t)?!1:xH(r,Ph)!==null}var sM,cM=x(()=>{Ve();yo();sM=`${Ph}.`});async function SH(r,t){let e=Rn(r,t);return e?await r.vault.cachedRead(e):""}async function pl(r,t,e,n="generic",i=new Set,o=0){let s=ow(n),a=_c(e);t.templatesToScan.clear(),await t.scanString(e,s,n);let l=[...t.templatesToScan].filter(c=>a.has(c));if(t.templatesToScan.clear(),!(o>=Lw))for(let c of l){if(i.has(c))continue;let d=`${s?"path":"content"}:${c}`,u=t.scannedTemplateRefDepths.get(d);if(!(u!==void 0&&u<=o)){t.scannedTemplateRefDepths.set(d,o),i.add(c);try{await pl(r,t,await SH(r,c),n,i,o+1)}finally{i.delete(c)}}}}async function Yre(r,t,e){await t.scanString(e,!0,"templatePath"),await AH(r,t,e)}async function AH(r,t,e){if(_a(e)){S.logMessage(`Preflight: template path "${e}" uses format syntax; its body's prompts are collected at run time, not in the one-page form.`);return}await pl(r,t,await SH(r,e),"noteBody",new Set([e]))}async function IH(r,t,e,n){let i=new Ny(r,t,e);if(n.templatePath&&await i.scanString(n.templatePath,!0,"templatePath"),n.folder?.enabled)for(let s of n.folder.folders??[])await pl(r,i,s,"folder");n.fileNameFormat?.enabled&&await pl(r,i,n.fileNameFormat.format,"noteTitle"),n.templatePath&&await AH(r,i,n.templatePath);let o=n.fileNameFormat?.enabled?n.fileNameFormat.format:Cr;if(EI(n,o)){let s=i.requirements.get("value");s&&(s.runtimeOnly=!0)}return i}async function PH(r,t,e,n,i){let o=new Ny(r,t,e);await pl(r,o,n.captureTo,"captureTarget"),n.propertyCapture?.property.kind==="named"&&await pl(r,o,n.propertyCapture.property.format,"propertyName");let s=n.format?.enabled?n.format.format:Cr,a=n.propertyCapture?.property.kind==="named"?n.propertyCapture.property.format.trim():null,l=a&&!_a(a)?$s(r,a,{registeredOnly:!0}):null;if((n.format?.enabled||n.propertyCapture)&&(o.valueTakesLines=!!n.eachLine&&!n.propertyCapture,await pl(r,o,n.propertyCapture?o_(s,l):s,n.propertyCapture?"propertyValue":"captureText"),o.valueTakesLines=!1),n.propertyCapture&&l===null){let u=iM(s),p=u===null?void 0:o.requirements.get(u);p&&(p.runtimeOnly=!0)}!n.propertyCapture&&n.insertAfter?.enabled&&!n.insertAfter.promptHeading&&await pl(r,o,n.insertAfter.after,"lineTarget"),!n.propertyCapture&&n.insertBefore?.enabled&&await pl(r,o,n.insertBefore.before,"lineTarget");let c=n.createFileIfItDoesntExist;c?.enabled&&c.createWithTemplate&&c.template&&await Yre(r,o,c.template);let d=i_({isFolder:u=>vg(r,u),markdownFileExists:u=>r.vault.getAbstractFileByPath(n_(u))instanceof kH.TFile},n.captureTo??"",n.captureToActiveFile);if(d){let{paths:u,labels:p,aliases:m}=r_(r,t_(r,d)),h=n.createFileIfItDoesntExist?.enabled??!1,g=aM(n.id);u.length===0&&h?o.requirements.set(g,{id:g,label:"Select capture target file",type:"file-picker",source:"collected",options:u,displayOptions:p,runtimeOnly:!0,placeholder:"Type a new note name in the capture target picker"}):u.length===0?o.requirements.set(g,{id:g,label:"Select capture target file",type:"dropdown",options:u,displayOptions:p,placeholder:"No files found in target scope"}):o.requirements.set(g,{id:g,label:"Select capture target file",type:"file-picker",options:u,displayOptions:p,optionAliases:m,...h?{suggesterConfig:{allowCustomInput:!0},newNoteName:d.kind==="folder"?"scope":"vault"}:{}});for(let[v,b]of[...o.requirements])v!==g&&(o.requirements.delete(v),o.requirements.set(v,b))}if(i){let u=n.useSelectionAsCaptureValue,p=t.settings.useSelectionAsCaptureValue??!0;if(typeof u=="boolean"?u:p){let h=e.variables.get("value");if(h==null){let g=el(r);g.trim().length>0&&e.variables.set("value",g)}}}return o}async function Kre(r,t,e){let n=[];try{let i=ox(t),o=i!==void 0?e?.get(i):void 0;o===void 0&&(o=await Zd(t,r,{reportLoadErrors:!1}),i!==void 0&&o!==void 0&&e?.set(i,o));let s=bH(o?.script);for(let a of s){let l=yH(a);l&&n.push(l)}}catch(i){let o=t.path??t.id,s=i instanceof Error?i.message:String(i);if(ix(i))return S.logMessage(`QuickAdd preflight could not inspect user script '${o}': ${s}`),n;S.logWarning(`Preflight could not inspect user script '${o}': ${s}`)}return n}async function Qre(r,t,e,n,i){let o=Ly(l=>Vc(t,l),n,e.variables.get("value")),s=new Map,a=i?.seedCaptureSelectionAsValue??!1;for(let l of o.members){let c=l.kind==="script"?await Kre(r,l.command,i?.preloadedUserScripts):Un(l.choice)?Array.from((await IH(r,t,e,l.choice)).requirements.values()):Array.from((await PH(r,t,e,l.choice,a)).requirements.values());for(let d of c){let u=s.get(d.id);if(u){u.optional=(u.optional??!1)&&(d.optional??!1),d.pathContext&&(u.pathContext=!0),d.runtimeOnly&&(u.runtimeOnly=!0),u.type==="text"&&d.type==="textarea"&&(u.type="textarea");continue}s.set(d.id,{...d,group:l.group})}}return Xre(e.variables,s),Array.from(s.values())}function Xre(r,t){let e=[];for(let n of t.values())Af(n.id)&&e.push(n.id);if(!(e.length<2))for(let n of e)r.has(n)||r.set(n,null)}function Jre(r,t){let e=t.pickDate?Yp(Ha(r.dateOrigin)):Ha(r.dateOrigin);if(!(e?.kind!=="ask"||t.clocks?.date))return{id:Ta,label:`Date for ${r.name}`,type:"date",dateFormat:"YYYY-MM-DD",defaultValue:e.defaultValue,source:"collected"}}function Zre(r,t,e){let n=Jre(r,t);return n?[n,...e.filter(i=>i.id!==Ta)]:e}async function na(r,t,e,n,i){let o;if(ji(n))o=await Qre(r,t,e,n,i);else if(Un(n))o=[...(await IH(r,t,e,n)).requirements.values()];else if(n.type==="Capture")o=[...(await PH(r,t,e,n,i?.seedCaptureSelectionAsValue??!1)).requirements.values()];else return[];return Zre(n,e,o)}function $H(r,t,e){return Ly(n=>Vc(r,n),t,e).deferred}function ml(r,t){let e=r.filter(n=>Af(n.id)).length;return r.filter(n=>{if(lM(n.id))return TH(t,n.id)!==null?!1:!_H(t,n.id,e);let i=Ul(t,n.id);return i?t.get(i)==null:!0})}var kH,Vy=x(()=>{rM();wH();OT();kH=require("obsidian");is();$p();Ve();jp();lc();al();Jd();ou();tr();gi();ye();eu();Fh();nM();yo();oM();fp();CH();mp();cM();e_()});function FH(){return{pending:new Map,active:null,discoveryMacros:new Set}}function MH(r,t){r.preparedInputs.discoveryMacros.add(t)}function RH(r,t){return r.preparedInputs.discoveryMacros.has(t)}function DH(r,t,e){r.preparedInputs.pending.set(t,e)}function OH(r,t){return r.preparedInputs.active?.choiceId===t}function LH(r,t){let e=r.preparedInputs.active;return e?.choiceId===t?e.discovery:null}function NH(r){r.preparedInputs.pending.clear(),r.preparedInputs.discoveryMacros.clear(),r.preparedInputs.active=null}async function By(r,t,e){let n=r.preparedInputs,i=n.pending.get(t);if(!i)return e();n.pending.delete(t);let o=n.active;n.active=i;let s=r.variables.has("value"),a=r.variables.get("value"),l=!1;for(let[c,d]of i.values)r.variables.get(c)==null&&(r.variables.set(c,d),c==="value"&&(l=!0));try{return await e()}finally{l&&r.variables.get("value")===i.values.get("value")&&(s?r.variables.set("value",a):r.variables.delete("value")),n.active=o}}var If=x(()=>{});function VH(r,t){let e=r.flatMap(n=>{if(n.kind==="always")return[n.metadata];let i=t.get(n.noteId);return i?.kind==="create"?[n.create]:i?.kind==="existing"&&n.existing?[n.existing]:[]});return e.length===0?null:{...e[0],optional:e.length>0&&e.every(n=>n.optional),pathContext:e.some(n=>n.pathContext),runtimeOnly:e.some(n=>n.runtimeOnly)}}function s_(r){return{...r}}function uM(r,t){let e=t.get(r.noteId);return e?.kind==="create"||r.includeExisting&&e?.kind==="existing"}function dM(r,t){return Un(r)&&bc(r,r.fileNameFormat.enabled?r.fileNameFormat.format:Cr,t.variables.get("value"))}async function BH(r,t,e,n){let i=d=>Vc(t,d),o;if(ji(n)){for(let d of Mt(n.macro?.commands)){if(!Tr(d))continue;let u=Sf(d,i);u.collect.kind==="scanChoice"&&dM(u.collect.choice,e)&&MH(e,n.id)}if(!RH(e,n.id))return null;o=Ly(i,n,e.variables.get("value")).members}else if(dM(n,e))o=[{kind:"choice",choice:n,occurrenceId:n.id,group:{id:n.id,label:n.name}}];else return null;let s=new Map,a=new Map,l={notes:[],visibleForNotes:new Map,fieldUsages:new Map},c=[];if(ji(n)){let d={...n,macro:{...n.macro,commands:[]}},u=ml(await na(r,t,e,d),e.variables);if(u.length>0){let p=new Map;for(let m of u)s.set(m.id,m),p.set(m.id,{variable:m.id,condition:null}),a.set(m.id,[null]),l.fieldUsages.set(m.id,[{kind:"always",metadata:s_(m)}]);c.push({occurrenceId:n.id,choiceId:n.id,noteId:null,bindings:p})}}for(let d of o){let u={...d.group,id:d.occurrenceId},p=d.kind==="choice"?d.choice:null,m=p!==null&&dM(p,e)?p:null,h=m?`__qa.note.${d.occurrenceId}`:null,g={occurrenceId:d.occurrenceId,choiceId:p?.id??d.occurrenceId,noteId:h,bindings:new Map};c.push(g),m&&h&&(l.notes.push({id:h,choice:m,group:u}),s.set(h,{id:h,label:"Note",type:"text",pathContext:!0,group:u}));let v=p??(ji(n)&&d.kind==="script"?{...n,macro:{...n.macro,commands:[d.command]}}:null);if(!v)continue;let b=ml(await na(r,t,e,v,{preloadedUserScripts:e.preloadedUserScripts}),e.variables),y=new Map;if(m&&bC(m.existingNoteAction)!=="open"){let w={...m,fileNameFormat:{enabled:!1,format:""},folder:{...m.folder,enabled:!1}};for(let T of await na(r,t,e,w))y.set(T.id,T)}let C=p&&sl(p)&&(p.useSelectionAsCaptureValue??t.settings.useSelectionAsCaptureValue??!0)?el(r):"";for(let w of b){if(m&&w.id==="value")continue;let T=w.id==="value"?`__qa.value.${d.occurrenceId}`:w.id,P=h?{noteId:h,includeExisting:y.has(w.id)}:null;g.bindings.set(T,{variable:w.id,condition:P});let _=l.fieldUsages.get(T)??[],I=y.get(w.id),O={...w,id:T,group:u,...w.id==="value"&&C.trim()?{defaultValue:C}:{}};_.push(h?{kind:"note",noteId:h,create:s_(O),existing:I?s_(I):null}:{kind:"always",metadata:s_(O)}),l.fieldUsages.set(T,_);let N=s.get(T);N?(N.optional=!!(N.optional&&w.optional),w.pathContext&&(N.pathContext=!0),w.runtimeOnly&&(N.runtimeOnly=!0)):s.set(T,O);let K=a.get(T)??[];K.push(P),a.set(T,K)}}for(let[d,u]of a)u.includes(null)||l.visibleForNotes.set(d,u.filter(p=>p!==null));return{requirements:[...s.values()],config:l,steps:c}}function UH(r,t,e,n){for(let i of t.steps){let o=i.noteId?n.get(i.noteId)??null:null,s=new Map;for(let[a,{variable:l,condition:c}]of i.bindings)(!c||uM(c,n))&&e.has(a)&&s.set(l,e.get(a));DH(r,i.occurrenceId,{choiceId:i.choiceId,values:s,discovery:o})}}var pM=x(()=>{OT();al();Ve();Jd();ja();Hr();is();ZT();e_();Vy();If()});function ene(r){let t=[];for(let e of r){let n=t.at(-1);n&&n.group?.id===e.group?.id?n.fields.push(e):t.push({group:e.group,fields:[e]})}return t}function tne(r){let t=new Set;for(let e of r)e.group&&t.add(e.group.id);return t.size>=2}function a_(r){return JSON.stringify(Object.entries(r).filter(([t,e])=>e!==void 0&&!["id","group","optional","pathContext","runtimeOnly"].includes(t)).sort(([t],[e])=>t.localeCompare(e)))}var kr,Pf,mM=x(()=>{uH();kr=require("obsidian");mP();fP();Ov();iP();oP();kx();rr();mH();hH();kf();pM();ja();Pf=class extends kr.Modal{constructor(e,n,i,o,s){super(e);this.discoveryForm=s;this.result=new Map;this.multiSelections=new Map;this.fileSelections=new Map;this.discoverySelections=new Map;this.discoverySuggesters=[];this.fieldElements=new Map;this.fieldAnchors=new Map;this.fieldControls=new Map;this.discoveryInputs=new Map;this.dateParseErrors=new Set;this.previewContainerEl=null;this.previewToken=0;this.settled=!1;this.imagePasteHandles=new Map;this.imagePasteInputs=new Map;this.freeTextFields=[];this.requirements=n.map(a=>({...a})),this.updateFieldMetadata(),this.initialValues=new Map,this.computePreview=o,i?.forEach((a,l)=>{typeof a=="string"&&this.initialValues.set(l,a)}),this.updatePreviewDebounced=(0,kr.debounce)(this.updatePreviews.bind(this),150,!0),this.peek=new Mm({app:e,title:"Provide inputs",containerEl:this.containerEl,scope:this.scope,getField:()=>this.insertTarget()?.el,getValue:()=>this.insertTarget()?.el.value??"",setValue:a=>{let l=this.insertTarget();l&&(this.result.set(l.id,a),this.updatePreviewDebounced())},persistDraft:()=>{},markDraftChanged:()=>{let a=this.insertTarget();a&&(this.result.set(a.id,a.el.value),this.updatePreviewDebounced())},close:()=>this.close()}),this.waitForClose=new Promise((a,l)=>{this.resolvePromise=a,this.rejectPromise=l}),this.display(),this.open()}display(){if(this.containerEl.addClass("quickAddModal","onePageInputModal"),Ax(this.containerEl),this.discoveryForm&&this.containerEl.addClass("qa-discovery-form"),this.contentEl.empty(),this.contentEl.createEl("h2",{text:"Provide inputs"}).addClass("qa-onepage-title"),this.computePreview&&(this.previewContainerEl=this.contentEl.createDiv(),this.previewContainerEl.addClass("qa-onepage-preview","qa-hidden")),tne(this.requirements))for(let s of ene(this.requirements)){s.group&&!(this.discoveryForm&&s.fields.length===1&&s.fields[0].label===s.group.label)&&this.contentEl.createEl("h3",{text:s.group.label,cls:"qa-onepage-section"});for(let a of s.fields)this.renderField(a)}else this.requirements.forEach(s=>this.renderField(s));this.updateFieldVisibility(!1),this.computePreview&&this.updatePreviews(),this.modalEl.addClass("qa-has-modal-footer");let n=this.modalEl.createDiv({cls:"qa-prompt-actions qa-modal-footer"}),i=n.createDiv({cls:"qa-prompt-actions-primary"});new kr.ButtonComponent(i).setButtonText("Submit").setCta().onClick(()=>this.submit()),new kr.ButtonComponent(i).setButtonText("Cancel").onClick(()=>this.cancel());let o=n.createDiv({cls:"qa-prompt-actions-secondary"});Ix(new kr.ButtonComponent(o).setButtonText("Peek at note").onClick(()=>this.peek.peek()))}open(){if(super.open(),!this.modalEl.ownerDocument.activeElement?.matches(".qa-onepage-file-picker__remove"))return;let e=Array.from(this.contentEl.querySelectorAll("input, textarea, select")).filter(i=>!i.closest("[hidden]")&&!i.matches(":disabled"));(e.find(i=>!i.closest(".qa-onepage-file-picker")?.querySelector(".qa-onepage-file-picker__chip"))??e[0])?.focus()}onOpen(){this.peek.onHostOpened();let e=this.scope;typeof e?.register=="function"&&(e.register(["Mod"],"Enter",()=>(this.submit(),!1)),e.register(["Mod","Shift"],Dv,()=>(this.peek.peek(),!1)))}renderField(e){let n=new Set(this.contentEl.children),i=this.discoveryForm?.notes.find(s=>s.id===e.id);i?this.renderNoteField(i):this.renderFieldControl(e);let o=Array.from(this.contentEl.children).filter(s=>s.instanceOf(HTMLElement)&&!n.has(s));if(this.fieldElements.set(e.id,o),!i){this.controlFor(e).elements=o;let s=this.fieldAnchors.get(e.id);s||(s=this.contentEl.ownerDocument.createComment(e.id),this.contentEl.append(s),this.fieldAnchors.set(e.id,s));for(let a of o)this.contentEl.insertBefore(a,s)}}controlFor(e){let n=this.fieldControls.get(e);return n||(n={requirement:e,elements:[],value:"",dateParseError:!1,suggesters:[],dispose:[]},this.fieldControls.set(e,n)),n}publishControl(e){let n=e.requirement;this.settled||!this.requirements.includes(n)||(this.result.set(n.id,e.value),e.multiSelections?this.multiSelections.set(n.id,e.multiSelections):this.multiSelections.delete(n.id),e.fileSelections?this.fileSelections.set(n.id,e.fileSelections):this.fileSelections.delete(n.id),e.dateParseError?this.dateParseErrors.add(n.id):this.dateParseErrors.delete(n.id))}get activeRequirements(){return this.requirements.filter(e=>this.isFieldVisible(e.id))}isFieldVisible(e){if(this.requirements.find(i=>i.id===e)?.runtimeOnly)return!1;let n=this.discoveryForm?.visibleForNotes.get(e);return!n||n.some(i=>uM(i,this.discoverySelections))}updateFieldVisibility(e=!0){this.updateFieldMetadata();for(let[n,i]of this.fieldElements)for(let o of i)o.hidden=!this.isFieldVisible(n);for(let n of this.fieldControls.values())if(!(this.requirements.includes(n.requirement)&&this.isFieldVisible(n.requirement.id)))for(let i of n.suggesters)i.close();for(let[n,i]of this.imagePasteInputs)this.syncImagePaste(n,i);e&&this.updatePreviewDebounced()}updateFieldMetadata(){for(let e=0;e<this.requirements.length;e++){let n=this.requirements[e],i=this.discoveryForm?.fieldUsages.get(n.id);if(!i)continue;let o=VH(i,this.discoverySelections);if(!o)continue;let s={...o,id:n.id,group:n.group};if(!this.fieldElements.has(n.id)){this.requirements[e]=s;continue}if(a_(n)!==a_(s)){let a=this.controlFor(n);a.value=this.result.get(n.id)??a.value;for(let c of a.suggesters)c.close();for(let c of a.elements)c.hidden=!0,c.remove();let l=Array.from(this.fieldControls.values()).find(c=>c.requirement.id===n.id&&a_(c.requirement)===a_(s));if(n=l?.requirement??s,this.requirements[e]=n,l){for(let c of l.elements)this.contentEl.insertBefore(c,this.fieldAnchors.get(n.id)??null);this.fieldElements.set(n.id,l.elements),this.publishControl(l)}else this.renderField(n)}Object.assign(n,{optional:s.optional,pathContext:s.pathContext,runtimeOnly:s.runtimeOnly});for(let a of this.fieldElements.get(n.id)??[]){if(a.querySelector(".setting-item-name")?.replaceChildren(this.decorateLabel(n)),n.type!=="dropdown")continue;let l=a.querySelector("select");if(!l||n.options?.includes(""))continue;let c=Array.from(l.options).find(d=>d.value==="");if(n.optional&&!c)l.createEl("option",{value:"",text:"Skip (leave empty)",prepend:!0});else if(!n.optional&&c){c.remove();let d=this.controlFor(n);d.value=l.value,this.publishControl(d)}}}}renderNoteField(e){let n=new kr.Setting(this.contentEl).setName("Note");n.settingEl.addClass("qa-onepage-file-picker-setting");let i=n.controlEl.createDiv({cls:"qa-onepage-file-picker"}),o=i.createDiv({cls:"qa-onepage-file-picker__selection"});o.setAttribute("aria-live","polite");let s=new kr.TextComponent(i).setPlaceholder("Search notes or create new note");s.inputEl.addClass("qa-onepage-file-picker__input"),s.inputEl.setAttribute("aria-label",`Note for ${e.choice.name}`);let a,l=c=>{a?.close(),this.discoverySelections.set(e.id,c),o.empty();let d=uc(e.choice.existingNoteAction),u=c.kind==="existing"?`${d==="Open"?"":`${d}: `}${c.path.replace(/\.md$/i,"")}`:`Create: ${c.title}`,p=o.createDiv({cls:"qa-onepage-file-picker__chip"});p.createSpan({cls:"qa-onepage-file-picker__chip-label",text:u});let m=p.createEl("button",{cls:"qa-onepage-file-picker__remove",text:"\xD7"});m.type="button",m.setAttribute("aria-label","Change note"),m.addEventListener("click",()=>{this.discoverySelections.delete(e.id),o.empty(),s.inputEl.hidden=!1,this.updateFieldVisibility(),s.inputEl.focus()}),s.inputEl.hidden=!0,this.updateFieldVisibility(),m.focus()};try{a=new QT(this.app,s.inputEl,e.choice,l,this.scope),this.discoverySuggesters.push(a)}catch{new kr.Notice("Note search is unavailable. Type a new note title.")}this.discoveryInputs.set(e.id,{input:s.inputEl,select:l,resolve:()=>a?a.resolveInput(s.inputEl.value):ra(s.inputEl.value)})}renderFieldControl(e){new GT(this.app,this.contentEl,{controlFor:n=>this.controlFor(n),initialValue:n=>this.initialValues.get(n),publish:n=>this.publishControl(n),updatePreview:()=>this.updatePreviewDebounced(),decorateLabel:n=>this.decorateLabel(n),attachFreeText:(n,i)=>{this.enableImagePaste(n,i),this.attachFreeTextBehaviors(n,i)}}).render(e)}attachFreeTextBehaviors(e,n){let o={id:e.id,el:n,fileSuggester:new Pm(this.app,n),tagSuggester:new $m(this.app,n,{refreshIndex:this.freeTextFields.length===0})};this.freeTextFields.push(o),this.controlFor(e).suggesters.push(o.fileSuggester,o.tagSuggester),n.addEventListener("focus",()=>{this.lastFocusedFreeText=o})}insertTarget(){return this.lastFocusedFreeText&&this.contentEl.contains(this.lastFocusedFreeText.el)&&this.isFieldVisible(this.lastFocusedFreeText.id)?this.lastFocusedFreeText:this.freeTextFields.find(e=>this.contentEl.contains(e.el)&&this.isFieldVisible(e.id))}enableImagePaste(e,n){this.imagePasteInputs.set(e,n),this.syncImagePaste(e,n)}syncImagePaste(e,n){let i=this.imagePasteHandles.get(e);if(this.settled||e.pathContext||!this.requirements.includes(e)||!this.isFieldVisible(e.id)){if(!this.settled&&!e.pathContext&&i?.isBusy()){i.whenIdle().then(()=>this.syncImagePaste(e,n));return}i?.detach(),this.imagePasteHandles.delete(e)}else i||this.imagePasteHandles.set(e,_x(this.app,n,{}))}decorateLabel(e){if(!e.optional)return e.label;let n=this.contentEl.ownerDocument,i=n.win.createFragment();return i.appendChild(n.createTextNode(e.label)),i.createSpan({text:" (optional)",cls:"qa-onepage-optional-badge"}),i}submit(){if(this.settled)return;let e=new Set(this.requirements.filter(c=>!this.isFieldVisible(c.id)).map(c=>c.id));for(let c of this.discoveryForm?.notes??[]){if(this.discoverySelections.has(c.id))continue;let d=this.discoveryInputs.get(c.id);if(d){if(!d.input.value.trim()){new kr.Notice("Enter a note title or choose an existing note."),d.input.focus();return}try{d.select(d.resolve())}catch(u){new kr.Notice(u instanceof Error?u.message:"Could not select this note."),d.input.focus();return}}}let n=c=>c.type==="file-picker"&&!c.optional&&!c.suggesterConfig?.multiSelect,i=this.requirements.find(c=>e.has(c.id)&&this.isFieldVisible(c.id)&&!c.optional&&!n(c)&&!(this.result.get(c.id)??this.initialValues.get(c.id)??c.defaultValue));if(i){this.focusField(i.id);return}let o=this.requirements.find(c=>this.isFieldVisible(c.id)&&n(c)&&!this.result.get(c.id));if(o){new kr.Notice(`QuickAdd: Choose a file for "${o.label}".`),this.focusField(o.id);return}let s=Array.from(this.imagePasteHandles.values()).find(c=>c.isBusy());if(s){s.whenIdle().then(()=>this.submit());return}let a={},l=this.requirements.find(c=>this.isFieldVisible(c.id)&&c.type==="date"&&!c.optional&&this.dateParseErrors.has(c.id));if(l){new kr.Notice(`QuickAdd: "${l.label}" is not a valid date. Fix it or clear it before submitting.`),this.focusField(l.id);return}for(let[c,d]of this.multiSelections){let u=(this.result.get(c)??"").replace(/,\s*$/,"").trim();d.join(", ")!==u&&this.multiSelections.delete(c)}Object.assign(a,this.collectAnswers()),this.settled=!0,this.close(),this.resolvePromise(a)}focusField(e){let n=this.fieldElements.get(e)?.[0];kr.Platform.isPhone?n?.scrollIntoView({block:"nearest"}):n?.querySelector("input, textarea, select")?.focus()}collectAnswers(){let e=new Map(this.requirements.map(i=>[i.id,i])),n={};return this.result.forEach((i,o)=>{if(!this.isFieldVisible(o))return;let s=e.get(o);if(s?.type==="date"&&i===""){let a=this.dateParseErrors.has(o);if(!s.optional||a)return}n[o]=i}),n}collectPreviewAnswers(){let e=this.collectAnswers(),n=new Map(this.requirements.map(i=>[i.id,i]));for(let[i,o]of this.fileSelections)this.isFieldVisible(i)&&(e[i]=n.get(i)?.suggesterConfig?.multiSelect?[...o]:o[0]??"");return e}cancel(){this.settled=!0,this.close(),this.rejectPromise(rn())}onClose(){this.peek.onHostClosed();for(let e of this.imagePasteHandles.values())e.detach();this.imagePasteHandles.clear(),this.imagePasteInputs.clear();for(let e of this.fieldControls.values()){for(let n of e.suggesters)n.destroy();for(let n of e.dispose)n()}this.freeTextFields.length=0,this.lastFocusedFreeText=void 0;for(let e of this.discoverySuggesters)e.destroy();this.discoverySuggesters.length=0,this.settled||(this.settled=!0,this.rejectPromise(rn()))}async updatePreviews(){if(!this.computePreview||!this.previewContainerEl)return;let e=++this.previewToken;try{let n=await this.computePreview(this.collectPreviewAnswers());if(e!==this.previewToken||!this.previewContainerEl)return;pH(this.previewContainerEl,n)}catch{}}}});function rne(r){if(!r||typeof r!="object")return;let t={};return typeof r.min=="number"&&Number.isFinite(r.min)&&(t.min=r.min),typeof r.max=="number"&&Number.isFinite(r.max)&&(t.max=r.max),t.min!==void 0&&t.max!==void 0&&t.max<t.min&&(delete t.min,delete t.max),typeof r.step=="number"&&Number.isFinite(r.step)&&r.step>0&&(t.step=r.step),Object.keys(t).length>0?t:void 0}function nne(r){if(!r||typeof r!="object")return;let{min:t,max:e}=r,n=r.step??1;if(!(typeof t!="number"||typeof e!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(e)||!Number.isFinite(n)||e<=t||n<=0))return{min:t,max:e,step:n}}async function qH(r,t,e){let n={},i=[];for(let l of e){let c=t.variables.get(l.id);if(c!=null){n[l.id]=String(c);continue}let d=nne(l.sliderConfig),u=d??rne(l.numericConfig),p=l.type==="slider"&&!d?"number":l.type;i.push({id:l.id,label:l.label??l.id,type:p,placeholder:l.placeholder,defaultValue:l.defaultValue,numericConfig:u,sliderConfig:d,options:l.options,dateFormat:l.dateFormat,description:l.description,optional:l.optional,suggesterConfig:l.suggesterConfig,source:"script"})}let o={};if(i.length>0){let l=t?.promptProvider;if(l)try{let c=await l.requestInputs(i);o=Object.fromEntries(Object.entries(c).map(([d,u])=>[d,Array.isArray(u)?u.join(", "):u]))}catch(c){ea(c)}else{let c=new Pf(r,i,t.variables);try{o=await c.waitForClose}catch(d){ea(d)}}}for(let l of e){let c=o[l.id];l.type==="suggester"&&l.suggesterConfig?.multiSelect&&typeof c=="string"&&(o[l.id]=c.replace(/,\s*$/,""))}let s={...n,...o};for(let l of e)s[l.id]===void 0&&(s[l.id]="");Object.entries(s).forEach(([l,c])=>t.variables.set(l,c));let a={};for(let l of e){let c=s[l.id];if(c===void 0)continue;let d=c;if(l.type==="date"&&l.dateFormat&&typeof c=="string"&&c.startsWith("@date:")){let u=c.slice(6),p=Po(u,l.dateFormat);p&&(d=p)}a[l.id]=d}return a}var zH=x(()=>{mM();uu();jF()});function Eu(r){return new TextEncoder().encode(r).length}function ine(r){let t=0;for(let e of r){if(e.role==="tool"){for(let n of e.results)t+=Eu(n.content);continue}if(t+=Eu(e.content),e.role==="assistant"&&e.toolCalls){for(let n of e.toolCalls)if(typeof n.rawArgs=="string")t+=Eu(n.rawArgs);else if(n.args)try{t+=Eu(JSON.stringify(n.args))}catch{}}}return t}function one(r,t){let e;if(typeof r=="string")e=r;else if(r==null)e='{"ok":true}';else try{e=JSON.stringify(r)}catch{return{content:"tool returned a value that could not be serialized",isError:!0}}if(Eu(e)>t){let n=" \u2026[truncated]",i=Math.max(0,t-Eu(n)),o=Math.min(e.length,i);for(;o>0&&Eu(e.slice(0,o))>i;)o=Math.floor(o*.9)||o-1;e=e.slice(0,o)+n}return{content:e,isError:!1}}async function HH(r){let t=r.maxResultBytes??32768,e=r.maxTranscriptBytes??524288,n=Math.max(1,r.maxSteps),i=[...r.request.messages],o=[],s={promptTokens:0,completionTokens:0,totalTokens:0},a=0,l=!1,c=null;for(let m=0;m<n;m++){if(m>0&&r.isOnlineDisabled?.())return d("aborted");let h=m===n-1,g=l||h,v={...r.request,messages:i,...g?{toolChoice:"none"}:{}};a+=ine(i);let b;try{b=await r.dispatch(v,{isFinalStep:g})}catch(C){if(r.isContextOverflow?.(C))return d("context-overflow");throw C}if(c=b,s.promptTokens+=b.usage.promptTokens,s.completionTokens+=b.usage.completionTokens,s.totalTokens+=b.usage.totalTokens,b.normalizedStopReason!=="tool_calls"||b.toolCalls.length===0||g){o.push({stepNumber:m,text:b.content,toolCalls:b.toolCalls,toolResults:[],finishReason:b.rawStopReason,usage:b.usage}),await r.onStepFinish?.(o[o.length-1]);let C=b.normalizedStopReason==="length"?"length":h&&!l&&m>0?"max-steps":"stop";return d(C)}i.push({role:"assistant",content:b.content,toolCalls:b.toolCalls,providerRaw:b.providerRaw});let y=[];for(let C of b.toolCalls)y.push(await u(C));i.push({role:"tool",results:y}),o.push({stepNumber:m,text:b.content,toolCalls:b.toolCalls,toolResults:y,finishReason:b.rawStopReason,usage:b.usage}),await r.onStepFinish?.(o[o.length-1]),a>e&&(l=!0),r.shouldStop?.({steps:o})&&(l=!0)}return d("max-steps");function d(m){return{text:c?.content??"",steps:o,finishReason:m,usage:s,messages:i,finalTurn:c??{content:"",toolCalls:[],normalizedStopReason:"stop",rawStopReason:"",usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}}async function u(m){if(m.parseError)return p(m,"could not parse the tool arguments as JSON");let h=r.getTool(m.name);if(!h)return p(m,`unknown tool "${m.name}"`);let g=m.args??{},v=r.validateArgs(h,g);if(v)return p(m,`invalid arguments: ${v}`);if(!await r.confirm(m,h))return p(m,"tool call denied by user");let y;try{y=await h.execute(g,{toolCallId:m.id,toolName:m.name})}catch(T){if(r.isAbortError(T))throw T;return p(m,`tool execution failed: ${T instanceof Error?T.message:String(T)}`)}let{content:C,isError:w}=one(y,t);return{toolCallId:m.id,name:m.name,content:C,isError:w}}function p(m,h){return{toolCallId:m.id,name:m.name,content:h,isError:!0}}}var WH=x(()=>{});function c_(r,t="schema"){if(r===null||typeof r!="object"||Array.isArray(r))throw new fl(`${t} must be a JSON Schema object.`);for(let e of Object.keys(r))if(!GH.has(e))throw new fl(`${t} uses unsupported JSON Schema keyword "${e}". QuickAdd tool schemas support only: ${[...GH].join(", ")}. (Constraints like pattern/minLength/additionalProperties/$ref/allOf/anyOf/format are rejected because at least one provider would silently drop them.)`);if(r.type!==void 0){let e=Array.isArray(r.type)?r.type:[r.type];for(let n of e)if(!sne.has(n))throw new fl(`${t} has invalid type "${String(n)}".`)}if(r.properties!==void 0){if(r.properties===null||typeof r.properties!="object"||Array.isArray(r.properties))throw new fl(`${t}.properties must be an object.`);for(let[e,n]of Object.entries(r.properties))c_(n,`${t}.properties.${e}`)}if(r.required!==void 0&&(!Array.isArray(r.required)||r.required.some(e=>typeof e!="string")))throw new fl(`${t}.required must be an array of strings.`);if(r.items!==void 0){if(Array.isArray(r.items))throw new fl(`${t}.items as an array (tuple validation) is not supported in QuickAdd's schema subset.`);c_(r.items,`${t}.items`)}if(r.enum!==void 0&&!Array.isArray(r.enum))throw new fl(`${t}.enum must be an array.`)}function l_(r){return r===null?"null":Array.isArray(r)?"array":typeof r=="number"?Number.isInteger(r)?"integer":"number":typeof r=="boolean"?"boolean":typeof r=="string"?"string":"object"}function ane(r,t){let e=l_(r);return e===t||t==="number"&&e==="integer"}function Uy(r,t,e="$"){if(t.type!==void 0){let n=Array.isArray(t.type)?t.type:[t.type];if(!n.some(i=>ane(r,i)))return`${e}: expected ${n.join(" | ")}, got ${l_(r)}`}if(Array.isArray(t.enum)&&!t.enum.some(i=>d_(i,r)))return`${e}: value is not one of the allowed enum values`;if("const"in t&&!d_(t.const,r))return`${e}: value does not equal the required const`;if(l_(r)==="object"){let n=r;if(Array.isArray(t.required)){for(let i of t.required)if(!Object.prototype.hasOwnProperty.call(n,i))return`${e}.${i}: required property is missing`}if(t.properties){for(let[i,o]of Object.entries(t.properties))if(i in n){let s=Uy(n[i],o,`${e}.${i}`);if(s)return s}}}if(l_(r)==="array"&&t.items&&!Array.isArray(t.items)){let n=r;for(let i=0;i<n.length;i++){let o=Uy(n[i],t.items,`${e}[${i}]`);if(o)return o}}return null}function d_(r,t){if(r===t)return!0;if(typeof r!=typeof t)return!1;if(r===null||t===null)return r===t;if(Array.isArray(r)&&Array.isArray(t))return r.length===t.length&&r.every((e,n)=>d_(e,t[n]));if(typeof r=="object"&&typeof t=="object"){let e=Object.keys(r),n=Object.keys(t);return e.length!==n.length?!1:e.every(i=>d_(r[i],t[i]))}return!1}var GH,sne,fl,jH=x(()=>{GH=new Set(["type","properties","required","items","enum","const","description","title"]),sne=new Set(["object","array","string","number","integer","boolean","null"]),fl=class extends Error{constructor(t){super(t),this.name="ToolSchemaError"}}});function u_(r){return r.toLowerCase().startsWith(Qb)}var fM=x(()=>{Ve()});function p_(r){let t=r.trim();if(!t)throw new Error("assignToVariable cannot be empty.");if(new Set(["value","title","text","meta"]).has(t.toLowerCase()))throw new Error(`assignToVariable "${t}" is reserved (it would hijack a built-in formatter token).`);if(t.toLowerCase().endsWith("-quoted"))throw new Error(`assignToVariable "${t}" cannot end with "-quoted" (collides with the quoted output variable).`);if(u_(t))throw new Error(`assignToVariable "${t}" uses the reserved "__qa." prefix for QuickAdd internal variables.`);if(/[|,]/.test(t))throw new Error(`assignToVariable "${t}" contains characters unreachable by {{VALUE:name}}.`)}var hM=x(()=>{fM()});function lne(r,t){if(!t||typeof t!="object")return"";let e=t,n=typeof e.path=="string"?e.path.trim():"",i=typeof e.heading=="string"?e.heading.trim():"";if(!n&&!i)return"";let o=[];return n&&o.push(`Target: ${n}`),i&&o.push(`Heading: ${i}`),o.join(" \xB7 ")}function cne(r){try{return JSON.stringify(r,null,2)??String(r)}catch{return String(r)}}var Tu,qy,YH=x(()=>{Tu=require("obsidian");Ka();qy=class r extends Tu.Modal{constructor(e,n,i){super(e);this.toolName=n;this.args=i;this.outcome=null;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Prompt(e,n,i){return new r(e,n,i).waitForClose}display(){this.containerEl.addClass("quickAddModal","qaAIToolConfirm"),this.contentEl.empty(),this.titleEl.textContent=`Run AI tool: ${this.toolName}?`,this.contentEl.createEl("p",{text:"The AI requested this tool call with the arguments below."});let e=lne(this.toolName,this.args);e&&this.contentEl.createEl("p",{cls:"qaAIToolSummary",text:e});let n=this.contentEl.createEl("pre",{cls:"qaAIToolArgs"});n.textContent=cne(this.args),n.setCssStyles({whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"16rem",overflowY:"auto"});let i=this.contentEl.createDiv({cls:"yesNoPromptButtonContainer"}),o=new Tu.ButtonComponent(i).setButtonText("Abort run").onClick(()=>this.submit("abort")),s=new Tu.ButtonComponent(i).setButtonText("Deny").onClick(()=>this.submit("deny")),a=new Tu.ButtonComponent(i).setButtonText("Approve all this run").onClick(()=>this.submit("allow-all")),l=new Tu.ButtonComponent(i).setButtonText("Approve").onClick(()=>this.submit("allow"));s.buttonEl.focus(),qC([o.buttonEl,s.buttonEl,a.buttonEl,l.buttonEl])}submit(e){this.outcome=e,this.close()}onClose(){super.onClose(),this.resolvePromise(this.outcome??"deny")}}});function pne(r){return r instanceof at}function QH(r){return ty(r)==="input_context"}function mne(r){return{content:r.content,toolCalls:r.toolCalls??[],normalizedStopReason:r.normalizedStopReason??"stop",rawStopReason:r.stopReason,usage:r.usage,providerRaw:r.providerRaw}}function fne(r){if(r)return typeof r=="string"?r:{name:r.toolName}}function hne(r){return{toolCallId:r.id,toolName:r.name,input:r.args}}function gne(r){return{toolCallId:r.toolCallId,toolName:r.name,output:r.content,isError:r.isError??!1}}function XH(r,t){let e;try{e=JSON.parse(vne(r))}catch(i){return{ok:!1,error:`not valid JSON (${i instanceof Error?i.message:String(i)})`}}let n=Uy(e,t);return n?{ok:!1,error:n}:{ok:!0,value:e}}function vne(r){let t=r.trim(),e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);return e?e[1]:t}var KH,dne,une,gM,m_,JH=x(()=>{je();xu();lT();kn();ti();Dm();kc();df();J$();nt();aT();WH();jH();hM();YH();KH=/^[a-zA-Z0-9_-]{1,64}$/,dne=20,une=100,gM=new WeakSet;m_=class{constructor(t,e,n,i){this.app=t;this.plugin=e;this.choiceExecutor=n;this.config=i;this.running=!1;this.approveAllThisRun=!1;let o=new Set;for(let[s,a]of Object.entries(i.tools??{})){if(!KH.test(s))throw new Error(`Invalid tool name "${s}". Tool names must match ${KH}.`);if(o.has(s))throw new Error(`Duplicate tool name "${s}".`);o.add(s),c_(a.inputSchema,`tool "${s}".inputSchema`)}}async generate(t={}){if(this.running)throw new Error("This agent is already running a generate() call. Await it, or create a separate agent for concurrent runs.");let e=typeof t.assignToVariable=="string"&&t.assignToVariable.length>0;if(e&&(this.assertAssignableName(t.assignToVariable),gM.has(this.choiceExecutor)))throw new Error("Another AI run with assignToVariable is already in flight in this context \u2014 they would race the shared variables. Run them sequentially.");this.running=!0,e&&gM.add(this.choiceExecutor);let n=sT(this.app);try{return await this.run(t,n)}finally{this.running=!1,e&&gM.delete(this.choiceExecutor);try{n()}catch{}}}async run(t,e){this.approveAllThisRun=!1;let n=U.getState();if(n.disableOnlineFeatures)throw new Error("Rejecting AI request: Online features are disabled in settings.");let{model:i,provider:o}=Vv(this.config.model),s=await So(this.app,o),a=await this.buildSeedMessages(t),l=this.buildToolDefinitions(),c=this.buildRegistry(),d=t.schema?{schema:t.schema,name:"response",strict:!0}:void 0,u={messages:a,...l.length>0?{tools:l}:{},toolChoice:fne(t.toolChoice??this.config.toolChoice)??"auto",maxOutputTokens:t.maxOutputTokens??this.config.maxOutputTokens,modelParams:this.config.modelOptions},p=Math.max(1,Math.min(this.config.maxSteps??dne,une)),m=lu(n.ai.showAssistant);m.setMessage("starting","QuickAdd is running the AI agent.");try{let h=await HH({request:u,maxSteps:p,dispatch:async(v,b)=>{let y=this.buildTurnRequest(v,b.isFinalStep,d);try{let C=await tF(this.app,s,i,o,y,e,!n.ai.showAssistant);return mne(C)}catch(C){throw QH(C)&&Me(C),C}},getTool:v=>c.get(v),confirm:(v,b)=>this.confirm(v,b),validateArgs:(v,b)=>Uy(b,v.definition.parameters),isAbortError:pne,isContextOverflow:QH,isOnlineDisabled:()=>U.getState().disableOnlineFeatures,shouldStop:this.buildShouldStop(),onStepFinish:v=>this.reportStep(m,v)}),g=this.toGenerateResult(h);return t.schema&&(g.object=await this.resolveStructuredObject(h,u,i,o,s,t.schema,e)),typeof t.assignToVariable=="string"&&t.assignToVariable&&this.assignVariable(t.assignToVariable,g.text),m.setMessage("finished",`Ran ${g.steps.length} step${g.steps.length===1?"":"s"}.`),window.setTimeout(()=>m.hide(),5e3),g}catch(h){throw m.fail(h),h}}reportStep(t,e){let n=e.toolCalls.map(o=>o.name),i=n.length>0?`Step ${e.stepNumber+1}: running ${n.join(", ")}.`:`Step ${e.stepNumber+1}: generating a response.`;t.setMessage("thinking",i)}async buildSeedMessages(t){let e=[],n=t.system??this.config.system??U.getState().ai.defaultSystemPrompt;n&&n.trim().length>0&&e.push({role:"system",content:n});let i=t.prompt??"",o=i?await new _i(this.app,this.plugin,this.choiceExecutor).formatFileContent(i):"";return e.push({role:"user",content:o}),e}buildToolDefinitions(){return Object.entries(this.config.tools??{}).map(([t,e])=>({name:t,description:e.description,parameters:e.inputSchema,...e.strict?{strict:!0}:{}}))}buildRegistry(){let t=new Map;for(let[e,n]of Object.entries(this.config.tools??{}))t.set(e,{definition:{name:e,description:n.description,parameters:n.inputSchema,strict:n.strict},execute:(i,o)=>n.execute(i,o),readOnly:n.readOnly});return t}buildShouldStop(){let t=this.config.stopWhen?Array.isArray(this.config.stopWhen)?this.config.stopWhen:[this.config.stopWhen]:[];if(t.length!==0)return({steps:e})=>{let n=e.flatMap(i=>i.toolCalls.map(o=>o.name));return t.some(i=>i({stepNumber:e.length,toolCallNames:n}))}}buildTurnRequest(t,e,n){return!!(t.tools&&t.tools.length>0)&&!e?{...t,responseFormat:void 0}:{...t,tools:void 0,toolChoice:e?"none":t.toolChoice,responseFormat:n}}async confirm(t,e){let n=t.args??{},i=await this.resolvePerToolApproval(e,n);if(!(i||this.needsGlobalConfirmation(e))||this.approveAllThisRun&&!i)return!0;if(this.choiceExecutor.interactive===!1)throw new ue(`'${t.name}' needs approval before it runs, but this run is non-interactive. Set the AI assistant's tool-confirmation to "never", mark the tool readOnly, or re-run with the ui flag.`);let s=await qy.Prompt(this.app,t.name,t.args??{});if(s==="abort")throw new at("AI tool run aborted by user");return s==="allow-all"?(this.approveAllThisRun=!0,!0):s==="allow"}async resolvePerToolApproval(t,e){let i=this.config.tools?.[t.definition.name]?.needsApproval;return typeof i=="function"?await i({args:e}):i===!0}needsGlobalConfirmation(t){let e=U.getState().ai.confirmToolCalls??"destructive";return e==="always"?!0:e==="destructive"?t.readOnly!==!0:!1}async resolveStructuredObject(t,e,n,i,o,s,a){if(t.finalTurn.rawStopReason==="refusal")return;let l=XH(t.finalTurn.content,s);if(l.ok)return l.value;if(t.finishReason==="aborted"||t.finishReason==="context-overflow"||U.getState().disableOnlineFeatures)return;let c=[...t.messages,{role:"assistant",content:t.finalTurn.content},{role:"user",content:`Your previous reply was not valid JSON matching the required schema (${l.error}). Reply with ONLY a JSON object that matches the schema \u2014 no prose, no code fences.`}],d={...e,messages:c,tools:void 0,toolChoice:"none",responseFormat:{schema:s,name:"response",strict:!0}};try{let u=await tF(this.app,o,n,i,d,a),p=XH(u.content,s);return p.ok?p.value:void 0}catch{return}}toGenerateResult(t){let e=t.steps.map(i=>({stepNumber:i.stepNumber,text:i.text,toolCalls:i.toolCalls.map(hne),toolResults:i.toolResults.map(gne),finishReason:i.finishReason})),n=e[e.length-1];return{text:t.text,steps:e,toolCalls:n?.toolCalls??[],toolResults:n?.toolResults??[],usage:{inputTokens:t.usage.promptTokens,outputTokens:t.usage.completionTokens,totalTokens:t.usage.totalTokens},finishReason:t.finishReason}}assignVariable(t,e){let n=t.trim(),i=("> "+e).replace(/\n/g,`
- > `);this.choiceExecutor.variables.set(n,e),this.choiceExecutor.variables.set(`${n}-quoted`,i)}assertAssignableName(t){p_(t)}}});function hl(r,t,e=!1){let n=oi(r),i=n.find(u=>u.line===t),o=!!i;if(!o&&e)throw new Error(`Target line ${t} is not a heading, but we are trying to find the end of its section.`);if(!o&&!e){let u=n.find(h=>h.line>t)?.line??null,p=yne(r,t,h=>h.trim()===""),m=[u,p].filter(h=>h!==null);return m.length>0?Math.min(...m)-1:r.length-1}let s=i,l=n.find(u=>u.line>s.line&&(!e||u.level<=s.level))?.line??r.length,c=d2(r,s),d=l-1;for(;d>c&&r[d].trim()==="";)d--;return d===0&&r[1]?.trim()===""?1:Math.max(d,c)}function yne(r,t,e){for(let n=t+1;n<r.length;n++)if(e(r[n]))return n;return null}var f_=x(()=>{mu()});function zy(r){let t=TF(r);return r.map((e,n)=>t[n]?e.replace(/^(\s*)#+(\s)/,`$1${bne}$2`):e)}function wne(r){let t=r.match(/^\[?v?(\d+)\.(\d+)\.(\d+)(?:[-+\]].*)?$/i)??r.match(/^\[?v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/i);if(!t)return{value:0,parsed:!1};let e=n=>Math.min(Number(n??"0"),999999);return{value:e(t[1])*1e12+e(t[2])*1e6+e(t[3]),parsed:!0}}function ZH(r,t,e){switch(t.by){case"lexical":return{value:r.toLocaleLowerCase(),parsed:!0};case"numeric":{let n=r.match(/^-?\d+(?:\.\d+)?/);return n?{value:Number(n[0]),parsed:!0}:{value:0,parsed:!1}}case"date":{let n=e?e(r,t.dateFormat||void 0,!1):null;return n&&n.isValid()?{value:n.valueOf(),parsed:!0}:{value:0,parsed:!1}}case"semver":return wne(r);default:return{value:0,parsed:!0}}}function Cne(r,t){if(typeof r.value=="string"&&typeof t.value=="string")return r.value<t.value?-1:r.value>t.value?1:0;let e=r.value,n=t.value;return e<n?-1:e>n?1:0}function eW(r,t,e,n,i,o=0){let s=zy(r),a=oi(s).filter(p=>p.line>=o),l=a.filter(p=>p.level===e),c=ZH(oi([t])[0]?.heading.trim()??"",n,i);if(l.length===0){let p=a.filter(m=>m.level<e).pop();return p?{mode:"after",line:hl(s,p.line,!0)}:{mode:"bodyStart"}}let d=()=>{let p=l[l.length-1];return{mode:"after",line:hl(s,p.line,!0)}};if(n.by==="insertion")return n.direction==="desc"?{mode:"before",line:l[0].line}:d();if(!c.parsed)return d();let u=n.unparseable??"bottom";for(let p of l){let m=ZH(p.heading.trim(),n,i),h;if(!m.parsed)h=u==="bottom";else{let g=Cne(c,m);h=n.direction==="desc"?g>0:g<0}if(h)return{mode:"before",line:p.line}}return d()}var bne,vM=x(()=>{f_();mu();bne="\u200B"});function yM(r){let t=r.split(`
- `);for(;t.length>1&&t[t.length-1].trim()==="";)t.pop();return t}function bM(r){return r.length===0||r.length===1&&r[0].trim()===""}function wM(r,t){if(t.length<=1){let e=xne(r,t[0]??"");return{start:e,end:e}}return Ene(r,t)}function xne(r,t){let e=t.trimEnd(),n=-1;for(let i=0;i<r.length;i++){let o=r[i].trimStart();if(o===e)return i;if(o.startsWith(e)){let a=o.slice(e.length);if(/^\s*$/.test(a))return i;n===-1&&(n=i);continue}let s=o.indexOf(e);if(s!==-1){let a=o.slice(s+e.length);if(/^\s*$/.test(a))return i;n===-1&&(n=i)}}return n}function Ene(r,t){let e=t.length,n=t.map(i=>tW(i));for(let i=0;i+e<=r.length;i++){let o=!0;for(let s=0;s<e;s++)if(tW(r[i+s])!==n[s]){o=!1;break}if(o)return{start:i,end:i+e-1}}return{start:-1,end:-1}}function tW(r){return r.trimEnd()}function h_(r,t,e){return r?oi(t).some(n=>n.line===e):!1}function Tne(r,t){return r==="skip"?!0:r==="none"?!1:_ne(t)}function _ne(r){return/^\s{0,3}#{1,6}\s+\S/.test(r)}function g_(r,t,e,n){if(t<0)return t;let i=r[t]??"";if(!Tne(n,i))return t;let s=e.endsWith(`
- `)?Math.max(r.length-1,0):r.length,a=t;for(let l=t+1;l<s;l++){if(r[l].trim().length===0){a=l;continue}break}return a}function Hy(r,t,e,n){if(t<0)return t;let i=t,o=t+1;for(;o<r.length&&r[o].trim().length===0;)i=o,o++;return i===t||o!==r.length||!n.endsWith(`
- `)?t:e.endsWith(`
- `)?Math.max(t,i-1):i}function rW(r){return r.includes(`
- `)||r.includes("\r")}function nW(r,t){let e=r.indexOf(`
- `,t);return e===-1?r.length:e>0&&r[e-1]==="\r"?e-1:e}function CM(r){let t=ul(r);return t>0?r.slice(0,t).split(`
- `).length-1:0}function iW(r){return oi([r.replace(/\r$/,"")]).length>0}function oW(r){let t=new Set(oi(r.map(e=>e.replace(/\r$/,""))).map(e=>e.line));return r.map((e,n)=>t.has(n)?e:"")}function sW(r,t){let e=CM(t),n=r.map((i,o)=>o<e?"":i);return zy(n).map(i=>i.replace(/\r$/,""))}function $f(r,t,e,n,i=r.length){let o=t.split(`
- `),s=o.slice(0,e+1).join(`
- `),a=o.slice(e+1).join(`
- `),c=(o[e+1]??"").trim(),d=t.endsWith(`
- `)&&e+1===o.length-1,u=e+1<o.length&&!d&&c==="",p=n&&r.endsWith(`
- `)&&u?r.slice(0,-1):r,m=!r.endsWith(`
- `)&&a.length>0?`
- `:"";return{content:`${s}
- ${p}${m}${a}`,insertedEndOffset:s.length+1+Math.min(i,p.length)}}function aW(r,t,e,n=r.length){let i=t.length>0&&!r.endsWith(`
- `)?`
- `:"",o=Math.max(0,Math.min(n,r.length));if(e<=0)return{content:`${r}${i}${t}`,insertedEndOffset:o};let s=t.split(`
- `),a=s.slice(0,e).join(`
- `),l=s.slice(e).join(`
- `);return{content:`${a}
- ${r}${i}${l}`,insertedEndOffset:a.length+1+o}}function lW(r,t,e,n,i){let o=n,s=o.includes(`\r
- `)?`\r
- `:`
- `,a=t.mode==="before"?t.line:t.line+1,l=0;for(let C=0;C<a&&C<r.length;C++)l+=r[C].length+1;l>o.length&&(l=o.length);let c=o.slice(0,l),d=o.slice(l),u=a>0?(r[a-1]??"").replace(/\r$/,""):"",p=a<r.length?(r[a]??"").replace(/\r$/,""):"",m=e.split(`
- `).map(C=>C.replace(/\r$/,""));m.length>1&&m[m.length-1]===""&&m.pop();let h=[];a>0&&u.trim()!==""&&h.push(""),h.push(...m),a<r.length&&p.trim()!==""&&h.push("");let g=h.join(s),v=c.length>0&&!/\n$/.test(c)?s:"",b=d.length>0||/\n$/.test(o)?s:"",y=c.length+v.length;return{content:`${c}${v}${g}${b}${d}`,insertedEndOffset:y+(i===void 0?g.length:(a>0&&u.trim()!==""?s.length:0)+Math.min(e.slice(0,i).split(`
- `).map(C=>C.replace(/\r$/,"")).join(s).length,m.join(s).length))}}var v_=x(()=>{mu();vM();Rc()});function xM(r){return xr(r)}function EM(r,t){return t.some(e=>r===e||r.startsWith(`${e}/`))}function _u(r,t){let e=(t??[]).map(n=>xM(n)).filter(n=>n.length>0);return e.length===0?!0:r?EM(r.normalize("NFC"),e):!1}var y_=x(()=>{tn()});function ku(r,t={}){let e=(r??"").trim();if(!e)throw new $o("Path is empty.");let n=e.replace(/\\/g,"/").normalize("NFC");if(n.startsWith("/")||/^[a-zA-Z]:/.test(n))throw new $o(`Refusing to write to an absolute path outside the vault: "${n}".`);let i=n.replace(/\/+/g,"/").replace(/^\/+|\/+$/g,""),o=i.split("/").filter(a=>a.length>0);if(o.length===0)throw new $o("Path is empty after normalization.");for(let a of o){if(a==="."||a==="..")throw new $o(`Refusing path with a traversal segment ("${a}"): "${i}".`);if(a.startsWith("."))throw new $o(`Refusing to write into a dot/config path segment ("${a}"): "${i}".`);kne(a,i)}let s=(t.allowedRoots??[]).map(a=>xM(a)).filter(a=>a.length>0);if(s.length>0&&!EM(i,s))throw new $o(`Path "${i}" is not under an allowed root (${s.join(", ")}).`);return i}function kne(r,t){if(qh.test(r))throw new $o(`Path segment "${r}" contains control characters: "${t}".`);if(zh.test(r))throw new $o(`Path segment "${r}" contains an illegal character (\\ : * ? " < > |): "${t}".`);if(Hh.test(r))throw new $o(`Path segment "${r}" cannot end with a space or a period: "${t}".`);let e=r.split(".")[0]??"";if(e&&kd(e))throw new $o(`Path segment "${r}" is a reserved device name: "${t}".`)}var $o,dW=x(()=>{Wh();y_();$o=class extends Error{constructor(t){super(t),this.name="UnsafeVaultPathError"}}});function Ff(r,t){let e=Object.entries(r),n=new Set(e.map(([o])=>o));if(uW(t.only,n,"only"),uW(t.exclude,n,"exclude"),t.only){let o=new Set(t.only);e=e.filter(([s])=>o.has(s))}if(t.exclude){let o=new Set(t.exclude);e=e.filter(([s])=>!o.has(s))}let i=t.prefix??"";return Object.fromEntries(e.map(([o,s])=>[i+o,s]))}function Wy(r){return{...r,__qaTool:!0}}function uW(r,t,e){if(!r)return;let n=r.filter(i=>!t.has(i));n.length!==0&&S.logWarning(`AI tools: ${e} listed unknown tool name(s) ${n.map(i=>`"${i}"`).join(", ")}. Valid names: ${[...t].join(", ")}.`)}var b_=x(()=>{ye()});function yW(r,t={}){let e=t.allowedRoots,n={read_note:Su({description:"Read a note's full markdown content by vault path.",inputSchema:Au({path:Fo("Vault path to the note, e.g. Notes/Foo.md")},["path"]),readOnly:!0,execute:async({path:i})=>{let o=ku(String(i),{allowedRoots:e}),s=r.vault.getAbstractFileByPath(o);if(!(s instanceof _M.TFile))return{found:!1,path:o};let a=await r.vault.cachedRead(s);return{found:!0,path:o,content:a.length>pW?a.slice(0,pW)+`
- \u2026[truncated]`:a}}}),list_notes:Su({description:"List markdown notes, optionally within a folder.",inputSchema:Au({folder:Fo("Folder to list (omit for the whole vault)."),limit:mW("Max results (default 100, capped at 200).")},[]),readOnly:!0,execute:async({folder:i,limit:o})=>{let s=i?ku(String(i),{allowedRoots:e}):"",a=gW(hW(o,Sne),1,Ane),l=Xo(r,s).filter(c=>_u(c.path,e));return{total:l.length,notes:l.slice(0,a).map(c=>({path:c.path,basename:c.basename}))}}}),search_notes:Su({description:"Search notes by name and/or content. Returns matching paths with a short snippet.",inputSchema:Au({query:Fo("Text to search for."),in:fW(["name","content","both"],"Where to search (default both)."),limit:mW("Max results (default 25, capped at 50).")},["query"]),readOnly:!0,execute:async({query:i,in:o,limit:s})=>{let a=String(i).toLowerCase(),l=o??"both",c=gW(hW(s,Ine),1,Pne),d=r.vault.getMarkdownFiles().filter(h=>_u(h.path,e)),u=[],p=0,m=!1;for(let h of d){if(u.length>=c)break;if(l!=="content"&&h.basename.toLowerCase().includes(a)){u.push({path:h.path});continue}if(l!=="name"){if(p>=$ne){m=!0;continue}p++;let v=await r.vault.cachedRead(h),b=v.toLowerCase().indexOf(a);b>=0&&u.push({path:h.path,snippet:Mne(v,b)})}}return{results:u,scannedFiles:p,truncated:u.length>=c||m}}}),get_property_values:Su({description:"List the distinct values a frontmatter property takes across the vault (e.g. existing tags or statuses).",inputSchema:Au({field:Fo("Frontmatter property name."),folder:Fo("Optional folder scope.")},["field"]),readOnly:!0,execute:async({field:i,folder:o})=>{let s=o?ku(String(o),{allowedRoots:e}):"",a=(o?Xo(r,s):r.vault.getMarkdownFiles()).filter(c=>_u(c.path,e)),l=new Set;for(let c of a){let u=r.metadataCache.getFileCache(c)?.frontmatter?.[String(i)];if(u!=null){for(let p of Array.isArray(u)?u:[u])if(typeof p!="object"){let m=String(p).trim();m&&l.add(m)}}}return{field:String(i),values:[...l].sort().slice(0,200)}}}),create_note:Su({description:"Create a new markdown note. Fails if the path already exists.",inputSchema:Au({path:Fo("Vault path for the new note."),content:Fo("Initial markdown content.")},["path"]),needsApproval:!0,execute:async({path:i,content:o})=>{let s=ku(TM(String(i)),{allowedRoots:e});return await of(r,s),await Fne(r,s),{created:!0,path:(await r.vault.create(s,String(o??""))).path}}}),append_to_note:Su({description:"Append text to an existing note (frontmatter-aware for top inserts).",inputSchema:Au({path:Fo("Vault path to the existing note."),content:Fo("Markdown to append."),position:fW(["top","bottom"],"Where to add it (default bottom).")},["path","content"]),needsApproval:!0,execute:async({path:i,content:o,position:s})=>{let a=ku(TM(String(i)),{allowedRoots:e}),l=vW(r,a);await of(r,a);let c=String(o);return await Co(r,l,d=>s==="top"?w2(d,c.endsWith(`
- `)?c:c+`
- `):`${d}${d.endsWith(`
- `)||d.length===0?"":`
- `}${c}`),{appended:!0,path:a}}}),insert_under_heading:Su({description:"Insert markdown under an existing heading (matched exactly). Errors if the heading is not found.",inputSchema:Au({path:Fo("Vault path to the existing note."),heading:Fo("Exact heading text (without the # markers)."),content:Fo("Markdown to insert under the heading.")},["path","heading","content"]),needsApproval:!0,execute:async({path:i,heading:o,content:s})=>{let a=ku(TM(String(i)),{allowedRoots:e}),l=vW(r,a);await of(r,a);let c=r.metadataCache.getFileCache(l)?.headings??[],d=c.find(b=>b.heading===String(o));if(!d)throw new Error(`Heading "${o}" not found in ${a}`);let u=await r.vault.read(l),p=u.split(`
- `),m=d.position.start.line,g=(c.find(b=>b.position.start.line>m&&b.level<=d.level)?.position.start.line??p.length)-1;for(;g>m&&p[g].trim()==="";)g--;let v=$f(String(s),u,g,!1);return await r.vault.modify(l,v.content),{inserted:!0,path:a,heading:String(o)}}})};return Ff(n,t)}function Su(r){return{...r,__qaTool:!0}}function Au(r,t){return{type:"object",properties:r,required:t}}function Fo(r){return{type:"string",description:r}}function mW(r){return{type:"integer",description:r}}function fW(r,t){return{type:"string",enum:r,description:t}}function hW(r,t){let e=Number(r);return Number.isFinite(e)?Math.floor(e):t}function gW(r,t,e){return Math.max(t,Math.min(e,r))}function TM(r){if(/\.md$/i.test(r))return r;if(/\.[a-z0-9]+$/i.test(r))throw new Error(`This tool only operates on markdown notes (.md); refused path: "${r}".`);return`${r}.md`}function vW(r,t){let e=r.vault.getAbstractFileByPath(t);if(!(e instanceof _M.TFile))throw new Error(`Note not found: ${t}`);return e}async function Fne(r,t){let e=t.lastIndexOf("/");if(e<=0)return;let n=t.slice(0,e);if(!r.vault.getAbstractFileByPath(n))try{await r.vault.createFolder(n)}catch{}}function Mne(r,t){let e=Math.max(0,t-40);return r.slice(e,t+80).replace(/\s+/g," ").trim()}var _M,pW,Sne,Ane,Ine,Pne,$ne,bW=x(()=>{_M=require("obsidian");gi();v_();Rc();Ds();y_();dW();i$();b_();pW=16e3,Sne=100,Ane=200,Ine=25,Pne=50,$ne=400});function CW(r,t={}){let e=t.allowedRoots,n=()=>{let s=r.workspace.getActiveFile();return!(s instanceof w_.TFile)||s.extension!=="md"?null:_u(s.path,e)?s:null},i=()=>{let s=r.workspace.getActiveViewOfType(w_.MarkdownView);return s&&_u(s.file?.path,e)?s:null},o={get_active_note:Wy({description:"Get the currently active note (path, basename, and content). Returns active:null if there is none.",inputSchema:{type:"object",properties:{}},readOnly:!0,execute:async()=>{let s=n();if(!s)return{active:null};let a=await r.vault.cachedRead(s);return{active:{path:s.path,basename:s.basename,content:a.length>wW?a.slice(0,wW)+`
- \u2026[truncated]`:a}}}}),get_selection:Wy({description:"Get the text currently selected in the active editor (empty string if none).",inputSchema:{type:"object",properties:{}},readOnly:!0,execute:async()=>({selection:i()?.editor?.getSelection()??""})})};return Ff(o,t)}var w_,wW,xW=x(()=>{w_=require("obsidian");y_();b_();wW=16e3});function EW(r={}){let t={get_date:Wy({description:"Get the current date/time. Optionally pass a moment.js format and a day offset.",inputSchema:{type:"object",properties:{format:{type:"string",description:"moment.js format, e.g. YYYY-MM-DD"},offset:{type:"integer",description:"Day offset from today (e.g. 1 = tomorrow)."}}},readOnly:!0,execute:async({format:e,offset:n})=>({date:$a({format:e!=null?String(e):void 0,offset:n!=null?Number(n):void 0})})})};return Ff(t,r)}var TW=x(()=>{bw();b_()});function kW(r,t,e,n){async function i(s,a){let l=U.getState();if(l.disableOnlineFeatures)throw new Error("Rejecting request to `prompt` via API AI module. Online features are disabled in settings.");let{model:c,provider:d}=Vv(s),u=await So(r,d);return a?.assignToVariable&&p_(a.assignToVariable),{model:c,provider:d,apiKey:u,modelOptions:a?.modelOptions??{},outputVariableName:a?.assignToVariable||a?.variableName||"output",showAssistantMessages:a?.showAssistantMessages??!0,systemPrompt:a?.systemPrompt??l.ai.defaultSystemPrompt}}function o(s,a,l){if(!s)return Me(new Error("AI Assistant returned null"),l),{};if(a?.shouldAssignVariables||a?.assignToVariable)for(let[c,d]of Object.entries(s))e.variables.set(c,d);return s}return{prompt:async(s,a,l)=>{let c=await Lz(r,{...await i(a,l),prompt:s},(d,u)=>n(d,u,!1));return o(c,l,"AI Prompt error")},chunkedPrompt:async(s,a,l,c,d)=>{let u=await iF(r,{...await i(l,c),text:s,promptTemplate:a,chunkSeparator:c?.chunkSeparator??/\n/,resultJoiner:c?.chunkJoiner??`
- `,shouldMerge:c?.shouldMerge??!0,maxChunkTokens:c?.maxChunkTokens},(p,m)=>n(p,{...d,...m},!1));return o(u,c,"Chunked AI Prompt error")},getModels:()=>eU(),getMaxTokens:s=>Vv(s).model.maxTokens,estimateTokens(s){return Ci(s)},countTokens(s,a){return _W||(_W=!0,S.logMessage("quickAddApi.ai.countTokens is deprecated and now returns a provider-agnostic estimate (the model argument is ignored). Use estimateTokens(text) instead.")),Ci(s)},getRequestLogs(s=10){return vz(s)},getRequestLogById(s){return bz(s)},getLastRequestLog(){return wz()},clearRequestLogs(){Cz()},agent:s=>new m_(r,t,e,s),tool:s=>({...s,__qaTool:!0}),stepCountIs:s=>({stepNumber:a})=>a>=s,hasToolCall:s=>({toolCallNames:a})=>a.includes(s),tools:{vault:s=>yW(r,s),workspace:s=>CW(r,s),system:s=>EW(s)}}}var _W,SW=x(()=>{oF();Dm();kc();Nv();JH();hM();bW();xW();TW();je();nt();ye();_W=!1});function AW(r){return{getFieldValues:async(t,e)=>{let n=e?.includeInlineCodeBlocks?.map(a=>a.trim().toLowerCase()).filter(a=>a.length>0),i={folder:e?.folder,folders:e?.folders,tags:e?.tags,inline:e?.includeInline??!1,inlineCodeBlocks:n},o=r.vault.getMarkdownFiles();o=Os.filterFiles(o,i,a=>r.metadataCache.getFileCache(a));let s=new Set;for(let a of o){let c=r.metadataCache.getFileCache(a)?.frontmatter?.[t];if(c!=null){if(Array.isArray(c))c.forEach(d=>{if(d==null||typeof d=="object")return;let u=String(d).trim();u&&s.add(u)});else if(typeof c!="object"){let d=String(c).trim();d&&s.add(d)}}if(i.inline)try{let d=await r.vault.cachedRead(a);gf.getFieldValues(d,t,{includeCodeBlocks:n}).forEach(p=>s.add(p))}catch{}}return Array.from(s).sort()},clearCache:t=>{cl.getInstance().clear(t)}}}var IW=x(()=>{gT();Nw();gF()});function PW(r){return{entries:Array.from(r.entries()),dateFormats:x0(r)}}function $W(r,t){r.clear();for(let[e,n]of t.entries)r.set(e,n);ng(r,t.dateFormats)}var qn,Mf,kM=x(()=>{xu();Pd();BT();VT();is();Tf();nt();bw();jF();zH();SW();IW();qn=class qn{static GetApi(t,e,n,i){let o=async(a,l,c=!0)=>{let d=c?PW(n.variables):null;l&&Object.keys(l).forEach(u=>{n.variables.set(u,l[u])});try{let u=new _i(t,e,n);return i&&(u.choiceChain=i),await u.formatFileContent(a)}finally{d&&$W(n.variables,d)}},s=async(a,l,c)=>{let d;try{d=e.getChoiceByName(a)}catch{d=void 0}if(!d){Me(new Error(`Choice named '${a}' not found`),"API executeChoice error");return}if(!Ef(n,c?.date)){Me(new Error(`Could not parse date origin '${String(c?.date)}'`),"API executeChoice error");return}l&&Object.keys(l).forEach(p=>{n.variables.set(p,l[p])}),await n.execute(d,i);let u=n.consumeAbortSignal?.();if(n.variables.clear(),ng(n.variables,new Map),u)throw u};return{requestInputs:a=>qH(t,n,a),inputPrompt:(a,l,c,d)=>{let u=n?.promptProvider;return u?u.inputPrompt(a,l,c):qn.inputPrompt(t,a,l,c,d)},datePrompt:(a,l)=>{let c=n?.promptProvider;return c?c.datePrompt(a,l):qn.datePrompt(t,a,l)},wideInputPrompt:(a,l,c,d)=>{let u=n?.promptProvider;return u?u.wideInputPrompt(a,l,c):qn.wideInputPrompt(t,a,l,c,d)},yesNoPrompt:(a,l)=>{let c=n?.promptProvider;return c?c.yesNoPrompt(a,l):qn.yesNoPrompt(t,a,l)},infoDialog:(a,l)=>{let c=n?.promptProvider;return c?c.infoDialog(a,l):qn.infoDialog(t,a,l)},suggester:(a,l,c,d=!1,u)=>{let p=n?.promptProvider;return p?p.suggester(a,l,c,d):qn.suggester(t,a,l,c,d,u)},checkboxPrompt:(a,l,c)=>{let d=n?.promptProvider;return d?d.checkboxPrompt(a,l,c):qn.checkboxPrompt(t,a,l,c)},executeChoice:(...a)=>NO(s(...a)),applyTemplateToActiveFile:async(a,l)=>{if(!a)throw new Error("applyTemplateToActiveFile requires a template path.");if(!Bc(a))throw new Error("applyTemplateToActiveFile only supports markdown templates. Canvas and base templates cannot be applied to a markdown note.");if(l?.mode!==void 0&&!J2(l.mode))throw new Error(`Invalid mode '${String(l.mode)}'. Valid modes: ${Ay.map(d=>d.id).join(", ")}.`);let c=PW(n.variables);try{return await Iy(t,e,{templatePath:a,mode:l?.mode,choiceExecutor:n,chain:i})}finally{$W(n.variables,c)}},format:o,ai:kW(t,e,n,o),utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async a=>await navigator.clipboard.writeText(a),getSelection:()=>el(t),getSelectedText:()=>{let a=mn(t);return a?a.editor.somethingSelected()?a.editor.getSelection():(Me(new Error("No text selected"),"Could not get selected text"),""):(Me(new Error("No active Markdown editor"),"Could not get selected text"),"")}},date:{now:(a,l)=>$a({format:a,offset:l}),tomorrow:a=>$a({format:a,offset:1}),yesterday:a=>$a({format:a,offset:-1})},fieldSuggestions:AW(t)}}};qn.inputPrompt=ta.inputPrompt,qn.datePrompt=ta.datePrompt,qn.wideInputPrompt=ta.wideInputPrompt,qn.yesNoPrompt=ta.yesNoPrompt,qn.infoDialog=ta.infoDialog,qn.suggester=ta.suggester,qn.checkboxPrompt=ta.checkboxPrompt;Mf=qn});function Rne(r){return r!==null&&typeof r=="object"}function FW(r){return typeof r=="function"}async function MW(r,t){let{app:e,plugin:n,choiceName:i,params:o,executor:s,preloadedUserScripts:a,promptLabel:l}=t,c=ox(r),d=c===void 0?void 0:a.get(c);c!==void 0&&d!==void 0&&a.delete(c),d===void 0&&(d=await Zd(r,e));let u=d?.script;if(!u){S.logError(`failed to load user script ${r.path}.`);return}r.settings||(r.settings={});let p=d?.settings;p&&km(r.settings,p);async function m(g){let v=await xT(e,n,r,p);return{output:await g(o,v)}}async function h(g){if(FW(g))return m(g);if(Rne(g)){if(Object.keys(g).length===0)throw new Error(`user script in macro for '${i}' is an empty object`);if(FW(g.entry))return m(g.entry);let v=Object.keys(g);try{let b=String(await Ki(s,{remote:y=>Qi(y,{items:v.map(C=>({value:C,title:C})),placeholder:l,what:"the user-script member picker"}),headless:()=>{if(v.length===1)return Promise.resolve(v[0]);throw new ue("This macro's user script exports multiple members and needs to ask which one to run, but this run is non-interactive. Reference a single member (e.g. myScript::start), or re-run with the ui flag.")},app:()=>It.Suggest(e,v,v,l)}));if(!Object.hasOwn(g,b))throw new Error(`This macro's user script does not export a member named "${b}".`);return await h(g[b])}catch(b){throw b instanceof at?b:Be(b)?new et("Input cancelled by user"):b}}switch(typeof g){case"bigint":case"boolean":case"number":case"string":return{output:g.toString()};case"object":return;default:S.logError(`user script in macro for '${i}' is invalid`)}}try{return await h(u)}catch(g){throw g instanceof at||Me(g,`Failed to run user script ${r.name} in "${i}"`),g}}var RW=x(()=>{eu();ex();kF();ye();nt();ti();kn();rr();Gi();wu();Cu()});var Rf,SM=x(()=>{NF();Rf=class extends vf{}});function LW(r){if(!r)return!1;let t=r,e=t.getViewState?.();return!!t.pinned||!!e?.pinned||!!e?.state?.pinned}function C_(r){let t=r.workspace;return(t.rootSplit?t.getMostRecentLeaf?.(t.rootSplit):null)??t.getMostRecentLeaf?.()??null}function AM(r){return r.workspace.getActiveViewOfType(Uc.View)?.leaf??null}function Dne(r){let t=[];return r.workspace.iterateRootLeaves(e=>{t.includes(e)||t.push(e)}),t}function DW(r){return r.parent?.id??r.parent??null}function One(r,t){let e=DW(t),n=r.filter(s=>s===t||LW(s)?!1:e===null||DW(s)!==e);if(n.length===0)return null;let i=r.indexOf(t);return(i===-1?r:[...r.slice(i+1),...r.slice(0,i)]).find(s=>n.includes(s))??n[0]}function Lne(r){return r instanceof Uc.TFile?!0:typeof r=="object"&&r!==null&&"path"in r&&typeof r.path=="string"&&"extension"in r&&typeof r.extension=="string"}function Nne(r,t,e,n){if(n&&(t==="tab"||t==="reuse")&&LW(n))return One(Dne(r),n)??r.workspace.getLeaf("tab");switch(t){case"reuse":return r.workspace.getLeaf(!1);case"tab":return r.workspace.getLeaf("tab");case"split":return r.workspace.getLeaf("split",e);case"window":return r.workspace.getLeaf("window");case"left-sidebar":return r.workspace.getLeftLeaf(!0);case"right-sidebar":return r.workspace.getRightLeaf(!0);default:return r.workspace.getLeaf("tab")}}async function x_(r,t,e={}){let{location:n="tab",direction:i="vertical",mode:o,focus:s=!0,eState:a,originLeaf:l}=e,c=typeof t=="string"?r.vault.getAbstractFileByPath(t):t;if(!Lne(c)){let m=typeof t=="string"?t:t.path;throw new Error(`File not found: ${m}`)}let d=l??C_(r),u=s?null:AM(r),p=Nne(r,n,i,d);if(!p)throw new Error("Could not obtain a workspace leaf.");if(u&&AM(r)!==u&&r.workspace.setActiveLeaf(u,{focus:!1}),s?await p.openFile(c):await p.openFile(c,{active:!1}),o&&o!=="default"&&!(typeof o=="object"&&o.mode==="default")){let m=p.getViewState(),h={...m.state??{}};o==="preview"||typeof o=="object"&&o.mode==="preview"?(h.mode="preview",delete h.source):o==="source"?(h.mode="source",h.source=!0):o==="live"||o==="live-preview"?(h.mode="source",h.source=!1):typeof o=="object"&&o.mode==="source"&&(h.mode="source",h.source=o.source),await p.setViewState({...m,...!s&&{active:!1},state:{...h,...a}})}return s&&r.workspace.setActiveLeaf(p,{focus:!0}),p}function OW(r){return(0,Uc.normalizePath)(r).replace(/\/{2,}/g,"/").replace(/^\/+/,"")}function Vne(r,t){return OW(r)===OW(t)}function NW(r,t,e=!0){let n,i=AM(r);return r.workspace.iterateRootLeaves(o=>{if(n&&n===i)return;let s=o.view;if(s instanceof Uc.FileView&&s.file&&(s.file===t||Vne(t.path,s.file.path))){n=o;return}}),n!==void 0?(e&&r.workspace.setActiveLeaf(n,{focus:!0}),n):null}var Uc,E_=x(()=>{Uc=require("obsidian")});async function BW(r,t){return r.mode==="script"?await t.evaluateScriptCondition(r):Bne(r,t.variables)}function Bne(r,t){let e=r.variableName?.trim();if(!e)return S.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(e in t))return r.operator==="isFalsy";let n=t[e];switch(r.operator){case"isTruthy":return!!n;case"isFalsy":return!n}if(ql(r.operator)){let i=b0(r);return i===void 0?(S.logWarning(`Conditional command: Operator '${r.operator}' requires a comparison value.`),!1):r.operator==="contains"?VW(n,i,r):r.operator==="notContains"?!VW(n,i,r):Une(n,i,r)}return!1}function VW(r,t,e){if(r==null)return!1;if(typeof t=="string"&&t.length===0)return S.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1;if(Array.isArray(r))return r.map(o=>jS(o,e.valueType)).some(o=>o===t);if(typeof r=="string")return r.includes(Fs(t));if(typeof r=="number"&&typeof t=="number")return r===t;let n=Fs(r),i=Fs(t);return typeof n=="string"&&n.includes(i)}function Une(r,t,e){let n=jS(r,e.valueType);switch(e.operator){case"equals":return n===t;case"notEquals":return n!==t;case"lessThan":return T_(n,t,(i,o)=>i<o);case"lessThanOrEqual":return T_(n,t,(i,o)=>i<=o);case"greaterThan":return T_(n,t,(i,o)=>i>o);case"greaterThanOrEqual":return T_(n,t,(i,o)=>i>=o);default:return!1}}function T_(r,t,e){let n=Number(r),i=Number(t);return Number.isNaN(n)||Number.isNaN(i)?(S.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):e(n,i)}var UW=x(()=>{ye();Hl()});function qW(r,t=void 0){return r==="horizontal"?"horizontal":r==="vertical"?"vertical":t}function qc(r,t,e){return e?{location:r,direction:e,focus:t,mode:"default"}:{location:r,focus:t,mode:"default"}}function zW(r){let t=r.focus??!0;if(r.location)switch(r.location){case"reuse":return qc("reuse",t);case"tab":return qc("tab",t);case"split":return qc("split",t,qW(r.direction,"vertical"));case"window":return qc("window",t);case"left-sidebar":return qc("left-sidebar",t);case"right-sidebar":return qc("right-sidebar",t);default:break}let e=r.openInNewTab??!1,n=qW(r.direction);return e?qc("split",t,n??"vertical"):qc("reuse",t)}var HW=x(()=>{Rx()});function WW(r){let t={hasOwnProperty:e=>r.has(e)};return new Proxy(t,{get(e,n){if(n==="hasOwnProperty")return t.hasOwnProperty;if(typeof n=="string")return r.get(n)},set(e,n,i){return typeof n!="string"||r.set(n,i),!0},deleteProperty(e,n){return typeof n!="string"||r.delete(n),!0},has(e,n){return typeof n=="string"&&r.has(n)},ownKeys(){return Array.from(r.keys())},getOwnPropertyDescriptor(e,n){if(n==="hasOwnProperty")return{value:t.hasOwnProperty,writable:!0,configurable:!0,enumerable:!1};if(!(typeof n!="string"||!r.has(n)))return{value:r.get(n),writable:!0,configurable:!0,enumerable:!0}}})}var GW=x(()=>{});function jW(r,t="command"){if(typeof r!="string"||!r.trim())return`the saved entry has no ${t} type, so QuickAdd cannot tell what it was meant to do. It is in .obsidian/plugins/quickadd/data.json.`;let e=t==="command"?zne.get(r):void 0;return e||`QuickAdd does not recognise the ${t} type '${r}'. It can come from a newer version of QuickAdd, an imported package, or a hand-edited .obsidian/plugins/quickadd/data.json.`}function YW(r){return`${r.scriptPath}::${r.exportName??"default"}`}var qne,KW,zne,Xs,by=x(()=>{G2();TT();OT();GF();qne=Nj(require("obsidian"));ye();nt();Zt();kM();Pd();RW();SM();rs();eu();Wi();xP();CP();EP();TP();_P();kP();SP();AP();IP();PP();_p();xu();E_();KW=require("obsidian");ti();UW();yy();HW();GW();Hr();ZT();e_();If();zne=new Map([["InfiniteAIAssistant",'The "Infinite AI Assistant" command type was removed - no released version could ever run one. Delete the step from the macro. For chunked AI prompts, use quickAddApi.ai.chunkedPrompt() in a user script.']]);Xs=class extends Rf{constructor(e,n,i,o,s,a,l,c=null,d=[i]){super(e);this.originLeaf=c;this.chain=d;this.conditionalScriptCache=new Map;this.choice=i,this.plugin=n,this.macro=i?.macro,this.choiceExecutor=o,this.preloadedUserScripts=a??new Map,this.promptLabel=l;let u=this.initSharedVariables(o,s);this.choiceExecutor.variables=u,this.params=this.buildParams(e,n,o,u)}buildParams(e,n,i,o){let s=WW(o),a={app:e,quickAddApi:Mf.GetApi(e,n,i,this.chain),obsidian:qne,abort:l=>{throw new at(l)}};return Object.defineProperty(a,"variables",{get:()=>s,set:l=>{if(l===o||l===s)return;let c=l instanceof Map?Array.from(l.entries()).filter(([d])=>typeof d=="string"):l&&typeof l=="object"?Object.entries(l):null;c&&(o.clear(),ng(o,new Map),c?.forEach(([d,u])=>o.set(d,u)))},enumerable:!0,configurable:!1}),a}initSharedVariables(e,n){let i=e.variables;return n?(i&&n!==i&&i.forEach((o,s)=>{n.has(s)||n.set(s,o)}),n):i??new Map}async run(){if(Wt(this.macro?.commands))throw new Error(`Could not read the commands for macro '${this.choice.name}'. The saved value is not a list of commands - QuickAdd has not changed it. It is in .obsidian/plugins/quickadd/data.json.`);let e=Mt(this.macro?.commands);if(e.length===0){Pv(this.macro?.commands)||S.logError(`No commands in the macro for choice '${this.choice.name}'`);return}this.previousStep=void 0,await this.executeCommands(e)}getOutput(){return this.output}async executeCommands(e){try{for(let[n,i]of e.entries()){if(!i)continue;let o=i.type==="Choice"||i.type==="NestedChoice"?Sf(i,l=>Vc(this.plugin,l)):null,s=Y2(this.previousStep,i,l=>Vc(this.plugin,l));s&<(`templater-rerun:${this.choice.id}:${i.id}`,`Macro '${this.choice.name}' runs "Templater: Replace templates in the active file" after '${s}'. QuickAdd already runs Templater in the notes it creates and captures, so this step is deprecated and can run template code twice. Remove it from the macro.`),i.type!=="Wait"&&i.type!=="Conditional"&&(this.previousStep=i);let a=o?.collect.kind==="scanChoice"&&tM(o.collect.choice,this.choiceExecutor.variables.get("value"));await By(this.choiceExecutor,i.id,async()=>{switch(i.type){case"Obsidian":this.executeObsidianCommand(i);break;case"UserScript":await this.executeUserScript(i);break;case"Choice":await this.executeChoice(i);break;case"Wait":await kw(i.time);break;case"NestedChoice":await this.executeNestedChoice(i);break;case"EditorCommand":await this.executeEditorCommand(i);break;case"AIAssistant":await this.executeAIAssistant(i);break;case"OpenFile":await this.executeOpenFile(i);break;case"Conditional":await this.executeConditional(i);break;default:{let l=i.type;this.reportUnrunnableCommand(i,jW(l));break}}}),a&&await this.choiceExecutor.prepareMacroInputs(this.choice,e.slice(n+1))}}catch(n){if(Mc(n,{logPrefix:"Macro execution aborted",noticePrefix:"Macro execution aborted",defaultReason:"Macro execution aborted"})){this.choiceExecutor.signalAbort?.(n);return}throw n}}reportUnrunnableCommand(e,n){let i=typeof e?.name=="string"&&e.name.trim()?`'${e.name}'`:"an unnamed command";S.logError(`Skipped ${i} in the macro for '${this.choice.name}': ${n} QuickAdd did not stop the macro, so its result may be incomplete.`)}async executeUserScript(e){let n=await MW(e,{app:this.app,plugin:this.plugin,choiceName:this.choice.name,params:this.params,executor:this.choiceExecutor,preloadedUserScripts:this.preloadedUserScripts,promptLabel:this.promptLabel});n&&(this.output=n.output)}executeObsidianCommand(e){let n=this.app.commands.commands;if(n&&!n[e.commandId]){S.logError(`Obsidian command '${e.name}' is no longer available.`);return}p2(this.chain,()=>this.app.commands.executeCommandById(e.commandId))}async executeChoice(e){let n;try{n=this.plugin.getChoiceById(e.choiceId)}catch(o){let s=o instanceof Error?o.message:String(o);if(!/not found/i.test(s))throw o;S.logError(`choice '${e.name}' could not be found.`);return}await this.choiceExecutor.execute(n,this.chain);let i=this.choiceExecutor.consumeAbortSignal?.();if(i)throw i}async executeNestedChoice(e){let n=e.choice;if(!n){S.logError(`choice in ${e.name} is invalid`);return}await this.choiceExecutor.execute(n,this.chain);let i=this.choiceExecutor.consumeAbortSignal?.();if(i)throw i}async executeEditorCommand(e){switch(e.editorCommandType){case"Cut":await Nm.run(this.app);break;case"Copy":await Lm.run(this.app);break;case"Paste":await Vm.run(this.app);break;case"Paste with format":await Bm.run(this.app);break;case"Select active line":Um.run(this.app);break;case"Select link on active line":qm.run(this.app);break;case"Move cursor to file start":zm.run(this.app);break;case"Move cursor to file end":Hm.run(this.app);break;case"Move cursor to line start":Wm.run(this.app);break;case"Move cursor to line end":Gm.run(this.app);break;default:{let n=e.editorCommandType;this.reportUnrunnableCommand(e,jW(n,"editor command"))}}}async executeAIAssistant(e){return H2(this.app,this.choice,this.choiceExecutor,this.chain,e,()=>this.pickModelInteractively())}async pickModelInteractively(){return W2(this.app,this.choiceExecutor)}async executeConditional(e){let n=await BW(e.condition,{variables:this.params.variables,evaluateScriptCondition:async s=>await this.evaluateScriptCondition(s)}),i=n?e.thenCommands:e.elseCommands;if(Wt(i))throw new Error(`Could not read the ${n?"then":"else"} commands for '${e.name}'. The saved value is not a list of commands - QuickAdd has not changed it. It is in .obsidian/plugins/quickadd/data.json.`);if(!Array.isArray(i)||i.length===0)return;await this.executeCommands(i);let o=this.choiceExecutor.consumeAbortSignal?.();if(o)throw o}async runSubset(e){e?.length&&await this.executeCommands(e)}setOutput(e){this.output=e}async evaluateScriptCondition(e){let n=YW(e),i=this.conditionalScriptCache.get(n);if(!i){if(i=await this.loadConditionalScript(e),!i)return!1;this.conditionalScriptCache.set(n,i)}let o;try{o=await i()}catch(s){throw Me(s,`Failed to evaluate conditional script '${e.scriptPath}'.`),s}return typeof o!="boolean"?(S.logWarning(`Conditional script '${e.scriptPath}' must return a boolean result.`),!1):o}async loadConditionalScript(e){try{let n=await $v(this.buildConditionalUserScript(e),this.app);return n==null?void 0:typeof n=="function"?async()=>await n(this.params):async()=>n}catch(n){throw Me(n,`Failed to load conditional script '${e.scriptPath}'.`),n}}buildConditionalUserScript(e){return{id:`conditional-script-${YW(e)}`,name:e.exportName?`${e.scriptPath}::${e.exportName}`:e.scriptPath,type:"UserScript",path:e.scriptPath,settings:{}}}async executeOpenFile(e){try{let n=new _i(this.app,zr(),this.choiceExecutor);n.setPromptRunContext({choiceName:this.choice?.name,draftScopeId:`${this.choice?.id??"macro"}#openFile:${e.id}`}),n.choiceChain=this.chain;let o=(await n.formatFileName(e.filePath,"filePath")).replace(/\\/g,"/"),s=o.split("/");if(s.some((d,u)=>d===".."||d===""&&u!==0&&u!==s.length-1)){S.logError(`OpenFile: Path traversal not allowed in '${o}'`);return}let l=this.app.vault.getAbstractFileByPath(o);if(!l||!(l instanceof KW.TFile)){S.logError(`OpenFile: '${o}' does not exist or is not a file`);return}let c=zW(e);await x_(this.app,l,{...c,originLeaf:this.originLeaf})}catch(n){S.logError(`OpenFile: Failed to open file '${e.filePath}': ${n.message}`)}}}});var doe={};eb(doe,{default:()=>K_});module.exports=Vj(doe);var xj=require("obsidian");var ny=require("obsidian");var iR;typeof window<"u"&&((iR=window.__svelte??(window.__svelte={})).v??(iR.v=new Set)).add("5");var ua={};var Rt=Symbol("uninitialized"),Zi=Symbol("filename");var tb="http://www.w3.org/1999/xhtml";var oR=globalThis.process?.env?.NODE_ENV,j=oR&&!oR.toLowerCase().startsWith("prod");var eo=Array.isArray,sR=Array.prototype.indexOf,yl=Array.prototype.includes,$u=Array.from,ok=Object.keys,Wr=Object.defineProperty,li=Object.getOwnPropertyDescriptor,rb=Object.getOwnPropertyDescriptors,nb=Object.prototype,aR=Array.prototype,bl=Object.getPrototypeOf,sk=Object.isExtensible;var $t=()=>{};function ib(r){for(var t=0;t<r.length;t++)r[t]()}function ob(){var r,t,e=new Promise((n,i)=>{r=n,t=i});return{promise:e,resolve:r,reject:t}}function ak(r,t){if(Array.isArray(r))return r;if(t===void 0||!(Symbol.iterator in r))return Array.from(r);let e=[];for(let n of r)if(e.push(n),e.length===t)break;return e}var vn=Symbol("$state"),sb=Symbol("component"),Hf=Symbol("legacy props"),lR=Symbol(""),ab=Symbol("proxy path"),lb=Symbol("attributes"),Wf=Symbol("class"),Gf=Symbol("style"),jf=Symbol("text"),wl=Symbol("form reset"),lk=Symbol("hmr anchor"),pa=new class extends Error{constructor(){super(...arguments);fe(this,"name","StaleReactionError");fe(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},cb=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");var Wc=3,ki=8;var ma="font-weight: bold",fa="font-weight: normal";function cR(r){j?console.warn(`%c[svelte] await_reactivity_loss
- %cDetected reactivity loss when reading \`${r}\`. This happens when state is read in an async function after an earlier \`await\`
- https://svelte.dev/e/await_reactivity_loss`,ma,fa):console.warn("https://svelte.dev/e/await_reactivity_loss")}function dR(r,t){j?console.warn(`%c[svelte] await_waterfall
- %cAn async derived, \`${r}\` (${t}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app
- https://svelte.dev/e/await_waterfall`,ma,fa):console.warn("https://svelte.dev/e/await_waterfall")}function uR(){j?console.warn(`%c[svelte] derived_inert
- %cReading a derived belonging to a now-destroyed effect may result in stale values
- https://svelte.dev/e/derived_inert`,ma,fa):console.warn("https://svelte.dev/e/derived_inert")}function pR(r,t,e){j?console.warn(`%c[svelte] hydration_attribute_changed
- %cThe \`${r}\` attribute on \`${t}\` changed its value between server and client renders. The client value, \`${e}\`, will be ignored in favour of the server value
- https://svelte.dev/e/hydration_attribute_changed`,ma,fa):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function Gc(r){j?console.warn(`%c[svelte] hydration_mismatch
- %c${r?`Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${r}`:"Hydration failed because the initial UI does not match what was rendered on the server"}
- https://svelte.dev/e/hydration_mismatch`,ma,fa):console.warn("https://svelte.dev/e/hydration_mismatch")}function mR(){j?console.warn(`%c[svelte] lifecycle_double_unmount
- %cTried to unmount a component that was not mounted
- https://svelte.dev/e/lifecycle_double_unmount`,ma,fa):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function fR(){j?console.warn("%c[svelte] select_multiple_invalid_value\n%cThe `value` property of a `<select multiple>` element should be an array, but it received a non-array value. The selection will be kept as is.\nhttps://svelte.dev/e/select_multiple_invalid_value",ma,fa):console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function db(r){j?console.warn(`%c[svelte] state_proxy_equality_mismatch
- %cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${r}\` will produce unexpected results
- https://svelte.dev/e/state_proxy_equality_mismatch`,ma,fa):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function hR(){j?console.warn("%c[svelte] svelte_boundary_reset_noop\n%cA `<svelte:boundary>` `reset` function only resets the boundary the first time it is called\nhttps://svelte.dev/e/svelte_boundary_reset_noop",ma,fa):console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var xe=!1;function Ir(r){xe=r}var Oe;function Tt(r){if(r===null)throw Gc(),ua;return Oe=r}function Gr(){return Tt(bn(Oe))}function $(r){if(xe){if(bn(Oe)!==null)throw Gc(),ua;Oe=r}}function Xt(r=1){if(xe){for(var t=r,e=Oe;t--;)e=bn(e);Oe=e}}function us(r=!0){for(var t=0,e=Oe;;){if(e.nodeType===ki){var n=e.data;if(n==="]"){if(t===0)return e;t-=1}else(n==="["||n==="[!"||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(t+=1)}var i=bn(e);r&&e.remove(),e=i}}function Kf(r){if(!r||r.nodeType!==ki)throw Gc(),ua;return r.data}function ub(r){return r===this.v}function pb(r,t){return r!=r?t==t:r!==t||r!==null&&typeof r=="object"||typeof r=="function"}function mb(r){return!pb(r,this.v)}function gR(r){if(j){let t=new Error(`invariant_violation
- An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app \u2014 please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${r}"
- https://svelte.dev/e/invariant_violation`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/invariant_violation")}function Qf(r){if(j){let t=new Error(`lifecycle_outside_component
- \`${r}(...)\` can only be used during component initialisation
- https://svelte.dev/e/lifecycle_outside_component`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function yR(){if(j){let r=new Error("async_derived_orphan\nCannot create a `$derived(...)` with an `await` expression outside of an effect tree\nhttps://svelte.dev/e/async_derived_orphan");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/async_derived_orphan")}function ck(){if(j){let r=new Error("bind_invalid_checkbox_value\nUsing `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\nhttps://svelte.dev/e/bind_invalid_checkbox_value");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/bind_invalid_checkbox_value")}function bR(){if(j){let r=new Error(`derived_references_self
- A derived value cannot reference itself recursively
- https://svelte.dev/e/derived_references_self`);throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/derived_references_self")}function dk(r,t,e){if(j){let n=new Error(`each_key_duplicate
- ${e?`Keyed each block has duplicate key \`${e}\` at indexes ${r} and ${t}`:`Keyed each block has duplicate key at indexes ${r} and ${t}`}
- https://svelte.dev/e/each_key_duplicate`);throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/each_key_duplicate")}function wR(r,t,e){if(j){let n=new Error(`each_key_volatile
- Keyed each block has key that is not idempotent \u2014 the key for item at index ${r} was \`${t}\` but is now \`${e}\`. Keys must be the same each time for a given item
- https://svelte.dev/e/each_key_volatile`);throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/each_key_volatile")}function CR(r){if(j){let t=new Error(`effect_in_teardown
- \`${r}\` cannot be used inside an effect cleanup function
- https://svelte.dev/e/effect_in_teardown`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_in_teardown")}function xR(){if(j){let r=new Error("effect_in_unowned_derived\nEffect cannot be created inside a `$derived` value that was not itself created inside an effect\nhttps://svelte.dev/e/effect_in_unowned_derived");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function ER(r){if(j){let t=new Error(`effect_orphan
- \`${r}\` can only be used inside an effect (e.g. during component initialisation)
- https://svelte.dev/e/effect_orphan`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_orphan")}function TR(){if(j){let r=new Error(`effect_update_depth_exceeded
- Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state
- https://svelte.dev/e/effect_update_depth_exceeded`);throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function _R(){if(j){let r=new Error(`hydration_failed
- Failed to hydrate the application
- https://svelte.dev/e/hydration_failed`);throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/hydration_failed")}function kR(){if(j){let r=new Error("invalid_snippet\nCould not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`\nhttps://svelte.dev/e/invalid_snippet");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/invalid_snippet")}function SR(r){if(j){let t=new Error(`props_invalid_value
- Cannot do \`bind:${r}={undefined}\` when \`${r}\` has a fallback value
- https://svelte.dev/e/props_invalid_value`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/props_invalid_value")}function AR(r){if(j){let t=new Error(`rune_outside_svelte
- The \`${r}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files
- https://svelte.dev/e/rune_outside_svelte`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/rune_outside_svelte")}function IR(){if(j){let r=new Error("state_descriptors_fixed\nProperty descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\nhttps://svelte.dev/e/state_descriptors_fixed");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function PR(){if(j){let r=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/state_prototype_fixed")}function $R(){if(j){let r=new Error("state_unsafe_mutation\nUpdating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\nhttps://svelte.dev/e/state_unsafe_mutation");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function FR(){if(j){let r=new Error("svelte_boundary_reset_onerror\nA `<svelte:boundary>` `reset` function cannot be called while an error is still being handled\nhttps://svelte.dev/e/svelte_boundary_reset_onerror");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var ur=!1,ha=!1,Do=!1;var qj="font-weight: bold",zj="font-weight: normal";function uk(r){j?console.warn(`%c[svelte] state_snapshot_uncloneable
- %c${r?`The following properties cannot be cloned with \`$state.snapshot\` \u2014 the return value contains the originals:
- ${r}`:"Value cannot be cloned with `$state.snapshot` \u2014 the original value was returned"}
- https://svelte.dev/e/state_snapshot_uncloneable`,qj,zj):console.warn("https://svelte.dev/e/state_snapshot_uncloneable")}var Hj=[];function jc(r,t=!1,e=!1){if(j&&!t){let n=[],i=Xf(r,new Map,"",n,null,e);if(n.length===1&&n[0]==="")uk();else if(n.length>0){let o=n.length>10?n.slice(0,7):n.slice(0,10),s=n.length-o.length,a=o.map(l=>`- <value>${l}`).join(`
- `);s>0&&(a+=`
- - ...and ${s} more`),uk(a)}return i}return Xf(r,new Map,"",Hj,null,e)}function Xf(r,t,e,n,i=null,o=!1){if(typeof r=="object"&&r!==null){var s=t.get(r);if(s!==void 0)return s;if(r instanceof Map)return new Map(r);if(r instanceof Set)return new Set(r);if(eo(r)){var a=Array(r.length);t.set(r,a),i!==null&&t.set(i,a);for(var l=0;l<r.length;l+=1){var c=r[l];l in r&&(a[l]=Xf(c,t,j?`${e}[${l}]`:e,n,null,o))}return a}if(bl(r)===nb){a={},t.set(r,a),i!==null&&t.set(i,a);for(var d of Object.keys(r))a[d]=Xf(r[d],t,j?`${e}.${d}`:e,n,null,o);return a}if(r instanceof Date)return r.getTime(),structuredClone(r);if(typeof r.toJSON=="function"&&!o)return Xf(r.toJSON(),t,j?`${e}.toJSON()`:e,n,r)}if(r instanceof EventTarget)return r;try{return structuredClone(r)}catch{return j&&n.push(e),r}}var Jf=null;function In(r,t){return r.label=t,fb(r.v,t),r}function fb(r,t){return r?.[ab]?.(t),r}function Oo(r){let t=new Error,e=Wj();return e.length===0?null:(e.unshift(`
- `),Wr(t,"stack",{value:e.join(`
- `)}),Wr(t,"name",{value:r}),t)}function Wj(){let r=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let t=new Error().stack;if(Error.stackTraceLimit=r,!t)return[];let e=t.split(`
- `),n=[];for(let i=0;i<e.length;i++){let o=e[i],s=o.replaceAll("\\","/");if(o.trim()!=="Error"){if(o.includes("validate_each_keys"))return[];s.includes("svelte/src/internal")||s.includes("node_modules/.vite")||n.push(o)}}return n}function RR(r,t){if(!j)throw new Error("invariant(...) was not guarded by if (DEV)");r||gR(t)}var rt=null;function ga(r){rt=r}var ps=null;function Ru(r){ps=r}var Lo=null;function hb(r){Lo=r}function ie(r,t=!1,e){rt={p:rt,i:!1,c:null,e:null,s:r,x:null,r:we,l:ha&&!t?{s:null,u:null,$:[]}:null},j&&(rt.function=e,Lo=e)}function oe(r){var t=rt,e=t.e;if(e!==null){t.e=null;for(var n of e)pk(n)}return r!==void 0&&(t.x=r),t.i=!0,rt=t.p,j&&(Lo=rt?.function??null),Zf(r)}function Zf(r={}){return Wr(r,sb,{value:!0}),r}function No(){return!ha||rt!==null&&rt.l===null}var Yc=[];function DR(){var r=Yc;Yc=[],ib(r)}function br(r){if(Yc.length===0&&!Kc){var t=Yc;queueMicrotask(()=>{t===Yc&&DR()})}Yc.push(r)}function OR(){for(;Yc.length>0;)DR()}var Gj=-7169;function _t(r,t){r.f=r.f&Gj|t}function Du(r){(r.f&512)!==0||r.deps===null?_t(r,1024):_t(r,4096)}function LR(r){if(r!==null)for(let t of r)(t.f&2)===0||(t.f&65536)===0||(t.f^=65536,LR(t.deps))}function gb(r,t,e){(r.f&2048)!==0?t.add(r):(r.f&4096)!==0&&e.add(r),LR(r.deps),_t(r,1024)}var NR=!1,vb=!1;function mk(r){var t=vb;try{return vb=!1,[r(),vb]}finally{vb=t}}function Jc(r){xe&&Kr(r)!==null&&Lu(r)}var VR=!1;function yb(){VR||(VR=!0,document.addEventListener("reset",r=>{Promise.resolve().then(()=>{if(!r.defaultPrevented)for(let t of r.target.elements)t[wl]?.()})},{capture:!0}))}function no(r){var t=Pe,e=we;Fr(null),Mr(null);try{return r()}finally{Fr(t),Mr(e)}}function bb(r,t,e,n=e){r.addEventListener(t,()=>no(e));let i=r[wl];i?r[wl]=()=>{i(),n(!0)}:r[wl]=()=>n(!0),yb()}function wb(r,t,e,n){let i=No()?xl:Zc;var o=r.filter(m=>!m.settled),s=t.map(i);if(j&&s.forEach((m,h)=>{m.label=t[h].toString().replace("() => ","").replaceAll("$.eager(() => ","$state.eager(").replace(/\$\.get\((.+?)\)/g,(g,v)=>v)}),e.length===0&&o.length===0){n(s);return}var a=we,l=BR(),c=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(m=>m.promise)):null;function d(m){if((a.f&16384)===0){l();try{n([...s,...m])}catch(h){di(h,a)}Nu()}}var u=fk();if(e.length===0){c.then(()=>d([])).finally(u);return}function p(){Promise.all(e.map(m=>gk(m))).then(d).catch(m=>di(m,a)).finally(u)}c?c.then(()=>{l(),p(),Nu()}):p()}function BR(){var r=we,t=Pe,e=rt,n=_e;if(j)var i=ps;return function(s=!0){Mr(r),Fr(t),ga(e),s&&(r.f&16384)===0&&(n?.activate(),n?.apply()),j&&(hk(null),Ru(i))}}var Yj=!1;function Nu(r=!0){Yj=!1,Mr(null),Fr(null),ga(null),r&&_e?.deactivate(),j&&(hk(null),Ru(null))}function fk(){var r=we,t=r.b,e=_e,n=!!t?.is_rendered();return t?.update_pending_count(1,e),e.increment(n,r),()=>{t?.update_pending_count(-1,e),e.decrement(n,r)}}var ui=null;function hk(r){ui=r}var th=new Set;function xl(r){var t=2050;we!==null&&(we.f|=524288);let e={ctx:rt,deps:null,effects:null,equals:ub,f:t,fn:r,reactions:null,rv:0,v:Rt,wv:0,parent:we,ac:null};return j&&Do&&(e.created=Oo("created at")),e}var Vu=Symbol("obsolete");function gk(r,t,e){let n=we;n===null&&yR();var i=void 0,o=Fn(Rt);j&&(o.label=t??r.toString());var s=!Pe,a=new Set;return zR(()=>{var l=we;j&&(ui={effect:l,effect_deps:new Set,warned:!1});var c=ob();i=c.promise;try{Promise.resolve(r()).then(c.resolve,m=>{m!==pa&&c.reject(m)}).finally(Nu)}catch(m){c.reject(m),Nu()}if(j){if(ui){if(l.deps!==null)for(let m=0;m<Hn;m+=1)ui.effect_deps.add(l.deps[m]);if(Qr!==null)for(let m=0;m<Qr.length;m+=1)ui.effect_deps.add(Qr[m])}ui=null}var d=_e;if(s){if((l.f&32768)!==0)var u=fk();if(n.b?.is_rendered())d.async_deriveds.get(l)?.reject(Vu);else for(let m of a.values())m.reject(Vu);a.add(c),d.async_deriveds.set(l,c)}let p=(m,h=void 0)=>{j&&(ui=null),u?.(),a.delete(c),h!==Vu&&(d.activate(),h?(o.f|=8388608,Bo(o,h)):((o.f&8388608)!==0&&(o.f^=8388608),j&&e!==void 0&&!o.equals(m)&&(th.add(o),setTimeout(()=>{th.has(o)&&(l.f&16384)===0&&(dR(o.label,e),th.delete(o))})),Bo(o,m)),d.deactivate())};c.promise.then(p,m=>p(null,m||"unknown"))}),Yr(()=>{for(let l of a)l.reject(Vu)}),j&&(o.f|=4194304),new Promise(l=>{function c(d){function u(){d===i?l(o):c(i)}d.then(u,u)}c(i)})}function k(r){let t=xl(r);return ur||Eb(t),t}function Zc(r){let t=xl(r);return t.equals=mb,t}function UR(r){var t=r.effects;if(t!==null){r.effects=null;for(var e=0;e<t.length;e+=1)sr(t[e])}}var vk=[];function rh(r){var t,e=we,n=r.parent;if(!Si&&n!==null&&r.v!==Rt&&(n.f&24576)!==0)return uR(),r.v;if(Mr(n),j){let i=ed;Cb(new Set);try{yl.call(vk,r)&&bR(),vk.push(r),r.f&=-65537,UR(r),t=xb(r)}finally{Mr(e),Cb(i),vk.pop()}}else try{r.f&=-65537,UR(r),t=xb(r)}finally{Mr(e)}return t}function yk(r){var t=rh(r);if(!r.equals(t)&&(r.wv=Bu(),(!_e?.is_fork||r.deps===null)&&(_e!==null?(_e.capture(r,t,!0),ms?.capture(r,t,!0)):r.v=t,r.deps===null))){_t(r,1024);return}Si||(Xr!==null?(Cl()||_e?.is_fork)&&Xr.set(r,t):Du(r))}function qR(r){if(r.effects!==null)for(let t of r.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&no(()=>{t.ac.abort(pa),t.ac=null}),t.fn!==null&&(t.teardown=$t),td(t,0),nh(t))}function bk(r){if(r.effects!==null)for(let t of r.effects)t.teardown&&t.fn!==null&&fs(t)}var Tb=null,Uu=null,_e=null,ms=null,Xr=null,xk=null,Kc=!1,wk=!1,rd=null,sh=null,HR=0,Ck=new Set,Xj=1,zu,ba,wa,Hu,Wu,Gu,Ca,ju,Wn,ah,xa,Uo,hs,Yu,El,wt,Ek,ih,Tk,GR,jR,qu,YR,oh,_b=class _b{constructor(){qe(this,wt);fe(this,"id",Xj++);qe(this,zu,!1);fe(this,"linked",!0);qe(this,ba,null);qe(this,wa,null);fe(this,"async_deriveds",new Map);fe(this,"current",new Map);fe(this,"previous",new Map);qe(this,Hu,new Set);qe(this,Wu,new Set);qe(this,Gu,0);qe(this,Ca,new Map);qe(this,ju,null);qe(this,Wn,[]);qe(this,ah,[]);qe(this,xa,new Set);qe(this,Uo,new Set);qe(this,hs,new Map);qe(this,Yu,new Set);fe(this,"is_fork",!1);qe(this,El,!1);Uu===null?Tb=Uu=this:(De(Uu,wa,this),De(this,ba,Uu)),Uu=this}skip_effect(t){L(this,hs).has(t)||L(this,hs).set(t,{d:[],m:[]}),L(this,Yu).delete(t)}unskip_effect(t,e=n=>this.schedule(n)){var n=L(this,hs).get(t);if(n){L(this,hs).delete(t);for(var i of n.d)_t(i,2048),e(i);for(i of n.m)_t(i,4096),e(i)}L(this,Yu).add(t)}capture(t,e,n=!1){t.v!==Rt&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&8388608)===0&&(this.current.set(t,[e,n]),Xr?.set(t,e)),this.is_fork||(t.v=e)}activate(){_e=this}deactivate(){_e=null,Xr=null}flush(){try{j&&Ck.clear(),wk=!0,_e=this,tt(this,wt,ih).call(this)}finally{if(HR=0,xk=null,rd=null,sh=null,wk=!1,_e=null,Xr=null,oo.clear(),j)for(let t of Ck)t.updated=null}}discard(){for(let t of L(this,Wu))t(this);L(this,Wu).clear();for(let t of this.async_deriveds.values())t.reject(Vu);tt(this,wt,oh).call(this),L(this,ju)?.resolve()}register_created_effect(t){L(this,ah).push(t)}increment(t,e){if(De(this,Gu,L(this,Gu)+1),t){let n=L(this,Ca).get(e)??0;L(this,Ca).set(e,n+1)}}decrement(t,e){if(De(this,Gu,L(this,Gu)-1),t){let n=L(this,Ca).get(e)??0;n===1?L(this,Ca).delete(e):L(this,Ca).set(e,n-1)}L(this,El)||(De(this,El,!0),br(()=>{De(this,El,!1),this.linked&&this.flush()}))}transfer_effects(t,e){for(let n of t)L(this,xa).add(n);for(let n of e)L(this,Uo).add(n);t.clear(),e.clear()}oncommit(t){L(this,Hu).add(t)}ondiscard(t){L(this,Wu).add(t)}settled(){return(L(this,ju)??De(this,ju,ob())).promise}static ensure(){if(_e===null){let t=_e=new _b;!wk&&!Kc&&br(()=>{L(t,zu)||t.flush()})}return _e}apply(){if(!ur||!this.is_fork&&L(this,ba)===null&&L(this,wa)===null){Xr=null;return}Xr=new Map;for(let[e,[n]]of this.current)Xr.set(e,n);for(let e=Tb;e!==null;e=L(e,wa))if(!(e===this||e.is_fork)){var t=!1;if(e.id<this.id){for(let[n,[,i]]of e.current)if(!i&&this.current.has(n)){t=!0;break}}if(!t)for(let[n,i]of e.previous)Xr.has(n)||Xr.set(n,i)}}schedule(t){if(xk=t,t.b?.is_pending&&(t.f&16777228)!==0&&(t.f&32768)===0){t.b.defer_effect(t);return}for(var e=t;e.parent!==null;){e=e.parent;var n=e.f;if(rd!==null&&e===we&&(ur||(Pe===null||(Pe.f&2)===0)&&!NR))return;if((n&96)!==0){if((n&1024)===0)return;e.f^=1024}}L(this,Wn).push(e)}};zu=new WeakMap,ba=new WeakMap,wa=new WeakMap,Hu=new WeakMap,Wu=new WeakMap,Gu=new WeakMap,Ca=new WeakMap,ju=new WeakMap,Wn=new WeakMap,ah=new WeakMap,xa=new WeakMap,Uo=new WeakMap,hs=new WeakMap,Yu=new WeakMap,El=new WeakMap,wt=new WeakSet,Ek=function(){if(this.is_fork)return!0;for(let n of L(this,Ca).keys()){for(var t=n,e=!1;t.parent!==null;){if(L(this,hs).has(t)){e=!0;break}t=t.parent}if(!e)return!0}return!1},ih=function(){var l,c,d;if(De(this,zu,!0),HR++>1e3&&(tt(this,wt,oh).call(this),Jj()),j)for(let u of this.current.keys())Ck.add(u);for(let u of L(this,xa))L(this,Uo).delete(u),_t(u,2048),this.schedule(u);for(let u of L(this,Uo))_t(u,4096),this.schedule(u);let t=L(this,Wn);De(this,Wn,[]),this.apply();var e=rd=[],n=[],i=sh=[];for(let u of t)try{tt(this,wt,Tk).call(this,u,e,n)}catch(p){throw XR(u),tt(this,wt,Ek).call(this)||this.discard(),p}if(_e=null,i.length>0){var o=_b.ensure();for(let u of i)o.schedule(u)}if(rd=null,sh=null,tt(this,wt,Ek).call(this)){tt(this,wt,qu).call(this,n),tt(this,wt,qu).call(this,e);for(let[u,p]of L(this,hs))QR(u,p);i.length>0&&tt(l=_e,wt,ih).call(l);return}let s=tt(this,wt,GR).call(this);if(s){tt(this,wt,qu).call(this,n),tt(this,wt,qu).call(this,e),tt(c=s,wt,jR).call(c,this);return}L(this,xa).clear(),L(this,Uo).clear();for(let u of L(this,Hu))u(this);L(this,Hu).clear(),ms=this,WR(n),WR(e),ms=null,L(this,ju)?.resolve();var a=_e;if(L(this,Gu)===0&&(L(this,Wn).length===0||a!==null)&&(tt(this,wt,oh).call(this),ur&&(tt(this,wt,YR).call(this),_e=a)),L(this,Wn).length>0)if(a!==null){let u=a;L(u,Wn).push(...L(this,Wn).filter(p=>!L(u,Wn).includes(p)))}else a=this;a!==null&&(oo.clear(),tt(d=a,wt,ih).call(d))},Tk=function(t,e,n){t.f^=1024;for(var i=t.first;i!==null;){var o=i.f,s=(o&96)!==0,a=s&&(o&1024)!==0,l=a||(o&8192)!==0||L(this,hs).has(i);if(!l&&i.fn!==null){s?i.f^=1024:(o&4)!==0?e.push(i):ur&&(o&16777224)!==0?n.push(i):Tl(i)&&((o&16)!==0&&L(this,Uo).add(i),fs(i));var c=i.first;if(c!==null){i=c;continue}}for(;i!==null;){var d=i.next;if(d!==null){i=d;break}i=i.parent}}},GR=function(){for(var t=L(this,ba);t!==null;){if(!t.is_fork){for(let[e,[,n]]of this.current)if(t.current.has(e)&&!n)return t}t=L(t,ba)}return null},jR=function(t){var n;for(let[i,o]of t.current)!this.previous.has(i)&&t.previous.has(i)&&this.previous.set(i,t.previous.get(i)),this.current.set(i,o);for(let[i,o]of t.async_deriveds){let s=this.async_deriveds.get(i);s&&o.promise.then(s.resolve).catch(s.reject)}t.async_deriveds.clear(),this.transfer_effects(L(t,xa),L(t,Uo));let e=i=>{var o=i.reactions;if(o!==null&&!((i.f&2)!==0&&(i.f&6144)===0))for(let l of o){var s=l.f;if((s&2)!==0)e(l);else{var a=l;s&4194320&&!this.async_deriveds.has(a)&&(L(this,Uo).delete(a),_t(a,2048),this.schedule(a))}}};for(let i of this.current.keys())e(i);this.oncommit(()=>t.discard()),tt(n=t,wt,oh).call(n),_e=this,tt(this,wt,ih).call(this)},qu=function(t){for(var e=0;e<t.length;e+=1)gb(t[e],L(this,xa),L(this,Uo))},YR=function(){var u;for(let p=Tb;p!==null;p=L(p,wa)){var t=p.id<this.id,e=[];for(let[m,[h,g]]of this.current){if(p.current.has(m)){var n=p.current.get(m)[0];if(t&&h!==n)p.current.set(m,[h,g]);else continue}e.push(m)}if(t)for(let[m,h]of this.async_deriveds){let g=p.async_deriveds.get(m);g&&h.promise.then(g.resolve).catch(g.reject)}var i=[...p.current.keys()].filter(m=>!p.current.get(m)[1]);if(!(!L(p,zu)||i.length===0)){var o=i.filter(m=>!this.current.has(m));if(o.length===0)t&&p.discard();else if(e.length>0){if(j&&!L(p,El)&&RR(L(p,Wn).length===0,"Batch has scheduled roots"),t)for(let m of L(this,Yu))p.unskip_effect(m,h=>{var g;(h.f&4194320)!==0?p.schedule(h):tt(g=p,wt,qu).call(g,[h])});p.activate();var s=new Set,a=new Map;for(var l of e)KR(l,o,s,a);a=new Map;var c=[...p.current].filter(([m,h])=>{let g=this.current.get(m);return g?g[0]!==h[0]||g[1]!==h[1]:!0}).map(([m])=>m);if(c.length>0)for(let m of L(this,ah))(m.f&155648)===0&&_k(m,c,a)&&((m.f&4194320)!==0?(_t(m,2048),p.schedule(m)):L(p,xa).add(m));if(L(p,Wn).length>0&&!L(p,El)){p.apply();for(var d of L(p,Wn))tt(u=p,wt,Tk).call(u,d,[],[]);De(p,Wn,[])}p.deactivate()}}}},oh=function(){if(this.linked){var t=L(this,ba),e=L(this,wa);t===null?Tb=e:De(t,wa,e),e===null?Uu=t:De(e,ba,t),this.linked=!1}};var Ai=_b;function od(r){var t=Kc;Kc=!0;try{var e;for(r&&(_e!==null&&!_e.is_fork&&_e.flush(),e=r());;){if(OR(),_e===null)return e;_e.flush()}}finally{Kc=t}}function Jj(){if(j){var r=new Map;for(let e of _e.current.keys())for(let[n,i]of e.updated??[]){var t=r.get(n);t||(t={error:i.error,count:0},r.set(n,t)),t.count+=i.count}for(let e of r.values())e.error&&console.error(e.error)}try{TR()}catch(e){j&&Wr(e,"stack",{value:""}),di(e,xk)}}var io=null;function WR(r){var t=r.length;if(t!==0){for(var e=0;e<t;){var n=r[e++];if((n.f&24576)===0&&Tl(n)&&(io=new Set,fs(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&kk(n),io?.size>0)){oo.clear();for(let i of io){if((i.f&24576)!==0)continue;let o=[i],s=i.parent;for(;s!==null;)io.has(s)&&(io.delete(s),o.push(s)),s=s.parent;for(let a=o.length-1;a>=0;a--){let l=o[a];(l.f&24576)===0&&fs(l)}}io.clear()}}io=null}}function KR(r,t,e,n){if(!e.has(r)&&(e.add(r),r.reactions!==null))for(let i of r.reactions){let o=i.f;(o&2)!==0?KR(i,t,e,n):(o&4194320)!==0&&(o&2048)===0&&_k(i,t,n)&&(_t(i,2048),lh(i))}}function _k(r,t,e){let n=e.get(r);if(n!==void 0)return n;if(r.deps!==null)for(let i of r.deps){if(yl.call(t,i))return!0;if((i.f&2)!==0&&_k(i,t,e))return e.set(i,!0),!0}return e.set(r,!1),!1}function lh(r){_e.schedule(r)}function QR(r,t){if(!((r.f&32)!==0&&(r.f&1024)!==0)){(r.f&2048)!==0?t.d.push(r):(r.f&4096)!==0&&t.m.push(r),_t(r,1024);for(var e=r.first;e!==null;)QR(e,t),e=e.next}}function XR(r){_t(r,1024);for(var t=r.first;t!==null;)XR(t),t=t.next}var ed=new Set,oo=new Map;function Cb(r){ed=r}var Sk=!1;function ZR(){Sk=!0}function Fn(r,t){var e={f:0,v:r,reactions:null,equals:ub,rv:0,wv:0};return j&&Do&&(e.created=t??Oo("created at"),e.updated=null,e.set_during_effect=!1,e.trace=null),e}function pe(r,t){let e=Fn(r,t);return Eb(e),e}function Qc(r,t=!1,e=!0){var i;let n=Fn(r);return t||(n.equals=mb),ha&&e&&rt!==null&&rt.l!==null&&((i=rt.l).s??(i.s=[])).push(n),n}function q(r,t,e=!1){Pe!==null&&(!Gn||(Pe.f&131072)!==0)&&No()&&(Pe.f&4325394)!==0&&(so===null||!so.has(r))&&$R();let n=e?Ze(t):t;return j&&fb(n,r.label),Bo(r,n,sh)}function Bo(r,t,e=null){if(!r.equals(t)){Si?oo.set(r,t):oo.has(r)||oo.set(r,r.v);var n=Ai.ensure();if(n.capture(r,t),j){if(Do||we!==null){r.updated??(r.updated=new Map);let i=(r.updated.get("")?.count??0)+1;if(r.updated.set("",{error:null,count:i}),Do||i>5){let o=Oo("updated at");if(o!==null){let s=r.updated.get(o.stack);s||(s={error:o,count:0},r.updated.set(o.stack,s)),s.count++}}}we!==null&&(r.set_during_effect=!0)}if((r.f&2)!==0){let i=r;(r.f&2048)!==0&&rh(i),Xr===null&&Du(i)}r.wv=Bu(),eD(r,2048,e),No()&&we!==null&&(we.f&1024)!==0&&(we.f&96)===0&&(Ii===null?tD([r]):Ii.push(r)),!n.is_fork&&ed.size>0&&!Sk&&kb()}return t}function kb(){Sk=!1;for(let r of ed){(r.f&1024)!==0&&_t(r,4096);let t;try{t=Tl(r)}catch{t=!0}t&&fs(r)}ed.clear()}function Ak(r,t=1){var e=f(r);return q(r,t===1?++e:--e)}function sd(r){q(r,r.v+1)}function eD(r,t,e){var n=r.reactions;if(n!==null)for(var i=No(),o=n.length,s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===we)){var c=(l&2048)===0;if(c&&_t(a,t),(l&131072)!==0)ed.add(a);else if((l&2)!==0){var d=a;Xr?.delete(d),(l&65536)===0&&(l&512&&(we===null||(we.f&2097152)===0)&&(a.f|=65536),eD(d,4096,e))}else if(c){var u=a;(l&16)!==0&&io!==null&&io.add(u),e!==null?e.push(u):lh(u)}}}}var eY=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function Ze(r){if(typeof r!="object"||r===null||vn in r||sb in r)return r;let t=bl(r);if(t!==nb&&t!==aR)return r;var e=new Map,n=eo(r),i=pe(0),o=j&&Do?Oo("created at"):null,s=_l,a=u=>{if(_l===s)return u();var p=Pe,m=_l;Fr(null),Ik(s);var h=u();return Fr(p),Ik(m),h};n&&(e.set("length",pe(r.length,o)),j&&(r=rY(r)));var l="";let c=!1;function d(u){if(!c){c=!0,l=u,In(i,`${l} version`);for(let[p,m]of e)In(m,ad(l,p));c=!1}}return new Proxy(r,{defineProperty(u,p,m){(!("value"in m)||m.configurable===!1||m.enumerable===!1||m.writable===!1)&&IR();var h=e.get(p);return h===void 0?a(()=>{var g=pe(m.value,o);return e.set(p,g),j&&typeof p=="string"&&In(g,ad(l,p)),g}):q(h,m.value,!0),!0},deleteProperty(u,p){var m=e.get(p);if(m===void 0){if(p in u){let h=a(()=>pe(Rt,o));e.set(p,h),sd(i),j&&In(h,ad(l,p))}}else q(m,Rt),sd(i);return!0},get(u,p,m){if(p===vn)return r;if(j&&p===ab)return d;var h=e.get(p),g=p in u;if(h===void 0&&(!g||li(u,p)?.writable)&&(h=a(()=>{var b=Ze(g?u[p]:Rt),y=pe(b,o);return j&&In(y,ad(l,p)),y}),e.set(p,h)),h!==void 0){var v=f(h);return v===Rt?void 0:v}return Reflect.get(u,p,m)},getOwnPropertyDescriptor(u,p){var m=Reflect.getOwnPropertyDescriptor(u,p);if(m&&"value"in m){var h=e.get(p);h&&(m.value=f(h))}else if(m===void 0){var g=e.get(p),v=g?.v;if(g!==void 0&&v!==Rt)return{enumerable:!0,configurable:!0,value:v,writable:!0}}return m},has(u,p){if(p===vn)return!0;var m=e.get(p),h=m!==void 0&&m.v!==Rt||Reflect.has(u,p);if(m!==void 0||we!==null&&(!h||li(u,p)?.writable)){m===void 0&&(m=a(()=>{var v=h?Ze(u[p]):Rt,b=pe(v,o);return j&&In(b,ad(l,p)),b}),e.set(p,m));var g=f(m);if(g===Rt)return!1}return h},set(u,p,m,h){var g=e.get(p),v=p in u;if(n&&p==="length")for(var b=m;b<g.v;b+=1){var y=e.get(b+"");y!==void 0?q(y,Rt):b in u&&(y=a(()=>pe(Rt,o)),e.set(b+"",y),j&&In(y,ad(l,b)))}if(g===void 0)(!v||li(u,p)?.writable)&&(g=a(()=>pe(void 0,o)),j&&In(g,ad(l,p)),q(g,Ze(m)),e.set(p,g));else{v=g.v!==Rt;var C=a(()=>Ze(m));q(g,C)}var w=Reflect.getOwnPropertyDescriptor(u,p);if(w?.set&&w.set.call(h,m),!v){if(n&&typeof p=="string"){var T=e.get("length"),P=Number(p);Number.isInteger(P)&&P>=T.v&&q(T,P+1)}sd(i)}return!0},ownKeys(u){f(i);var p=Reflect.ownKeys(u).filter(g=>{var v=e.get(g);return v===void 0||v.v!==Rt});for(var[m,h]of e)h.v!==Rt&&!(m in u)&&p.push(m);return p},setPrototypeOf(){PR()}})}function ad(r,t){return typeof t=="symbol"?`${r}[Symbol(${t.description??""})]`:eY.test(t)?`${r}.${t}`:/^\d+$/.test(t)?`${r}[${t}]`:`${r}['${t}']`}function Qu(r){try{if(r!==null&&typeof r=="object"&&vn in r)return r[vn]}catch{}return r}function Sb(r,t){return Object.is(Qu(r),Qu(t))}var tY=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function rY(r){return new Proxy(r,{get(t,e,n){var i=Reflect.get(t,e,n);return tY.has(e)?function(...o){ZR();var s=i.apply(this,o);return kb(),s}:i}})}function rD(){let r=Array.prototype,t=Array.__svelte_cleanup;t&&t();let{indexOf:e,lastIndexOf:n,includes:i}=r;r.indexOf=function(o,s){let a=e.call(this,o,s);if(a===-1){for(let l=s??0;l<this.length;l+=1)if(Qu(this[l])===o){db("array.indexOf(...)");break}}return a},r.lastIndexOf=function(o,s){let a=n.call(this,o,s??this.length-1);if(a===-1){for(let l=0;l<=(s??this.length-1);l+=1)if(Qu(this[l])===o){db("array.lastIndexOf(...)");break}}return a},r.includes=function(o,s){let a=i.call(this,o,s);if(!a){for(let l=0;l<this.length;l+=1)if(Qu(this[l])===o){db("array.includes(...)");break}}return a},Array.__svelte_cleanup=()=>{r.indexOf=e,r.lastIndexOf=n,r.includes=i}}var Pk,nD,ch,iD,oD;function Ab(){if(Pk===void 0){Pk=window,nD=document,ch=/Firefox/.test(navigator.userAgent);var r=Element.prototype,t=Node.prototype,e=Text.prototype;iD=li(t,"firstChild").get,oD=li(t,"nextSibling").get,sk(r)&&(r[Wf]=void 0,r[lb]=null,r[Gf]=void 0,r.__e=void 0),sk(e)&&(e[jf]=void 0),j&&(r.__svelte_meta=null,rD())}}function ar(r=""){return document.createTextNode(r)}function Kr(r){return iD.call(r)}function bn(r){return oD.call(r)}function R(r,t){if(!xe)return Kr(r);var e=Kr(Oe);if(e===null)e=Oe.appendChild(ar());else if(t&&e.nodeType!==Wc){var n=ar();return e?.before(n),Tt(n),n}return t&&dh(e),Tt(e),e}function ae(r,t=!1){if(!xe){var e=Kr(r);return e instanceof Comment&&e.data===""?bn(e):e}if(t){if(Oe?.nodeType!==Wc){var n=ar();return Oe?.before(n),Tt(n),n}dh(Oe)}return Oe}function re(r,t=!1){if(!xe)return Kr(r);var e=R(r,t);return $(r),e}function E(r,t=1,e=!1){let n=xe?Oe:r;for(var i;t--;)i=n,n=bn(n);if(!xe)return n;if(e){if(n?.nodeType!==Wc){var o=ar();return n===null?i?.after(o):n.before(o),Tt(o),o}dh(n)}return Tt(n),n}function Lu(r){r.textContent=""}function Ib(){if(!ur||io!==null)return!1;var r=we.f;return(r&32768)!==0}function qo(r,t,e){return t==null||t===tb?e?document.createElement(r,{is:e}):document.createElement(r):e?document.createElementNS(t,r,{is:e}):document.createElementNS(t,r)}function dh(r){if(r.nodeValue.length<65536)return;let t=r.nextSibling;for(;t!==null&&t.nodeType===Wc;)t.remove(),r.nodeValue+=t.nodeValue,t=r.nextSibling}var $k=new WeakMap;function sD(r){var t=we;if(t===null)return Pe.f|=8388608,r;if(j&&r instanceof Error&&!$k.has(r)&&$k.set(r,nY(r,t)),(t.f&32768)===0&&(t.f&4)===0)throw j&&!t.parent&&r instanceof Error&&aD(r),r;di(r,t)}function di(r,t){if(!(t!==null&&(t.f&16384)!==0)){for(;t!==null;){if((t.f&128)!==0&&(t.f&33570816)===0){if((t.f&32768)===0)throw r;try{t.b.error(r);return}catch(e){r=e}}t=t.parent}throw j&&r instanceof Error&&aD(r),r}}function nY(r,t){let e=li(r,"message");if(!(e&&!e.configurable)){for(var n=ch?" ":" ",i=`
- ${n}in ${t.fn?.name||"<unknown>"}`,o=t.ctx;o!==null;)i+=`
- ${n}in ${o.function?.[Zi].split("/").pop()}`,o=o.p;return{message:r.message+`
- ${i}
- `,stack:r.stack?.split(`
- `).filter(s=>!s.includes("svelte/src/internal")).join(`
- `)}}}function aD(r){let t=$k.get(r);t&&(Wr(r,"message",{value:t.message}),Wr(r,"stack",{value:t.stack}))}function cD(r){we===null&&(Pe===null&&ER(r),xR()),Si&&CR(r)}function oY(r,t){var e=t.last;e===null?t.last=t.first=r:(e.next=r,r.prev=e,t.last=r)}function gs(r,t){var e=we;if(j)for(;e!==null&&(e.f&131072)!==0;)e=e.parent;e!==null&&(e.f&8192)!==0&&(r|=8192);var n={ctx:rt,deps:null,nodes:null,f:r|2048|512,first:null,fn:t,last:null,next:null,parent:e,b:e&&e.b,prev:null,teardown:null,wv:0,ac:null};j&&(n.component_function=Lo),_e?.register_created_effect(n);var i=n;if((r&4)!==0)rd!==null?rd.push(n):Ai.ensure().schedule(n);else if(t!==null){try{fs(n)}catch(s){throw sr(n),s}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&524288)===0&&(i=i.first,(r&16)!==0&&(r&65536)!==0&&i!==null&&(i.f|=65536))}if(i!==null&&(i.parent=e,e!==null&&oY(i,e),Pe!==null&&(Pe.f&2)!==0&&(r&64)===0)){var o=Pe;(o.effects??(o.effects=[])).push(i)}return n}function Cl(){return Pe!==null&&!Gn}function Yr(r){let t=gs(8,null);return _t(t,1024),t.teardown=r,t}function Ot(r){cD("$effect"),j&&Wr(r,"name",{value:"$effect"});var t=we.f,e=!Pe&&(t&32)!==0&&rt!==null&&!rt.i;if(e){var n=rt;(n.e??(n.e=[])).push(r)}else return pk(r)}function pk(r){return gs(1048580,r)}function Rk(r){Ai.ensure();let t=gs(524352,r);return()=>{sr(t)}}function dD(r){Ai.ensure();let t=gs(524352,r);return(e={})=>new Promise(n=>{e.outro?vs(t,()=>{sr(t),n(void 0)}):(sr(t),n(void 0))})}function wr(r){return gs(4,r)}function zR(r){return gs(4718592,r)}function Jr(r,t=0){return gs(8|t,r)}function Q(r,t=[],e=[],n=[]){wb(n,t,e,i=>{gs(8,()=>{r(...i.map(f))})})}function jn(r,t=0){var e=gs(16|t,r);return j&&(e.dev_stack=ps),e}function Rr(r){return gs(524320,r)}function Dk(r){var t=r.teardown;if(t!==null){let e=Si,n=Pe;Fk(!0),Fr(null);try{t.call(null)}catch(i){di(i,r.parent)}finally{Fk(e),Fr(n)}}}function nh(r,t=!1){var e=r.first;for(r.first=r.last=null;e!==null;){let i=e.ac;i!==null&&no(()=>{i.abort(pa)});var n=e.next;(e.f&64)!==0?e.parent=null:sr(e,t),e=n}}function uD(r){for(var t=r.first;t!==null;){var e=t.next;(t.f&32)===0&&sr(t),t=e}}function sr(r,t=!0){var e=!1;(t||(r.f&262144)!==0)&&r.nodes!==null&&r.nodes.end!==null&&(pD(r.nodes.start,r.nodes.end),e=!0),r.f|=33554432,nh(r,t&&!e),td(r,0);var n=r.nodes&&r.nodes.t;if(n!==null)for(let o of n)o.stop();Dk(r),r.f^=33554432,r.f|=16384;var i=r.parent;i!==null&&i.first!==null&&kk(r),j&&(r.component_function=null),r.next=r.prev=r.teardown=r.ctx=r.deps=r.fn=r.nodes=r.ac=r.b=null}function pD(r,t){for(;r!==null;){var e=r===t?null:bn(r);r.remove(),r=e}}function kk(r){var t=r.parent,e=r.prev,n=r.next;e!==null&&(e.next=n),n!==null&&(n.prev=e),t!==null&&(t.first===r&&(t.first=n),t.last===r&&(t.last=e))}function vs(r,t,e=!0){var n=[];r.f|=256,mD(r,n,!0);var i=()=>{e&&sr(r),t&&t()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function mD(r,t,e){if((r.f&8192)===0){r.f^=8192;var n=r.nodes&&r.nodes.t;if(n!==null)for(let a of n)(a.is_global||e)&&t.push(a);for(var i=r.first;i!==null;){var o=i.next;if((i.f&64)===0){var s=(i.f&65536)!==0||(i.f&32)!==0&&(r.f&16)!==0;mD(i,t,s?e:!1)}i=o}}}function Xu(r){r.f&=-257,fD(r,!0)}function fD(r,t){if((r.f&256)===0&&(r.f&8192)!==0){r.f^=8192,(r.f&1024)===0&&(_t(r,2048),Ai.ensure().schedule(r));for(var e=r.first;e!==null;){var n=e.next,i=(e.f&65536)!==0||(e.f&32)!==0;fD(e,i?t:!1),e=n}var o=r.nodes&&r.nodes.t;if(o!==null)for(let s of o)(s.is_global||t)&&s.in()}}function Ju(r,t){if(r.nodes)for(var e=r.nodes.start,n=r.nodes.end;e!==null;){var i=e===n?null:bn(e);t.append(e),e=i}}var hD=null;var Pb=!1,Si=!1;function Fk(r){Si=r}var Pe=null,Gn=!1;function Fr(r){Pe=r}var we=null;function Mr(r){we=r}var so=null;function Eb(r){Pe!==null&&(!ur||(Pe.f&2)!==0)&&(so??(so=new Set)).add(r)}var Qr=null,Hn=0,Ii=null;function tD(r){Ii=r}var vD=1,ld=0,_l=ld;function Ik(r){_l=r}function Bu(){return++vD}function Tl(r){var t=r.f;if((t&2048)!==0)return!0;if(t&2&&(r.f&=-65537),(t&4096)!==0){for(var e=r.deps,n=e.length,i=0;i<n;i++){var o=e[i];if(Tl(o)&&yk(o),o.wv>r.wv)return!0}(t&512)!==0&&Xr===null&&_t(r,1024)}return!1}function yD(r,t,e=!0){var n=r.reactions;if(n!==null&&!(!ur&&so!==null&&so.has(r)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&2)!==0?yD(o,t,!1):t===o&&(e?_t(o,2048):(o.f&1024)!==0&&_t(o,4096),lh(o))}}function xb(r){var t=Qr,e=Hn,n=Ii,i=Pe,o=so,s=rt,a=Gn,l=_l,c=r.f;Qr=null,Hn=0,Ii=null,Pe=(c&96)===0?r:null,so=null,ga(r.ctx),Gn=!1,_l=++ld,r.ac!==null&&(no(()=>{r.ac.abort(pa)}),r.ac=null);try{r.f|=2097152;var d=r.fn,u=d();r.f|=32768;var p=gD(r);if(No()&&Ii!==null&&!Gn&&p!==null&&(r.f&6146)===0)for(var m=0;m<Ii.length;m++)yD(Ii[m],r);if(i!==null&&i!==r){if(ld++,i.deps!==null)for(let h=0;h<e;h+=1)i.deps[h].rv=ld;if(t!==null)for(let h of t)h.rv=ld;Ii!==null&&(n===null?n=Ii:n.push(...Ii))}return(r.f&8388608)!==0&&(r.f^=8388608),u}catch(h){return gD(r),sD(h)}finally{r.f^=2097152,Qr=t,Hn=e,Ii=n,Pe=i,so=o,ga(s),Gn=a,_l=l}}function gD(r){var i;var t=r.deps,e=_e?.is_fork;if(Qr!==null){var n;if(e||td(r,Hn),t!==null&&Hn>0)for(t.length=Hn+Qr.length,n=0;n<Qr.length;n++)t[Hn+n]=Qr[n];else r.deps=t=Qr;if(Cl()&&(r.f&512)!==0)for(n=Hn;n<t.length;n++)((i=t[n]).reactions??(i.reactions=[])).push(r)}else!e&&t!==null&&Hn<t.length&&(td(r,Hn),t.length=Hn);return t}function sY(r,t){let e=t.reactions;if(e!==null){var n=sR.call(e,r);if(n!==-1){var i=e.length-1;i===0?e=t.reactions=null:(e[n]=e[i],e.pop())}}if(e===null&&(t.f&2)!==0&&(Qr===null||!yl.call(Qr,t))){var o=t;(o.f&512)!==0&&(o.f^=512,o.f&=-65537),o.v!==Rt&&Du(o),o.ac!==null&&no(()=>{o.ac.abort(pa),o.ac=null,_t(o,2048)}),qR(o),td(o,0)}}function td(r,t){var e=r.deps;if(e!==null)for(var n=t;n<e.length;n++)sY(r,e[n])}function fs(r){var t=r.f;if((t&16384)===0){_t(r,1024);var e=we,n=Pb;if(we=r,Pb=(t&96)===0,j){var i=Lo;hb(r.component_function);var o=ps;Ru(r.dev_stack??ps)}try{(t&16777232)!==0?uD(r):nh(r),Dk(r);var s=xb(r);if(r.teardown=typeof s=="function"?s:null,r.wv=vD,j&&Do&&(r.f&2048)!==0&&r.deps!==null)for(var a of r.deps)a.set_during_effect&&(a.wv=Bu(),a.set_during_effect=!1)}finally{Pb=n,we=e,j&&(hb(i),Ru(o))}}}async function ys(){if(ur)return new Promise(r=>{requestAnimationFrame(()=>r()),setTimeout(()=>r())});await Promise.resolve(),od()}function f(r){var t=r.f,e=(t&2)!==0;if(hD?.add(r),Pe!==null&&!Gn){var n=we!==null&&(we.f&16384)!==0;if(!n&&(so===null||!so.has(r))){var i=Pe.deps;if((Pe.f&2097152)!==0)r.rv<ld&&(r.rv=ld,Qr===null&&i!==null&&i[Hn]===r?Hn++:Qr===null?Qr=[r]:Qr.push(r));else{Pe.deps??(Pe.deps=[]),yl.call(Pe.deps,r)||Pe.deps.push(r);var o=r.reactions;o===null?r.reactions=[Pe]:yl.call(o,Pe)||o.push(Pe)}}}if(j){if(!Gn&&ui&&_e===null&&ms===null&&!ui.warned&&(ui.effect.f&2097152)===0&&!ui.effect_deps.has(r)){ui.warned=!0,cR(r.label);var s=Oo("traced at");s&&console.warn(s)}if(th.delete(r),Do&&!Gn&&Jf!==null&&Pe!==null&&Jf.reaction===Pe){if(r.trace)r.trace();else if(s=Oo("traced at"),s){var a=Jf.entries.get(r);a===void 0&&(a={traces:[]},Jf.entries.set(r,a));var l=a.traces[a.traces.length-1];s.stack!==l?.stack&&a.traces.push(s)}}}if(Si&&oo.has(r))return oo.get(r);if(e){var c=r;if(Si){var d=c.v;return((c.f&1024)===0&&c.reactions!==null||wD(c))&&(d=rh(c)),oo.set(c,d),d}var u=(c.f&512)===0&&!Gn&&Pe!==null&&(Pb||(Pe.f&512)!==0),p=(c.f&32768)===0;Tl(c)&&(u&&(c.f|=512),yk(c)),u&&!p&&(bk(c),bD(c))}if(Xr?.has(r))return Xr.get(r);if((r.f&8388608)!==0)throw r.v;return r.v}function bD(r){if(r.f|=512,r.deps!==null)for(let t of r.deps)(t.reactions??(t.reactions=[])).push(r),(t.f&2)!==0&&(t.f&512)===0&&(bk(t),bD(t))}function wD(r){if(r.v===Rt)return!0;if(r.deps===null)return!1;for(let t of r.deps)if(oo.has(t)||(t.f&2)!==0&&wD(t))return!0;return!1}function pt(r){var t=Gn;try{return Gn=!0,r()}finally{Gn=t}}function Fb(r){if(!(typeof r!="object"||!r||r instanceof EventTarget)){if(vn in r)$b(r);else if(!Array.isArray(r))for(let t in r){let e=r[t];typeof e=="object"&&e&&vn in e&&$b(e)}}}function $b(r,t=new Set){if(typeof r=="object"&&r!==null&&!(r instanceof EventTarget)&&!t.has(r)){t.add(r),r instanceof Date&&r.getTime();for(let n in r)try{$b(r[n],t)}catch{}let e=bl(r);if(e!==Object.prototype&&e!==Array.prototype&&e!==Map.prototype&&e!==Set.prototype&&e!==Date.prototype){let n=rb(e);for(let i in n){let o=n[i].get;if(o)try{o.call(r)}catch{}}}}}var cd=Symbol("events"),Nk=new Set,Mb=new Set;function CD(r,t,e,n={}){function i(o){if(n.capture||Rb.call(t,o),!o.cancelBubble)return no(()=>e?.call(this,o))}return r.startsWith("pointer")||r.startsWith("touch")||r==="wheel"?br(()=>{t.addEventListener(r,i,n)}):t.addEventListener(r,i,n),i}function Yn(r,t,e,n,i){var o={capture:n,passive:i},s=CD(r,t,e,o);(t===document.body||t===window||t===document||t instanceof HTMLMediaElement)&&Yr(()=>{t.removeEventListener(r,s,o)})}function ge(r,t,e){(t[cd]??(t[cd]={}))[r]=e}function He(r){for(var t=0;t<r.length;t++)Nk.add(r[t]);for(var e of Mb)e(r)}var Ok=null,Lk=!1;function Rb(r){var t=this,e=t.ownerDocument,n=r.type,i=r.composedPath?.()||[],o=i[0]||r.target;Ok=r,Lk||(Lk=!0,setTimeout(()=>{Lk=!1,Ok=null}));var s=0,a=Ok===r&&r[cd];if(a){var l=i.indexOf(a);if(l!==-1&&(t===document||t===window)){r[cd]=t;return}var c=i.indexOf(t);if(c===-1)return;l<=c&&(s=l)}if(o=i[s]||r.target,o!==t){Wr(r,"currentTarget",{configurable:!0,get(){return o||e}});var d=Pe,u=we;Fr(null),Mr(null);try{for(var p,m=[];o!==null&&o!==t;){try{var h=o[cd]?.[n];h!=null&&(!o.disabled||r.target===o)&&h.call(o,r)}catch(g){p?m.push(g):p=g}if(r.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(p){for(let g of m)queueMicrotask(()=>{throw g});throw p}}finally{r[cd]=t,delete r.currentTarget,Fr(d),Mr(u)}}}var aY=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:r=>r});function xD(r){return aY?.createHTML(r)??r}function Vk(r){var t=qo("template");return t.innerHTML=xD(r.replaceAll("<!>","<!---->")),t.content}function Pi(r,t){var e=we;e.nodes===null&&(e.nodes={start:r,end:t,a:null,t:null})}function F(r,t){var e=(t&1)!==0,n=(t&2)!==0,i,o=!r.startsWith("<!>");return()=>{if(xe)return Pi(Oe,null),Oe;i===void 0&&(i=Vk(o?r:"<!>"+r),e||(i=Kr(i)));var s=n||ch?document.importNode(i,!0):i.cloneNode(!0);if(e){var a=Kr(s),l=s.lastChild;Pi(a,l)}else Pi(s,s);return s}}function bs(r=""){if(!xe){var t=ar(r+"");return Pi(t,t),t}var e=Oe;return e.nodeType!==Wc?(e.before(e=ar()),Tt(e)):dh(e),Pi(e,e),e}function bt(){if(xe)return Pi(Oe,null),Oe;var r=document.createDocumentFragment(),t=document.createComment(""),e=ar();return r.append(t,e),Pi(t,e),r}function A(r,t){if(xe){var e=we;((e.f&32768)===0||e.nodes.end===null)&&(e.nodes.end=Oe),Gr();return}r!==null&&r.before(t)}function $i(){var r;if(xe&&Oe&&Oe.nodeType===ki&&Oe.textContent?.startsWith("$")){let t=Oe.textContent.substring(1);return Gr(),t}return(r=window.__svelte??(window.__svelte={})).uid??(r.uid=1),`c${window.__svelte.uid++}`}var mY=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"];var Lce=[...mY,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"];var fY=["touchstart","touchmove"];function ED(r){return fY.includes(r)}var hY=["$state","$state.raw","$derived","$derived.by"],Nce=[...hY,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"];function TD(r){let t=0,e=Fn(0),n;return j&&In(e,"createSubscriber version"),()=>{Cl()&&(f(e),Jr(()=>(t===0&&(n=pt(()=>r(()=>sd(e)))),t+=1,()=>{br(()=>{t-=1,t===0&&(n?.(),n=void 0,sd(e))})})))}}var gY=589824;function hh(r,t,e,n){new Uk(r,t,e,n)}var Fi,ph,ao,dd,Kn,Mi,Qn,Ri,ws,ud,kl,Zu,mh,fh,Cs,Ob,St,kD,SD,qk,AD,zk,uh,Db,Hk,Wk,Uk=class{constructor(t,e,n,i){qe(this,St);fe(this,"parent");fe(this,"is_pending",!1);fe(this,"transform_error");qe(this,Fi);qe(this,ph,xe?Oe:null);qe(this,ao);qe(this,dd);qe(this,Kn);qe(this,Mi,null);qe(this,Qn,null);qe(this,Ri,null);qe(this,ws,null);qe(this,ud,0);qe(this,kl,0);qe(this,Zu,!1);qe(this,mh,new Set);qe(this,fh,new Set);qe(this,Cs,null);qe(this,Ob,TD(()=>(De(this,Cs,Fn(L(this,ud))),j&&In(L(this,Cs),"$effect.pending()"),()=>{De(this,Cs,null)})));De(this,Fi,t),De(this,ao,e),De(this,dd,o=>{var s=we;s.b=this,s.f|=128,n(o)}),this.parent=we.b,this.transform_error=i??this.parent?.transform_error??(o=>o),De(this,Kn,jn(()=>{if(xe){let o=L(this,ph);Gr();let s=o.data==="[!";if(o.data.startsWith("[?")){let l=JSON.parse(o.data.slice("[?".length));tt(this,St,SD).call(this,l)}else s?tt(this,St,AD).call(this):tt(this,St,kD).call(this)}else tt(this,St,zk).call(this)},gY)),xe&&De(this,Fi,Oe)}defer_effect(t){gb(t,L(this,mh),L(this,fh))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!L(this,ao).pending}update_pending_count(t,e){tt(this,St,Hk).call(this,t,e),De(this,ud,L(this,ud)+t),!(!L(this,Cs)||L(this,Zu))&&(De(this,Zu,!0),br(()=>{De(this,Zu,!1),L(this,Cs)&&Bo(L(this,Cs),L(this,ud))}))}get_effect_pending(){return L(this,Ob).call(this),f(L(this,Cs))}error(t){if(!L(this,ao).onerror&&!L(this,ao).failed)throw t;_e?.is_fork?(L(this,Mi)&&_e.skip_effect(L(this,Mi)),L(this,Qn)&&_e.skip_effect(L(this,Qn)),L(this,Ri)&&_e.skip_effect(L(this,Ri)),_e.oncommit(()=>{tt(this,St,Wk).call(this,t)})):tt(this,St,Wk).call(this,t)}};Fi=new WeakMap,ph=new WeakMap,ao=new WeakMap,dd=new WeakMap,Kn=new WeakMap,Mi=new WeakMap,Qn=new WeakMap,Ri=new WeakMap,ws=new WeakMap,ud=new WeakMap,kl=new WeakMap,Zu=new WeakMap,mh=new WeakMap,fh=new WeakMap,Cs=new WeakMap,Ob=new WeakMap,St=new WeakSet,kD=function(){try{De(this,Mi,Rr(()=>L(this,dd).call(this,L(this,Fi))))}catch(t){this.error(t)}},SD=function(t){let e=L(this,ao).failed,{reset:n,invoke_onerror:i}=tt(this,St,qk).call(this,t);br(i),e&&De(this,Ri,Rr(()=>{e(L(this,Fi),()=>t,()=>n)}))},qk=function(t){var e=!1,n=!1;let i=()=>{if(e){hR();return}e=!0,n&&FR(),L(this,Ri)!==null&&vs(L(this,Ri),()=>{De(this,Ri,null)}),tt(this,St,Db).call(this,()=>{tt(this,St,zk).call(this)})};return{reset:i,invoke_onerror:()=>{try{n=!0,L(this,ao).onerror?.(t,i),n=!1}catch(s){di(s,L(this,Kn)&&L(this,Kn).parent)}}}},AD=function(){let t=L(this,ao).pending;t&&(this.is_pending=!0,De(this,Qn,Rr(()=>t(L(this,Fi)))),br(()=>{var e=De(this,ws,document.createDocumentFragment()),n=ar(),i=!1;if(e.append(n),De(this,Mi,tt(this,St,Db).call(this,()=>{try{return Rr(()=>L(this,dd).call(this,n))}catch(o){try{this.error(o),i=!0}catch(s){di(s,L(this,Kn).parent)}return null}})),L(this,Mi)===null){De(this,ws,null),i&&tt(this,St,uh).call(this,_e);return}L(this,kl)===0&&(L(this,Fi).before(e),De(this,ws,null),vs(L(this,Qn),()=>{De(this,Qn,null)}),tt(this,St,uh).call(this,_e))}))},zk=function(){try{if(this.is_pending=this.has_pending_snippet(),De(this,kl,0),De(this,ud,0),De(this,Mi,Rr(()=>{L(this,dd).call(this,L(this,Fi))})),L(this,kl)>0){var t=De(this,ws,document.createDocumentFragment());Ju(L(this,Mi),t);let e=L(this,ao).pending;De(this,Qn,Rr(()=>e(L(this,Fi))))}else tt(this,St,uh).call(this,_e)}catch(e){this.error(e)}},uh=function(t){this.is_pending=!1,t.transfer_effects(L(this,mh),L(this,fh))},Db=function(t){var e=we,n=Pe,i=rt;Mr(L(this,Kn)),Fr(L(this,Kn)),ga(L(this,Kn).ctx);try{return Ai.ensure(),t()}finally{Mr(e),Fr(n),ga(i)}},Hk=function(t,e){var n;if(!this.has_pending_snippet()){this.parent&&tt(n=this.parent,St,Hk).call(n,t,e);return}De(this,kl,L(this,kl)+t),L(this,kl)===0&&(tt(this,St,uh).call(this,e),L(this,Qn)&&vs(L(this,Qn),()=>{De(this,Qn,null)}),L(this,ws)&&(L(this,Fi).before(L(this,ws)),De(this,ws,null)))},Wk=function(t){L(this,Mi)&&(sr(L(this,Mi)),De(this,Mi,null)),L(this,Qn)&&(sr(L(this,Qn)),De(this,Qn,null)),L(this,Ri)&&(sr(L(this,Ri)),De(this,Ri,null)),xe&&(Tt(L(this,ph)),Xt(),Tt(us()));let e=L(this,ao).failed,n=i=>{let{reset:o,invoke_onerror:s}=tt(this,St,qk).call(this,i);s(),e&&De(this,Ri,tt(this,St,Db).call(this,()=>{try{return Rr(()=>{var a=we;a.b=this,a.f|=128,e(L(this,Fi),()=>i,()=>o)})}catch(a){return di(a,L(this,Kn).parent),null}}))};br(()=>{var i;try{i=this.transform_error(t)}catch(o){di(o,L(this,Kn)&&L(this,Kn).parent);return}i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(n,o=>di(o,L(this,Kn)&&L(this,Kn).parent)):n(i)})};var Gk=!0;function ee(r,t){var n;var e=t==null?"":typeof t=="object"?`${t}`:t;e!==(r[n=jf]??(r[n]=r.nodeValue))&&(r[jf]=e,r.nodeValue=`${e}`)}function pd(r,t){return ID(r,t)}function Yk(r,t){Ab(),t.intro=t.intro??!1;let e=t.target,n=xe,i=Oe;try{for(var o=Kr(e);o&&(o.nodeType!==ki||o.data!=="[");)o=bn(o);if(!o)throw ua;Ir(!0),Tt(o);let s=ID(r,{...t,anchor:o});return Ir(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
- `).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==ua&&console.warn("Failed to hydrate: ",s),t.recover===!1&&_R(),Ab(),Lu(e),Ir(!1),pd(r,t)}finally{Ir(n),Tt(i)}}var Lb=new Map;function ID(r,{target:t,anchor:e,props:n={},events:i,context:o,intro:s=!0,transformError:a}){Ab();var l=void 0,c=dD(()=>{var d=e??t.appendChild(ar());hh(d,{pending:()=>{}},m=>{ie({});var h=rt;if(o&&(h.c=o),i&&(n.$$events=i),xe&&Pi(m,null),Gk=s,l=r(m,n)||Zf(),Gk=!0,xe&&(we.nodes.end=Oe,Oe===null||Oe.nodeType!==ki||Oe.data!=="]"))throw Gc(),ua;oe()},a);var u=new Set,p=m=>{for(var h=0;h<m.length;h++){var g=m[h];if(!u.has(g)){u.add(g);var v=ED(g);for(let C of[t,document]){var b=Lb.get(C);b===void 0&&(b=new Map,Lb.set(C,b));var y=b.get(g);y===void 0?(C.addEventListener(g,Rb,{passive:v}),b.set(g,1)):b.set(g,y+1)}}}};return p($u(Nk)),Mb.add(p),()=>{for(var m of u)for(let v of[t,document]){var h=Lb.get(v),g=h.get(m);--g==0?(v.removeEventListener(m,Rb),h.delete(m),h.size===0&&Lb.delete(v)):h.set(m,g)}Mb.delete(p),d!==e&&d.parentNode?.removeChild(d)}});return jk.set(l,c),l}var jk=new WeakMap;function ep(r,t){let e=jk.get(r);return e?(jk.delete(r),e(t)):(j&&mR(),Promise.resolve())}var zo,xs,Di,md,gh,vh,Nb,Ho=class{constructor(t,e=!0){fe(this,"anchor");qe(this,zo,new Map);qe(this,xs,new Map);qe(this,Di,new Map);qe(this,md,new Set);qe(this,gh,!0);qe(this,vh,t=>{if(L(this,zo).has(t)){var e=L(this,zo).get(t),n=L(this,xs).get(e);if(n)Xu(n),L(this,md).delete(e);else{var i=L(this,Di).get(e);i&&(Xu(i.effect),L(this,xs).set(e,i.effect),L(this,Di).delete(e),j&&(i.fragment.lastChild[lk]=this.anchor),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),n=i.effect)}for(let[o,s]of L(this,zo)){if(L(this,zo).delete(o),o===t)break;let a=L(this,Di).get(s);a&&(sr(a.effect),L(this,Di).delete(s))}for(let[o,s]of L(this,xs)){if(o===e||L(this,md).has(o))continue;let a=()=>{if(Array.from(L(this,zo).values()).includes(o)){var c=document.createDocumentFragment();Ju(s,c),c.append(ar()),L(this,Di).set(o,{effect:s,fragment:c})}else sr(s);L(this,md).delete(o),L(this,xs).delete(o)};L(this,gh)||!n?(L(this,md).add(o),vs(s,a,!1)):a()}}});qe(this,Nb,t=>{L(this,zo).delete(t);let e=Array.from(L(this,zo).values());for(let[n,i]of L(this,Di))e.includes(n)||(sr(i.effect),L(this,Di).delete(n))});this.anchor=t,De(this,gh,e)}ensure(t,e){var n=_e,i=Ib();if(e&&!L(this,xs).has(t)&&!L(this,Di).has(t))if(i){var o=document.createDocumentFragment(),s=ar();o.append(s),L(this,Di).set(t,{effect:Rr(()=>e(s)),fragment:o})}else L(this,xs).set(t,Rr(()=>e(this.anchor)));if(L(this,zo).set(n,t),i){for(let[a,l]of L(this,xs))a===t?n.unskip_effect(l):n.skip_effect(l);for(let[a,l]of L(this,Di))a===t?n.unskip_effect(l.effect):n.skip_effect(l.effect);n.oncommit(L(this,vh)),n.ondiscard(L(this,Nb))}else xe&&(this.anchor=Oe),L(this,vh).call(this,n)}};zo=new WeakMap,xs=new WeakMap,Di=new WeakMap,md=new WeakMap,gh=new WeakMap,vh=new WeakMap,Nb=new WeakMap;function Sl(r,t,...e){var n=new Ho(r);jn(()=>{let i=t()??null;j&&i==null&&kR(),n.ensure(i,i&&(o=>i(o,...e)))},65536)}if(j){let r=function(t){if(!(t in globalThis)){let e;Object.defineProperty(globalThis,t,{configurable:!0,get:()=>{if(e!==void 0)return e;AR(t)},set:n=>{e=n}})}};r("$state"),r("$effect"),r("$derived"),r("$inspect"),r("$props"),r("$bindable")}function yh(r){rt===null&&Qf("onMount"),ha&&rt.l!==null?bY(rt).m.push(r):Ot(()=>{let t=pt(r);if(typeof t=="function")return t})}function $D(r){rt===null&&Qf("onDestroy"),yh(()=>()=>pt(r))}function bY(r){var t=r.l;return t.u??(t.u={a:[],b:[],m:[]})}var MD=new Map;function RD(r,t){var e=MD.get(r);e||(e=new Set,MD.set(r,e)),e.add(t)}function z(r,t,e=!1){var n;xe&&(n=Oe,Gr());var i=new Ho(r),o=e?65536:0;function s(a,l){if(xe){var c=Kf(n);if(a!==parseInt(c.substring(1))){var d=us();Tt(d),i.anchor=d,Ir(!1),i.ensure(a,l),Ir(!0);return}}i.ensure(a,l)}jn(()=>{var a=!1;t((l,c=0)=>{a=!0,s(c,l)}),a||s(-1,null)},o)}var EY=Symbol("NaN");function bh(r,t,e){xe&&Gr();var n=new Ho(r),i=!No();jn(()=>{var o=t();o!==o&&(o=EY),i&&o!==null&&typeof o=="object"&&(o={}),n.ensure(o,e)})}function fd(r,t){return t}function AY(r,t,e){for(var n=[],i=t.length,o,s=t.length,a=0;a<i;a++){let u=t[a];vs(u,()=>{if(o){if(o.pending.delete(u),o.done.add(u),o.pending.size===0){var p=r.outrogroups;Kk(r,$u(o.done)),p.delete(o),p.size===0&&(r.outrogroups=null)}}else s-=1},!1)}if(s===0){var l=n.length===0&&e!==null&&r.pending.size===0;if(l){var c=e,d=c.parentNode;Lu(d),d.append(c),r.items.clear()}Kk(r,t,!l)}else o={pending:new Set(t),done:new Set},(r.outrogroups??(r.outrogroups=new Set)).add(o)}function Kk(r,t,e=!0){var n;if(r.pending.size>0){n=new Set;for(let s of r.pending.values())for(let a of s)n.add(r.items.get(a).e)}for(var i=0;i<t.length;i++){var o=t[i];if(n?.has(o)){o.f|=33554432;let s=document.createDocumentFragment();Ju(o,s)}else sr(t[i],e)}}var Vb;function gt(r,t,e,n,i,o=null){var s=r,a=new Map,l=(t&4)!==0;if(l){var c=r;s=xe?Tt(Kr(c)):c.appendChild(ar())}xe&&Gr();var d=null,u=Zc(()=>{var C=e();return eo(C)?C:C==null?[]:$u(C)});j&&In(u,"{#each ...}");var p,m=new Map,h=!0;function g(C){(y.effect.f&16384)===0&&(y.pending.delete(C),y.fallback=d,IY(y,p,s,t,n),d!==null&&(p.length===0?(d.f&33554432)===0?Xu(d):(d.f^=33554432,Ch(d,null,s)):vs(d,()=>{d=null})))}function v(C){y.pending.delete(C)}var b=jn(()=>{p=f(u);var C=p.length;let w=!1;if(xe){var T=Kf(s)==="[!";T!==(C===0)&&(s=us(),Tt(s),Ir(!1),w=!0)}for(var P=new Set,_=_e,I=Ib(),O=0;O<C;O+=1){xe&&Oe.nodeType===ki&&Oe.data==="]"&&(s=Oe,w=!0,Ir(!1));var N=p[O],K=n(N,O);if(j){var ne=n(N,O);K!==ne&&wR(String(O),String(K),String(ne))}var H=h?null:a.get(K);H?(H.v&&Bo(H.v,N),H.i&&Bo(H.i,O),I&&_.unskip_effect(H.e)):(H=PY(a,h?s:Vb??(Vb=ar()),N,K,O,i,t,e),h||(H.e.f|=33554432),a.set(K,H)),P.add(K)}if(C===0&&o&&!d&&(h?d=Rr(()=>o(s)):(d=Rr(()=>o(Vb??(Vb=ar()))),d.f|=33554432)),C>P.size&&(j?$Y(p,n):dk("","","")),xe&&C>0&&Tt(us()),!h)if(m.set(_,P),I){for(let[D,G]of a)P.has(D)||_.skip_effect(G.e);_.oncommit(g),_.ondiscard(v)}else g(_);w&&Ir(!0),f(u)}),y={effect:b,flags:t,items:a,pending:m,outrogroups:null,fallback:d};h=!1,xe&&(s=Oe)}function wh(r){for(;r!==null&&(r.f&32)===0;)r=r.next;return r}function IY(r,t,e,n,i){var o=(n&8)!==0,s=t.length,a=r.items,l=wh(r.effect.first),c,d=null,u,p=[],m=[],h,g,v,b;if(o)for(b=0;b<s;b+=1)h=t[b],g=i(h,b),v=a.get(g).e,(v.f&33554432)===0&&(v.nodes?.a?.measure(),(u??(u=new Set)).add(v));for(b=0;b<s;b+=1){if(h=t[b],g=i(h,b),v=a.get(g).e,r.outrogroups!==null)for(let N of r.outrogroups)N.pending.delete(v),N.done.delete(v);if((v.f&8192)!==0&&(Xu(v),o&&(v.nodes?.a?.unfix(),(u??(u=new Set)).delete(v))),(v.f&33554432)!==0)if(v.f^=33554432,v===l)Ch(v,null,e);else{var y=d?d.next:l;v===r.effect.last&&(r.effect.last=v.prev),v.prev&&(v.prev.next=v.next),v.next&&(v.next.prev=v.prev),Al(r,d,v),Al(r,v,y),Ch(v,y,e),d=v,p=[],m=[],l=wh(d.next);continue}if(v!==l){if(c!==void 0&&c.has(v)){if(p.length<m.length){var C=m[0],w;d=C.prev;var T=p[0],P=p[p.length-1];for(w=0;w<p.length;w+=1)Ch(p[w],C,e);for(w=0;w<m.length;w+=1)c.delete(m[w]);Al(r,T.prev,P.next),Al(r,d,T),Al(r,P,C),l=C,d=P,b-=1,p=[],m=[]}else c.delete(v),Ch(v,l,e),Al(r,v.prev,v.next),Al(r,v,d===null?r.effect.first:d.next),Al(r,d,v),d=v;continue}for(p=[],m=[];l!==null&&l!==v;)(c??(c=new Set)).add(l),m.push(l),l=wh(l.next);if(l===null)continue}(v.f&33554432)===0&&p.push(v),d=v,l=wh(v.next)}if(r.outrogroups!==null){for(let N of r.outrogroups)N.pending.size===0&&(Kk(r,$u(N.done)),r.outrogroups?.delete(N));r.outrogroups.size===0&&(r.outrogroups=null)}if(l!==null||c!==void 0){var _=[];if(c!==void 0)for(v of c)(v.f&8192)===0&&_.push(v);for(;l!==null;)(l.f&8192)===0&&l!==r.fallback&&_.push(l),l=wh(l.next);var I=_.length;if(I>0){var O=(n&4)!==0&&s===0?e:null;if(o){for(b=0;b<I;b+=1)_[b].nodes?.a?.measure();for(b=0;b<I;b+=1)_[b].nodes?.a?.fix()}AY(r,_,O)}}o&&br(()=>{if(u!==void 0)for(v of u)v.nodes?.a?.apply()})}function PY(r,t,e,n,i,o,s,a){var l=(s&1)!==0?(s&16)===0?Qc(e,!1,!1):Fn(e):null,c=(s&2)!==0?Fn(i):null;return j&&l&&(l.trace=()=>{a()[c?.v??i]}),{v:l,i:c,e:Rr(()=>(o(t,l??e,c??i,a),()=>{r.delete(n)}))}}function Ch(r,t,e){if(r.nodes)for(var n=r.nodes.start,i=r.nodes.end,o=t&&(t.f&33554432)===0?t.nodes.start:e;n!==null;){var s=bn(n);if(o.before(n),n===i)return;n=s}}function Al(r,t,e){t===null?r.effect.first=e:t.next=e,e===null?r.effect.last=t:e.prev=t}function $Y(r,t){let e=new Map,n=r.length;for(let i=0;i<n;i++){let o=t(r[i],i);if(e.has(o)){let s=String(e.get(o)),a=String(i),l=String(o);l.startsWith("[object ")&&(l=null),dk(s,a,l)}e.set(o,i)}}function Ae(r,t){wr(()=>{r=we?.parent?.nodes?.start??r;var e=r.getRootNode(),n=e.host?e:e.head??e.ownerDocument.head;if(!n.querySelector("#"+t.hash)){let i=qo("style");i.id=t.hash,i.textContent=t.code,n.appendChild(i),j&&RD(t.hash,i)}})}function Ft(r,t,e){wr(()=>{var n=pt(()=>t(r,e?.())||{});if(e&&n?.update){var i=!1,o={};Jr(()=>{var s=e();Fb(s),i&&pb(o,s)&&(o=s,n.update(s))}),i=!0}if(n?.destroy)return()=>n.destroy()})}var OD=[...`
- \r\f\xA0\v\uFEFF`];function ND(r,t,e){var n=r==null?"":""+r;if(t&&(n=n?n+" "+t:t),e){for(var i of Object.keys(e))if(e[i])n=n?n+" "+i:i;else if(n.length)for(var o=i.length,s=0;(s=n.indexOf(i,s))>=0;){var a=s+o;(s===0||OD.includes(n[s-1]))&&(a===n.length||OD.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function LD(r,t=!1){var e=t?" !important;":";",n="";for(var i of Object.keys(r)){var o=r[i];o!=null&&o!==""&&(n+=" "+i+": "+o+e)}return n}function Qk(r){return r[0]!=="-"||r[1]!=="-"?r.toLowerCase():r}function VD(r,t){if(t){var e="",n,i;if(Array.isArray(t)?(n=t[0],i=t[1]):n=t,r){r=String(r).replaceAll(/\/\*.*?\*\//g,"").trim();var o=!1,s=0,a=!1,l=[];n&&l.push(...Object.keys(n).map(Qk)),i&&l.push(...Object.keys(i).map(Qk));var c=0,d=-1;let g=r.length;for(var u=0;u<g;u++){var p=r[u];if(a?p==="/"&&r[u-1]==="*"&&(a=!1):o?o===p&&(o=!1):p==="/"&&r[u+1]==="*"?a=!0:p==='"'||p==="'"?o=p:p==="("?s++:p===")"&&s--,!a&&o===!1&&s===0){if(p===":"&&d===-1)d=u;else if(p===";"||u===g-1){if(d!==-1){var m=Qk(r.substring(c,d).trim());if(!l.includes(m)){p!==";"&&u++;var h=r.substring(c,u).trim();e+=" "+h+";"}}c=u+1,d=-1}}}}return n&&(e+=LD(n)),i&&(e+=LD(i,!0)),e=e.trim(),e===""?null:e}return r==null?null:String(r)}function Ge(r,t,e,n,i,o){var s=r[Wf];if(xe||s!==e||s===void 0){var a=ND(e,n,o);(!xe||a!==r.getAttribute("class"))&&(a==null?r.removeAttribute("class"):t?r.className=a:r.setAttribute("class",a)),r[Wf]=e}else if(o&&i!==o)for(var l in o){var c=!!o[l];(i==null||c!==!!i[l])&&r.classList.toggle(l,c)}return o}function Xk(r,t={},e,n){for(var i in e){var o=e[i];t[i]!==o&&(e[i]==null?r.style.removeProperty(i):r.style.setProperty(i,o,n))}}function tp(r,t,e,n){var i=r[Gf];if(xe||i!==t){var o=VD(t,n);(!xe||o!==r.getAttribute("style"))&&(o==null?r.removeAttribute("style"):r.style.cssText=o),r[Gf]=t}else n&&(Array.isArray(n)?(Xk(r,e?.[0],n[0]),Xk(r,e?.[1],n[1],"important")):Xk(r,e,n));return n}function Jk(r,t){t?r.hasAttribute("selected")||r.setAttribute("selected",""):r.removeAttribute("selected")}function DY(r,t){var e=r.__defaultValue,n=r.multiple,i=n?e??[]:null;if(!(n&&!eo(i))){var o=r.selectedIndex,s=t&&n?new Set(r.selectedOptions):null;for(var a of r.options){var l=rp(a);Jk(a,n?i.includes(l):Sb(l,e))}if(t)if(s!==null)for(a of r.options){var c=s.has(a);a.selected!==c&&(a.selected=c)}else r.selectedIndex!==o&&(r.selectedIndex=o)}}function Il(r,t,e=!1){if(r.multiple){if(t==null)return;if(!eo(t))return fR();for(var n of r.options)n.selected=t.includes(rp(n));return}for(n of r.options){var i=rp(n);if(Sb(i,t)){n.selected=!0;return}}(!e||t!==void 0)&&(r.selectedIndex=-1)}function Pl(r){var t=new MutationObserver(e=>{e.every(OY)||("__defaultValue"in r&&DY(r,!1),"__value"in r&&Il(r,r.__value))});t.observe(r,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),Yr(()=>{t.disconnect()})}function Zk(r,t,e=t){var n=new WeakSet,i=!0;bb(r,"change",o=>{var s=o?"[selected]":":checked",a;if(r.multiple)a=[].map.call(r.querySelectorAll(s),rp);else{var l=r.querySelector(s)??r.querySelector("option:not([disabled])");a=l&&rp(l)}e(a),r.__value=a,_e!==null&&n.add(_e)}),wr(()=>{var o=t();if(r===document.activeElement){var s=ur?ms:_e;if(n.has(s))return}if(Il(r,o,i),i&&o===void 0){var a=r.querySelector(":checked");a!==null&&(o=rp(a),e(o))}r.__value=o,i=!1})}function rp(r){return"__value"in r?r.__value:r.value}function OY(r){if(r.target.closest("selectedcontent")!==null)return!0;if(r.type==="childList"){var t=[...r.addedNodes,...r.removedNodes];return t.length>0&&t.every(e=>e.nodeName==="SELECTEDCONTENT")}return!1}var BY=Symbol("is custom element"),UY=Symbol("is html"),qY=cb?"link":"LINK";var zY=cb?"progress":"PROGRESS";function Ct(r){if(xe){var t=!1,e=()=>{if(!t){if(t=!0,r.hasAttribute("value")){var n=r.value;le(r,"value",null),r.value=n}if(r.hasAttribute("checked")){var i=r.checked;le(r,"checked",null),r.checked=i}}};r[wl]=e,br(e),yb()}}function Xn(r,t){var e=tS(r);e.value===(e.value=t??void 0)||r.value===t&&(t!==0||r.nodeName!==zY)||(r.value=t??"")}function hd(r,t){var e=tS(r);e.checked!==(e.checked=t??void 0)&&(r.checked=t)}function le(r,t,e,n){var i=tS(r);if(xe&&(i[t]=r.getAttribute(t),t==="src"||t==="srcset"||t==="href"&&r.nodeName===qY)){n||WY(r,t,e??"");return}i[t]!==(i[t]=e)&&(t==="loading"&&(r[lR]=e),e==null?r.removeAttribute(t):typeof e!="string"&&HY(r).has(t)?r[t]=e:r.setAttribute(t,e))}function tS(r){var t;return r[t=lb]??(r[t]={[BY]:r.nodeName.includes("-"),[UY]:r.namespaceURI===tb})}var BD=new Map;function HY(r){var t=r.getAttribute("is")||r.nodeName,e=BD.get(t);if(e)return e;BD.set(t,e=new Set);for(var n,i=r,o=Element.prototype;o!==i;){n=rb(i);for(var s in n)n[s].set&&s!=="innerHTML"&&s!=="textContent"&&s!=="innerText"&&e.add(s);i=bl(i)}return e}function WY(r,t,e){j&&(t==="srcset"&&GY(r,e)||eS(r.getAttribute(t)??"",e)||pR(t,r.outerHTML.replace(r.innerHTML,r.innerHTML&&"..."),String(e)))}function eS(r,t){return r===t?!0:new URL(r,document.baseURI).href===new URL(t,document.baseURI).href}function UD(r){return r.split(",").map(t=>t.trim().split(" ").filter(Boolean))}function GY(r,t){var e=UD(r.srcset),n=UD(t);return n.length===e.length&&n.every(([i,o],s)=>o===e[s][1]&&(eS(e[s][0],i)||eS(i,e[s][0])))}function Jn(r,t,e=t){var n=new WeakSet;bb(r,"input",async i=>{j&&r.type==="checkbox"&&ck();var o=i?r.defaultValue:r.value;if(o=rS(r)?nS(o):o,e(o),_e!==null&&n.add(_e),await ys(),o!==(o=t())){var s=r.selectionStart,a=r.selectionEnd,l=r.value.length;if(r.value=o??"",a!==null){var c=r.value.length;s===a&&a===l&&c>l?(r.selectionStart=c,r.selectionEnd=c):(r.selectionStart=s,r.selectionEnd=Math.min(a,c))}}}),(xe&&r.defaultValue!==r.value||pt(t)==null&&r.value)&&(e(rS(r)?nS(r.value):r.value),_e!==null&&n.add(_e)),Jr(()=>{j&&r.type==="checkbox"&&ck();var i=t();if(r===document.activeElement){var o=ur?ms:_e;if(n.has(o))return}rS(r)&&i===nS(r.value)||r.type==="date"&&!i&&!r.value||i!==r.value&&(r.value=i??"")})}function rS(r){var t=r.type;return t==="number"||t==="range"}function nS(r){return r===""?null:+r}function iS(r,t){return r===t||r?.[vn]===t}function Cn(r=Zf(),t,e,n){var i=rt.r,o=we;return wr(()=>{var s,a;return Jr(()=>{s=a,a=n?.()||[],pt(()=>{iS(e(...a),r)||(t(r,...a),s&&iS(e(...s),r)&&t(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;let c=()=>{a&&iS(e(...a),r)&&t(null,...a)},d=l.teardown;l.teardown=()=>{c(),d?.()}}}),r}function X(r,t,e,n){var i=!ha||(e&2)!==0,o=(e&8)!==0,s=(e&16)!==0,a=n,l=!0,c=void 0,d=()=>s&&i?(c??(c=xl(n)),f(c)):(l&&(l=!1,a=s?pt(n):n),a);let u;if(o){var p=vn in r||Hf in r;u=li(r,t)?.set??(p&&t in r?w=>r[t]=w:void 0)}var m,h=!1;o?[m,h]=mk(()=>r[t]):m=r[t],m===void 0&&n!==void 0&&(m=d(),u&&(i&&SR(t),u(m)));var g;if(i?g=()=>{var w=r[t];return w===void 0?d():(l=!0,w)}:g=()=>{var w=r[t];return w!==void 0&&(a=void 0),w===void 0?a:w},i&&(e&4)===0)return g;if(u){var v=r.$$legacy;return(function(w,T){return arguments.length>0?((!i||!T||v||h)&&u(T?g():w),w):g()})}var b=!1,y=((e&1)!==0?xl:Zc)(()=>(b=!1,g()));j&&(y.label=t),o&&f(y);var C=we;return(function(w,T){if(arguments.length>0){let P=T?f(y):i&&o?Ze(w):w;return q(y,P),b=!0,a!==void 0&&(a=P),w}return Si&&b||(C.f&16384)!==0?y.v:f(y)})}function zD(r){return new sS(r)}var Ea,lo,sS=class{constructor(t){qe(this,Ea);qe(this,lo);var e=new Map,n=(o,s)=>{var a=Qc(s,!1,!1);return e.set(o,a),a};let i=new Proxy({...t.props||{},$$events:{}},{get(o,s){return f(e.get(s)??n(s,Reflect.get(o,s)))},has(o,s){return s===Hf?!0:(f(e.get(s)??n(s,Reflect.get(o,s))),Reflect.has(o,s))},set(o,s,a){return q(e.get(s)??n(s,a),a),Reflect.set(o,s,a)}});De(this,lo,(t.hydrate?Yk:pd)(t.component,{target:t.target,anchor:t.anchor,props:i,context:t.context,intro:t.intro??!1,recover:t.recover,transformError:t.transformError})),!ur&&(!t?.props?.$$host||t.sync===!1)&&od(),De(this,Ea,i.$$events);for(let o of Object.keys(L(this,lo)))o==="$set"||o==="$destroy"||o==="$on"||Wr(this,o,{get(){return L(this,lo)[o]},set(s){L(this,lo)[o]=s},enumerable:!0});L(this,lo).$set=o=>{Object.assign(i,o)},L(this,lo).$destroy=()=>{ep(L(this,lo))}}$set(t){L(this,lo).$set(t)}$on(t,e){L(this,Ea)[t]=L(this,Ea)[t]||[];let n=(...i)=>e.call(this,...i);return L(this,Ea)[t].push(n),()=>{L(this,Ea)[t]=L(this,Ea)[t].filter(i=>i!==n)}}$destroy(){L(this,lo).$destroy()}};Ea=new WeakMap,lo=new WeakMap;var oK;typeof HTMLElement=="function"&&(oK=class extends HTMLElement{constructor(t,e,n){super();fe(this,"$$ctor");fe(this,"$$s");fe(this,"$$c");fe(this,"$$cn",!1);fe(this,"$$d",{});fe(this,"$$r",!1);fe(this,"$$p_d",{});fe(this,"$$l",{});fe(this,"$$l_u",new Map);fe(this,"$$me");fe(this,"$$shadowRoot",null);this.$$ctor=t,this.$$s=e,n&&(this.$$shadowRoot=this.attachShadow(n))}addEventListener(t,e,n){if(this.$$l[t]=this.$$l[t]||[],this.$$l[t].push(e),this.$$c){let i=this.$$c.$on(t,e);this.$$l_u.set(e,i)}super.addEventListener(t,e,n)}removeEventListener(t,e,n){if(super.removeEventListener(t,e,n),this.$$c){let i=this.$$l_u.get(e);i&&(i(),this.$$l_u.delete(e))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let t=function(i){return o=>{let s=qo("slot");i!=="default"&&(s.name=i),A(o,s)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let e={},n=sK(this);for(let i of this.$$s)i in n&&(i==="default"&&!this.$$d.children?(this.$$d.children=t(i),e.default=!0):e[i]=t(i));for(let i of this.attributes){let o=this.$$g_p(i.name);o in this.$$d||(this.$$d[o]=aS(o,i.value,this.$$p_d,"toProp"))}for(let i in this.$$p_d)!(i in this.$$d)&&this[i]!==void 0&&(this.$$d[i]=this[i],delete this[i]);this.$$c=zD({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:e,$$host:this}}),this.$$me=Rk(()=>{Jr(()=>{this.$$r=!0;for(let i of ok(this.$$c)){if(!this.$$p_d[i]?.reflect)continue;this.$$d[i]=this.$$c[i];let o=aS(i,this.$$d[i],this.$$p_d,"toAttribute");o==null?this.removeAttribute(this.$$p_d[i].attribute||i):this.setAttribute(this.$$p_d[i].attribute||i,o)}this.$$r=!1})});for(let i in this.$$l)for(let o of this.$$l[i]){let s=this.$$c.$on(i,o);this.$$l_u.set(o,s)}this.$$l={}}}attributeChangedCallback(t,e,n){this.$$r||(t=this.$$g_p(t),this.$$d[t]=aS(t,n,this.$$p_d,"toProp"),this.$$c?.$set({[t]:this.$$d[t]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(t){return ok(this.$$p_d).find(e=>this.$$p_d[e].attribute===t||!this.$$p_d[e].attribute&&e.toLowerCase()===t)||t}});function aS(r,t,e,n){let i=e[r]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!e[r])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function sK(r){let t={};return r.childNodes.forEach(e=>{t[e.slot||"default"]=!0}),t}var UU=require("obsidian");je();ye();var hU=require("obsidian");Ve();var $h={location:"tab",direction:"vertical",mode:"default",focus:!0};function en(r,t){if(!(t?.fillMissingOnly??!0))return{...$h,...r??{}};let n={...r??{}};return n.location==null&&(n.location=$h.location),n.direction==null&&(n.direction=$h.direction),n.mode==null&&(n.mode=$h.mode),n.focus==null&&(n.focus=$h.focus),n}var IO=require("obsidian");Ve();function sp(r){return r.trim().replace(/^\/+/,"")}function Rl(r){return r.trim().toLowerCase().endsWith(".canvas")}function TS(r,t){let e=sp(t);if(!e||e.includes("{{"))return null;let n=r.vault.getAbstractFileByPath(e);return!n||!(n instanceof IO.TFile)||n.extension!=="canvas"?null:n}function PO(r,t){let n=r.workspace.getMostRecentLeaf?.()?.view;if(!n||n.getViewType?.()!=="canvas")return null;let i=sp(t),o=sp(n.file?.path??r.workspace.getActiveFile()?.path??"");if(!i||i!==o)return null;let s=n.canvas?.selection?Array.from(n.canvas.selection):[];if(s.length!==1)return null;let a=s[0]?.id;return typeof a=="string"&&a.length>0?a:null}function dK(r){return typeof r=="string"?r:r&&typeof r=="object"&&"path"in r&&typeof r.path=="string"?r.path:"(missing file path)"}function uK(r){return typeof r.x!="number"||typeof r.y!="number"||typeof r.width!="number"||typeof r.height!="number"?"":`${Math.round(r.x)},${Math.round(r.y)} \xB7 ${Math.round(r.width)}x${Math.round(r.height)}`}function ES(r,t){return r.length<=t?r:r.slice(0,t-1)+"\u2026"}async function $O(r,t){try{let e=await r.vault.cachedRead(t),n=JSON.parse(e);if(!n||typeof n!="object")return[];let i=n.nodes;if(!Array.isArray(i))return[];let o=i.filter(a=>!!a&&typeof a=="object"&&typeof a.id=="string").map(a=>{let l=a.type==="text"?"text":a.type==="file"?"file":"other",c=uK(a);if(l==="text"){let h=(typeof a.text=="string"?a.text:"").split(`
- `).map(y=>y.trim()).filter(y=>y.length>0),g=ES(h[0]??"(empty text card)",90),v=[`${h.length} line${h.length===1?"":"s"}`];c&&v.push(c);let b=v.join(" \xB7 ");return{id:a.id,type:l,title:g,subtitle:b,searchText:`${a.id} ${g} ${b}`.toLowerCase(),capturable:!0,capturableReason:""}}if(l==="file"){let m=dK(a.file),h=xt.test(m),g=h?"":"Canvas file cards must link to markdown files (.md).",v=ES(m.split("/").pop()??m,90),b=[ES(m,120)];c&&b.push(c),h||b.push("Not capturable in this version");let y=b.join(" \xB7 ");return{id:a.id,type:l,title:v,subtitle:y,searchText:`${a.id} ${v} ${y}`.toLowerCase(),capturable:h,capturableReason:g}}let u=`Unsupported node (${typeof a.type=="string"&&a.type.length>0?a.type:"unknown"})`,p=c||"Type is not currently capturable";return{id:a.id,type:l,title:u,subtitle:p,searchText:`${a.id} ${u} ${p}`.toLowerCase(),capturable:!1,capturableReason:"This Canvas node type is not capturable."}}),s={text:0,file:1,other:2};return o.sort((a,l)=>{let c=s[a.type]-s[l.type];return c!==0?c:a.title.localeCompare(l.title)})}catch{return[]}}tr();Fh();Ps();on();lt();Ve();var AK=["noteContent","propertyValue","captureTarget","fileName","lineTarget"],IK=["captureTarget","fileName"],cr=AK,WO=3;function Ce(r,t,e=r.endsWith(":}}")?2:0){return{insert:r,description:t,caretOffset:e}}var PK=[{regex:aO,contexts:cr,suggestion:Ce("{{VALUE}}","Asks you for text when the choice runs")},{regex:lO,contexts:cr,suggestion:Ce("{{VALUE:}}","Asks once and reuses the answer by name, or lists options to pick from"),expansions:()=>[Ce("{{VALUE:title}}",'Asks once, then reuses the answer as "title"'),Ce("{{VALUE:option1,option2,option3}}","Asks you to pick one of these options"),Ce("{{VALUE:option1,option2,option3|custom}}","Same, but you can also type your own"),Ce("{{VALUE:title|label:Note title}}","Words the prompt yourself"),Ce("{{VALUE:option1,option2|label:Pick one}}","A list with your own prompt text"),Ce("{{VALUE:title|label:Note title|default:Untitled}}","Opens the prompt with an answer already filled in"),Ce("{{VALUE:<items>|text:<display items>}}","Shows one label in the list and inserts another"),Ce("{{VALUE:option1,option2|name:category}}","Names the pick, so {{VALUE:category}} reuses it"),Ce("{{VALUE:title|case:kebab}}","Reshapes the answer; type |case: for every style"),Ce("{{VALUE:title|trim}}","Trims whitespace off the answer"),Ce("{{VALUE:title|optional}}","Lets the prompt be skipped, leaving it empty")]},{regex:sO,contexts:cr,suggestion:Ce("{{NAME}}","Another name for {{VALUE}}; they do the same thing")},{regex:cO,contexts:cr,suggestion:Ce("{{VDATE:}}",'Asks you for a date; "tomorrow" works'),expansions:()=>[Ce("{{VDATE:date,YYYY-MM-DD}}",'Asks for a date, reused by name as "date"'),Ce("{{VDATE:date,YYYY-MM-DD|today}}","Same, with today filled in"),Ce("{{VDATE:dueDate,YYYY-MM-DD|next monday}}","Same, starting at next Monday"),Ce("{{VDATE:dueDate,YYYY-MM-DD|optional}}","Same, but skippable"),Ce("{{VDATE:date,dddd, MMMM Do, YYYY|case:lower}}","Lowercases the picked date after formatting")]},{regex:hO,contexts:cr,suggestion:Ce("{{FIELD:}}","Suggests values a property already has in your vault, like {{FIELD:project}}")},{regex:wO,contexts:["noteContent","propertyValue"],suggestion:Ce("{{PROPERTY}}","Inserts the property's current value (property Captures only)")},{regex:CO,contexts:["noteContent"],suggestion:Ce("{{CURSOR}}","Places the cursor here (Capture and Template bodies)")},{regex:fO,contexts:cr,suggestion:Ce("{{FILE:}}","Picks a note from a folder"),expansions:({context:r})=>{let t=[Ce("{{FILE:<folder>}}","Picks a note from that folder and inserts its name")];return IK.includes(r)||t.push(Ce("{{FILE:<folder>|link}}","Same, but inserts a link to the note"),Ce("{{FILE:<folder>|path}}","Same, but inserts its full path"),Ce("{{FILE:<folder>|type:image|link}}","Same, but links an image instead of a note"),Ce("{{FILE:<folder>|optional}}","Same, but skippable")),t.push(Ce("{{FILE:<folder>|custom}}","Same, but you can also type a name that is not there yet")),t}},{regex:yO,contexts:cr,suggestion:Ce("{{MVALUE}}","Asks you for a math formula (LaTeX), with a live preview")},{regex:iO,contexts:cr,suggestion:Ce("{{DATE}}","Today's date, as YYYY-MM-DD")},{regex:oO,contexts:cr,suggestion:Ce("{{DATE:}}","Today's date in a format you choose, like {{DATE:MMMM Do}}"),expansions:({formatDate:r})=>[...["YYYY-MM-DD","MMMM Do, YYYY","ddd D MMM","gggg-[W]ww"].map(t=>Ce(`{{DATE:${t}}}`,r(t))),Ce("{{DATE+7}}","Seven days from today"),Ce("{{DATE:YYYY-MM-DD|startof:week}}","Snapped to the start of the week, month, quarter or year"),Ce("{{DATE:dddd, MMMM Do, YYYY|case:lower}}","Lowercases the formatted date")]},{regex:kO,contexts:cr,suggestion:Ce("{{TIME}}","The current time, as HH:mm")},{regex:SO,contexts:cr,suggestion:Ce("{{TIME:}}","The current time in a format you choose, like {{TIME:HH.mm}}"),expansions:()=>[Ce("{{TIME:A|case:lower}}","Lowercases formatted text, such as AM to am")]},{regex:yS,contexts:cr,suggestion:Ce("{{DAILY}}","The daily note's path, from your Daily notes settings")},{regex:yS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{DAILY|link}}","A link to the daily note")},{regex:bS,contexts:cr,suggestion:Ce("{{WEEKLY}}","This week's note, from your Periodic Notes settings")},{regex:bS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{WEEKLY|link}}","A link to this week's note")},{regex:wS,contexts:cr,suggestion:Ce("{{MONTHLY}}","This month's note, from your Periodic Notes settings")},{regex:wS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{MONTHLY|link}}","A link to this month's note")},{regex:CS,contexts:cr,suggestion:Ce("{{QUARTERLY}}","This quarter's note, from your Periodic Notes settings")},{regex:CS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{QUARTERLY|link}}","A link to this quarter's note")},{regex:xS,contexts:cr,suggestion:Ce("{{YEARLY}}","This year's note, from your Periodic Notes settings")},{regex:xS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{YEARLY|link}}","A link to this year's note")},{regex:dO,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{LINKCURRENT}}","A link to that note: [[That note]]")},{regex:uO,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{LINKSECTION}}","A link to the section your cursor is in")},{regex:pO,contexts:["noteContent","propertyValue","captureTarget","fileName","lineTarget"],suggestion:Ce("{{FILENAMECURRENT}}","That note's file name")},{regex:vS,contexts:["noteContent","propertyValue","captureTarget"],suggestion:Ce("{{FOLDERCURRENT}}","That note's folder")},{regex:vS,contexts:["fileName"],suggestion:Ce("{{FOLDERCURRENT|name}}","That note's folder name, without the path")},{regex:xO,contexts:cr,suggestion:Ce("{{SELECTED}}","The text you had selected in the editor")},{regex:bO,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{TITLE}}","The new note's file name")},{regex:mO,contexts:["fileName"],suggestion:Ce("{{FOLDER|name}}","The name of the folder the new note lands in")},{regex:EO,contexts:cr,suggestion:Ce("{{CLIPBOARD}}","Whatever you copied last")},{regex:gO,contexts:cr,suggestion:Ce("{{TEMPLATE:}}","The contents of a template file"),expansions:({templatePaths:r})=>r.map(t=>Ce(`{{TEMPLATE:${t}}}`,"Inserts this template's contents"))},{regex:vO,contexts:cr,suggestion:Ce("{{MACRO:}}","Whatever a macro returns"),expansions:({macroNames:r})=>[...r.map(t=>Ce(`{{MACRO:${t}}}`,`Runs your "${t}" macro`)),Ce("{{MACRO:MyMacro|label:Label}}","Word the macro's own prompt yourself")]},{regex:_O,contexts:cr,suggestion:Ce("{{GLOBAL_VAR:}}","A snippet you defined in QuickAdd's settings"),expansions:({globalVariableNames:r})=>r.map(t=>Ce(`{{GLOBAL_VAR:${t}}}`,`Inserts your "${t}" snippet`))},{regex:TO,contexts:cr,suggestion:Ce("{{RANDOM:}}","A random ID of the length you give, like {{RANDOM:6}}")}],GO=[{insert:"kebab",description:"my-note-title",caretOffset:0,isFragment:!0},{insert:"snake",description:"my_note_title",caretOffset:0,isFragment:!0},{insert:"camel",description:"myNoteTitle",caretOffset:0,isFragment:!0},{insert:"pascal",description:"MyNoteTitle",caretOffset:0,isFragment:!0},{insert:"title",description:"My Note Title",caretOffset:0,isFragment:!0},{insert:"lower",description:"my note title",caretOffset:0,isFragment:!0},{insert:"upper",description:"MY NOTE TITLE",caretOffset:0,isFragment:!0},{insert:"slug",description:"my-note-title, guarded against reserved file names",caretOffset:0,isFragment:!0}];function jO(r){return PK.filter(t=>t.contexts.includes(r))}var $K=/^\{\{(VALUE|NAME|DATE|TIME|VDATE)([^\n\r}]*)\|case:([a-z-]*)$/i,YO=/^\{\{GLOBAL_VAR:[ \t]*([^\n\r}]*)$/i,KO="{{GLOBAL_VAR:",FK=new Set(["DATE","TIME","VDATE"]),MK=/<[^<>\n\r]+>/,sn=class extends Er{constructor(e,n,i,o="noteContent"){super(e,n);this.app=e;this.inputEl=n;this.plugin=i;this.context=o;this.replaceFrom=0;this.completingGlobalVarName=!1;this.matchedQuery="";this.macroNames=Jt(this.plugin.settings.choices).filter(s=>s.type==="Macro").map(s=>s.name),this.templatePaths=this.plugin.getTemplateFiles().map(s=>s.path)}getSuggestions(e){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=e.lastIndexOf("{{",n-1);if(i===-1)return[];this.completingGlobalVarName=!1;let o=e.slice(i,n);if(o.includes("}}"))return[];let s=o.match($K);if(s){let g=s[1]?.toUpperCase()??"",v=s[2]??"";if(FK.has(g)&&v.lastIndexOf("[")>v.lastIndexOf("]"))return[];let b=s[3]??"";this.matchedQuery=b,this.replaceFrom=n-b.length;let y=b.toLowerCase();return GO.filter(C=>C.insert.startsWith(y)).map(C=>({...C}))}let a=o.match(YO);if(a){let g=a[1]??"";return this.replaceFrom=i,this.matchedQuery=`GLOBAL_VAR:${g}`,this.completingGlobalVarName=!0,Object.keys(this.plugin?.settings?.globalVariables??{}).filter(v=>v.toLowerCase().startsWith(g.toLowerCase())).map(v=>({insert:`${KO}${v}}}`,description:`Inserts your "${v}" snippet`,caretOffset:0}))}if(o.includes(":"))return[];let l=[],c=new Set,d=g=>{c.has(g.insert)||(c.add(g.insert),l.push(g))};this.replaceFrom=i,this.matchedQuery=o.slice(2);let u=jO(this.context).filter(g=>{let v=g.regex.exec(o);return v!==null&&v.index+v[0].length===o.length}),p=this.matchedQuery.toLowerCase(),m=g=>g.suggestion.insert.slice(2).toLowerCase().startsWith(p),h=[...u.filter(m),...u.filter(g=>!m(g))];for(let g of h)if(d(g.suggestion),!!g.expansions&&!(this.matchedQuery.length<WO))for(let v of g.expansions({templatePaths:this.templatePaths,macroNames:this.macroNames,globalVariableNames:Object.keys(this.plugin?.settings?.globalVariables??{}),context:this.context,formatDate:b=>typeof window.moment=="function"?window.moment().format(b):b}))d(v);return l}selectSuggestion(e){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.replaceFrom,o=n;if(this.completingGlobalVarName){let a=this.inputEl.value,l=a.slice(i,n),c=YO.exec(l)?.[1],d=e.insert.slice(KO.length,-2);if(l.lastIndexOf("{{")!==0||c===void 0||!d.toLowerCase().startsWith(c.toLowerCase())){this.close();return}a.startsWith("}}",n)&&(o+=2)}Zb(this.inputEl,i,o,e.insert,{fromCompletion:!0});let s=MK.exec(e.insert);if(s){let a=i+s.index;this.inputEl.setSelectionRange(a,a+s[0].length)}else if(e.caretOffset>0){let a=i+e.insert.length-e.caretOffset;this.inputEl.setSelectionRange(a,a)}this.close()}renderSuggestion(e,n){if(!e)return;n.classList.add("qa-format-suggestion");let i=n.createSpan({cls:e.isFragment?"qa-format-suggestion-token qa-format-suggestion-token-fragment":"qa-format-suggestion-token"});this.renderMatch(i,e.insert,this.matchedQuery),n.createSpan({cls:"qa-format-suggestion-description",text:e.description})}};var RK=F('<label class="setting-item-name"> </label>'),DK=F('<div class="setting-item-name"> </div>'),OK=F('<div class="setting-item-description"> </div>'),LK=F('<div class="qa-field-body"><!></div>'),NK=F('<div><div class="setting-item-info"><!> <!></div> <div class="setting-item-control"><!></div> <!></div>');function be(r,t){let e=X(t,"name",3,void 0),n=X(t,"desc",3,void 0),i=X(t,"heading",3,!1),o=X(t,"labelFor",3,void 0),s=X(t,"control",3,void 0),a=X(t,"children",3,void 0),l=X(t,"body",3,void 0);var c=NK();let d;var u=R(c),p=R(u);{var m=w=>{var T=bt(),P=ae(T);{var _=O=>{var N=RK(),K=re(N,!0);Q(()=>{le(N,"for",o()),ee(K,e())}),A(O,N)},I=O=>{var N=DK(),K=re(N,!0);Q(()=>ee(K,e())),A(O,N)};z(P,O=>{o()?O(_):O(I,-1)})}A(w,T)};z(p,w=>{e()&&w(m)})}var h=E(p,2);{var g=w=>{var T=OK(),P=re(T,!0);Q(()=>ee(P,n())),A(w,T)};z(h,w=>{n()&&w(g)})}$(u);var v=E(u,2),b=R(v);Sl(b,()=>s()??a()??$t),$(v);var y=E(v,2);{var C=w=>{var T=LK(),P=R(T);Sl(P,l),$(T),A(w,T)};z(y,w=>{l()&&w(C)})}$(c),Q(()=>{d=Ge(c,1,"setting-item",null,d,{"setting-item-heading":i(),"qa-field":l()!==void 0}),le(c,"tabindex",i()?void 0:-1)}),A(r,c)}var VK=F('<div class="setting-item setting-item-heading"><div class="setting-item-name"> </div> <div class="setting-item-control"></div></div>'),BK=F('<div class="setting-group"><!> <div class="setting-items"><!></div></div>');function fo(r,t){let e=X(t,"heading",3,void 0);var n=BK(),i=R(n);{var o=l=>{var c=VK(),d=R(c),u=re(d,!0);Xt(2),$(c),Q(()=>ee(u,e())),A(l,c)};z(i,l=>{e()&&l(o)})}var s=E(i,2),a=R(s);Sl(a,()=>t.children),$(s),$(n),A(r,n)}var UK=F('<div role="switch"><input type="checkbox" tabindex="-1" aria-hidden="true" class="svelte-ecj6o4"/></div>'),qK={hash:"svelte-ecj6o4",code:`
- /* Let clicks fall through to the container so a single handler owns toggling. */.checkbox-container.svelte-ecj6o4 > input:where(.svelte-ecj6o4) {pointer-events:none;}`};function vt(r,t){ie(t,!0),Ae(r,qK);let e=X(t,"checked",15),n=X(t,"disabled",3,!1),i=X(t,"ariaLabel",3,void 0),o=X(t,"onchange",3,void 0),s=k(()=>e()??!1);function a(){n()||(e(!f(s)),o()?.(e()))}function l(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),a())}var c=UK();let d;var u=R(c);Ct(u),$(c),Q(()=>{d=Ge(c,1,"checkbox-container svelte-ecj6o4",null,d,{"is-enabled":f(s),"is-disabled":n()}),le(c,"aria-checked",f(s)),le(c,"aria-label",i()),le(c,"tabindex",n()?-1:0),hd(u,f(s))}),ge("click",c,a),ge("keydown",c,l),A(r,c),oe()}He(["click","keydown"]);var zK=F("<option> </option>"),HK=F('<select class="dropdown"></select>');function it(r,t){ie(t,!0);let e=X(t,"value",15,""),n=X(t,"disabled",3,!1),i=X(t,"ariaLabel",3,void 0),o=X(t,"onchange",3,void 0);var s=HK();gt(s,21,()=>t.options,a=>a.value,(a,l)=>{var c=zK(),d=re(c,!0),u={};Q(()=>{ee(d,f(l).label),u!==(u=f(l).value)&&(c.value=(c.__value=u)??"")}),A(a,c)}),$(s),Pl(s),Q(()=>{s.disabled=n(),le(s,"aria-label",i())}),ge("change",s,()=>o()?.(e())),Zk(s,e),A(r,s),oe()}He(["change"]);dp();Ps();on();var hi=class extends Er{constructor(e,n,i,o=1/0){super(e,n);this.app=e;this.inputEl=n;this.items=i;this.maxSuggestions=o;this.matchesByItem=new Map;this.items=i.map(s=>nn(s))}getSuggestions(e){let n=Ll(Ol(e),this.items,i=>i,{limit:this.maxSuggestions});return this.matchesByItem=new Map(n.map(({item:i,matches:o})=>[i,o])),n.map(({item:i})=>i)}selectSuggestion(e){this.inputEl.value=e,Sa(this.inputEl),this.close()}renderSuggestion(e,n){Is(n,Jb(e),this.matchesByItem.get(e)??[])}};function WK(r){return r?Array.isArray(r)?r:[r]:[]}function _d(r,t){let e=WK(t(r));return{destroy(){e.forEach(n=>n.destroy())}}}Nh();var KK=F("<textarea></textarea>"),QK=F('<input type="text"/>'),XK=F('<!> <div aria-live="polite"> </div>',1);function Dr(r,t){ie(t,!0);let e=X(t,"value",15,""),n=X(t,"placeholder",3,void 0),i=X(t,"inputKind",3,"text"),o=X(t,"required",3,!1),s=X(t,"requiredMessage",3,"This field is required"),a=X(t,"disabled",3,!1),l=X(t,"validator",3,void 0),c=X(t,"trim",3,!0),d=X(t,"suggestions",3,void 0),u=X(t,"maxSuggestions",3,1/0),p=X(t,"makeSuggesters",19,()=>[]),m=X(t,"app",3,void 0),h=X(t,"id",3,void 0),g=X(t,"ariaLabel",3,void 0),v=X(t,"onChange",3,void 0),b=pe(!1),y=pe(!1),C=pe(""),w=pe("neutral"),T=0,P=!1,_=`qa-hint-${Math.random().toString(36).slice(2)}`,I=te=>c()?te.trim():te;function O(te,W=!1,Z="neutral"){q(b,W,!0),q(C,te??"",!0),q(w,W?"neutral":Z,!0)}async function N(te){if(o()&&I(te).length===0)return O(f(y)?s():void 0,f(y)),!1;if(!l())return O(void 0),!0;let W=++T,Z=await Promise.resolve(l()(te));return W!==T||P?!0:typeof Z=="boolean"?(O(Z?void 0:"Invalid value",!Z),Z):typeof Z=="string"?(O(Z,!0),!1):(O(Z.message??(Z.valid?void 0:"Invalid value"),!Z.valid,Z.valid?Z.variant??"neutral":"neutral"),Z.valid)}function K(te){let W=te.currentTarget.value;q(y,!0),e(W),v()?.(W)}Ot(()=>{o(),f(y);let te=e();N(te)}),Ot(()=>()=>{P=!0});function ne(te){let W=[];m()&&d()&&d().length&&W.push(new hi(m(),te,d(),u()));for(let Z of p()){let se=Z(te);se&&W.push(se)}return W}var H=XK(),D=ae(H);{var G=te=>{var W=KK();Jc(W);let Z;le(W,"spellcheck",!1),Ft(W,(se,ce)=>_d?.(se,ce),()=>ne),Ft(W,se=>nw?.(se)),Q(()=>{Z=Ge(W,1,"qa-validated-input-full-width qa-validated-input-margin-8 qa-validated-input-textarea",null,Z,{"is-invalid":f(b),"is-valid":!f(b)&&f(w)==="success"&&f(C).length>0}),le(W,"id",h()),le(W,"placeholder",n()),W.disabled=a(),le(W,"aria-label",g()),le(W,"aria-invalid",f(b)),le(W,"aria-describedby",_),Xn(W,e())}),ge("input",W,K),Yn("blur",W,()=>q(y,!0)),A(te,W)},V=te=>{var W=QK();Ct(W);let Z;le(W,"spellcheck",!1),Ft(W,(se,ce)=>_d?.(se,ce),()=>ne),Q(()=>{Z=Ge(W,1,"qa-validated-input-full-width qa-validated-input-margin-8",null,Z,{"is-invalid":f(b),"is-valid":!f(b)&&f(w)==="success"&&f(C).length>0}),le(W,"id",h()),le(W,"placeholder",n()),W.disabled=a(),le(W,"aria-label",g()),le(W,"aria-invalid",f(b)),le(W,"aria-describedby",_),Xn(W,e())}),ge("input",W,K),Yn("blur",W,()=>q(y,!0)),A(te,W)};z(D,te=>{i()==="textarea"?te(G):te(V,-1)})}var M=E(D,2);let B;var J=re(M,!0);Q(()=>{B=Ge(M,1,"qa-field-hint",null,B,{"qa-field-hint--neutral":!f(b)&&f(w)==="neutral","qa-field-hint--success":!f(b)&&f(w)==="success"}),le(M,"id",_),ee(J,f(C))}),A(r,H),oe()}He(["input"]);function ri(r,t){let e=$i(),n=a=>{var l=bt(),c=ae(l);Sl(c,()=>t.children,()=>e),A(a,l)},i=X(t,"desc",3,void 0),o=X(t,"control",3,void 0),s=X(t,"bodyVisible",3,!0);{let a=k(()=>s()?e:void 0),l=k(()=>s()?n:void 0);be(r,{get name(){return t.name},get desc(){return i()},get control(){return o()},get labelFor(){return f(a)},get body(){return f(l)}})}}Pa();$p();function gA(r){let t=r.replace(/^\[(QuickAdd:[\s\S]*)\]$/i,"$1");if(/^QuickAdd:/i.test(t))return t.replace(/^QuickAdd:\s*/i,"");let e=t.replace(/^QuickAdd\s+/,"");return e===t?t:e.charAt(0).toUpperCase()+e.slice(1)}var Fp=class{formatOutputString(t){return`QuickAdd: (${t.level}) ${gA(t.message)}`}getQuickAddError(t,e,n,i){return{message:t,level:e,time:Date.now(),stack:n,originalError:i}}};nt();var Jl=class{constructor(){this.entries=[];this.seen=new Set}add(t,e,n){let i=gA(e).trim();if(!i)return;let o=`${t} ${i}`;this.seen.has(o)||(this.seen.add(o),this.entries.push({severity:t,message:i,...n?{kind:n}:{}}))}list(){return this.entries}get hasError(){return this.entries.some(t=>t.severity==="error")}};function Mp(r){if(Be(r))return null;if(!(r instanceof Error))return SL;let t=r.message??"";return Be(t)?null:t.startsWith("Unable to parse variable")?"This token is incomplete. {{VALUE:}} needs a name, for example {{VALUE:title}}.":t.trim()?t:SL}var SL="Preview unavailable - this format could not be resolved.";Qo();var T3={title:"My Document Title",name:"Document Name",project:"Project Alpha",category:"Notes",author:"Your Name",status:"Draft",priority:"High",tag:"important",type:"meeting",client:"Acme Corp"},_3={clipboard:"clipboard_content",date:"formatted_date",time:"current_time",random:"random_value",uuid:"unique_id"},k3=[{pattern:/date|time/i,example:"2024-01-15"},{pattern:/title|name/i,example:"Example Title"},{pattern:/tag/i,example:"important"},{pattern:/category|type/i,example:"Notes"},{pattern:/author|user/i,example:"Your Name"},{pattern:/project/i,example:"Project Alpha"},{pattern:/status/i,example:"In Progress"},{pattern:/priority/i,example:"High"},{pattern:/number|count|id/i,example:"001"}];function LL(r){let t=r.toLowerCase(),e=T3[t];return e||`${r}_example`}function NL(r){return _3[r.toLowerCase()]||`${r}_output`}function VL(r){for(let{pattern:t,example:e}of k3)if(t.test(r))return e;return`${r}_value`}function hg(r){return r.length>0?`${r[0]} (${r.length} options)`:"suggestion_list"}function BL(r,t){return Vd(r).length>0?t:r}function UL(r){let t=r.fieldName.trim();return t?`${t}_field_value`:"field_value"}function qL(r){return r?.path?r.basename:"current_file"}function vA(r){return`${r?.path?r.basename:"current_file"}#Section`}function zL(r){return r?.basename||"current_filename"}function HL(r){if(!r)return"current_folder";let t=r.parent?.path??"";return t==="/"?"":t}var Oa=class{static generate(t,e=new Date){let n=e.getFullYear(),i=this.getWeekNumber(e),o=e.getDate(),s=[["YYYY",n.toString()],["YY",n.toString().slice(-2)],["MMMM",this.MONTH_NAMES[e.getMonth()]],["MMM",this.MONTH_NAMES_SHORT[e.getMonth()]],["MM",(e.getMonth()+1).toString().padStart(2,"0")],["M",(e.getMonth()+1).toString()],["dddd",this.DAY_NAMES[e.getDay()]],["ddd",this.DAY_NAMES_SHORT[e.getDay()]],["Do",`${o}${this.ordinalSuffix(o)}`],["DD",e.getDate().toString().padStart(2,"0")],["D",o.toString()],["HH",e.getHours().toString().padStart(2,"0")],["H",e.getHours().toString()],["mm",e.getMinutes().toString().padStart(2,"0")],["m",e.getMinutes().toString()],["ss",e.getSeconds().toString().padStart(2,"0")],["s",e.getSeconds().toString()],["ww",i.toString().padStart(2,"0")],["w",i.toString()]],a="",l=0;for(;l<t.length;){let c=!1;for(let[d,u]of s)if(t.startsWith(d,l)){a+=u,l+=d.length,c=!0;break}c||(a+=t[l],l+=1)}return a}static ordinalSuffix(t){let e=t%100;if(e>=11&&e<=13)return"th";switch(t%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}}static getWeekNumber(t){let e=new Date(t.getFullYear(),0,1),n=(t.getTime()-e.getTime())/864e5;return Math.ceil((n+e.getDay()+1)/7)}};Oa.MONTH_NAMES=["January","February","March","April","May","June","July","August","September","October","November","December"],Oa.MONTH_NAMES_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Oa.DAY_NAMES=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Oa.DAY_NAMES_SHORT=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];Pd();Jh();function WL(r){let t=new Date;return r?wp(window.moment(t),r).toDate():t}gi();Ln();yo();var Op=class extends Xl{constructor(){super(...arguments);this.diagnostics=new Jl}warn(e){this.diagnostics.add("warning",e)}reportProblem(e){this.diagnostics.add("error",e)}standIn(e,n){return e}promptForValue(e){return this.standIn(e||this.valuePromptContext?.label||"user input","user input")}getVariableValue(e){let n=this.variables.get(e);if(typeof n=="string")return n;let i=GS(e);return this.standIn(LL(i),"user input")}async promptForVariable(e,n){let i=rg(this.variables,n?.variableKey??e);return i?Oa.generate(i):this.standIn(VL(e),"user input")}getMacroValue(e,n){return this.standIn(NL(e),"macro_output")}async suggestForField(e,n){return this.standIn(UL(n),"field_value")}getCurrentFileLink(){return this.app?qL(this.app.workspace.getActiveFile()):null}getCurrentFileLinkToSection(){return this.app?vA(this.app.workspace.getActiveFile()):vA(null)}getCurrentFileName(){return this.app?zL(this.app.workspace.getActiveFile()):"current_filename"}getCurrentFolderPath(){return this.app?HL(this.app.workspace.getActiveFile()):"current_folder"}previewDateVariable(e,n,i,o){let{withTime:s,snap:a,caseStyle:l}=o,c=i?.trim()||tg(s);KS(this.variables,n,c);let d=ig(this.variables.get(n),c,a,this.dateParser);if(d)return{format:c,text:this.applyCaseOption(d.text,l,e),answered:!0};try{let u=Oa.generate(c,WL(a));return{format:c,text:this.applyCaseOption(u,l,e),answered:!1}}catch{return{format:c,answered:!1}}}promptForMathValue(){return Promise.resolve("calculation_result")}async getSelectedText(){return"selected_text"}async getClipboardContent(){return"clipboard_content"}suggestForFile(e){let n=this.app?Dp(this.app,e):[];return n.length>0?`${Gl}${n[0].path}`:`${Ko}${e.folderPath||"file"}`}isTemplatePropertyTypesEnabled(){return!1}};yg();tr();Ve();Hd();eg();var Hp=class extends Op{constructor(e,n,i,o={}){super(e);this.plugin=n;this.opts=o;this.dateParser=i||To}async format(e){this.diagnostics=new Jl;try{return Dn(await this.formatInternal(e,{expandLinebreakEscapes:!0}))}catch(n){let i=Mp(n);return i&&this.diagnostics.add("error",i),Dn(e)}}async formatInternal(e,{expandLinebreakEscapes:n}){let i=e;return i=await this.replaceGlobalVarInString(i),n&&(i=this.expandLinebreakEscapesOutsideTokens(i)),i=this.replaceDateInString(i),i=this.replaceTimeInString(i),i=await this.replaceValueInString(i),i=await this.replaceSelectedInString(i),i=await this.replaceClipboardInString(i),i=await this.replaceDateVariableInString(i),i=await this.replaceVariableInString(i),i=this.replaceCurrentFileTokensInString(i,{links:!0,fileName:!0,folder:!0,...this.opts.resolveActiveFolder===!1?{}:{activeFolder:"content"}}),i=await this.replaceMacrosInString(i),i=await this.replaceTemplateInString(i),i=await this.replaceFieldVarInString(i),i=await this.replaceFileInString(i),i=await this.replaceMathValueInString(i),i=this.replaceRandomInString(i),i}async replaceGlobalVarInString(e){return Zl(e,this.plugin?.settings?.globalVariables)}suggestForValue(e,n=!1,i){return hg(i?.displayValues??e)}suggestForValueMulti(e,n,i){return[hg(i?.displayValues??e)]}async getTemplateContent(e){let n=this.app;if(!n)return this.reportProblem(`Template preview unavailable: ${e}`),`[QuickAdd: template preview unavailable] ${e}`;let i=Rn(n,e);if(!i)return this.reportProblem(`Template not found: ${e}`),`[QuickAdd: template not found] ${e}`;this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0}),this.templateInclusion.depth++;try{return await this.formatInternal(await n.vault.cachedRead(i),{expandLinebreakEscapes:!1})}catch(o){let s=Mp(o);return s&&this.diagnostics.add("error",s),`[QuickAdd: template preview failed] ${e}`}finally{this.templateInclusion.depth--}}async replaceDateVariableInString(e){return e.replace(new RegExp(Ts.source,"gi"),(n,i,o,s)=>{let{options:a,error:l}=ww(s);l&&this.reportProblem(l);let c=i?.trim();if(!c)return n;let d=this.previewDateVariable(n,c,o,a);if(d.answered)return d.text;let u=d.text??`[${d.format} format]`;return a.defaultValue&&(u+=` (default: ${a.defaultValue})`),a.optional&&(u+=" (optional)"),u})}replaceRandomInString(e){let n=e;return n=n.replace(/{{RANDOM:(\d+)}}/gi,(i,o)=>{let s=parseInt(o);if(s<=0||s>100)return i;let a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",l="";for(let c=0;c<Math.min(s,8);c++)l+=a.charAt(Math.floor(Math.random()*a.length));return s>8&&(l+=`... (${s} chars)`),l}),n}};Pa();yg();$p();eg();var Wp=require("obsidian");Ve();Hd();Qo();tr();var f1=25;function K4(r){let t=r.lastIndexOf("{{");return t===-1?!1:r.indexOf("}}",t+2)===-1}function Q4(r){let t=bo(r);if(t.length===0)return r;let e="",n=0;for(let i of t)e+=r.slice(n,i.start),n=i.end;return e+r.slice(n)}var Gp=class extends Op{constructor(e,n,i){super(e);this.plugin=n;this.templateIncludeBudget=f1;this.dateParser=i||To}setRunClocks(e){this.clocks=e}async format(e){let n=e;this.diagnostics=new Jl,this.templateIncludeBudget=f1;try{n=Dn(await this.formatInternal(e,{included:!1}))}catch(o){let s=Mp(o);return s&&this.diagnostics.add("error",s),Dn(e)}this.reportCircularTitle(e,n);let i=DL(n);for(let o of i.problems)this.diagnostics.add("error",o,"path");return this.reportIllegalChars(e,n),i.path}reportCircularTitle(e,n){!uo.test(e)&&!uo.test(n)||this.reportProblem("A file name cannot contain {{title}}, because the title is derived from the file name itself - so this choice would fail at run time.")}reportIllegalChars(e,n){if(this.diagnostics.hasError||K4(e)||QS(e))return;let i=Vd(Q4(n));i.length!==0&&(this.existsInVault(n)||this.diagnostics.add("error",$L(i),"path"))}existsInVault(e){let n=this.app?.vault;if(typeof n?.getAbstractFileByPath!="function")return!1;let i=e.trim();return i?i.endsWith("/")?n.getAbstractFileByPath(i.slice(0,-1))instanceof Wp.TFolder:n.getAbstractFileByPath(i)instanceof Wp.TFile||n.getAbstractFileByPath(`${i}.md`)instanceof Wp.TFile?!0:n.getAbstractFileByPath(i)instanceof Wp.TFolder:!1}async formatInternal(e,{included:n}){let i=e;return i=await this.replaceTemplateOutsideScripts(i),i=await this.replaceGlobalVarInString(i),i=await this.replaceMacrosInString(i),i=this.replaceDateInString(i),i=this.replaceTimeInString(i),i=await this.replaceValueInString(i),i=await this.replaceSelectedInString(i),i=await this.replaceClipboardInString(i),i=await this.replaceDateVariableInString(i),i=await this.replaceVariableInString(i),i=await this.replaceFieldVarInString(i),i=await this.replaceFileInString(i),i=await this.replaceMathValueInString(i),i=this.replaceCurrentFileTokensInString(i,n?{links:!0,fileName:!0,folder:!0,activeFolder:"content"}:{fileName:!0,folder:!0,activeFolder:"path"}),i=this.replaceRandomInString(i),i}async replaceGlobalVarInString(e){return Zl(e,this.plugin?.settings?.globalVariables)}standIn(e,n){return BL(e,n)}suggestForValue(e,n=!1,i){return e[0]??hg(e)}async replaceTemplateOutsideScripts(e){let n=bo(e);if(n.length===0)return this.replaceTemplateInString(e);let i="",o=0;for(let s of n)i+=await this.replaceTemplateInString(e.slice(o,s.start)),i+=e.slice(s.start,s.end),o=s.end;return i+await this.replaceTemplateInString(e.slice(o))}async getTemplateContent(e){let n=this.app;if(!n)return this.reportProblem(`Template preview unavailable: ${e}`),`[QuickAdd: template preview unavailable] ${e}`;if(this.templateIncludeBudget<=0){let o="[QuickAdd: too many template includes to preview]";return this.reportProblem(o),o}let i=Rn(n,e);if(!i)return this.reportProblem(`Template not found: ${e}`),`[QuickAdd: template not found] ${e}`;this.templateIncludeBudget--,this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0}),this.templateInclusion.depth++;try{let o=await n.vault.cachedRead(i),s=this.resolveTitleInIncludedBody(await this.formatInternal(o,{included:!0}));return this.warnIfJoinedIntoOneLine(e,s),s}catch(o){let s=Mp(o);return s&&this.diagnostics.add("error",s),`[QuickAdd: template preview failed] ${e}`}finally{this.templateInclusion.depth--}}resolveTitleInIncludedBody(e){if(!uo.test(e))return e;let n=this.variables.get("title"),i=typeof n=="string"?n:"";return e.replace(new RegExp(uo.source,"gi"),()=>i)}warnIfJoinedIntoOneLine(e,n){let i=n.split(/\r?\n/).filter(o=>o.trim());i.length<2||this.warn(`Template "${e}" is ${i.length} lines; a file name is one line, so they are joined with spaces.`)}async replaceDateVariableInString(e){return e.replace(new RegExp(Ts.source,"gi"),(n,i,o,s)=>{let a=i?.trim();if(!a)return n;let{options:l,error:c}=ww(s);c&&this.reportProblem(c);let d=this.previewDateVariable(n,a,o,l);return d.text??`[${d.format}]`})}replaceRandomInString(e){let n=e;return n=n.replace(/{{RANDOM:(\d+)}}/gi,(i,o)=>{let s=parseInt(o);if(s<=0||s>100)return i;let a="ABC123",l="";for(let c=0;c<Math.min(s,6);c++)l+=a.charAt(c%a.length);return s>6&&(l+="..."),l}),n}};var X4=F('<div><span class="qa-visually-hidden"> </span> </div>'),J4=F('<div class="qa-preview-issues"></div>'),Z4=F('<div><span class="qa-preview-label"> </span><span class="qa-preview-value" aria-live="polite"> </span></div> <!>',1);function Bi(r,t){ie(t,!0);let e=X(t,"formatterKind",3,"format"),n=500,i=pe(""),o=pe(Ze([])),s=pe(!1),a=0,l=k(()=>t.value.trim().length>0),c=k(()=>t.hideWhen?t.hideWhen(f(i))&&!f(o).some(v=>v.severity==="error"&&v.kind!=="path"):!1),d=k(()=>f(s)?f(o).filter(v=>v.severity==="error"):[]),u=k(()=>f(d).some(v=>v.kind!=="path")),p=k(()=>!f(u)&&f(d).length>0);Ot(()=>{let v=t.value;if(!v.trim()){a++,q(i,""),q(o,[],!0);return}let b=e()==="fileName"?new Gp(t.app,t.plugin):new Hp(t.app,t.plugin,void 0,{resolveActiveFolder:e()!=="lineTarget"});b.setTargetFolderPath(t.targetFolderPath===null?null:t.targetFolderPath?.trim()?t.targetFolderPath:"Folder/Name");let y=++a;(async()=>{try{let C=await b.format(v);if(y!==a)return;q(i,C,!0),q(o,b.diagnostics.list(),!0)}catch{if(y!==a)return;q(i,v,!0),q(o,[{severity:"error",message:"Preview unavailable."}],!0)}})()}),Ot(()=>{t.value,q(s,!1);let v=setTimeout(()=>{q(s,!0)},n);return()=>clearTimeout(v)});var m=bt(),h=ae(m);{var g=v=>{var b=Z4(),y=ae(b);let C;var w=R(y),T=re(w,!0),P=E(w),_=re(P,!0);$(y);var I=E(y,2);{var O=N=>{var K=J4();gt(K,21,()=>f(o),ne=>ne.severity+ne.message,(ne,H)=>{var D=X4();let G;var V=R(D),M=re(V,!0),B=E(V,1,!0);$(D),Q(()=>{G=Ge(D,1,"qa-preview-issue",null,G,{"qa-preview-issue--error":f(H).severity==="error"}),le(D,"title",f(H).message),ee(M,f(H).severity==="error"?"Error: ":"Warning: "),ee(B,f(H).message)}),A(ne,D)}),$(K),A(N,K)};z(I,N=>{f(s)&&f(o).length>0&&N(O)})}Q(()=>{C=Ge(y,1,"qa-preview-row",null,C,{"qa-preview-row--one-line":e()==="fileName"}),le(y,"title",e()==="fileName"?f(i):void 0),ee(T,f(u)?"Unresolved: ":f(p)?"Won't be created: ":"Preview: "),ee(_,f(i))}),A(v,b)};z(h,v=>{f(l)&&!f(c)&&v(g)})}A(r,m),oe()}Go();ye();var Qg="https://quickadd.obsidian.guide",es={gettingStarted:`${Qg}/docs/`,formatSyntax:`${Qg}/docs/FormatSyntax/`,onePageInputs:`${Qg}/docs/Advanced/onePageInputs/`,userScripts:`${Qg}/docs/Choices/MacroChoice/#user-scripts`,packages:`${Qg}/docs/Choices/Packages/`};function h1(r,t){try{(t?Mh(t):window).open(r,"_blank","noopener,noreferrer")}catch(e){S.logError(`QuickAdd: Failed to open documentation (${r}): ${e}`)}}function Kw(r,t,e){let n=At(r,"a");return n.textContent=e,n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.classList.add("quickadd-docs-link"),r.append(n),n}var e6=F('<div class="qa-token-hint">Type <code>{{</code> to insert a token · <a class="quickadd-docs-link" target="_blank" rel="noopener noreferrer">Format syntax</a></div>');function Wd(r,t){ie(t,!0);let e=k(()=>!t.value.includes("{{"));var n=bt(),i=ae(n);{var o=s=>{var a=e6(),l=E(R(a),3);$(a),Q(()=>le(l,"href",es.formatSyntax)),A(s,a)};z(i,s=>{f(e)&&s(o)})}A(r,n),oe()}var g1=require("obsidian");Ql();Ip();var t6=F('<input type="text" class="text-input" aria-label="Frontmatter property" placeholder="related" required=""/>'),LA=F("<!> <!>",1),r6=F("<!> <!> <!> <!>",1);function Xg(r,t){ie(t,!0);let e=X(t,"appendLink",15),n=X(t,"app",3,void 0),i=k(()=>Kl(e())),o=k(()=>f(i).linkType??"link"),s=k(()=>f(i).displayText),a=k(()=>f(i).frontmatterHandling??Ld),l=k(()=>f(i).destination.type==="specifiedFile"?f(i).destination.path:""),c=k(()=>f(i).enabled?f(i).requireActiveFile?"required":"optional":"disabled"),d=k(()=>f(i).destination.type),u=k(()=>n()?n().vault.getMarkdownFiles().map(V=>V.path):[]),p=[{value:"required",label:"Enabled (strict)"},{value:"optional",label:"Enabled (skip if unavailable)"},{value:"disabled",label:"Disabled"}],m=[{value:"activeFile",label:"Current note"},{value:"specifiedFile",label:"Specified note"}],h=[{value:"replaceSelection",label:"Replace selection"},{value:"afterSelection",label:"After selection"},{value:"endOfLine",label:"End of line"},{value:"newLine",label:"New line"},{value:"inFrontmatter",label:"In frontmatter property"}],g=[{value:"link",label:"Link"},{value:"embed",label:"Embed"}],v=[{value:"none",label:"Default"},{value:"selection",label:"Selected text"}],b=[{value:"alwaysAppend",label:"Create or convert"},{value:"createProperty",label:"Create if missing"},{value:"error",label:"Require list"}];function y(V){let M=e(),B=typeof M=="boolean"?f(i):M,J=V.placement??B.placement,te=V.destination??B.destination??f(i).destination,W=te.type==="activeFile"&&Ap(J)?V.linkType??B.linkType??f(o):"link",Z=te.type==="activeFile"&&Fw(J)&&W==="link"?V.displayText??f(s):"none";return{enabled:V.enabled??!0,placement:J,requireActiveFile:V.requireActiveFile??B.requireActiveFile??f(i).requireActiveFile,linkType:W,displayText:Z,destination:te,frontmatterProperty:V.frontmatterProperty??B.frontmatterProperty,frontmatterHandling:V.frontmatterHandling??B.frontmatterHandling}}function C(V){switch(V){case"disabled":e(y({enabled:!1}));break;case"required":e(y({requireActiveFile:!0}));break;case"optional":e(y({requireActiveFile:!1}));break}}function w(V){e(y({placement:V}))}function T(V){e(y({linkType:V}))}function P(V){e(y({displayText:V}))}function _(V){e(y({frontmatterProperty:V.currentTarget.value}))}function I(V){e(y({frontmatterHandling:V}))}function O(V){let M=V==="specifiedFile"?{type:"specifiedFile",path:f(l)}:{type:"activeFile"};e(y({destination:M}))}function N(V){e(y({destination:{type:"specifiedFile",path:V.trim()}}))}function K(V){let M=V.trim();if(!M)return"Destination file is required";if(!n())return!0;let B=n().vault.getAbstractFileByPath(dA(M));return B instanceof g1.TFile&&B.extension==="md"?!0:"Markdown file not found"}var ne=LA(),H=ae(ne);{let V=J=>{it(J,{get value(){return f(c)},get options(){return p},onchange:C})},M=k(()=>`Link to ${t.fileLabel} file`),B=k(()=>`Choose whether QuickAdd should insert a link to the ${t.fileLabel} file.`);be(H,{get name(){return f(M)},get desc(){return f(B)},control:V,$$slots:{control:!0}})}var D=E(H,2);{var G=V=>{var M=LA(),B=ae(M);{let Z=ce=>{it(ce,{get value(){return f(d)},get options(){return m},onchange:O})},se=k(()=>`Where QuickAdd writes the link to the ${t.fileLabel} file.`);be(B,{name:"Link destination",get desc(){return f(se)},control:Z,$$slots:{control:!0}})}var J=E(B,2);{var te=Z=>{var se=r6(),ce=ae(se);be(ce,{name:"Link placement",desc:"Where to place the link when appending",control:ct=>{it(ct,{get value(){return f(i).placement},get options(){return h},onchange:w})},$$slots:{control:!0}});var $e=E(ce,2);{var Xe=ze=>{be(ze,{name:"Link type",desc:"Choose whether to insert a link or an embed. Embeds transclude the note's contents at the placement position.",control:Ke=>{it(Ke,{get value(){return f(o)},get options(){return g},onchange:T})},$$slots:{control:!0}})},Ye=k(()=>Ap(f(i).placement));z($e,ze=>{f(Ye)&&ze(Xe)})}var he=E($e,2);{var Re=ze=>{be(ze,{name:"Link display text",desc:"What the inserted link displays. 'Selected text' keeps the highlighted text as the link's display text; with nothing selected, the plain link is inserted.",control:Ke=>{it(Ke,{get value(){return f(s)},get options(){return v},onchange:P})},$$slots:{control:!0}})},Je=k(()=>Fw(f(i).placement)&&f(o)==="link");z(he,ze=>{f(Je)&&ze(Re)})}var ve=E(he,2);{var Ne=ze=>{var ct=LA(),Ke=ae(ct);be(Ke,{name:"Frontmatter property",desc:"Required property to insert the link into.",control:Ar=>{var zn=t6();Ct(zn),Q(me=>{Xn(zn,f(i).frontmatterProperty??""),le(zn,"aria-invalid",me)},[()=>!f(i).frontmatterProperty?.trim()]),ge("input",zn,_),A(Ar,zn)},$$slots:{control:!0}});var ot=E(Ke,2);be(ot,{name:"Property handling",desc:"Choose how strict QuickAdd should be when the property is missing or not a list.",control:Ar=>{it(Ar,{get value(){return f(a)},get options(){return b},onchange:I})},$$slots:{control:!0}}),A(ze,ct)},Ie=k(()=>Da(f(i).placement));z(ve,ze=>{f(Ie)&&ze(Ne)})}A(Z,se)},W=Z=>{be(Z,{name:"Destination file",desc:"Existing Markdown note that receives the link at the bottom.",control:ce=>{Dr(ce,{get value(){return f(l)},placeholder:"Index.md",get app(){return n()},get suggestions(){return f(u)},maxSuggestions:50,required:!0,requiredMessage:"Destination file is required",validator:K,ariaLabel:"Append link destination file",onChange:N})},$$slots:{control:!0}})};z(J,Z=>{f(d)==="activeFile"?Z(te):Z(W,-1)})}A(V,M)};z(D,V=>{f(c)!=="disabled"&&V(G)})}A(r,ne),oe()}He(["input"]);function Jg(r,t){ie(t,!0);let e=X(t,"openFile",15);be(r,{name:"Open",get desc(){return t.description},control:i=>{vt(i,{get checked(){return e()},set checked(o){e(o)}})},$$slots:{control:!0}}),oe()}var n6=F("<!> <!> <!> <!>",1);function Zg(r,t){ie(t,!0);let e=X(t,"fileOpening",15);e(en(e()));let n=[{value:"reuse",label:"Reuse current tab"},{value:"tab",label:"New tab"},{value:"split",label:"Split pane"},{value:"window",label:"New window"},{value:"left-sidebar",label:"Left sidebar"},{value:"right-sidebar",label:"Right sidebar"}],i=[{value:"vertical",label:"Split right"},{value:"horizontal",label:"Split down"}],o=[{value:"source",label:"Source"},{value:"preview",label:"Preview"},{value:"live",label:"Live Preview"},{value:"default",label:"Default"}],s=k(()=>typeof e().mode=="string"?e().mode:"default");var a=n6(),l=ae(a);{let h=v=>{it(v,{get value(){return e().location},get options(){return n},onchange:b=>e(e().location=b,!0)})},g=k(()=>`Where to open the ${t.contextLabel} file`);be(l,{name:"File opening location",get desc(){return f(g)},control:h,$$slots:{control:!0}})}var c=E(l,2);{var d=h=>{be(h,{name:"Split direction",desc:"How to arrange the new pane relative to the current one",control:v=>{it(v,{get value(){return e().direction},get options(){return i},onchange:b=>e(e().direction=b,!0)})},$$slots:{control:!0}})};z(c,h=>{e().location==="split"&&h(d)})}var u=E(c,2);be(u,{name:"View mode",desc:"How to display the opened file",control:g=>{it(g,{get value(){return f(s)},get options(){return o},onchange:v=>e(e().mode=v,!0)})},$$slots:{control:!0}});var p=E(u,2);{var m=h=>{be(h,{name:"Focus new pane",desc:"Focus the opened tab immediately after opening",control:v=>{vt(v,{get checked(){return e().focus},set checked(b){e(e().focus=b,!0)}})},$$slots:{control:!0}})};z(p,h=>{e().location!=="reuse"&&h(m)})}A(r,a),oe()}function ev(r,t){ie(t,!0);let e=X(t,"onePageInput",15),n=[{value:"",label:"Follow global setting"},{value:"always",label:"Always"},{value:"never",label:"Never"}],i=k(()=>e()??"");function o(s){e(s==="always"||s==="never"?s:void 0)}be(r,{name:"One-page input override",desc:"Override the global setting for this choice. 'Always' forces the one-page modal even if disabled globally; 'Never' disables it even if enabled globally.",control:a=>{it(a,{get value(){return f(i)},get options(){return n},onchange:o})},$$slots:{control:!0}}),oe()}jp();lc();var s6=F('<input type="text" class="qa-validated-input-full-width" placeholder="-2"/> <!>',1),a6=F('<input type="text" class="qa-validated-input-full-width" placeholder="day"/>'),l6=F("<!> <!> <!> <!>",1);function sv(r,t){ie(t,!0);let e=X(t,"dateOrigin",15),n=tv.map(_=>({value:_,label:_})),i=k(()=>Wa(e())),o=k(()=>e()?.kind==="ask"?e():void 0),s=k(()=>f(i)==="custom"&&e()?.kind==="relative"?e():void 0),a=k(()=>e()?.kind==="variable"?e():void 0),l=k(()=>ov(f(o)?.defaultValue)),c=k(()=>sC(f(o)?.defaultValue));function d(_){iC(_)&&e(oC({preset:_,previous:e()}))}function u(_){if(e()?.kind!=="ask")return;let I=aC(_,e().defaultValue);e(I?{kind:"ask",defaultValue:I}:{kind:"ask"})}function p(_){if(e()?.kind!=="relative")return;let I=_.trim();/^[+-]?\d+$/.test(I)&&e({...e(),offset:Number(I)})}function m(_){e()?.kind==="relative"&&rv(_)&&e({...e(),unit:_})}function h(_){e()?.kind==="variable"&&e({kind:"variable",name:_})}var g=l6(),v=ae(g);be(v,{get name(){return Qw},get desc(){return Xw},control:I=>{it(I,{get value(){return f(i)},get options(){return rC},onchange:d})},$$slots:{control:!0}});var b=E(v,2);{var y=_=>{be(_,{get name(){return Jw},get desc(){return Zw},control:O=>{it(O,{get value(){return f(l)},get options(){return f(c)},onchange:u})},$$slots:{control:!0}})};z(b,_=>{f(o)&&_(y)})}var C=E(b,2);{var w=_=>{be(_,{get name(){return nv},get desc(){return eC},control:O=>{var N=s6(),K=ae(N);Ct(K);var ne=E(K,2);it(ne,{get value(){return f(s).unit},get options(){return n},onchange:m}),Q(H=>{Xn(K,H),le(K,"aria-label",nv)},[()=>String(f(s).offset)]),ge("input",K,H=>{let D=H.currentTarget;D instanceof HTMLInputElement&&p(D.value)}),A(O,N)},$$slots:{control:!0}})};z(C,_=>{f(s)&&_(w)})}var T=E(C,2);{var P=_=>{be(_,{get name(){return iv},get desc(){return tC},control:O=>{var N=a6();Ct(N),Q(()=>{Xn(N,f(a).name),le(N,"aria-label",iv)}),ge("input",N,K=>{let ne=K.currentTarget;ne instanceof HTMLInputElement&&h(ne.value)}),A(O,N)},$$slots:{control:!0}})};z(T,_=>{f(a)&&_(P)})}A(r,g),oe()}He(["input"]);lc();var av="Add to command palette",lC="Run this choice from the command palette or a hotkey.",cC="A second command that asks which day first. Your hotkey for the main command still uses Which day.";function Kp(r){return`Also add "${BA(r)}"`}function dC(r){return`choice:${r}`}function VA(r){return`${dC(r)}:pick-day`}function BA(r){return`${r} (pick a day)`}function lv(r){return Wa(r)!=="ask"}function b1(r){return!!r.enabled&&lv(r.origin)}var c6=F("<!> <!>",1);function cv(r,t){ie(t,!0);let e=X(t,"command",15),n=X(t,"pickDayCommand",15),i=k(()=>e()&&lv(t.dateOrigin));var o=c6(),s=ae(o);be(s,{get name(){return av},get desc(){return lC},control:d=>{vt(d,{get ariaLabel(){return av},get checked(){return e()},set checked(u){e(u)}})},$$slots:{control:!0}});var a=E(s,2);{var l=c=>{{let d=p=>{{let m=k(()=>Kp(t.name));vt(p,{get ariaLabel(){return f(m)},get checked(){return n()},set checked(h){n(h)}})}},u=k(()=>Kp(t.name));be(c,{get name(){return f(u)},get desc(){return cC},control:d,$$slots:{control:!0}})}};z(a,c=>{f(i)&&c(l)})}A(r,o),oe()}gi();var d6=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),u6=new Intl.Collator(void 0,{numeric:!0,sensitivity:"variant"});function uC(r){return r.trim().replace(/^\/+/,"").replace(/\/+$/,"")}function p6(r,t){let e=uC(r),n=uC(t);if(e===n)return 0;let i=e===""?[]:e.split("/"),o=n===""?[]:n.split("/"),s=Math.min(i.length,o.length);for(let a=0;a<s;a++){let l=d6.compare(i[a],o[a]);if(l!==0)return l;let c=u6.compare(i[a],o[a]);if(c!==0)return c}return i.length-o.length}function Ga(r){return[...r].sort(p6)}function m6(r,t){let e=uC(r),n=uC(t);return n?e===n||e.startsWith(`${n}/`):!0}function w1(r,t){let e=[],n=new Set;for(let i of t)for(let o of r)n.has(o)||m6(o,i)&&(e.push(o),n.add(o));return e}var cc=require("obsidian");var f6=F('<div class="qa-canvas-node-empty"> </div>'),h6=F('<div class="qa-canvas-node-empty">No nodes match the current filter.</div>'),g6=F('<button type="button"> </button>'),v6=F('<button type="button" disabled="">Unavailable</button>'),y6=F('<div><div class="qa-canvas-node-item-header"><span> </span> <span class="qa-canvas-node-title"> </span></div> <div class="qa-canvas-node-subtitle"> </div> <div class="qa-canvas-node-meta"><code> </code></div> <div class="qa-canvas-node-item-actions"><!> <button type="button">Copy ID</button></div></div>'),b6=F('<div class="qa-canvas-node-picker"><div class="qa-canvas-node-actions"><button type="button">Open target canvas</button> <button type="button">Use selected in open canvas</button> <button type="button">Clear</button></div> <div class="qa-canvas-node-filter"><input type="text" placeholder="Filter by card text, file path, or node id\u2026" aria-label="Filter canvas nodes"/></div> <div class="qa-canvas-node-status"> </div> <div class="qa-canvas-node-list"><!></div></div>');function UA(r,t){ie(t,!0);let e=X(t,"nodeId",15),n=pe(Ze([])),i=pe("loading"),o=pe(""),s=pe(""),a=k(()=>{let H=f(s).trim().toLowerCase();return H.length?f(n).filter(D=>D.searchText.includes(H)):f(n)}),l=k(()=>(e()??"").trim()),c=k(()=>f(i)==="ready"?`Showing ${f(a).length} of ${f(n).length} nodes`:f(i)==="empty"?f(o):"Loading canvas nodes\u2026");yh(()=>{(async()=>{let H=TS(t.app,t.canvasTargetPath);if(!H){q(o,"Node picker works for direct .canvas paths that already exist in your vault. Format syntax paths cannot be listed here."),q(i,"empty");return}if(q(n,await $O(t.app,H),!0),f(n).length===0){q(o,"No selectable nodes found in the target canvas."),q(i,"empty");return}q(i,"ready")})()});function d(H){e(H)}function u(){let H=TS(t.app,t.canvasTargetPath);if(!H){new cc.Notice("Target canvas file was not found.");return}t.app.workspace.getLeaf(!0).openFile(H).catch(()=>new cc.Notice("Could not open target canvas."))}function p(){let H=PO(t.app,t.canvasTargetPath);if(!H){new cc.Notice("Open the target canvas and select exactly one card to use this action.");return}let D=f(n).find(G=>G.id===H);if(!D){new cc.Notice(f(i)==="ready"?"The selected node was not found in the loaded canvas.":"Canvas nodes are still loading. Wait a moment and try again.");return}if(!D.capturable){new cc.Notice(D.capturableReason);return}d(H)}function m(H){(async()=>{try{await navigator.clipboard.writeText(H),new cc.Notice(`Copied node id ${H}`)}catch{new cc.Notice("Could not copy node id automatically.")}})()}function h(H){return H==="text"?"TEXT":H==="file"?"FILE":"NODE"}var g=b6(),v=R(g),b=R(v),y=E(b,2),C=E(y,2);$(v);var w=E(v,2),T=R(w);Ct(T),$(w);var P=E(w,2),_=re(P,!0),I=E(P,2),O=R(I);{var N=H=>{var D=f6(),G=re(D,!0);Q(()=>ee(G,f(o))),A(H,D)},K=H=>{var D=h6();A(H,D)},ne=H=>{var D=bt(),G=ae(D);gt(G,17,()=>f(a),V=>V.id,(V,M)=>{let B=k(()=>f(l)===f(M).id);var J=y6();let te;var W=R(J),Z=R(W),se=re(Z,!0),ce=E(Z,2),$e=re(ce,!0);$(W);var Xe=E(W,2),Ye=re(Xe,!0),he=E(Xe,2),Re=R(he),Je=re(Re,!0);$(he);var ve=E(he,2),Ne=R(ve);{var Ie=Ke=>{var ot=g6();let or;var Ar=re(ot,!0);Q(()=>{or=Ge(ot,1,"",null,or,{"mod-cta":f(B)}),ee(Ar,f(B)?"Selected":"Use node")}),ge("click",ot,()=>d(f(M).id)),A(Ke,ot)},ze=Ke=>{var ot=v6();Q(()=>le(ot,"title",f(M).capturableReason)),A(Ke,ot)};z(Ne,Ke=>{f(M).capturable?Ke(Ie):Ke(ze,-1)})}var ct=E(Ne,2);$(ve),$(J),Q(Ke=>{te=Ge(J,1,"qa-canvas-node-item",null,te,{"is-selected":f(B)}),Ge(Z,1,`qa-canvas-node-type is-${f(M).type??""}`),ee(se,Ke),ee($e,f(M).title),ee(Ye,f(M).subtitle),ee(Je,f(M).id)},[()=>h(f(M).type)]),ge("click",ct,()=>m(f(M).id)),A(V,J)}),A(H,D)};z(O,H=>{f(i)==="empty"?H(N):f(i)==="ready"&&f(a).length===0?H(K,1):H(ne,-1)})}$(I),$(g),Q(()=>ee(_,f(c))),ge("click",b,u),ge("click",y,p),ge("click",C,()=>d("")),Jn(T,()=>f(s),H=>q(s,H)),A(r,g),oe()}He(["click"]);pC();mC();function E6(r){return r.trim().replace(/^\/+/,"")}function dv(r){return[...new Set((r??[]).map(t=>t.trim()).filter(Boolean))]}function uv(r,t="or"){return r.length<=1?r[0]??"":t==="+"?r.join(" + "):r.length===2?`${r[0]} ${t} ${r[1]}`:`${r.slice(0,-1).join(", ")}, ${t} ${r[r.length-1]}`}function E1(r){let t=dv(r.folders??(r.folder?[r.folder]:[])),e=dv(r.tags),n=dv(r.excludeFolders),i=dv(r.excludeTags),o=dv(r.excludeFiles),s=[];return t.length>0&&s.push(`${t.length===1?"folder":"folders"} ${uv(t)}`),e.length>0&&s.push(`${e.length===1?"tag":"tags"} ${uv(e,"+")}`),n.length>0&&s.push(`excluding ${n.length===1?"folder":"folders"} ${uv(n)}`),i.length>0&&s.push(`excluding ${i.length===1?"tag":"tags"} ${uv(i,"+")}`),o.length>0&&s.push(`excluding ${o.length===1?"file":"files"} ${uv(o)}`),s.length>0?s.join("; "):"all notes"}function pv(r){let t=E6(r),e=Xp(t);if(e){if(!e.field)return{recognized:!0,valid:!1,variant:"error",message:"Property capture target needs a field name, e.g. property:type=draft."};let i=e.value?`frontmatter ${e.field} = ${e.value}`:`frontmatter field ${e.field}`,o=E1(e.filter),s=o==="all notes"?"":`; ${o}`;return{recognized:!0,valid:!0,variant:"success",message:`Recognized property target: ${i}${s}.`}}let n=Qp(t);return n?n.multiSelect?{recognized:!0,valid:!1,variant:"error",message:"Capture target filters select one destination file. Use {{FILE:...|multi}} in the capture format for multi-value metadata."}:{recognized:!0,valid:!0,variant:"success",message:`Recognized filtered picker: ${E1(n.filter)}.`}:null}var T6=F('<button type="button">Daily note</button>'),_6=F("<!> <!> <!>",1),k6=F('<!> <div class="qa-canvas-node-helper">Tip: open this canvas and select one card to grab its id instantly.</div> <!>',1),T1=F("<!> <!>",1);function qA(r,t){ie(t,!0);let e=X(t,"choice",15),n=k(()=>{let y=Ga(La(t.app)).filter(T=>T.length>0).map(T=>T.endsWith("/")?T:T+"/"),C=t.app.vault.getMarkdownFiles().map(T=>T.path),w=t.app.vault.getFiles().filter(T=>T.extension==="canvas").map(T=>T.path);return Array.from(new Set([...y,...C,...w]))}),i=[y=>new sn(t.app,y,t.plugin,"captureTarget")],o=k(()=>pv(e().captureTo??"")),s=k(()=>f(o)!==null),a=y=>pv(y)!==null,l=k(()=>!f(s)&&Rl(e().captureTo));function c(y){let C=!!e().captureToActiveFile&&e().activeFileWritePosition==="bottom";e(e().captureToActiveFile=y,!0),!y&&C&&e(e().prepend=!0,!0),!y&&e().newLineCapture?.enabled&&e(e().newLineCapture.enabled=!1,!0)}function d(y){let C=sp(e().captureTo),w=Rl(e().captureTo),T=pv(y)!==null;e(e().captureTo=y,!0);let P=sp(y),_=Rl(y);(T||!_||w&&_&&C!==P)&&e(e().captureToCanvasNodeId="",!0)}let u="{{DAILY}}";function p(){d(u),e(e().createFileIfItDoesntExist={...e().createFileIfItDoesntExist,enabled:!0,createWithTemplate:!1},!0)}function m(y){let C=pv(y);return C?{valid:C.valid,message:C.message,variant:C.valid?"success":void 0}:y.trim()?!0:{valid:!0,message:"Leave empty to pick the note each time this choice runs."}}var h=T1(),g=ae(h);be(g,{name:"Capture to active file",desc:"Capture into whichever note is open when the choice runs, instead of a fixed target.",control:C=>{vt(C,{get checked(){return e().captureToActiveFile},onchange:c})},$$slots:{control:!0}});var v=E(g,2);{var b=y=>{var C=T1(),w=ae(C);ri(w,{name:"Capture to",desc:"Vault-relative path to a file or folder, a #tag, or property:field=value. Supports format syntax like {{DATE}}; end with '/' to capture into a folder.",control:O=>{var N=bt(),K=ae(N);{var ne=D=>{var G=T6();ge("click",G,p),A(D,G)},H=k(()=>(e().captureTo??"").trim()!==u);z(K,D=>{f(H)&&D(ne)})}A(O,N)},children:(O,N=$t)=>{var K=_6(),ne=ae(K);Dr(ne,{get id(){return N()},get value(){return e().captureTo},placeholder:"Daily/{{DATE}}.md",get app(){return t.app},get suggestions(){return f(n)},maxSuggestions:50,get makeSuggesters(){return i},validator:m,onChange:d});var H=E(ne,2);Wd(H,{get value(){return e().captureTo}});var D=E(H,2);{var G=V=>{Bi(V,{get value(){return e().captureTo},formatterKind:"fileName",get app(){return t.app},get plugin(){return t.plugin},hideWhen:a})};z(D,V=>{f(s)||V(G)})}A(O,K)},$$slots:{control:!0,default:!0}});var T=E(w,2);{var P=_=>{var I=k6(),O=ae(I);be(O,{name:"Target canvas node",desc:"Choose a card from the canvas below, or paste an exact node id.",control:ne=>{{let H=k(()=>e().captureToCanvasNodeId??"");Dr(ne,{get value(){return f(H)},placeholder:"Canvas node id",ariaLabel:"Canvas node id",required:!0,requiredMessage:"A canvas capture target requires a node id \u2014 pick a card below or paste an exact node id.",onChange:D=>e(e().captureToCanvasNodeId=D.trim(),!0)})}},$$slots:{control:!0}});var N=E(O,4);bh(N,()=>e().captureTo,K=>{UA(K,{get canvasTargetPath(){return e().captureTo},get app(){return t.app},get nodeId(){return e().captureToCanvasNodeId},set nodeId(ne){e(e().captureToCanvasNodeId=ne,!0)}})}),A(_,I)};z(T,_=>{f(l)&&_(P)})}A(y,C)};z(v,y=>{e().captureToActiveFile||y(b)})}A(r,h),oe()}He(["click"]);var I1=require("obsidian");var S1=require("obsidian");Ve();function zA(r){let e=r.match(/\{\{DATE:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|[]|\|(?!(?:startof|endof):[a-z])(?!(?:case):[a-z-]+\}\}))*)(?:\+-?\d+)?(?:\|(?:startof|endof):[a-z]+)?(?:\|case:[a-z-]+)?\}\}/i)?.[1]?.trim();if(e)return e;let i=r.match(/\{\{VDATE:[^,}]+,([^}\n\r]*)\}\}/i)?.[1]?.split("|")[0]?.trim();if(i)return i}var S6=F(`<div class="setting-item-description">You'll pick a heading from the target note when you run this capture, and the
- text is inserted under it. Use the toggles below to control placement within that
- section.</div>`),_1=F("<!> <!>",1),A6=F(`<div class="setting-item-description">Inline insertion needs a single-line target. The line break (\\n) can't be
- matched on the same line \u2014 remove it, or turn off "Inline insertion".</div>`),k1=F("<!> <!> <!>",1),I6=F(`<div class="setting-item-description">No sorting: newest-first prepends the new section above existing ones;
- oldest-first appends it below.</div>`),P6=F(`<div class="setting-item-description">This heading uses a date token QuickAdd can't auto-read for sorting. Pick
- "Date" and enter the format, or sections stay in insertion order.</div>`),$6=F(`<div class="setting-item-description">The "Insert after" heading is created at its sorted position among ALL
- same-level headings in the note (it is not scoped to one parent section). It
- does NOT re-sort headings you already have; only the new one is placed. Use
- "Insert at end of section" above for newest-on-top vs. appended entries within
- each section.</div> <!> <!> <!> <!> <!> <!>`,1),F6=F("<!> <!> <!> <!> <!>",1);function HA(r,t){ie(t,!0);let e=X(t,"insertAfter",15);e().inline===void 0&&e(e().inline=!1,!0),e().replaceExisting===void 0&&e(e().replaceExisting=!1,!0),e().promptHeading===void 0&&e(e().promptHeading=!1,!0),e().insertAtEnd===void 0&&e(e().insertAtEnd=!1,!0),e().considerSubsections===void 0&&e(e().considerSubsections=!1,!0),e().blankLineAfterMatchMode||e(e().blankLineAfterMatchMode="auto",!0),e().createIfNotFound||e(e().createIfNotFound=!1,!0),e().createIfNotFoundLocation||e(e().createIfNotFoundLocation=Oi,!0);let n=[V=>new sn(t.app,V,t.plugin,"lineTarget")],i=[{value:"auto",label:"Auto (headings only)"},{value:"skip",label:"Always skip"},{value:"none",label:"Never skip"}],o=k(()=>e().inline?[{value:Oi,label:"Top"},{value:yd,label:"Bottom"},{value:bd,label:"Cursor"}]:[{value:Oi,label:"Top"},{value:yd,label:"Bottom"},{value:bd,label:"Cursor"},{value:Wo,label:"Ordered among siblings"}]),s=[{value:"insertion",label:"Insertion order (no sorting)"},{value:"lexical",label:"Text (A\u2192Z)"},{value:"numeric",label:"Number"},{value:"date",label:"Date"},{value:"semver",label:"Version (semver)"}],a=[{value:"desc",label:"Newest / highest first"},{value:"asc",label:"Oldest / lowest first"}],l=[{value:"bottom",label:"Sort to bottom"},{value:"top",label:"Sort to top"}],c=pe(!!e().orderBy),d=k(()=>e().createIfNotFoundLocation===Wo),u=k(()=>e().createIfNotFound&&f(d)),p=k(()=>new Hp(t.app,t.plugin)),m=pe(!1);Ot(()=>{let V=e().after??"",M=f(p);if(!e().inline||V===""){q(m,!1);return}let B=!1;return M.format(V).then(J=>{B||q(m,/[\n\r]/.test(J),!0)}).catch(()=>{B||q(m,!1)}),()=>{B=!0}});let h=k(()=>e().orderBy??{by:"insertion",direction:"desc",unparseable:"bottom"}),g=k(()=>/\{\{V?DATE\b/i.test(e().after??"")),v=k(()=>f(u)&&e().orderBy?.by==="insertion"&&f(g)&&!zA(e().after??""));Ot(()=>{if(!f(u))return;let V=zA(e().after??"");if(!e().orderBy){e(e().orderBy={by:V?"date":"insertion",direction:"desc",dateFormat:V,unparseable:"bottom"},!0);return}!f(c)&&(e().orderBy.by==="insertion"||e().orderBy.by==="date")&&(e(e().orderBy.by=V?"date":"insertion",!0),e(e().orderBy.dateFormat=V,!0))});function b(V){e(e().createIfNotFoundLocation=V,!0),V===Wo?e(e().inline=!1,!0):(e(e().orderBy=void 0,!0),q(c,!1))}function y(V){q(c,!0),e().orderBy&&e(e().orderBy.by=V,!0)}function C(V){e().promptHeading||V&&!e().after.startsWith("#")&&(e(e().considerSubsections=!1,!0),new S1.Notice("Consider subsections requires the target to be a heading (starts with #)"))}function w(V){V&&(e(e().inline=!1,!0),e(e().replaceExisting=!1,!0))}var T=F6(),P=ae(T);be(P,{name:"Choose heading when capturing",desc:"Instead of typing a target line now, show a dropdown of the target note's headings when you run this capture and insert under the one you pick.",control:M=>{vt(M,{onchange:w,get checked(){return e().promptHeading},set checked(B){e(e().promptHeading=B,!0)}})},$$slots:{control:!0}});var _=E(P,2);{var I=V=>{var M=S6();A(V,M)},O=V=>{var M=k1(),B=ae(M);ri(B,{name:"Insert after",desc:"Insert capture after specified text. Accepts format syntax. Tip: use a heading (starts with #) to target a section. Blank line handling is configurable below.",children:(se,ce=$t)=>{var $e=_1(),Xe=ae($e);Dr(Xe,{get id(){return ce()},placeholder:"Insert after",required:!0,requiredMessage:"Insert after text is required",get makeSuggesters(){return n},get value(){return e().after},set value(he){e(e().after=he,!0)}});var Ye=E(Xe,2);Bi(Ye,{get value(){return e().after},formatterKind:"lineTarget",get app(){return t.app},get plugin(){return t.plugin}}),A(se,$e)},$$slots:{default:!0}});var J=E(B,2);{let Z=ce=>{vt(ce,{get disabled(){return f(d)},get checked(){return e().inline},set checked($e){e(e().inline=$e,!0)}})},se=k(()=>f(d)?"Inline insertion can't be combined with ordered placement.":"Insert captured content on the same line, immediately after the matched text (no newline added).");be(J,{name:"Inline insertion",get desc(){return f(se)},control:Z,$$slots:{control:!0}})}var te=E(J,2);{var W=Z=>{var se=A6();A(Z,se)};z(te,Z=>{f(m)&&Z(W)})}A(V,M)};z(_,V=>{e().promptHeading?V(I):V(O,-1)})}var N=E(_,2);{var K=V=>{be(V,{name:"Replace existing value",desc:"Replace everything after the matched text up to end-of-line.",control:B=>{vt(B,{get checked(){return e().replaceExisting},set checked(J){e(e().replaceExisting=J,!0)}})},$$slots:{control:!0}})},ne=V=>{var M=k1(),B=ae(M);be(B,{name:"Insert at end of section",desc:"Place the text at the end of the matched section instead of the top.",control:Z=>{vt(Z,{get checked(){return e().insertAtEnd},set checked(se){e(e().insertAtEnd=se,!0)}})},$$slots:{control:!0}});var J=E(B,2);{let W=se=>{{let ce=k(()=>e().blankLineAfterMatchMode??"auto");it(se,{get value(){return f(ce)},get options(){return i},get disabled(){return e().insertAtEnd},onchange:$e=>e(e().blankLineAfterMatchMode=$e,!0)})}},Z=k(()=>e().insertAtEnd?"Not used when inserting at end of section.":"Controls whether Insert After skips existing blank lines after the matched line.");be(J,{name:"Blank lines after match",get desc(){return f(Z)},control:W,$$slots:{control:!0}})}var te=E(J,2);{let W=se=>{{let ce=k(()=>!e().insertAtEnd);vt(se,{get disabled(){return f(ce)},onchange:C,get checked(){return e().considerSubsections},set checked($e){e(e().considerSubsections=$e,!0)}})}},Z=k(()=>e().insertAtEnd?e().promptHeading?"Also include the chosen heading\u2019s subsections (nested headings inside its section).":"Also include the section\u2019s subsections (requires target to be a heading starting with #). Subsections are headings inside the section.":"Only affects placement when \u201CInsert at end of section\u201D is on.");be(te,{name:"Consider subsections",get desc(){return f(Z)},control:W,$$slots:{control:!0}})}A(V,M)};z(N,V=>{e().inline?V(K):V(ne,-1)})}var H=E(N,2);be(H,{name:"Create line if not found",desc:"Creates the 'insert after' line if it is not found.",control:M=>{var B=_1(),J=ae(B);vt(J,{get checked(){return e().createIfNotFound},set checked(W){e(e().createIfNotFound=W,!0)}});var te=E(J,2);{let W=k(()=>e().createIfNotFoundLocation||Oi);it(te,{get value(){return f(W)},get options(){return f(o)},ariaLabel:"Where to create the line",onchange:b})}A(M,B)},$$slots:{control:!0}});var D=E(H,2);{var G=V=>{var M=$6(),B=E(ae(M),2);be(B,{name:"Sort sections by",control:Re=>{it(Re,{get value(){return f(h).by},get options(){return s},onchange:y})},$$slots:{control:!0}});var J=E(B,2);be(J,{name:"Section order",control:Re=>{it(Re,{get value(){return f(h).direction},get options(){return a},onchange:Je=>{e().orderBy&&e(e().orderBy.direction=Je,!0)}})},$$slots:{control:!0}});var te=E(J,2);{var W=he=>{be(he,{name:"Date format",desc:"Moment format used to parse existing heading dates for sorting (e.g. YYYY-MM-DD).",control:Je=>{{let ve=k(()=>f(h).dateFormat??"");Dr(Je,{get value(){return f(ve)},placeholder:"YYYY-MM-DD",ariaLabel:"Date format",onChange:Ne=>{q(c,!0),e().orderBy&&e(e().orderBy.dateFormat=Ne,!0)}})}},$$slots:{control:!0}})};z(te,he=>{f(h).by==="date"&&he(W)})}var Z=E(te,2);{var se=he=>{be(he,{name:"Existing unparseable headings",desc:"Where to rank EXISTING headings whose text can't be parsed for this sort. (A new heading that can't be parsed is appended at the end.)",control:Je=>{{let ve=k(()=>f(h).unparseable??"bottom");it(Je,{get value(){return f(ve)},get options(){return l},ariaLabel:"Existing unparseable headings",onchange:Ne=>{e().orderBy&&e(e().orderBy.unparseable=Ne,!0)}})}},$$slots:{control:!0}})};z(Z,he=>{(f(h).by==="date"||f(h).by==="numeric"||f(h).by==="semver")&&he(se)})}var ce=E(Z,2);{var $e=he=>{var Re=I6();A(he,Re)};z(ce,he=>{f(h).by==="insertion"&&he($e)})}var Xe=E(ce,2);{var Ye=he=>{var Re=P6();A(he,Re)};z(Xe,he=>{f(v)&&he(Ye)})}A(V,M)};z(D,V=>{f(u)&&e().orderBy&&V(G)})}A(r,T),oe()}Ve();var WA=F("<!> <!>",1);function GA(r,t){ie(t,!0);let e=X(t,"insertBefore",15);e().createIfNotFound===void 0&&e(e().createIfNotFound=!1,!0),e().createIfNotFoundLocation||e(e().createIfNotFoundLocation=Oi,!0);let n=[l=>new sn(t.app,l,t.plugin,"lineTarget")],i=[{value:Oi,label:"Top"},{value:yd,label:"Bottom"},{value:bd,label:"Cursor"}];var o=WA(),s=ae(o);ri(s,{name:"Insert before",desc:"Insert capture before specified text. Accepts format syntax.",children:(c,d=$t)=>{var u=WA(),p=ae(u);Dr(p,{get id(){return d()},placeholder:"Insert before",required:!0,requiredMessage:"Insert before text is required",get makeSuggesters(){return n},get value(){return e().before},set value(h){e(e().before=h,!0)}});var m=E(p,2);Bi(m,{get value(){return e().before},formatterKind:"lineTarget",get app(){return t.app},get plugin(){return t.plugin}}),A(c,u)},$$slots:{default:!0}});var a=E(s,2);be(a,{name:"Create line if not found",desc:"Creates the 'insert before' line if it is not found.",control:c=>{var d=WA(),u=ae(d);vt(u,{get checked(){return e().createIfNotFound},set checked(m){e(e().createIfNotFound=m,!0)}});var p=E(u,2);{let m=k(()=>e().createIfNotFoundLocation||Oi);it(p,{get value(){return f(m)},get options(){return i},onchange:h=>e(e().createIfNotFoundLocation=h,!0)})}A(c,d)},$$slots:{control:!0}}),A(r,o),oe()}var M6=F("<!> <!> <!>",1);function jA(r,t){ie(t,!0);let e=X(t,"config",15),n=[c=>new sn(t.app,c,t.plugin)],i="";var o=M6(),s=ae(o);{let c=p=>{it(p,{get value(){return e().property.kind},options:[{value:"named",label:"Named property"},{value:"prompt",label:"Choose when capturing"}],onchange:m=>{e().property.kind==="named"&&(i=e().property.format),e(e().property=m==="prompt"?{kind:"prompt"}:{kind:"named",format:i},!0)}})},d=(p,m=$t)=>{var h=bt(),g=ae(h);{var v=b=>{Dr(b,{get id(){return m()},placeholder:"Property name",required:!0,requiredMessage:"Property name is required",get makeSuggesters(){return n},get value(){return e().property.format},set value(y){e(e().property.format=y,!0)}})};z(g,b=>{e().property.kind==="named"&&b(v)})}A(p,h)},u=k(()=>e().property.kind==="named");ri(s,{name:"Property",get bodyVisible(){return f(u)},control:c,children:d,$$slots:{control:!0,default:!0}})}var a=E(s,2);{let c=u=>{it(u,{get value(){return e().action},options:[{value:"set",label:"Set value"},{value:"addToList",label:"Add to list"}],onchange:p=>{e(e().action=p==="addToList"?"addToList":"set",!0)}})},d=k(()=>e().action==="addToList"?"Each line is one item. New items go below the existing ones. Put {{PROPERTY}} on its own line to choose where the existing items go.":"Replaces the value. For a list, each line is one item. Put {{PROPERTY}} where the current value should stay. A Text property keeps all lines as one value. A property with no type yet rejects several lines. Use Add to list, or set the type to Text in Obsidian first.");be(a,{name:"Action",get desc(){return f(d)},control:c,$$slots:{control:!0}})}var l=E(a,2);be(l,{name:"Create property if missing",control:d=>{vt(d,{get checked(){return e().createIfMissing},set checked(u){e(e().createIfMissing=u,!0)}})},$$slots:{control:!0}}),A(r,o),oe()}function A1(r){let t=r.insertAfter.enabled||!!r.insertBefore?.enabled;return r.captureToActiveFile&&!t&&r.newLineCapture?.enabled?r.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":r.captureToActiveFile&&!t?r.activeFileWritePosition==="top"?"activeFileTop":r.activeFileWritePosition==="bottom"||r.prepend?"append":"currentLine":r.insertAfter.enabled?"insertAfter":r.insertBefore?.enabled?"insertBefore":r.prepend?"prepend":"append"}function fC(r){if(r.propertyCapture)return"property";let t=!!r.insertAfter?.enabled||!!r.insertBefore?.enabled;return r.captureToActiveFile&&!t?r.newLineCapture?.enabled?r.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":r.activeFileWritePosition==="top"?"activeTop":r.activeFileWritePosition==="bottom"||r.prepend?"bottom":"top":r.prepend||r.captureToActiveFile&&r.activeFileWritePosition==="bottom"?"bottom":r.insertAfter?.enabled?"after":r.insertBefore?.enabled?"before":"top"}var R6=F(`<div class="setting-item-description">Canvas note: 'At cursor' and 'New line above/below cursor' are not supported
- for Canvas card capture. Use top, bottom, insert-after, or insert-before
- placement.</div>`),D6=F("<!> <!> <!> <!> <!>",1);function YA(r,t){ie(t,!0);let e=X(t,"choice",15),n=k(()=>!!e().captureToActiveFile),i=k(()=>fC(e())),o=k(()=>[{value:"top",label:f(n)?"At cursor":"Top of file"},...f(n)?[{value:"activeTop",label:"Top of file (after frontmatter)"},{value:"newLineAbove",label:"New line above cursor"},{value:"newLineBelow",label:"New line below cursor"}]:[],{value:"after",label:"After line\u2026"},{value:"before",label:"Before line\u2026"},{value:"bottom",label:"Bottom of file"},{value:"property",label:"Property"}]);function s(y){if(y==="property"){e().propertyCapture??e(e().propertyCapture={property:{kind:"named",format:""},action:"set",createIfMissing:!0},!0);return}if(delete e().propertyCapture,e(e().prepend=!1,!0),e(e().insertAfter.enabled=!1,!0),e(e().insertAfter.promptHeading=!1,!0),e(e().insertAfter.inline=!1,!0),e(e().insertAfter.replaceExisting=!1,!0),e().insertBefore||e(e().insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"},!0),e(e().insertBefore.enabled=!1,!0),e().newLineCapture||e(e().newLineCapture={enabled:!1,direction:"below"},!0),e(e().newLineCapture.enabled=!1,!0),e(e().activeFileWritePosition="cursor",!0),y==="top"){f(n)||e(e().prepend=!1,!0);return}if(y==="activeTop"){f(n)&&e(e().activeFileWritePosition="top",!0);return}if(y==="bottom"){f(n)?e(e().activeFileWritePosition="bottom",!0):e(e().prepend=!0,!0);return}if(y==="newLineAbove"){e(e().newLineCapture.enabled=!0,!0),e(e().newLineCapture.direction="above",!0);return}if(y==="newLineBelow"){e(e().newLineCapture.enabled=!0,!0),e(e().newLineCapture.direction="below",!0);return}if(y==="before"){e(e().insertBefore.enabled=!0,!0);return}e(e().insertAfter.enabled=!0,!0)}let a=k(()=>{if(e().propertyCapture)return!1;let y=typeof e().captureTo=="string"&&Rl(e().captureTo),C=t.app.workspace.getActiveViewOfType(I1.FileView)?.getViewType()==="canvas",w=f(n)&&!e().insertAfter.enabled&&!e().insertBefore?.enabled&&!e().newLineCapture?.enabled&&(e().activeFileWritePosition??"cursor")==="cursor"&&!e().prepend;return!(!(e().newLineCapture?.enabled||w)||(f(n)?!C:!y))});var l=D6(),c=ae(l);{let y=w=>{it(w,{get value(){return f(i)},get options(){return f(o)},onchange:s})},C=k(()=>f(n)?"Where to place the capture in the current file.":"Where to place the capture in the target file.");be(c,{name:"Write position",get desc(){return f(C)},control:y,$$slots:{control:!0}})}var d=E(c,2);{var u=y=>{jA(y,{get app(){return t.app},get plugin(){return t.plugin},get config(){return e().propertyCapture},set config(C){e(e().propertyCapture=C,!0)}})};z(d,y=>{e().propertyCapture&&y(u)})}var p=E(d,2);{var m=y=>{HA(y,{get app(){return t.app},get plugin(){return t.plugin},get insertAfter(){return e().insertAfter},set insertAfter(C){e(e().insertAfter=C,!0)}})};z(p,y=>{!e().propertyCapture&&e().insertAfter.enabled&&y(m)})}var h=E(p,2);{var g=y=>{GA(y,{get app(){return t.app},get plugin(){return t.plugin},get insertBefore(){return e().insertBefore},set insertBefore(C){e(e().insertBefore=C,!0)}})};z(h,y=>{!e().propertyCapture&&e().insertBefore?.enabled&&y(g)})}var v=E(h,2);{var b=y=>{var C=R6();A(y,C)};z(v,y=>{f(a)&&y(b)})}A(r,l),oe()}var O6=new Set(["activity","airplay","alarm-check","alarm-clock-off","alarm-clock","alarm-minus","alarm-plus","album","alert-circle","alert-octagon","alert-triangle","align-center-horizontal","align-center-vertical","align-center","align-end-horizontal","align-end-vertical","align-horizontal-distribute-center","align-horizontal-distribute-end","align-horizontal-distribute-start","align-horizontal-justify-center","align-horizontal-justify-end","align-horizontal-justify-start","align-horizontal-space-around","align-horizontal-space-between","align-justify","align-left","align-right","align-start-horizontal","align-start-vertical","align-vertical-distribute-center","align-vertical-distribute-end","align-vertical-distribute-start","align-vertical-justify-center","align-vertical-justify-end","align-vertical-justify-start","align-vertical-space-around","align-vertical-space-between","anchor","aperture","archive","arrow-big-down","arrow-big-left","arrow-big-right","arrow-big-up","arrow-down-circle","arrow-down-left","arrow-down-right","arrow-down","arrow-left-circle","arrow-left-right","arrow-left","arrow-right-circle","arrow-right","arrow-up-circle","arrow-up-left","arrow-up-right","arrow-up","asterisk","at-sign","award","axe","banknote","bar-chart-2","bar-chart","baseline","battery-charging","battery-full","battery-low","battery-medium","battery","beaker","bell-minus","bell-off","bell-plus","bell-ring","bell","bike","binary","bitcoin","bluetooth-connected","bluetooth-off","bluetooth-searching","bluetooth","bold","book-open","book","bookmark-minus","bookmark-plus","bookmark","bot","box-select","box","briefcase","brush","bug","building-2","building","bus","calculator","calendar","camera-off","camera","car","carrot","cast","check-circle-2","check-circle","check-square","check","chevron-down","chevron-first","chevron-last","chevron-left","chevron-right","chevron-up","chevrons-down-up","chevrons-down","chevrons-left","chevrons-right","chevrons-up-down","chevrons-up","chrome","circle-slashed","circle","clipboard-check","clipboard-copy","clipboard-list","clipboard-x","clipboard","clock-1","clock-10","clock-11","clock-12","clock-2","clock-3","clock-4","clock-5","clock-6","clock-7","clock-8","clock-9","clock","cloud-drizzle","cloud-fog","cloud-hail","cloud-lightning","cloud-moon","cloud-off","cloud-rain-wind","cloud-rain","cloud-snow","cloud-sun","cloud","cloudy","clover","code-2","code","codepen","codesandbox","coffee","coins","columns","command","compass","contact","contrast","cookie","copy","copyleft","copyright","corner-down-left","corner-down-right","corner-left-down","corner-left-up","corner-right-down","corner-right-up","corner-up-left","corner-up-right","cpu","credit-card","crop","cross","crosshair","crown","currency","database","delete","dice-1","dice-2","dice-3","dice-4","dice-5","dice-6","disc","divide-circle","divide-square","divide","dollar-sign","download-cloud","download","dribbble","droplet","droplets","drumstick","edit-2","edit-3","edit","egg","equal-not","equal","eraser","euro","expand","external-link","eye-off","eye","facebook","fast-forward","feather","figma","file-check-2","file-check","file-code","file-digit","file-input","file-minus-2","file-minus","file-output","file-plus-2","file-plus","file-search","file-text","file-x-2","file-x","file","files","film","filter","flag-off","flag-triangle-left","flag-triangle-right","flag","flame","flashlight-off","flashlight","flask-conical","flask-round","folder-minus","folder-open","folder-plus","folder","form-input","forward","frame","framer","frown","function-square","gamepad-2","gamepad","gauge","gavel","gem","ghost","gift","git-branch-plus","git-branch","git-commit","git-fork","git-merge","git-pull-request","github","gitlab","glasses","globe-2","globe","grab","graduation-cap","grid","grip-horizontal","grip-vertical","hammer","hand-metal","hand","hard-drive","hard-hat","hash","haze","headphones","heart","help-circle","hexagon","highlighter","history","home","image-minus","image-off","image-plus","image","import","inbox","indent","indian-rupee","infinity","info","inspect","instagram","italic","japanese-yen","key","keyboard","landmark","languages","laptop-2","laptop","lasso-select","lasso","layers","layout-dashboard","layout-grid","layout-list","layout-template","layout","library","life-buoy","lightbulb-off","lightbulb","link-2-off","link-2","link","linkedin","list-checks","list-minus","list-ordered","list-plus","list-x","list","loader-2","loader","locate-fixed","locate-off","locate","lock","log-in","log-out","mail","map-pin","map","maximize-2","maximize","megaphone","meh","menu","message-circle","message-square","mic-off","mic","minimize-2","minimize","minus-circle","minus-square","minus","monitor-off","monitor-speaker","monitor","moon","more-horizontal","more-vertical","mountain-snow","mountain","mouse-pointer-2","mouse-pointer-click","mouse-pointer","mouse","move-diagonal-2","move-diagonal","move-horizontal","move-vertical","move","music","navigation-2","navigation","network","octagon","option","outdent","package-check","package-minus","package-plus","package-search","package-x","package","palette","palmtree","paperclip","pause-circle","pause-octagon","pause","pen-tool","pencil","percent","person-standing","phone-call","phone-forwarded","phone-incoming","phone-missed","phone-off","phone-outgoing","phone","pie-chart","piggy-bank","pin","pipette","plane","play-circle","play","plug-zap","plus-circle","plus-square","plus","pocket","podcast","pointer","pound-sterling","power-off","power","printer","qr-code","quote","radio-receiver","radio","redo","refresh-ccw","refresh-cw","regex","repeat-1","repeat","reply-all","reply","rewind","rocket","rocking-chair","rotate-ccw","rotate-cw","rss","ruler","russian-ruble","save","scale","scan-line","scan","scissors","screen-share-off","screen-share","search","send","separator-horizontal","separator-vertical","server-crash","server-off","server","settings-2","settings","share-2","share","sheet","shield-alert","shield-check","shield-close","shield-off","shield","shirt","shopping-bag","shopping-cart","shovel","shrink","shuffle","sidebar-close","sidebar-open","sidebar","sigma","signal-high","signal-low","signal-medium","signal-zero","signal","skip-back","skip-forward","skull","slack","slash","sliders","smartphone-charging","smartphone","smile","snowflake","sort-asc","sort-desc","speaker","sprout","square","star-half","star","stop-circle","stretch-horizontal","stretch-vertical","strikethrough","subscript","sun","sunrise","sunset","superscript","swiss-franc","switch-camera","table","tablet","tag","target","tent","terminal-square","terminal","text-cursor-input","text-cursor","thermometer-snowflake","thermometer-sun","thermometer","thumbs-down","thumbs-up","ticket","timer-off","timer-reset","timer","toggle-left","toggle-right","tornado","trash-2","trash","trello","trending-down","trending-up","triangle","truck","tv-2","tv","twitch","twitter","type","umbrella","underline","undo","unlink-2","unlink","unlock","upload-cloud","upload","user-check","user-minus","user-plus","user-x","user","users","verified","vibrate","video-off","video","view","voicemail","volume-1","volume-2","volume-x","volume","wallet","wand","watch","waves","webcam","wifi-off","wifi","wind","wrap-text","wrench","x-circle","x-octagon","x-square","x","youtube","zap-off","zap","zoom-in","zoom-out","search-large","lucide-clock","lucide-cloud","lucide-cross","lucide-folder","lucide-info","lucide-languages","lucide-link","lucide-pencil","lucide-pin","lucide-search","lucide-star","lucide-trash"]),hC=Array.from(O6);lt();var P1=require("obsidian"),L6=F('<span class="quickadd-icon svelte-18szklt"></span>'),N6={hash:"svelte-18szklt",code:".quickadd-icon.svelte-18szklt {display:inline-flex;align-items:center;}.quickadd-icon.svelte-18szklt svg {display:inline-block;vertical-align:middle;}"};function Qe(r,t){ie(t,!0),Ae(r,N6);let e=X(t,"size",3,16),n=pe(void 0);Ot(()=>{if(!f(n)||!t.iconId)return;(0,P1.setIcon)(f(n),t.iconId);let o=f(n).querySelector("svg");o&&(o.setAttribute("width",`${e()}`),o.setAttribute("height",`${e()}`))});var i=L6();Cn(i,o=>q(n,o),()=>f(n)),A(r,i),oe()}var V6=F('<div class="qa-choice-icon-setting-control svelte-1267c4j"><span class="qa-choice-icon-setting-preview svelte-1267c4j" aria-hidden="true"><!></span> <input type="text" class="qa-choice-icon-input svelte-1267c4j" aria-label="Choice icon"/></div>'),B6={hash:"svelte-1267c4j",code:".qa-choice-icon-setting-control.svelte-1267c4j {display:flex;align-items:center;gap:8px;min-width:min(18rem, 100%);}.qa-choice-icon-setting-preview.svelte-1267c4j {display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--text-muted);}.qa-choice-icon-input.svelte-1267c4j {width:100%;min-width:0;}"};function mv(r,t){ie(t,!0),Ae(r,B6);let e=X(t,"icon",15),n=k(()=>cp(t.type)),i=k(()=>typeof e()=="string"?e():""),o=k(()=>f(i).trim()||f(n));function s(l){return new hi(t.app,l,hC,50)}function a(l){let c=l.currentTarget.value.trim();e(c||void 0)}{let l=d=>{var u=V6(),p=R(u),m=R(p);Qe(m,{get iconId(){return f(o)},size:18}),$(p);var h=E(p,2);Ct(h),Ft(h,(g,v)=>_d?.(g,v),()=>s),$(u),Q(()=>{Xn(h,f(i)),le(h,"placeholder",f(n))}),ge("input",h,a),A(d,u)},c=k(()=>`Lucide/Obsidian icon id. Leave empty to use ${f(n)}.`);be(r,{name:"Icon",get desc(){return f(c)},control:l,$$slots:{control:!0}})}oe()}He(["input"]);var Jp=F("<!> <!>",1),U6=F("<!> <!> <!>",1),q6=F("<!> <!> <!> <!> <!> <!> <!>",1),z6=F("<!> <!> <!> <!> <!>",1);function KA(r,t){ie(t,!0);let e=X(t,"choice",15),n=k(()=>t.plugin.getTemplateFiles().map(y=>y.path)),i=k(()=>e().propertyCapture?"propertyValue":"noteContent"),o=k(()=>{let y=f(i);return[C=>new sn(t.app,C,t.plugin,y)]});function s(y){let C=y.trim();return C?_a(C)?{valid:!0,message:"Contains format syntax \u2014 resolved at run time."}:Rn(t.app,C)!==null||"Template not found":!0}let a=k(()=>e().format.enabled?e().format.format:""),l=[{value:"",label:"Follow global setting"},{value:"enabled",label:"Use selection"},{value:"disabled",label:"Ignore selection"}],c=k(()=>typeof e().useSelectionAsCaptureValue=="boolean"?e().useSelectionAsCaptureValue?"enabled":"disabled":"");function d(y){if(y===""){e(e().useSelectionAsCaptureValue=void 0,!0);return}e(e().useSelectionAsCaptureValue=y==="enabled",!0)}function u(y){e().templater||e(e().templater={},!0),e(e().templater.afterCapture=y?"wholeFile":"none",!0)}var p=z6(),m=ae(p);fo(m,{heading:"Location",children:(y,C)=>{var w=Jp(),T=ae(w);qA(T,{get app(){return t.app},get plugin(){return t.plugin},get choice(){return e()},set choice(I){e(I)}});var P=E(T,2);{var _=I=>{var O=Jp(),N=ae(O);be(N,{name:"Create file if it doesn't exist",control:D=>{vt(D,{get checked(){return e().createFileIfItDoesntExist.enabled},set checked(G){e(e().createFileIfItDoesntExist.enabled=G,!0)}})},$$slots:{control:!0}});var K=E(N,2);{var ne=H=>{ri(H,{name:"Create file with a template",desc:"Path to the template QuickAdd applies to the new file.",get bodyVisible(){return e().createFileIfItDoesntExist.createWithTemplate},control:V=>{vt(V,{get checked(){return e().createFileIfItDoesntExist.createWithTemplate},set checked(M){e(e().createFileIfItDoesntExist.createWithTemplate=M,!0)}})},children:(V,M=$t)=>{Dr(V,{get id(){return M()},get value(){return e().createFileIfItDoesntExist.template},placeholder:"Template path",get app(){return t.app},get suggestions(){return f(n)},maxSuggestions:50,validator:s,onChange:B=>e(e().createFileIfItDoesntExist.template=B.trim(),!0)})},$$slots:{control:!0,default:!0}})};z(K,H=>{e().createFileIfItDoesntExist.enabled&&H(ne)})}A(I,O)};z(P,I=>{e().captureToActiveFile||I(_)})}A(y,w)},$$slots:{default:!0}});var h=E(m,2);fo(h,{heading:"Position",children:(y,C)=>{YA(y,{get app(){return t.app},get plugin(){return t.plugin},get choice(){return e()},set choice(w){e(w)}})},$$slots:{default:!0}});var g=E(h,2);fo(g,{heading:"Linking",children:(y,C)=>{var w=Jp(),T=ae(w);Xg(T,{fileLabel:"captured",get app(){return t.app},get appendLink(){return e().appendLink},set appendLink(_){e(e().appendLink=_,!0)}});var P=E(T,2);be(P,{name:"Copy link to clipboard",desc:"Copy a link to the captured file after the Capture choice runs.",control:I=>{{let O=k(()=>e().copyLinkToClipboard??!1);vt(I,{get checked(){return f(O)},onchange:N=>e(e().copyLinkToClipboard=N,!0)})}},$$slots:{control:!0}}),A(y,w)},$$slots:{default:!0}});var v=E(g,2);fo(v,{heading:"Content",children:(y,C)=>{var w=Jp(),T=ae(w);{var P=I=>{var O=Jp(),N=ae(O);be(N,{name:"Task",desc:"Formats the value as a task.",control:H=>{vt(H,{get checked(){return e().task},set checked(D){e(e().task=D,!0)}})},$$slots:{control:!0}});var K=E(N,2);be(K,{name:"One entry per line",desc:"Writes the format once for each line of {{VALUE}}.",control:H=>{{let D=k(()=>e().eachLine??!1);vt(H,{get checked(){return f(D)},onchange:G=>e(e().eachLine=G,!0)})}},$$slots:{control:!0}}),A(I,O)};z(T,I=>{e().propertyCapture||I(P)})}var _=E(T,2);ri(_,{name:"Capture format",desc:"Leave empty to capture {{VALUE}} on its own - what you type at the prompt, or the current selection.",children:(O,N=$t)=>{var K=U6(),ne=ae(K);bh(ne,()=>f(i),G=>{var V=()=>f(a),M=B=>e(e().format={enabled:B.trim()!=="",format:B},!0);{let B=k(()=>e().propertyCapture?.action==="addToList"?"One item per line":"{{VALUE}}");Dr(G,{get id(){return N()},inputKind:"textarea",get value(){return V()},set value(J){M(J)},get placeholder(){return f(B)},get makeSuggesters(){return f(o)}})}});var H=E(ne,2);Wd(H,{get value(){return f(a)}});var D=E(H,2);Bi(D,{get value(){return f(a)},get app(){return t.app},get plugin(){return t.plugin}}),A(O,K)},$$slots:{default:!0}}),A(y,w)},$$slots:{default:!0}});var b=E(v,2);fo(b,{heading:"Behavior",children:(y,C)=>{var w=q6(),T=ae(w);{var P=D=>{var G=Jp(),V=ae(G);Jg(V,{description:"Open the captured file.",get openFile(){return e().openFile},set openFile(J){e(e().openFile=J,!0)}});var M=E(V,2);{var B=J=>{Zg(J,{contextLabel:"captured",get fileOpening(){return e().fileOpening},set fileOpening(te){e(e().fileOpening=te,!0)}})};z(M,J=>{e().openFile&&J(B)})}A(D,G)};z(T,D=>{e().captureToActiveFile||D(P)})}var _=E(T,2);be(_,{name:"Use editor selection as default value",desc:"Controls whether this Capture uses the current editor selection as {{VALUE}}. Does not affect {{SELECTED}}.",control:G=>{it(G,{get value(){return f(c)},get options(){return l},onchange:d})},$$slots:{control:!0}});var I=E(_,2);{var O=D=>{be(D,{name:"Run Templater on entire destination file after capture (deprecated)",desc:"Will be removed in a future release. QuickAdd already runs Templater in what it captures. This also runs every <% %> elsewhere in the destination file, including inside code blocks.",control:V=>{{let M=k(()=>e().templater?.afterCapture==="wholeFile");vt(V,{get checked(){return f(M)},onchange:u})}},$$slots:{control:!0}})};z(I,D=>{!e().propertyCapture&&e().templater?.afterCapture==="wholeFile"&&D(O)})}var N=E(I,2);sv(N,{get dateOrigin(){return e().dateOrigin},set dateOrigin(D){e(e().dateOrigin=D,!0)}});var K=E(N,2);ev(K,{get onePageInput(){return e().onePageInput},set onePageInput(D){e(e().onePageInput=D,!0)}});var ne=E(K,2);cv(ne,{get name(){return e().name},get dateOrigin(){return e().dateOrigin},get command(){return e().command},set command(D){e(e().command=D,!0)},get pickDayCommand(){return e().pickDayCommand},set pickDayCommand(D){e(e().pickDayCommand=D,!0)}});var H=E(ne,2);mv(H,{get type(){return e().type},get app(){return t.app},get icon(){return e().icon},set icon(D){e(e().icon=D,!0)}}),A(y,w)},$$slots:{default:!0}}),A(r,p),oe()}nt();var H6=F('<pre class="qaMountFailedDetail svelte-1vm72jj"> </pre>'),W6=F(`<div class="qaMountFailed svelte-1vm72jj"><div class="qaMountFailedHead svelte-1vm72jj"><!> <span class="qaMountFailedTitle svelte-1vm72jj"> </span></div> <p class="qaMountFailedBody svelte-1vm72jj">This part of QuickAdd could not be drawn, so it has been left out. Nothing
- was changed by the error. Include the message below if you report this.</p> <!></div>`),G6={hash:"svelte-1vm72jj",code:".qaMountFailed.svelte-1vm72jj {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);padding:12px 14px;margin:4px 0 8px;background:var(--background-secondary);}.qaMountFailedHead.svelte-1vm72jj {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaMountFailedTitle.svelte-1vm72jj {font-weight:var(--font-semibold);color:var(--text-normal);}.qaMountFailedBody.svelte-1vm72jj {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}.qaMountFailedDetail.svelte-1vm72jj {margin:10px 0 0;padding:8px 10px;border-radius:var(--radius-s);background:var(--background-primary);color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);white-space:pre-wrap;word-break:break-word;user-select:text;}"};function QA(r,t){Ae(r,G6);let e=X(t,"detail",3,"");var n=W6(),i=R(n),o=R(i);Qe(o,{iconId:"alert-triangle",size:16});var s=E(o,2),a=re(s);$(i);var l=E(i,4);{var c=d=>{var u=H6(),p=re(u,!0);Q(()=>ee(p,e())),A(d,u)};z(l,d=>{e()&&d(c)})}$(n),Q(()=>ee(a,`QuickAdd couldn't display ${t.what??""}`)),A(r,n)}var j6="this part of QuickAdd";function vi(r,t,e,n={}){let i=new Set(r.childNodes),o;try{o=pd(t,{target:r,props:e})}catch(a){return Y6(r,i,ka(a),n)}let s=!1;return{ok:!0,destroy(){s||(s=!0,ep(o))}}}function Y6(r,t,e,n){let i=n.what??j6;for(let l of Array.from(r.childNodes))t.has(l)||l.remove();Me(e,`Couldn't display ${i}`);let o=r.createDiv({cls:"qa-mount-failed-host"}),s=null;try{s=pd(n.fallbackComponent??QA,{target:o,props:{what:i,detail:e.message}})}catch{o.textContent=`QuickAdd couldn't display ${i}.`}let a=!1;return{ok:!1,destroy(){a||(a=!0,s&&ep(s),o.remove())}}}function Ui(r){return jc(r)}var Zp=require("obsidian");var $1=require("obsidian");ye();function K6(r,t){try{let e=r.setting;return!e?.open||!e?.openTabById?(S.logMessage("QuickAdd: Obsidian internal settings API is unavailable."),!1):(e.open(),e.openTabById(t),!0)}catch(e){return S.logMessage(`QuickAdd: Failed to open plugin settings automatically: ${e}`),!1}}function F1(r,t,e){try{let n=r.setting;return typeof n?.navigateToSearchResult!="function"?(S.logMessage("QuickAdd: Obsidian's settings page navigation is unavailable."),!1):(n.navigateToSearchResult({tab:t,pagePath:e},null),!0)}catch(n){return S.logMessage(`QuickAdd: Failed to open settings page: ${n}`),!1}}function M1(r){return r.setting}function R1(r,t){try{let e=M1(r);return typeof e?.openPage!="function"?(S.logMessage("QuickAdd: Obsidian's settings page navigation is unavailable."),!1):(e.openPage(t),!0)}catch(e){return S.logMessage(`QuickAdd: Failed to open settings page: ${e}`),!1}}function gC(r,t,e){t.title=e,t.titlebarEl.querySelector(".setting-page-title")?.setText(e),M1(r)?.updatePageTitle?.()}function dc(r,t,e){let n=K6(r,t);return!n&&e?.notice!==!1&&new $1.Notice("QuickAdd: Unable to open settings automatically. Open Settings \u2192 QuickAdd manually."),n}var _o=class extends Zp.SettingPage{constructor(e,n,i){super();this.app=e;this.onSave=i;this.rendered=!1;this.opener=null;this.title=n,this.rootEl.addClass("quickAddModal","qa-builder-page")}open(){return this.opener=Q6(activeDocument.activeElement),R1(this.app,this)?!0:(new Zp.Notice(`QuickAdd: Couldn't open the settings for \u201C${this.title}\u201D.`),!1)}display(){this.rendered||(this.rendered=!0,this.render(this.containerEl))}hide(){this.destroy(),super.hide(),this.onSave(this.result()),this.opener&&X6(this.opener)}save(){this.onSave(this.result())}destroy(){}addNameSetting(e,n,i,o){return new Zp.SettingGroup(e).addSetting(s=>{s.setName("Name").addText(a=>{a.setValue(n).onChange(l=>{o(l),gC(this.app,this,l.trim()||i)})})})}};function Q6(r){return r?.instanceOf(HTMLElement)?{el:r,label:r.closest("[data-choice-id]")?null:r.getAttribute("aria-label"),content:r.closest(".vertical-tab-content-container"),focusVisible:r.matches(":focus-visible")}:null}function X6({el:r,label:t,content:e,focusVisible:n}){window.setTimeout(()=>{let i=r.isConnected?r:t?e?.querySelector(`[aria-label="${CSS.escape(t)}"]`):null,o=r.ownerDocument.activeElement,s=o!==null&&(o===e||o.matches(".setting-item")&&!!i&&o.contains(i));i&&s&&i.focus({focusVisible:n})})}function em(r,t){return r.trim()||t}function D1(r){return r.setting}function O1(r){let t=D1(r)?.pageStack??[];for(let{page:e}of[...t].reverse())e instanceof _o&&e.save()}function vC(r){let t=D1(r);t?.pageStack?.some(e=>e.page instanceof _o)&&t.clearPageStack?.()}function L1(r){return Ze({...r,commitPending:void 0,choice:Ui(r.choice)})}var tm=class extends _o{constructor(e,n,i,o,s,a){super(e,n.name,o);this.choice=n;this.plugin=i;this.form=s;this.what=a;this.handle=null;this.name=n.name}render(e){let n=L1({choice:this.choice,app:this.app,plugin:this.plugin});this.addNameSetting(e,this.name,this.choice.name,i=>{this.name=i,n.choice.name=i}),this.handle=vi(e,this.form,n,{what:this.what}),this.handle.ok&&(this.formProps=n)}result(){return this.formProps?.commitPending?.(),{...Ui(this.formProps?.choice??this.choice),name:em(this.name,this.choice.name)}}destroy(){this.handle?.destroy(),this.handle=null}};var rm=class extends tm{constructor(t,e,n,i){super(t,e,n,i,KA,"this capture choice's settings"),this.containerEl.addClass("captureChoiceBuilder"),this.normalizeChoice()}normalizeChoice(){this.choice.insertBefore||(this.choice.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:Oi}),this.choice.activeFileWritePosition||(this.choice.activeFileWritePosition="cursor"),this.choice.createFileIfItDoesntExist||(this.choice.createFileIfItDoesntExist={enabled:!1,createWithTemplate:!1,template:""}),!this.choice.captureToActiveFile&&!Rl(this.choice.captureTo)&&(this.choice.captureToCanvasNodeId=""),this.choice.openFile&&(this.choice.fileOpening=en(this.choice.fileOpening))}};ja();ye();gi();tr();Fh();var wC=class extends hi{constructor(e,n,i,o){super(e,n,i);this.currentItems=o}updateCurrentItems(e){this.currentItems=e}getSuggestions(e){return super.getSuggestions(e).filter(n=>!this.currentItems.includes(n))}};var FV=require("obsidian");function K1(r,t){var e=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),e.push.apply(e,n)}return e}function Cv(r){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?K1(Object(e),!0).forEach(function(n){cm(r,n,e[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(e)):K1(Object(e)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(e,n))})}return r}function im(r){"@babel/helpers - typeof";return im=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},im(r)}function cm(r,t,e){return t in r?Object.defineProperty(r,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):r[t]=e,r}function nX(r,t){if(r==null)return{};var e={},n=Object.keys(r),i,o;for(o=0;o<n.length;o++)i=n[o],!(t.indexOf(i)>=0)&&(e[i]=r[i]);return e}function iX(r,t){if(r==null)return{};var e=nX(r,t),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(r);for(i=0;i<o.length;i++)n=o[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(r,n)&&(e[n]=r[n])}return e}function dI(r,t){return sX(r)||lX(r,t)||uI(r,t)||dX()}function ko(r){return oX(r)||aX(r)||uI(r)||cX()}function oX(r){if(Array.isArray(r))return eI(r)}function sX(r){if(Array.isArray(r))return r}function aX(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function lX(r,t){var e=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(e!=null){var n=[],i=!0,o=!1,s,a;try{for(e=e.call(r);!(i=(s=e.next()).done)&&(n.push(s.value),!(t&&n.length===t));i=!0);}catch(l){o=!0,a=l}finally{try{!i&&e.return!=null&&e.return()}finally{if(o)throw a}}return n}}function uI(r,t){if(r){if(typeof r=="string")return eI(r,t);var e=Object.prototype.toString.call(r).slice(8,-1);if(e==="Object"&&r.constructor&&(e=r.constructor.name),e==="Map"||e==="Set")return Array.from(r);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return eI(r,t)}}function eI(r,t){(t==null||t>r.length)&&(t=r.length);for(var e=0,n=new Array(t);e<t;e++)n[e]=r[e];return n}function cX(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function dX(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Qd(r,t){var e=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!e){if(Array.isArray(r)||(e=uI(r))||t&&r&&typeof r.length=="number"){e&&(r=e);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){e=e.call(r)},n:function(){var l=e.next();return o=l.done,l},e:function(l){s=!0,a=l},f:function(){try{!o&&e.return!=null&&e.return()}finally{if(s)throw a}}}}function Gt(r){return r.ownerDocument.defaultView||window}function TC(r,t,e){return{win:r,id:r.setTimeout(t,e)}}function xv(r){r&&r.win.clearTimeout(r.id)}function ts(r){return JSON.stringify(r,null,2)}function _C(r){if(!r)throw new Error("cannot get depth of a falsy node");return aV(r,0)}function aV(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return r.parentElement?aV(r.parentElement,t+1):t-1}function uX(r,t){if(Object.keys(r).length!==Object.keys(t).length)return!1;for(var e in r)if(!{}.hasOwnProperty.call(t,e)||t[e]!==r[e])return!1;return!0}function pX(r,t){if(r.length!==t.length)return!1;for(var e=0;e<r.length;e++)if(r[e]!==t[e])return!1;return!0}var mX="finalize",fX="consider";function dm(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(mX,{detail:{items:t,info:e}}))}function yc(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(fX,{detail:{items:t,info:e}}))}var MC="draggedEntered",kv="draggedLeft",RC="draggedOverIndex",pI="draggedLeftDocument",kC={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function hX(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(MC,{detail:{indexObj:t,draggedEl:e}}))}function gX(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(kv,{detail:{draggedEl:t,type:kC.LEFT_FOR_ANOTHER,theOtherDz:e}}))}function vX(r,t){r.dispatchEvent(new(Gt(r)).CustomEvent(kv,{detail:{draggedEl:t,type:kC.OUTSIDE_OF_ANY}}))}function yX(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(RC,{detail:{indexObj:t,draggedEl:e}}))}function bX(r){var t=Gt(r);t.dispatchEvent(new t.CustomEvent(pI,{detail:{draggedEl:r}}))}var hr={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:MC,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:RC,DRAGGED_LEFT:kv,DRAGGED_LEFT_ALL:"draggedLeftAll",DROPPED_INTO_ZONE:"droppedIntoZone",DROPPED_INTO_ANOTHER:"droppedIntoAnother",DROPPED_OUTSIDE_OF_ANY:"droppedOutsideOfAny",DRAG_STOPPED:"dragStopped"},pn={POINTER:"pointer",KEYBOARD:"keyboard"},wX={space:[" "],enter:["Enter"],space_or_enter:[" ","Enter"]},lV="space_or_enter",CX={space:"space-bar",enter:"enter",space_or_enter:"space-bar or enter"},um="isDndShadowItem",DC="data-is-dnd-shadow-item-internal",xX="data-is-dnd-shadow-item-hint",pm="id:dnd-shadow-placeholder-0000",EX="dnd-action-dragged-el",nr="id",tI=0;function cV(){tI++}function dV(){if(tI===0)throw new Error("Bug! trying to decrement when there are no dropzones");tI--}var mI=typeof window>"u",We=function(){};function rI(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,e,n=t?kX(r):r.getBoundingClientRect(),i=Gt(r).getComputedStyle(r),o=i.transform;if(o){var s,a,l,c;if(o.startsWith("matrix3d("))e=o.slice(9,-1).split(/, /),s=+e[0],a=+e[5],l=+e[12],c=+e[13];else if(o.startsWith("matrix("))e=o.slice(7,-1).split(/, /),s=+e[0],a=+e[3],l=+e[4],c=+e[5];else return n;var d=i.transformOrigin,u=n.left-l-(1-s)*parseFloat(d),p=n.top-c-(1-a)*parseFloat(d.slice(d.indexOf(" ")+1)),m=s?n.width/s:r.offsetWidth,h=a?n.height/a:r.offsetHeight;return{x:u,y:p,width:m,height:h,top:p,right:u+m,bottom:p+h,left:u}}else return n}function nI(r){var t=rI(r),e=Gt(r);return{top:t.top+e.scrollY,bottom:t.bottom+e.scrollY,left:t.left+e.scrollX,right:t.right+e.scrollX}}function uV(r){var t=r.getBoundingClientRect(),e=Gt(r);return{top:t.top+e.scrollY,bottom:t.bottom+e.scrollY,left:t.left+e.scrollX,right:t.right+e.scrollX}}function pV(r){return{x:(r.left+r.right)/2,y:(r.top+r.bottom)/2}}function TX(r,t){return Math.sqrt(Math.pow(r.x-t.x,2)+Math.pow(r.y-t.y,2))}function vv(r,t){return r.y<=t.bottom&&r.y>=t.top&&r.x>=t.left&&r.x<=t.right}function mV(r){return pV(uV(r))}function Q1(r,t){var e=mV(t);return TX(r,e)}function _X(r){var t=uV(r),e=r.ownerDocument.documentElement;return t.right<0||t.left>e.scrollWidth||t.bottom<0||t.top>e.scrollHeight}function kX(r){for(var t=r.getBoundingClientRect(),e={top:t.top,bottom:t.bottom,left:t.left,right:t.right},n=!1,i=!1,o=r.parentElement;o&&o!==r.ownerDocument.body;){var s=Gt(o).getComputedStyle(o),a=s.overflowY,l=s.overflowX,c=a==="scroll"||a==="auto",d=l==="scroll"||l==="auto";if(c||d){var u=o.getBoundingClientRect();if(c){var p=Math.max(e.top,u.top),m=Math.min(e.bottom,u.bottom);(p!==e.top||m!==e.bottom)&&(n=!0),e.top=p,e.bottom=m}if(d){var h=Math.max(e.left,u.left),g=Math.min(e.right,u.right);(h!==e.left||g!==e.right)&&(i=!0),e.left=h,e.right=g}}o=o.parentElement}return n||i?{top:e.top,bottom:e.bottom,left:e.left,right:e.right,width:Math.max(0,e.right-e.left),height:Math.max(0,e.bottom-e.top)}:{top:t.top,bottom:t.bottom,left:t.left,right:t.right,width:Math.max(0,t.right-t.left),height:Math.max(0,t.bottom-t.top)}}var sm;function fI(){We(function(){return"resetting indexes cache"}),sm=new Map}fI();function SX(r){var t=Array.from(r.children).findIndex(function(e){return e.getAttribute(DC)});if(t>=0)return sm.has(r)||sm.set(r,new Map),sm.get(r).set(t,nI(r.children[t])),t}function AX(r,t){var e=nI(t);if(!vv(r,e))return null;var n=t.children;if(n.length===0)return{index:0,isProximityBased:!0};for(var i=SX(t),o=0;o<n.length;o++){var s=nI(n[o]);if(vv(r,s)){var a=sm.has(t)&&sm.get(t).get(o);return a&&!vv(r,a)?{index:i,isProximityBased:!1}:{index:o,isProximityBased:!1}}}for(var l=Number.MAX_VALUE,c=void 0,d=0;d<n.length;d++){var u=Q1(r,n[d]);u<l&&(l=u,c=d)}if(n.length>0){var p=n.length,m=n[p-1],h=m.cloneNode(!1);h.style.visibility="hidden",h.style.pointerEvents="none",t.appendChild(h);var g=Q1(r,h);g<l&&(c=p),t.removeChild(h)}return{index:c,isProximityBased:!0}}var IX=200,X1=10,SC,EC;function PX(r,t){var e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:IX,n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0,o,s,a=!1,l,c=Gt(r),d={};EC=d;var u=Array.from(t).sort(function(m,h){return _C(h)-_C(m)});function p(){var m=i(),h=n.multiScrollIfNeeded();if(!h&&l&&Math.abs(l.x-m.x)<X1&&Math.abs(l.y-m.y)<X1){SC=TC(c,p,e);return}if(_X(r)){We(function(){return"off document"}),bX(r);return}l=m;var g=!1,v=Qd(u),b;try{for(v.s();!(b=v.n()).done;){var y=b.value;h&&fI();var C=AX(m,y);if(C!==null){var w=C.index;if(g=!0,y!==o){if(o&&gX(o,r,y),EC!==d)return;hX(y,C,r),o=y}else w!==s&&(yX(y,C,r),s=w);break}}}catch(T){v.e(T)}finally{v.f()}!g&&a&&o?(vX(o,r),o=void 0,s=void 0,a=!1):a=!0,EC===d&&(SC=TC(c,p,e))}p()}function $X(){We(function(){return"unobserving"}),EC=void 0,xv(SC),SC=void 0,fI()}var fv=30;function FX(){var r;function t(){r={directionObj:void 0,stepPx:0}}t();function e(o){var s=r,a=s.directionObj,l=s.stepPx;a&&(o.scrollBy(a.x*l,a.y*l),Gt(o).requestAnimationFrame(function(){return e(o)}))}function n(o){return fv-o}function i(o,s){if(!s)return!1;var a=MX(o,s),l=!!r.directionObj;if(a===null)return l&&t(),!1;var c=!1,d=!1;return s.scrollHeight>s.clientHeight&&(a.bottom<fv?(c=!0,r.directionObj={x:0,y:1},r.stepPx=n(a.bottom)):a.top<fv&&(c=!0,r.directionObj={x:0,y:-1},r.stepPx=n(a.top)),!l&&c)||s.scrollWidth>s.clientWidth&&(a.right<fv?(d=!0,r.directionObj={x:1,y:0},r.stepPx=n(a.right)):a.left<fv&&(d=!0,r.directionObj={x:-1,y:0},r.stepPx=n(a.left)),!l&&d)?(e(s),!0):(t(),!1)}return{scrollIfNeeded:i,resetScrolling:t}}function MX(r,t){var e=t===t.ownerDocument.scrollingElement?{top:0,bottom:Gt(t).innerHeight,left:0,right:Gt(t).innerWidth}:t.getBoundingClientRect();return vv(r,e)?{top:r.y-e.top,bottom:e.bottom-r.y,left:r.x-e.left,right:e.right-r.x}:null}function RX(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0;We(function(){return"creating multi-scroller"});var e=OX(r),n=Array.from(e).sort(function(l,c){return _C(c)-_C(l)}),i=FX(),o=i.scrollIfNeeded,s=i.resetScrolling;function a(){var l=t();if(!l||!n)return!1;for(var c=n.filter(function(p){return vv(l,p.getBoundingClientRect())||p===p.ownerDocument.scrollingElement}),d=0;d<c.length;d++){var u=o(l,c[d]);if(u)return!0}return!1}return{multiScrollIfNeeded:e.size>0?a:function(){return!1},destroy:function(){return s()}}}function DX(r){if(!r)return[];for(var t=[],e=r;e;){var n=Gt(e).getComputedStyle(e),i=n.overflow;i.split(" ").some(function(o){return o.includes("auto")||o.includes("scroll")})&&t.push(e),e=e.parentElement}return t}function OX(r){var t=new Set,e=Qd(r),n;try{for(e.s();!(n=e.n()).done;){var i=n.value;DX(i).forEach(function(s){return t.add(s)});var o=i.ownerDocument.scrollingElement;(o.scrollHeight>o.clientHeight||o.scrollWidth>o.clientHeight)&&t.add(o)}}catch(s){e.e(s)}finally{e.f()}return t}function LX(r){var t=r.cloneNode(!0),e=[],n=r.tagName==="SELECT",i=n?[r]:ko(r.querySelectorAll("select")),o=Qd(i),s;try{for(o.s();!(s=o.n()).done;){var a=s.value;e.push(a.value)}}catch(C){o.e(C)}finally{o.f()}if(i.length>0)for(var l=n?[t]:ko(t.querySelectorAll("select")),c=0;c<l.length;c++){var d=l[c],u=e[c],p=d.querySelector('option[value="'.concat(u,'"'));p&&p.setAttribute("selected",!0)}var m=r.tagName==="CANVAS",h=m?[r]:ko(r.querySelectorAll("canvas"));if(h.length>0)for(var g=m?[t]:ko(t.querySelectorAll("canvas")),v=0;v<g.length;v++){var b=h[v],y=g[v];y.width=b.width,y.height=b.height,b.width>0&&b.height>0&&y.getContext("2d").drawImage(b,0,0)}return t}var Ev=Object.freeze({USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT:"USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT"}),NX=cm({},Ev.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT,!1);function fV(r){if(!Ev[r])throw new Error("Can't get non existing feature flag ".concat(r,"! Supported flags: ").concat(Object.keys(Ev)));return NX[r]}var VX=.2;function Gd(r){return"".concat(r," ").concat(VX,"s ease")}function hV(r){var t=r.style.transitionProperty.split(",").map(function(e){return e.trim()});t.includes("all")||(t.includes("width")||(r.style.transition+=", ".concat(Gd("width"))),t.includes("height")||(r.style.transition+=", ".concat(Gd("height"))))}function BX(r,t){var e=r.getBoundingClientRect(),n=Gt(r),i=LX(r);gV(r,i),i.id=EX,i.style.position="fixed";var o=e.top,s=e.left;if(i.style.top="".concat(o,"px"),i.style.left="".concat(s,"px"),t){var a=pV(e);o-=a.y-t.y,s-=a.x-t.x,n.setTimeout(function(){i.style.top="".concat(o,"px"),i.style.left="".concat(s,"px")},0)}return i.style.margin="0",i.style.boxSizing="border-box",i.style.height="".concat(e.height,"px"),i.style.width="".concat(e.width,"px"),i.style.transition="".concat(Gd("top"),", ").concat(Gd("left"),", ").concat(Gd("background-color"),", ").concat(Gd("opacity"),", ").concat(Gd("color")," "),n.setTimeout(function(){return hV(i)},0),i.style.zIndex="9999",i.style.cursor="grabbing",i}function UX(r){r.style.cursor="grab"}function qX(r,t,e,n){hV(r),gV(t,r);var i=t.getBoundingClientRect(),o=r.getBoundingClientRect(),s=Gt(r).getComputedStyle(r),a=parseFloat(s.left),l=parseFloat(s.top),c=i.width-o.width,d=i.height-o.height;if(c||d){var u={left:o.width?(e-o.left)/o.width:0,top:o.height?(n-o.top)/o.height:0};fV(Ev.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT)||(r.style.height="".concat(i.height,"px"),r.style.width="".concat(i.width,"px")),r.style.left="".concat(a-u.left*c,"px"),r.style.top="".concat(l-u.top*d,"px")}}function gV(r,t){var e=Gt(r).getComputedStyle(r);Array.from(e).filter(function(n){return n.startsWith("background")||n.startsWith("padding")||n.startsWith("font")||n.startsWith("text")||n.startsWith("align")||n.startsWith("justify")||n.startsWith("display")||n.startsWith("flex")||n.startsWith("border")||n==="opacity"||n==="color"||n==="list-style-type"||fV(Ev.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT)&&(n==="width"||n==="height")}).forEach(function(n){return t.style.setProperty(n,e.getPropertyValue(n),e.getPropertyPriority(n))})}function zX(r,t){r.draggable=!1,r.ondragstart=function(){return!1},t?(r.style.userSelect="",r.style.WebkitUserSelect="",r.style.cursor=""):(r.style.userSelect="none",r.style.WebkitUserSelect="none",r.style.cursor="grab")}function vV(r){r.style.display="none",r.style.position="fixed",r.style.zIndex="-5"}function HX(r){r.style.visibility="hidden",r.setAttribute(DC,"true")}function WX(r){r.style.visibility="",r.removeAttribute(DC)}function iI(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){},e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:function(){return[]};r.forEach(function(n){var i=t(n);Object.keys(i).forEach(function(o){n.style[o]=i[o]}),e(n).forEach(function(o){return n.classList.add(o)})})}function hI(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){},e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:function(){return[]};r.forEach(function(n){var i=t(n);Object.keys(i).forEach(function(o){n.style[o]=""}),e(n).forEach(function(o){return n.classList.contains(o)&&n.classList.remove(o)})})}function GX(r){var t=r.style.minHeight,e=Gt(r).getComputedStyle(r);r.style.minHeight=e.getPropertyValue("height");var n=r.style.minWidth;return r.style.minWidth=e.getPropertyValue("width"),function(){r.style.minHeight=t,r.style.minWidth=n}}var jX="--any--",YX=100,KX=20,CC=3,QX=80,J1={outline:"rgba(255, 255, 102, 0.7) solid 2px"},Z1="data-is-dnd-original-dragged-item",ln,fr,yi,yv,Bt,OC,vc,dn,Vs,cn,Bs=!1,Tv=!1,gI,Sv=!1,om=[],bv,pc,gv=!1,vI=!1,Ns,mc=new Set,ft,_v,jd=new Map,Ur=new Map,hv=new WeakMap;function XX(r,t){We(function(){return"registering drop-zone if absent"}),jd.has(t)||jd.set(t,new Set),jd.get(t).has(r)||(jd.get(t).add(r),cV())}function eV(r,t){var e=jd.get(t);!e||!e.delete(r)||(dV(),e.size===0&&jd.delete(t))}function yI(r){return Array.from(jd.get(r)||[]).filter(function(t){return t.ownerDocument.defaultView===ft})}function JX(){We(function(){return"watching dragged element"});var r=yI(yv);if(r.length!==0){mc.size>0&&oI(),mc=new Set(r);var t=Qd(mc),e;try{for(t.s();!(e=t.n()).done;){var n=e.value;n.addEventListener(MC,yV),n.addEventListener(kv,bV),n.addEventListener(RC,wV)}}catch(a){t.e(a)}finally{t.f()}ft.addEventListener(pI,Yd);var i=Math.max.apply(Math,ko(Array.from(mc).map(function(a){return Ur.get(a).dropAnimationDurationMs}))),o=i===0?KX:Math.max(i,YX);bv=RX(mc,function(){return cn});var s=vI?function(){return{x:cn.x+ft.scrollX,y:cn.y+ft.scrollY}}:function(){return mV(fr)};PX(fr,mc,o*1.07,bv,s)}}function oI(){We(function(){return"unwatching dragged element"});var r=Qd(mc),t;try{for(r.s();!(t=r.n()).done;){var e=t.value;e.removeEventListener(MC,yV),e.removeEventListener(kv,bV),e.removeEventListener(RC,wV)}}catch(n){r.e(n)}finally{r.f()}mc=new Set,ft.removeEventListener(pI,Yd),bv&&(bv.destroy(),bv=void 0),$X()}function LC(r){return r.findIndex(function(t){return!!t[um]})}function ZX(r){var t;return Cv(Cv({},r),{},(t={},cm(t,um,!0),cm(t,nr,pm),t))}function yV(r){We(function(){return["dragged entered",r.currentTarget,r.detail]});var t=Ur.get(r.currentTarget),e=t.items,n=t.dropFromOthersDisabled;if(n&&r.currentTarget!==Bt){We(function(){return"ignoring dragged entered because drop is currently disabled"});return}if(Sv=!1,e=e.filter(function(a){return a[nr]!==vc[nr]&&a[nr]!==pm}),We(function(){return"dragged entered items ".concat(ts(e))}),Bt!==r.currentTarget){var i=Ur.get(Bt).items,o=i.filter(function(a){return!a[um]});if(yc(Bt,o,{trigger:hr.DRAGGED_ENTERED_ANOTHER,id:yi[nr],source:pn.POINTER}),!Bs)return}var s=r.detail.indexObj.index;dn=r.currentTarget,e.splice(s,0,vc),yc(r.currentTarget,e,{trigger:hr.DRAGGED_ENTERED,id:yi[nr],source:pn.POINTER})}function bV(r){if(Bs){We(function(){return["dragged left",r.currentTarget,r.detail]});var t=Ur.get(r.currentTarget),e=t.items,n=t.dropFromOthersDisabled;if(n&&r.currentTarget!==Bt&&r.currentTarget!==dn){We(function(){return"drop is currently disabled"});return}var i=ko(e),o=LC(i);o!==-1&&i.splice(o,1);var s=dn;dn=void 0;var a=r.detail,l=a.type,c=a.theOtherDz;if(l===kC.OUTSIDE_OF_ANY||l===kC.LEFT_FOR_ANOTHER&&c!==Bt&&Ur.get(c).dropFromOthersDisabled){We(function(){return"dragged left all, putting shadow element back in the origin dz"}),Sv=!0,dn=Bt;var d=s===Bt?i:ko(Ur.get(Bt).items);if(d.splice(OC,0,vc),yc(Bt,d,{trigger:hr.DRAGGED_LEFT_ALL,id:yi[nr],source:pn.POINTER}),!Bs)return}yc(r.currentTarget,i,{trigger:hr.DRAGGED_LEFT,id:yi[nr],source:pn.POINTER})}}function wV(r){We(function(){return["dragged is over index",r.currentTarget,r.detail]});var t=Ur.get(r.currentTarget),e=t.items,n=t.dropFromOthersDisabled;if(n&&r.currentTarget!==Bt){We(function(){return"drop is currently disabled"});return}var i=ko(e);Sv=!1;var o=r.detail.indexObj.index,s=LC(i);s!==-1&&i.splice(s,1),i.splice(o,0,vc),yc(r.currentTarget,i,{trigger:hr.DRAGGED_OVER_INDEX,id:yi[nr],source:pn.POINTER})}function AC(r){r.preventDefault();var t=r.touches?r.touches[0]:r;cn={x:t.clientX,y:t.clientY},fr.style.transform="translate3d(".concat(cn.x-Vs.x,"px, ").concat(cn.y-Vs.y,"px, 0)")}function Yd(){We(function(){return"dropped"}),Tv=!0,ft.removeEventListener("mousemove",AC),ft.removeEventListener("touchmove",AC),ft.removeEventListener("mouseup",Yd),ft.removeEventListener("touchend",Yd),oI(),UX(fr),dn||(We(function(){return"element was dropped right after it left origin but before entering somewhere else"}),dn=Bt),We(function(){return["dropped in dz",dn]});var r=Ur.get(dn),t=r.items,e=r.type;hI(yI(e),function(o){return Ur.get(o).dropTargetStyle},function(o){return Ur.get(o).dropTargetClasses});var n=LC(t);n===-1&&dn===Bt&&(n=OC),t=t.map(function(o){return o[um]?yi:o});function i(){oI(),gI(),dm(dn,t,{trigger:Sv?hr.DROPPED_OUTSIDE_OF_ANY:hr.DROPPED_INTO_ZONE,id:yi[nr],source:pn.POINTER}),dn!==Bt&&dm(Bt,Ur.get(Bt).items,{trigger:hr.DROPPED_INTO_ANOTHER,id:yi[nr],source:pn.POINTER});var o=Array.from(dn.children).find(function(s){return s.getAttribute(DC)});o&&WX(o),r5()}Ur.get(dn).dropAnimationDisabled?i():e5(n,i)}function e5(r,t){var e=r>-1?rI(dn.children[r],!1):rI(dn,!1),n={x:e.left-parseFloat(fr.style.left),y:e.top-parseFloat(fr.style.top)},i=Ur.get(dn),o=i.dropAnimationDurationMs,s="transform ".concat(o,"ms ease");fr.style.transition=fr.style.transition?fr.style.transition+","+s:s,fr.style.transform="translate3d(".concat(n.x,"px, ").concat(n.y,"px, 0)"),_v={timeout:TC(ft,CV,o),finalize:t}}function CV(){var r=_v,t=r.finalize;_v=void 0,t()}function xV(){We(function(){return"the drag's window is going away"}),Tv||Yd(),_v&&(xv(_v.timeout),CV())}function t5(r,t){var e={dz:r,destroy:t};om.push(e),Gt(r).requestAnimationFrame(function(){om.includes(e)&&(vV(r),r.ownerDocument.body.appendChild(r))})}function r5(){fr&&fr.remove&&fr.remove(),ln&&ln.remove&&ln.remove(),fr=void 0,ln=void 0,yi=void 0,yv=void 0,Bt=void 0,OC=void 0,vc=void 0,dn=void 0,Vs=void 0,cn=void 0,Bs=!1,Tv=!1,gI=void 0,Sv=!1,ft.removeEventListener("pagehide",xV),ft=void 0,xv(pc),pc=void 0,gv=!1,vI=!1,Ns=void 0,om.length&&(We(function(){return["will destroy zones that were removed during drag",om]}),om.forEach(function(r){var t=r.dz,e=r.destroy;e(),t.remove()}),om=[])}function n5(r,t){var e=!1,n=!1,i={items:void 0,type:void 0,flipDurationMs:0,dragDisabled:!1,morphDisabled:!1,dropFromOthersDisabled:!1,dropTargetStyle:J1,dropTargetClasses:[],transformDraggedElement:function(){},centreDraggedOnCursor:!1,useCursorForDetection:!1,dropAnimationDisabled:!1,delayTouchStartMs:0};We(function(){return["dndzone good to go options: ".concat(ts(t),", config: ").concat(ts(i)),{node:r}]});var o=new Map;function s(){ft.addEventListener("mousemove",d,{passive:!1}),ft.addEventListener("touchmove",d,{passive:!1,capture:!1}),ft.addEventListener("mouseup",c,{passive:!1}),ft.addEventListener("touchend",c,{passive:!1}),ft.addEventListener("pagehide",l)}function a(){ft.removeEventListener("mousemove",d),ft.removeEventListener("touchmove",d),ft.removeEventListener("mouseup",c),ft.removeEventListener("touchend",c),ft.removeEventListener("pagehide",l),pc&&(xv(pc),pc=void 0,gv=!1)}function l(){Ns===r&&(a(),ft=void 0,Ns=void 0,ln=void 0,Vs=void 0,cn=void 0)}function c(h){if(Ns===r&&(l(),h.type==="touchend")){var g=new(Gt(h.target)).Event("click",{bubbles:!0,cancelable:!0});h.target.dispatchEvent(g)}}function d(h){if(!(n||Ns!==r)){var g=!!h.touches,v=g?h.touches[0]:h;if(g&&i.delayTouchStartMs>0&&!gv){cn={x:v.clientX,y:v.clientY},(Math.abs(cn.x-Vs.x)>=CC||Math.abs(cn.y-Vs.y)>=CC)&&(xv(pc),pc=void 0,c(h));return}h.preventDefault(),cn={x:v.clientX,y:v.clientY},(Math.abs(cn.x-Vs.x)>=CC||Math.abs(cn.y-Vs.y)>=CC)&&p()}}function u(h){if(h.target!==h.currentTarget&&(h.target.value!==void 0||h.target.isContentEditable)){We(function(){return"won't initiate drag on a nested input element"});return}if(h.button){We(function(){return"ignoring none left click button: ".concat(h.button)});return}if(n||Bs||Ns){We(function(){return"cannot start a new drag before finalizing the current drag or pending gesture"});return}var g=!!h.touches,v=g&&i.delayTouchStartMs>0;v||h.preventDefault(),h.stopPropagation(),Ns=r;var b=g?h.touches[0]:h;if(Vs={x:b.clientX,y:b.clientY},cn=Cv({},Vs),ln=h.currentTarget,ft=Gt(ln),v){var y=ln;gv=!1,pc=TC(ft,function(){n||Ns!==r||ln!==y||(gv=!0,p())},i.delayTouchStartMs)}s()}function p(){var h;if(n||Ns!==r||Bs||!((h=ln)!==null&&h!==void 0&&h.parentElement)){l();return}a(),Ns=void 0,We(function(){return["drag start config: ".concat(ts(i)),ln]}),Bs=!0;var g=o.get(ln);OC=g,Bt=ln.parentElement;var v=Bt.closest("dialog")||Bt.closest("[popover]")||Bt.getRootNode(),b=v.body||v,y=i.items,C=i.type,w=i.centreDraggedOnCursor,T=i.useCursorForDetection,P=ko(y);yi=P[g],yv=C,vc=ZX(yi),vI=T,fr=BX(ln,w&&cn),b.appendChild(fr);function _(){if(!(!fr||Tv))if(ln.parentElement)ft.requestAnimationFrame(_);else{if(ln.setAttribute(Z1,!0),b.appendChild(ln),JX(),!fr)return;vV(ln),vc[nr]=yi[nr],fr.focus()}}ft.requestAnimationFrame(_),iI(yI(i.type).filter(function(I){return I===Bt||!Ur.get(I).dropFromOthersDisabled}),function(I){return Ur.get(I).dropTargetStyle},function(I){return Ur.get(I).dropTargetClasses}),P.splice(g,1,vc),gI=GX(Bt),ft.addEventListener("mousemove",AC,{passive:!1}),ft.addEventListener("touchmove",AC,{passive:!1,capture:!1}),ft.addEventListener("mouseup",Yd,{passive:!1}),ft.addEventListener("touchend",Yd,{passive:!1}),ft.addEventListener("pagehide",xV),yc(Bt,P,{trigger:hr.DRAG_STARTED,id:yi[nr],source:pn.POINTER})}function m(h){var g=h.items,v=g===void 0?void 0:g,b=h.flipDurationMs,y=b===void 0?0:b,C=h.type,w=C===void 0?jX:C,T=h.dragDisabled,P=T===void 0?!1:T,_=h.morphDisabled,I=_===void 0?!1:_,O=h.dropFromOthersDisabled,N=O===void 0?!1:O,K=h.dropTargetStyle,ne=K===void 0?J1:K,H=h.dropTargetClasses,D=H===void 0?[]:H,G=h.transformDraggedElement,V=G===void 0?function(){}:G,M=h.centreDraggedOnCursor,B=M===void 0?!1:M,J=h.useCursorForDetection,te=J===void 0?!1:J,W=h.dropAnimationDisabled,Z=W===void 0?!1:W,se=h.delayTouchStart,ce=se===void 0?!1:se,$e=Bs&&r.ownerDocument.defaultView===ft,Xe=r===Bt||i.type===yv&&!i.dropFromOthersDisabled,Ye=r===Bt||w===yv&&!N;i.dropAnimationDurationMs=y;var he=0;ce===!0?he=QX:typeof ce=="number"&&isFinite(ce)&&ce>=0&&(he=ce),i.delayTouchStartMs=he,i.type&&w!==i.type&&eV(r,i.type),i.type=w,i.items=ko(v),i.dragDisabled=P,i.morphDisabled=I,i.transformDraggedElement=V,i.centreDraggedOnCursor=B,i.useCursorForDetection=te,i.dropAnimationDisabled=Z,e&&$e&&!Tv&&(Xe!==Ye||!uX(ne,i.dropTargetStyle)||!pX(D,i.dropTargetClasses))&&(Xe&&hI([r],function(){return i.dropTargetStyle},function(){return i.dropTargetClasses}),Ye&&iI([r],function(){return ne},function(){return D})),i.dropTargetStyle=ne,i.dropTargetClasses=ko(D),i.dropFromOthersDisabled=N,Ur.set(r,i),XX(r,w);for(var Re=Bs?LC(i.items):-1,Je=0;Je<r.children.length;Je++){var ve=r.children[Je];if(zX(ve,P),Je===Re){I||qX(fr,ve,cn.x,cn.y),i.transformDraggedElement(fr,yi,Je),HX(ve);continue}ve.removeEventListener("mousedown",hv.get(ve)),ve.removeEventListener("touchstart",hv.get(ve)),P||(ve.addEventListener("mousedown",u),ve.addEventListener("touchstart",u),hv.set(ve,u)),o.set(ve,Je)}e=!0}return m(t),{update:function(g){We(function(){return"pointer dndzone will update newOptions: ".concat(ts(g))}),m(g)},destroy:function(){if(n)return;n=!0,l();var g=Qd(r.children),v;try{for(g.s();!(v=g.n()).done;){var b=v.value;b.removeEventListener("mousedown",hv.get(b)),b.removeEventListener("touchstart",hv.get(b))}}catch(C){g.e(C)}finally{g.f()}function y(){We(function(){return"pointer dndzone will destroy"});var C=Ur.get(r);C&&(eV(r,C.type),Ur.delete(r))}Bs&&!r.closest("[".concat(Z1,"]"))?(We(function(){return"pointer dndzone will be scheduled for destruction"}),t5(r,y)):y()}}}var xC,sI={DND_ZONE_ACTIVE:"dnd-zone-active",DND_ZONE_DRAG_DISABLED:"dnd-zone-drag-disabled"},EV=(xC={},cm(xC,sI.DND_ZONE_ACTIVE,"zoneActiveInstruction"),cm(xC,sI.DND_ZONE_DRAG_DISABLED,"zoneDragDisabledInstruction"),xC),TV={dragStarted:function(t){var e=t.itemLabel,n=t.zoneLabel,i=t.canMoveBetweenZones;return"Started dragging item ".concat(e,". Use the arrow keys to move it within its list ").concat(n)+(i?", or tab to another list in order to move the item into it":"")},movedToPosition:function(t){var e=t.itemLabel,n=t.zoneLabel,i=t.position;return"Moved item ".concat(e," to position ").concat(i," in the list ").concat(n)},movedToZoneEnd:function(t){var e=t.itemLabel,n=t.zoneLabel;return"Moved item ".concat(e," to the end of the list ").concat(n)},movedToZoneStart:function(t){var e=t.itemLabel,n=t.zoneLabel;return"Moved item ".concat(e," to the beginning of the list ").concat(n)},dropped:function(t){var e=t.itemLabel;return"Stopped dragging item ".concat(e)},zoneActiveInstruction:function(t){var e=t.keyboardDragTrigger;return"Tab to one the items and press ".concat(CX[e]," to start dragging it")},zoneDragDisabledInstruction:"This is a disabled drag and drop list"};var i5=Cv({},TV),o5={keyboardDragTrigger:lV},s5="dnd-action-aria-alert",fc=new Map;function aI(r){if(!fc.has(r)){var t=r.createElement("div");(function(){t.id=s5,t.style.position="fixed",t.style.bottom="0",t.style.left="0",t.style.zIndex="-5",t.style.opacity="0",t.style.height="0",t.style.width="0",t.setAttribute("role","alert")})(),r.body.prepend(t),fc.forEach(function(e,n){return!n.defaultView&&fc.delete(n)}),fc.set(r,t),Object.entries(EV).forEach(function(e){var n=dI(e,2),i=n[0],o=n[1];return r.body.prepend(c5(r,i,_V(o,o5)))})}}function a5(r){return mI?null:(r=r||document,r.readyState==="complete"?aI(r):r.addEventListener("DOMContentLoaded",function(){return aI(r)}),Cv({},sI))}function l5(r){if(!mI){r=r||document;var t=fc.get(r);t&&(Object.keys(EV).forEach(function(e){var n;return(n=r.getElementById(e))===null||n===void 0?void 0:n.remove()}),t.remove(),fc.delete(r))}}function c5(r,t,e){var n=r.createElement("div");return n.id=t,d5(n,e),n.style.display="none",n.style.position="fixed",n.style.zIndex="-5",n}function d5(r,t){r.replaceChildren();var e=r.ownerDocument.createElement("p");e.textContent=t,r.appendChild(e)}function Xd(r,t){if(!mI){t=t||document,fc.has(t)||aI(t);var e=fc.get(t);e.innerHTML="";var n=t.createTextNode(r);e.appendChild(n),e.style.display="none",e.style.display="inline"}}function tV(r,t,e){var n=r[t];return typeof n=="function"?n(e):n}function _V(r,t){try{return tV(i5,r,t)}catch(e){We(function(){return['aria string formatter for "'.concat(r,'" threw, falling back to the default'),e]});try{return tV(TV,r,t)}catch(n){return We(function(){return['default aria string formatter for "'.concat(r,'" also threw'),n]}),""}}}function am(r,t,e){Xd(_V(r,t),e)}var u5=lV;function p5(r){return wX[u5].includes(r)}var m5="--any--",rV={outline:"rgba(255, 255, 102, 0.7) solid 2px"},En=!1,lm,un,Us="",Ya,qi,hc="",IC,PC=new WeakSet,JA=new WeakMap,ZA=new WeakMap,lI=new Map,Br=new Map,gc=new Map,$C=new Map,FC=new Map,cI;function f5(r){for(var t=[r],e=(n=r.defaultView)===null||n===void 0?void 0:n.frameElement;e&&t[t.length-1]!==document;e=Gt(e).frameElement){var n;t.push(e.ownerDocument)}return t}function h5(r){var t=f5(r.ownerDocument);t.forEach(function(e,n){var i=FC.get(e);if(!i){We(function(){return"adding global keydown and click handlers"});var o={keydown:v5,click:y5,pagehide:b5};i={win:e.defaultView,zoneCount:0,documentCount:0,handlers:{}},Object.entries(o).forEach(function(s){var a,l=dI(s,2),c=l[0],d=l[1];i.handlers[c]=function(u){return d(u)},(a=i.win)===null||a===void 0||a.addEventListener(c,i.handlers[c])}),FC.set(e,i)}i.documentCount++,n===0&&i.zoneCount++===0&&(cI=a5(e))}),$C.set(r,t)}function kV(r){var t=$C.get(r);t&&($C.delete(r),t.forEach(function(e,n){var i=FC.get(e);n===0&&--i.zoneCount===0&&l5(e),!(--i.documentCount>0)&&(We(function(){return"removing global keydown and click handlers"}),FC.delete(e),Object.entries(i.handlers).forEach(function(o){var s,a=dI(o,2),l=a[0],c=a[1];return(s=i.win)===null||s===void 0?void 0:s.removeEventListener(l,c)}))}))}function g5(r,t){var e;We(function(){return"registering drop-zone if absent"}),gc.has(t)||gc.set(t,new Set),gc.get(t).has(r)||(gc.get(t).add(r),cV()),((e=$C.get(r))===null||e===void 0?void 0:e[0])!==r.ownerDocument&&(kV(r),h5(r))}function nV(r,t){We(function(){return"unregistering drop-zone"}),En&&un===r&&Kd();var e=gc.get(t);!e||!e.delete(r)||(dV(),e.size===0&&gc.delete(t),kV(r))}function v5(r){En&&r.key==="Escape"&&Kd()}function y5(r){En&&(PC.has(r.currentTarget.document.activeElement)||(We(function(){return"clicked outside of any draggable"}),Kd()))}function b5(r){En&&un&&Gt(un)===r.currentTarget&&(We(function(){return"the focused zone's window is going away"}),Kd())}function wv(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:IC;return r.ownerDocument===t}function w5(r,t){var e=r.getBoundingClientRect(),n=t.getBoundingClientRect();return e.top<n.top||e.left<n.left}function bI(r){var t=Br.get(r);return t.type===lm&&!t.dropFromOthersDisabled&&!Ya.contains(r)&&wv(r)}function SV(r){return r!==un&&bI(r)?0:-1}function C5(){Br.forEach(function(r,t){t.tabIndex=SV(t)})}function x5(){var r=Br.get(un);return r!=null&&r.items.some(function(t){return t[nr]===qi})?!0:(We(function(){return"dragged item is gone, dropping"}),Kd(),!1)}function iV(r){if(We(function(){return"zone focus"}),!!En){var t=r.currentTarget;if(!(t===un||!bI(t))&&x5()){var e=un,n=qi;Us=t.getAttribute("aria-label")||"";var i=Br.get(un),o=i.items,s=o.find(function(p){return p[nr]===qi}),a=o.indexOf(s),l=o.splice(a,1)[0],c=Br.get(t),d=c.items,u=c.autoAriaDisabled;w5(t,un)?(d.push(l),u||am("movedToZoneEnd",{itemLabel:hc,zoneLabel:Us,position:d.length,count:d.length},t.ownerDocument)):(d.unshift(l),u||am("movedToZoneStart",{itemLabel:hc,zoneLabel:Us,position:1,count:d.length},t.ownerDocument)),En&&(un=t),dm(e,o,{trigger:hr.DROPPED_INTO_ANOTHER,id:n,source:pn.KEYBOARD}),Br.has(t)&&dm(t,d,{trigger:hr.DROPPED_INTO_ZONE,id:n,source:pn.KEYBOARD})}}}function AV(){lI.forEach(function(r,t){var e=r.update;return e(Br.get(t))})}function Kd(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;if(!(!En||!un)){We(function(){return"drop"});var t=un,e=Br.get(t),n=qi,i=lm;if(e){var o=hc,s=Us,a=IC;if(Ya=null,qi=null,hc="",lm=null,un=null,Us="",IC=void 0,En=!1,!e.autoAriaDisabled){var l=e.items,c=l.findIndex(function(p){return p[nr]===n});am("dropped",{itemLabel:o,zoneLabel:s,position:(c<0?0:c)+1,count:l.length},t.ownerDocument)}var d=t.ownerDocument.activeElement;PC.has(d)&&d.blur(),r&&yc(t,e.items,{trigger:hr.DRAG_STOPPED,id:n,source:pn.KEYBOARD});var u=gc.get(i);u&&hI(Array.from(u).filter(function(p){return wv(p,a)}),function(p){return Br.get(p).dropTargetStyle},function(p){return Br.get(p).dropTargetClasses}),AV()}}}function E5(r,t){var e=!1,n={items:void 0,type:void 0,dragDisabled:!1,zoneTabIndex:0,zoneItemTabIndex:0,dropFromOthersDisabled:!1,dropTargetStyle:rV,dropTargetClasses:[],autoAriaDisabled:!1};function i(p,m,h){p.length<=1||p.splice(h,1,p.splice(m,1,p[h])[0])}function o(p){return En&&r===un&&wv(r)&&p.currentTarget===Ya&&p.target===Ya}function s(p){switch(We(function(){return["handling key down",p.key]}),p.key){case"Enter":case" ":{if(!p5(p.key)||(p.target.disabled!==void 0||p.target.href||p.target.isContentEditable)&&!PC.has(p.target))return;p.preventDefault(),p.stopPropagation(),En?Kd():a(p);break}case"ArrowDown":case"ArrowRight":{if(!o(p))return;p.preventDefault(),p.stopPropagation();var m=Br.get(r),h=m.items,g=Array.from(r.children),v=g.indexOf(p.currentTarget);if(We(function(){return["arrow down",v]}),v<g.length-1){if(n.autoAriaDisabled||am("movedToPosition",{itemLabel:hc,zoneLabel:Us,position:v+2,count:h.length},r.ownerDocument),!o(p))break;i(h,v,v+1),dm(r,h,{trigger:hr.DROPPED_INTO_ZONE,id:qi,source:pn.KEYBOARD})}break}case"ArrowUp":case"ArrowLeft":{if(!o(p))return;p.preventDefault(),p.stopPropagation();var b=Br.get(r),y=b.items,C=Array.from(r.children),w=C.indexOf(p.currentTarget);if(We(function(){return["arrow up",w]}),w>0){if(n.autoAriaDisabled||am("movedToPosition",{itemLabel:hc,zoneLabel:Us,position:w,count:y.length},r.ownerDocument),!o(p))break;i(y,w,w-1),dm(r,y,{trigger:hr.DROPPED_INTO_ZONE,id:qi,source:pn.KEYBOARD})}break}}}function a(p){We(function(){return"drag start"}),c(p.currentTarget),un=r,Us=r.getAttribute("aria-label")||"",lm=n.type,En=!0,IC=r.ownerDocument;var m=Array.from(gc.get(n.type)).filter(function(v){return v===un||bI(v)});if(iI(m,function(v){return Br.get(v).dropTargetStyle},function(v){return Br.get(v).dropTargetClasses}),!n.autoAriaDisabled){var h=Br.get(r).items,g=h.findIndex(function(v){return v[nr]===qi});am("dragStarted",{itemLabel:hc,zoneLabel:Us,position:(g<0?0:g)+1,count:h.length,canMoveBetweenZones:m.length>1},r.ownerDocument)}En&&(yc(r,Br.get(r).items,{trigger:hr.DRAG_STARTED,id:qi,source:pn.KEYBOARD}),AV())}function l(p){En&&p.currentTarget!==Ya&&(p.stopPropagation(),Kd(!1),a(p))}function c(p){var m=Br.get(r),h=m.items,g=Array.from(r.children),v=g.indexOf(p);Ya=p,Ya.tabIndex=n.zoneItemTabIndex,qi=h[v][nr],hc=g[v].getAttribute("aria-label")||""}function d(p){var m=p.items,h=m===void 0?[]:m,g=p.type,v=g===void 0?m5:g,b=p.dragDisabled,y=b===void 0?!1:b,C=p.zoneTabIndex,w=C===void 0?0:C,T=p.zoneItemTabIndex,P=T===void 0?0:T,_=p.dropFromOthersDisabled,I=_===void 0?!1:_,O=p.dropTargetStyle,N=O===void 0?rV:O,K=p.dropTargetClasses,ne=K===void 0?[]:K,H=p.autoAriaDisabled,D=H===void 0?!1:H;n.items=ko(h),n.dragDisabled=y,n.dropFromOthersDisabled=I,n.zoneTabIndex=w,n.zoneItemTabIndex=P,n.dropTargetStyle=N,n.dropTargetClasses=ne,n.autoAriaDisabled=D,n.type&&v!==n.type&&nV(r,n.type),n.type=v,g5(r,v),D||(r.setAttribute("role","list"),r.setAttribute("aria-describedby",y?cI.DND_ZONE_DRAG_DISABLED:cI.DND_ZONE_ACTIVE)),Br.set(r,n);var G=!1;En?(G=wv(r)&&n.type===lm&&n.items.some(function(B){return B[nr]===qi})&&r!==un,G&&(un=r,Us=r.getAttribute("aria-label")||""),r.tabIndex=SV(r)):r.tabIndex=n.zoneTabIndex,r.addEventListener("focus",iV);for(var V=function(J){var te,W=r.children[J];PC.add(W),W.tabIndex=En?-1:n.zoneItemTabIndex,D||W.setAttribute("role","listitem"),W.removeEventListener("keydown",JA.get(W)),W.removeEventListener("click",ZA.get(W)),y||(W.addEventListener("keydown",s),JA.set(W,s),W.addEventListener("click",l),ZA.set(W,l)),En&&wv(r)&&n.type===lm&&((te=n.items[J])===null||te===void 0?void 0:te[nr])===qi&&(We(function(){return["focusing on",{i:J,focusedItemId:qi}]}),Ya=W,Ya.tabIndex=n.zoneItemTabIndex,W.focus())},M=0;M<r.children.length;M++)V(M);G&&En&&C5()}d(t);var u={update:function(m){We(function(){return"keyboard dndzone will update newOptions: ".concat(ts(m))}),d(m)},destroy:function(){if(!e){e=!0,We(function(){return"keyboard dndzone will destroy"}),r.removeEventListener("focus",iV);var m=Qd(r.children),h;try{for(m.s();!(h=m.n()).done;){var g=h.value;g.removeEventListener("keydown",JA.get(g)),g.removeEventListener("click",ZA.get(g))}}catch(v){m.e(v)}finally{m.f()}nV(r,n.type),Br.delete(r),lI.delete(r)}}};return lI.set(r,u),u}var T5=["items","flipDurationMs","type","dragDisabled","morphDisabled","dropFromOthersDisabled","zoneTabIndex","zoneItemTabIndex","dropTargetStyle","dropTargetClasses","transformDraggedElement","autoAriaDisabled","centreDraggedOnCursor","useCursorForDetection","delayTouchStart","dropAnimationDisabled"];function mm(r,t){if(_5(r))return{update:function(){},destroy:function(){}};oV(t);var e=n5(r,t),n=E5(r,t);return{update:function(o){oV(o),e.update(o),n.update(o)},destroy:function(){e.destroy(),n.destroy()}}}function _5(r){return!!r.closest("[".concat(xX,'="true"]'))}function oV(r){var t=r.items;r.flipDurationMs,r.type,r.dragDisabled,r.morphDisabled,r.dropFromOthersDisabled;var e=r.zoneTabIndex,n=r.zoneItemTabIndex;r.dropTargetStyle;var i=r.dropTargetClasses;r.transformDraggedElement,r.autoAriaDisabled,r.centreDraggedOnCursor,r.useCursorForDetection;var o=r.delayTouchStart;r.dropAnimationDisabled;var s=iX(r,T5);if(Object.keys(s).length>0&&console.warn("dndzone will ignore unknown options",s),!t)throw new Error("no 'items' key provided to dndzone");var a=t.find(function(d){return!{}.hasOwnProperty.call(d,nr)});if(a)throw new Error("missing '".concat(nr,"' property for item ").concat(ts(a)));if(i&&!Array.isArray(i))throw new Error("dropTargetClasses should be an array but instead it is a ".concat(im(i),", ").concat(ts(i)));if(e&&!sV(e))throw new Error("zoneTabIndex should be a number but instead it is a ".concat(im(e),", ").concat(ts(e)));if(n&&!sV(n))throw new Error("zoneItemTabIndex should be a number but instead it is a ".concat(im(n),", ").concat(ts(n)));if(o!==void 0&&o!==!1){var l=o===!0,c=typeof o=="number"&&isFinite(o)&&o>=0;if(!l&&!c)throw new Error("delayTouchStart should be a boolean (true/false) or a non-negative number but instead it is a ".concat(im(o),", ").concat(ts(o)))}}function sV(r){return!isNaN(r)&&(function(t){return(t|0)===t})(parseFloat(r))}function IV(r){var t=r,e=new Set;return{get:function(){return t},set:function(i){t=i,Array.from(e).forEach(function(o){return o(t)})},subscribe:function(i){e.add(i),i(t)},unsubscribe:function(i){e.delete(i)}}}var xFe=IV(!0),EFe=IV(!1);var k5=[[9,5],[9,12],[9,19],[15,5],[15,12],[15,19]];function wI(r,t,e=!1){if(!r)return;r.classList.add("qa-drag-clone"),r.dataset.qaMulti=e?"true":"false";let n=r.querySelector(":scope > .qa-drag-pill");if(!n){n=r.createDiv({cls:"qa-drag-pill"});let s=n.createSpan({cls:"qa-drag-pill-grip"}).createSvg("svg",{attr:{viewBox:"0 0 24 24",width:14,height:14,fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}});for(let[a,l]of k5)s.createSvg("circle",{attr:{cx:a,cy:l,r:1}});n.createSpan({cls:"qa-drag-pill-label"})}let i=n.querySelector(".qa-drag-pill-label");i&&i.textContent!==t&&(i.textContent=t)}function bi(r){return r.filter(t=>t.id!==pm)}function fm(r,t){let e=r.findIndex(i=>i.id===pm);if(e===-1)return null;let n={...r[e]};return delete n[um],{item:{...n,id:t},index:e}}function PV(r,t){return r.map(e=>e.id===t.id?t:e)}function hm(r,t,e){let n=r.findIndex(a=>a.id===t);if(n===-1)return null;let i=n+e;if(i<0||i>=r.length||i===n)return null;let o=[...r],[s]=o.splice(n,1);return o.splice(i,0,s),o}var $V=r=>r.name??"";function gm(r,t=$V){if(r.detail.info.trigger!==hr.DRAG_STARTED)return;let e=r.detail.items.find(o=>o.id===pm),i=r.currentTarget?.ownerDocument.getElementById("dnd-action-dragged-el");!e||!i||wI(i,t(e),e.type==="Multi")}function vm(r){let t=r.resolveLabel??$V;return{items:r.items,dragDisabled:r.dragDisabled,flipDurationMs:0,morphDisabled:!0,useCursorForDetection:!0,centreDraggedOnCursor:!1,transformDraggedElement:(e,n)=>wI(e,n?t(n):"",n?.type==="Multi"),dropTargetStyle:{},dropTargetClasses:r.dropTargetClasses??[],dropAnimationDisabled:!0,autoAriaDisabled:!0,zoneItemTabIndex:-1,delayTouchStart:200,...r.type?{type:r.type}:{}}}function ym(){let r=pe(!1),t=!1;function e(){q(r,!0),t=!1;let n=()=>{window.removeEventListener("pointerup",n,!0),window.removeEventListener("pointercancel",n,!0),t||q(r,!1)};window.addEventListener("pointerup",n,!0),window.addEventListener("pointercancel",n,!0)}return{get armed(){return f(r)},markStarted(){t=!0},reset(){q(r,!1),t=!1},startDrag:e}}async function bm(r,t){if(await ys(),!r)return;r.querySelector(`button[aria-label="${CSS.escape(t)}"]`)?.focus()}var S5=F('<button type="button"><!></button>');function qr(r,t){ie(t,!0);let e=X(t,"size",3,16),n=k(()=>!!(t.onMoveUp||t.onMoveDown));function i(l){l.key==="ArrowUp"&&t.onMoveUp?(l.preventDefault(),l.stopPropagation(),t.onMoveUp()):l.key==="ArrowDown"&&t.onMoveDown&&(l.preventDefault(),l.stopPropagation(),t.onMoveDown())}var o=S5();let s;var a=R(o);Qe(a,{iconId:"grip-vertical",get size(){return e()}}),$(o),Q(()=>{s=Ge(o,1,"qa-icon-button qa-drag-handle",null,s,{"qa-drag-handle-ready":t.dragDisabled,"qa-drag-handle-active":!t.dragDisabled}),le(o,"aria-label",t.label),le(o,"aria-keyshortcuts",f(n)?"ArrowUp ArrowDown":void 0),le(o,"tabindex",t.dragDisabled?0:-1)}),ge("pointerdown",o,()=>t.onDragStart()),ge("keydown",o,i),A(r,o),oe()}He(["pointerdown","keydown"]);function NC(r){let t=e=>e.stopPropagation();return r.addEventListener("mousedown",t),r.addEventListener("touchstart",t,{passive:!0}),{destroy(){r.removeEventListener("mousedown",t),r.removeEventListener("touchstart",t)}}}var A5=F('<button type="button"><!></button>');function Et(r,t){let e=X(t,"size",3,16),n=X(t,"extraClass",3,""),i=X(t,"disabled",3,!1);var o=A5();let s;var a=R(o);Qe(a,{get iconId(){return t.iconId},get size(){return e()}}),$(o),Ft(o,l=>NC?.(l)),Q(()=>{s=Ge(o,1,`qa-icon-button ${n()}`,null,s,{"is-pressed":t.ariaPressed===!0}),le(o,"aria-label",t.label),le(o,"aria-pressed",t.ariaPressed),le(o,"aria-haspopup",t.ariaHasPopup),le(o,"title",t.title),o.disabled=i()}),ge("click",o,function(...l){t.onclick?.apply(this,l)}),A(r,o)}He(["click"]);var I5=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!></div></li>'),P5=F('<ol class="qa-folder-list svelte-19gohrx"></ol>'),$5={hash:"svelte-19gohrx",code:".qa-folder-list.svelte-19gohrx {display:grid;grid-template-columns:auto;width:auto;margin:12px 0;padding:0;list-style:none;}"};function CI(r,t){let e=$i();ie(t,!0),Ae(r,$5);let n=`folder:${e}`,i=FV.Platform.isMobile,o=ym(),s=k(()=>!i&&!o.armed),a=pe(void 0);function l(C){return C.map(w=>({id:w}))}let c=pe(null),d=k(()=>f(c)??l(t.folders)),u=null,p=C=>C.id;function m(C){o.markStarted(),gm(C,p);let w=C.detail.items;u=fm(w,C.detail.info.id)??u,q(c,bi(w),!0)}function h(C){let w=bi(C.detail.items),T=C.detail.info.id;u?.item.id===T&&!w.some(P=>P.id===T)&&(w=[...w],w.splice(Math.min(u.index,w.length),0,u.item)),t.onChange(w.map(P=>P.id)),q(c,null),u=null,C.detail.info.source===pn.POINTER&&o.reset()}function g(C,w){let T=document.activeElement?.getAttribute("aria-label"),P=hm(l(t.folders),C,w);if(!P)return;t.onChange(P.map(I=>I.id));let _=P.findIndex(I=>I.id===C);Xd(`Moved ${C} to position ${_+1} of ${P.length}`),T&&bm(f(a),T)}function v(C){t.onChange(t.folders.filter(w=>w!==C))}let b=()=>{o.startDrag()};var y=P5();gt(y,21,()=>bi(f(d)),C=>C.id,(C,w)=>{var T=I5(),P=R(T),_=re(P,!0),I=E(P,2),O=R(I);{let K=k(()=>`Remove folder ${f(w).id}`);Et(O,{iconId:"trash-2",get label(){return f(K)},onclick:()=>v(f(w).id)})}var N=E(O,2);{let K=k(()=>`Reorder ${f(w).id}`);qr(N,{get label(){return f(K)},get dragDisabled(){return f(s)},onDragStart:b,onMoveUp:()=>g(f(w).id,-1),onMoveDown:()=>g(f(w).id,1)})}$(I),$(T),Q(()=>ee(_,f(w).id)),A(C,T)}),$(y),Cn(y,C=>q(a,C),()=>f(a)),Ft(y,(C,w)=>mm?.(C,w),()=>vm({items:f(d),dragDisabled:f(s),type:n,resolveLabel:p})),Yn("consider",y,m),Yn("finalize",y,h),A(r,y),oe()}function VC(r){return r.enabled?r.chooseWhenCreatingNote?"prompt":r.createInSameFolderAsActiveFile?"active-file":"specified":"obsidian-default"}function MV(r,t){switch(t){case"obsidian-default":return{...r,enabled:!1,chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1};case"specified":return{...r,enabled:!0,chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1};case"active-file":return{...r,enabled:!0,createInSameFolderAsActiveFile:!0,chooseWhenCreatingNote:!1};case"prompt":return{...r,enabled:!0,chooseWhenCreatingNote:!0,createInSameFolderAsActiveFile:!1}}}var RV=[{value:"obsidian-default",label:"Obsidian default"},{value:"specified",label:"In a specific folder"},{value:"active-file",label:"Same folder as current file"},{value:"prompt",label:"Ask for folder each time"}],DV={"obsidian-default":"Use Obsidian's \u201CDefault location for new notes\u201D setting.",specified:"Create the note in the folder(s) below. With multiple folders, you'll be asked which one when the note is created.","active-file":"Create the note next to the currently active file (falls back to the vault root if no file is open).",prompt:"Choose any folder in the vault when the note is created."};Ve();Jd();Wl();function BC(r){if(!r?.enabled||r.chooseWhenCreatingNote||r.chooseFromSubfolders||r.createInSameFolderAsActiveFile)return;let t=r.folders??[];if(t.length!==1)return;let e=t[0]?.trim();if(e&&!e.includes("{{")&&!(bo(e).length>0))return e}var F5=F(`<div class="qa-folder-mode-warning">Add at least one folder. With none, the note falls back to the active
- file's folder (or you'll be prompted to pick one if no file is open).</div>`),M5=F('<div class="folderSelectionContainer"><div class="folderList"><!></div> <div class="folderInputContainer"><input type="text" class="qa-folder-path-input" placeholder="Folder path" aria-label="Folder path"/> <button type="button" class="mod-cta">Add</button></div></div> <!>',1),R5=F("<!> <!> <!>",1),TI=F("<!> <!>",1),D5=F("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1),O5=F("<!> <!> <!> <!>",1);function _I(r,t){ie(t,!0);let e=M=>{var B=M5(),J=ae(B),te=R(J),W=R(te);CI(W,{get folders(){return n().folder.folders},onChange:Ye=>n(n().folder.folders=Ye,!0)}),$(te);var Z=E(te,2),se=R(Z);Ct(se),wr(()=>Jn(se,()=>f(v),Ye=>q(v,Ye))),Ft(se,(Ye,he)=>_d?.(Ye,he),()=>y);var ce=E(se,2);$(Z),$(J);var $e=E(J,2);{var Xe=Ye=>{var he=F5();A(Ye,he)};z($e,Ye=>{f(h)&&Ye(Xe)})}Yn("keypress",se,w),ge("click",ce,C),A(M,B)},n=X(t,"choice",15),i=X(t,"commitPending",15),o=k(()=>t.plugin.getTemplateFiles().map(M=>M.path)),s=k(()=>Ga(La(t.app)));function a(M){let B=M.trim();return B?_a(B)?{valid:!0,message:"Contains format syntax \u2014 resolved at run time."}:Rn(t.app,B)!==null||"Template not found":!0}let l=k(()=>n().fileNameFormat.enabled?n().fileNameFormat.format:""),c=[M=>new sn(t.app,M,t.plugin,"fileName")],d=k(()=>xI(n(),n().fileNameFormat.enabled?n().fileNameFormat.format:Cr)),u=k(()=>f(d)?"Show matching notes and unresolved links in the note-title prompt.":"Only available when the file name prompt is the default note title: no custom format, {{VALUE}}, or {{NAME}}."),p=k(()=>VC(n().folder)),m=k(()=>DV[f(p)]),h=k(()=>f(p)==="specified"&&n().folder.folders.length===0);function g(M){n(n().folder=MV(n().folder,M),!0)}let v=pe(""),b;function y(M){return b=new wC(t.app,M,f(s),n().folder.folders),b}Ot(()=>{b?.updateCurrentItems(n().folder.folders)});function C(){let M=f(v).trim();if(M){if(n().folder.folders.some(B=>B===M)){S.logWarning("cannot add same folder twice.");return}n().folder.folders.push(M),q(v,"")}}function w(M){M.key==="Enter"&&C()}function T(){f(p)==="specified"&&C()}i(T),$D(T);let P=k(()=>H1(n().fileExistsBehavior)),_=k(()=>f(P)!=="prompt"&&f(P)!=="keep"),I=k(()=>U1(f(P)==="update"?"update":"create")),O=k(()=>n().fileExistsBehavior.kind==="apply"?n().fileExistsBehavior.mode:f(I)[0].id);function N(M){n(n().fileExistsBehavior=W1(M,n().fileExistsBehavior),!0)}function K(M){n(n().fileExistsBehavior={kind:"apply",mode:M},!0)}var ne=O5(),H=ae(ne);fo(H,{heading:"Template",children:(M,B)=>{var J=TI(),te=ae(J);ri(te,{name:"Template path",desc:"Path to the template this choice creates notes from.",children:(se,ce=$t)=>{Dr(se,{get id(){return ce()},get value(){return n().templatePath},placeholder:"Template path",get app(){return t.app},get suggestions(){return f(o)},maxSuggestions:50,validator:a,onChange:$e=>n(n().templatePath=$e.trim(),!0)})},$$slots:{default:!0}});var W=E(te,2);ri(W,{name:"File name",desc:"Leave empty to ask for the note title.",children:(se,ce=$t)=>{var $e=R5(),Xe=ae($e),Ye=()=>f(l),he=ve=>n(n().fileNameFormat={enabled:ve.trim()!=="",format:ve},!0);Dr(Xe,{get id(){return ce()},get value(){return Ye()},set value(ve){he(ve)},placeholder:"{{VALUE}}",get makeSuggesters(){return c}});var Re=E(Xe,2);Wd(Re,{get value(){return f(l)}});var Je=E(Re,2);{let ve=k(()=>BC(n().folder));Bi(Je,{get value(){return f(l)},formatterKind:"fileName",get targetFolderPath(){return f(ve)},get app(){return t.app},get plugin(){return t.plugin}})}A(se,$e)},$$slots:{default:!0}}),A(M,J)},$$slots:{default:!0}});var D=E(H,2);fo(D,{heading:"Location",children:(M,B)=>{var J=TI(),te=ae(J);{let se=$e=>{it($e,{get value(){return f(p)},get options(){return RV},ariaLabel:"New note location",onchange:g})},ce=k(()=>f(p)==="specified"?e:void 0);be(te,{name:"New note location",get desc(){return f(m)},get body(){return f(ce)},control:se,$$slots:{control:!0}})}var W=E(te,2);{var Z=se=>{be(se,{name:"Include subfolders",desc:"Get prompted to choose from both the selected folders and their subfolders when creating the note.",control:$e=>{vt($e,{get checked(){return n().folder.chooseFromSubfolders},set checked(Xe){n(n().folder.chooseFromSubfolders=Xe,!0)}})},$$slots:{control:!0}})};z(W,se=>{f(p)==="specified"&&se(Z)})}A(M,J)},$$slots:{default:!0}});var G=E(D,2);fo(G,{heading:"Linking",children:(M,B)=>{var J=TI(),te=ae(J);Xg(te,{fileLabel:"created",get app(){return t.app},get appendLink(){return n().appendLink},set appendLink(Z){n(n().appendLink=Z,!0)}});var W=E(te,2);be(W,{name:"Copy link to clipboard",desc:"Copy a link to the created file after the Template choice runs.",control:se=>{{let ce=k(()=>n().copyLinkToClipboard??!1);vt(se,{get checked(){return f(ce)},onchange:$e=>n(n().copyLinkToClipboard=$e,!0)})}},$$slots:{control:!0}}),A(M,J)},$$slots:{default:!0}});var V=E(G,2);fo(V,{heading:"Behavior",children:(M,B)=>{var J=D5(),te=ae(J);be(te,{name:"Search existing notes before creating",get desc(){return f(u)},control:ze=>{{let ct=k(()=>f(d)?n().discoverExistingNotesBeforeCreate??!1:!1),Ke=k(()=>!f(d));vt(ze,{get checked(){return f(ct)},get disabled(){return f(Ke)},onchange:ot=>n(n().discoverExistingNotesBeforeCreate=ot,!0)})}},$$slots:{control:!0}});var W=E(te,2);{var Z=Ie=>{be(Ie,{name:"When selecting an existing note",control:ct=>{{let Ke=k(()=>n().existingNoteAction??"open"),ot=k(()=>yC.map(or=>({value:or.id,label:or.label})));it(ct,{get value(){return f(Ke)},get options(){return f(ot)},onchange:or=>{let Ar=yC.find(zn=>zn.id===or);Ar&&n(n().existingNoteAction=Ar.id,!0)}})}},$$slots:{control:!0}})};z(W,Ie=>{f(d)&&n().discoverExistingNotesBeforeCreate&&Ie(Z)})}var se=E(W,2);{let Ie=ct=>{{let Ke=k(()=>V1.map(ot=>({value:ot.id,label:ot.label})));it(ct,{get value(){return f(P)},get options(){return f(Ke)},onchange:N})}},ze=k(()=>f(d)&&n().discoverExistingNotesBeforeCreate?"If a new note's path already exists":"If the target file already exists");be(se,{get name(){return f(ze)},desc:"Choose whether QuickAdd should ask what to do, update the existing file, create another file, or keep the existing file.",control:Ie,$$slots:{control:!0}})}var ce=E(se,2);{var $e=Ie=>{{let ze=ot=>{{let or=k(()=>f(I).map(Ar=>({value:Ar.id,label:Ar.label})));it(ot,{get value(){return f(O)},get options(){return f(or)},onchange:K})}},ct=k(()=>f(P)==="update"?"Update action":"New file naming"),Ke=k(()=>nm(f(O)).description);be(Ie,{get name(){return f(ct)},get desc(){return f(Ke)},control:ze,$$slots:{control:!0}})}};z(ce,Ie=>{f(_)&&Ie($e)})}var Xe=E(ce,2);Jg(Xe,{description:"Open the created file.",get openFile(){return n().openFile},set openFile(Ie){n(n().openFile=Ie,!0)}});var Ye=E(Xe,2);{var he=Ie=>{Zg(Ie,{contextLabel:"created",get fileOpening(){return n().fileOpening},set fileOpening(ze){n(n().fileOpening=ze,!0)}})};z(Ye,Ie=>{n().openFile&&Ie(he)})}var Re=E(Ye,2);sv(Re,{get dateOrigin(){return n().dateOrigin},set dateOrigin(Ie){n(n().dateOrigin=Ie,!0)}});var Je=E(Re,2);ev(Je,{get onePageInput(){return n().onePageInput},set onePageInput(Ie){n(n().onePageInput=Ie,!0)}});var ve=E(Je,2);cv(ve,{get name(){return n().name},get dateOrigin(){return n().dateOrigin},get command(){return n().command},set command(Ie){n(n().command=Ie,!0)},get pickDayCommand(){return n().pickDayCommand},set pickDayCommand(Ie){n(n().pickDayCommand=Ie,!0)}});var Ne=E(ve,2);mv(Ne,{get type(){return n().type},get app(){return t.app},get icon(){return n().icon},set icon(Ie){n(n().icon=Ie,!0)}}),A(M,J)},$$slots:{default:!0}}),A(r,ne),oe()}He(["click"]);var wm=class extends tm{constructor(t,e,n,i){super(t,e,n,i,_I,"this template choice's settings"),this.containerEl.addClass("templateChoiceBuilder"),this.normalizeChoice()}normalizeChoice(){var t,e,n,i,o,s,a,l,c,d,u;(t=this.choice).fileExistsBehavior??(t.fileExistsBehavior={kind:"prompt"}),this.choice.fileOpening=en(this.choice.fileOpening),(e=this.choice).templatePath??(e.templatePath=""),(n=this.choice).fileNameFormat??(n.fileNameFormat={enabled:!1,format:""}),(i=this.choice.fileNameFormat).enabled??(i.enabled=!1),(o=this.choice.fileNameFormat).format??(o.format=""),(s=this.choice).folder??(s.folder={enabled:!1,folders:[],chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1,chooseFromSubfolders:!1}),(a=this.choice.folder).enabled??(a.enabled=!1),(l=this.choice.folder).folders??(l.folders=[]),(c=this.choice.folder).chooseWhenCreatingNote??(c.chooseWhenCreatingNote=!1),(d=this.choice.folder).createInSameFolderAsActiveFile??(d.createInSameFolderAsActiveFile=!1),(u=this.choice.folder).chooseFromSubfolders??(u.chooseFromSubfolders=!1)}};Ka();var ls=require("obsidian");var xi=require("obsidian");var oU=require("obsidian");rs();Zt();Hl();function wc(r){if(r.type==="Choice")try{return zr().getChoiceById(r.choiceId).name}catch{return"(missing choice)"}if(r.type==="Conditional"){let t=r.condition;return`If ${zl(t)}`}return r.name}var L5=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!></div></li>');function SI(r,t){ie(t,!0);var e=L5(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let l=k(()=>`Delete ${wc(t.command)}`);Et(s,{iconId:"trash-2",get label(){return f(l)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var a=E(s,2);{let l=k(()=>`Reorder ${wc(t.command)}`);qr(a,{get label(){return f(l)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(l=>ee(i,l),[()=>wc(t.command)]),A(r,e),oe()}Zt();var N5=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> <input type="number" min="0" placeholder=" " class="dotInput svelte-1mt90y0" aria-label="Wait duration in milliseconds"/>ms</span> <div class="quickAddCommandControls"><!> <!></div></li>'),V5={hash:"svelte-1mt90y0",code:".dotInput.svelte-1mt90y0 {border:none;display:inline;font-family:inherit;font-size:inherit;padding:0;width:var(--qa-wait-input-width, 2ch);text-decoration:underline dotted;background-color:transparent;}.dotInput.svelte-1mt90y0:hover {background-color:transparent;}"};function AI(r,t){ie(t,!0),Ae(r,V5);let e=pe(void 0),n=pe(Ze(pt(()=>t.command.time)));function i(){if(!f(e))return;let m=String(f(e).value).length;f(e).style.setProperty("--qa-wait-input-width",`${m===0?2:m}ch`)}function o(m){let h=m.currentTarget.valueAsNumber;q(n,Number.isNaN(h)||h<0?0:h,!0),i(),t.onUpdateCommand({...t.command,time:f(n)})}yh(i);var s=N5(),a=R(s),l=R(a),c=E(l);Ct(c),Cn(c,m=>q(e,m),()=>f(e)),Xt(),$(a);var d=E(a,2),u=R(d);{let m=k(()=>`Delete ${t.command.name}`);Et(u,{iconId:"trash-2",get label(){return f(m)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var p=E(u,2);{let m=k(()=>`Reorder ${t.command.name}`);qr(p,{get label(){return f(m)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(d),$(s),Q(()=>{ee(l,`${t.command.name??""} for `),Xn(c,f(n))}),ge("input",c,o),A(r,s),oe()}He(["input"]);var B5=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function II(r,t){ie(t,!0);var e=B5(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let c=k(()=>`Configure ${t.command.name}`);Et(s,{iconId:"settings",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onConfigureChoice(t.command)})}var a=E(s,2);{let c=k(()=>`Delete ${t.command.name}`);Et(a,{iconId:"trash-2",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var l=E(a,2);{let c=k(()=>`Reorder ${t.command.name}`);qr(l,{get label(){return f(c)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(()=>ee(i,t.command.name)),A(r,e),oe()}var U5=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function PI(r,t){ie(t,!0);var e=U5(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let c=k(()=>`Configure ${t.command.name}`);Et(s,{iconId:"settings",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onConfigureScript(t.command)})}var a=E(s,2);{let c=k(()=>`Delete ${t.command.name}`);Et(a,{iconId:"trash-2",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var l=E(a,2);{let c=k(()=>`Reorder ${t.command.name}`);qr(l,{get label(){return f(c)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(()=>ee(i,t.command.name)),A(r,e),oe()}var Tn=require("obsidian");rs();function NV(r,t){let e=r.createDiv({cls:"qa-format-preview-host"}),n=Ze({value:t.value,app:t.app,plugin:t.plugin,targetFolderPath:null}),i=vi(e,Bi,n,{what:"the preview for this field"}),o=!1;return{setValue(s){o||(n.value=s)},destroy(){o||(o=!0,i.destroy(),e.remove())}}}Nh();function VV(r){r.addEventListener("focus",()=>{r.type="text"}),r.addEventListener("blur",()=>{r.type="password"}),r.type="password"}ex();Xa();function l8(r){return typeof r=="string"?r:r==null?"":String(r)}function eB(r){if(typeof r=="string")return r;if(r==null)return"";if(typeof r=="number"||typeof r=="boolean")return String(r);try{return JSON.stringify(r)??String(r)}catch{return String(r)}}var tx=class extends Tn.Modal{constructor(e,n,i,o){super(e);this.command=n;this.settings=i;this.onCommandChange=o;this.previewHandles=[];this.command.settings||(this.command.settings={}),km(this.command.settings,this.settings),this.display(),this.migrateSecretSettings()}display(){this.containerEl.addClass("quickAddModal","userScriptSettingsModal"),this.destroyPreviews(),this.contentEl.empty();let e=eB(this.settings?.name??this.command.name),n=eB(this.settings?.author);this.titleEl.innerText=`${e}${n?` by ${n}`:""}`;let i=this.settings.options;if(i)for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let s=i[o];if(_m(s)){let d=this.addSecretInput(o,"placeholder"in s?s.placeholder:void 0);s.description&&d.setDesc(s.description);continue}let a=s.defaultValue;this.command.settings[o]!==void 0&&(a=this.command.settings[o]);let l,c=s.type;c==="text"||c==="input"?l=this.addInputBox(o,a,s?.placeholder,s.secret):c==="textarea"?l=this.addTextArea(o,a,s?.placeholder):c==="checkbox"||c==="toggle"?l=this.addToggle(o,a):c==="dropdown"||c==="select"?l=this.addDropdown(o,s.options,a):c==="format"&&(l=this.addFormatInput(o,a,s.placeholder)),s.description&&l&&l.setDesc(s.description)}}addInputBox(e,n,i,o){return new Tn.Setting(this.contentEl).setName(e).addText(s=>{s.setValue(n).onChange(a=>{this.command.settings[e]=a,this.onCommandChange?.()}).setPlaceholder(i??""),o&&VV(s.inputEl)})}addSecretInput(e,n){let i=new Tn.Setting(this.contentEl).setName(e),o="",s,a=()=>{let c=this.command.settings?.[e];return XC(this.command,e)!==void 0||typeof c=="string"&&c.length>0},l=()=>{s&&(s.placeholder=a()?"Secret saved":n??"Paste secret")};return i.addText(c=>{c.setValue("").onChange(d=>{o=d}),c.inputEl.type="password",c.inputEl.addClass("qa-user-script-secret-input"),c.inputEl.setAttribute("aria-label",e),s=c.inputEl,l()}),i.addButton(c=>{c.setIcon("save").setTooltip("Save secret").onClick(async()=>{if(o.length===0){new Tn.Notice("Paste a secret before saving.");return}let d=await OI(this.app,this.command,e,o,XC(this.command,e),this.settings.options?.[e]);if(!d){new Tn.Notice("SecretStorage is unavailable. Secret was not saved.");return}this.command.settings[e]=jC(d),o="",s&&(s.value=""),l(),this.onCommandChange?.(),new Tn.Notice("Secret saved.")}),c.buttonEl.setAttribute("aria-label",`Save ${e}`)}),i.addButton(c=>{c.setIcon("trash-2").setTooltip("Clear secret").onClick(async()=>{let d=XC(this.command,e);if(d&&!await LI(this.app,d)){new Tn.Notice("SecretStorage is unavailable. Secret was not cleared.");return}delete this.command.settings[e],o="",s&&(s.value=""),l(),this.onCommandChange?.(),new Tn.Notice("Secret cleared.")}),c.buttonEl.setAttribute("aria-label",`Clear ${e}`)}),i}addTextArea(e,n,i){return new Tn.Setting(this.contentEl).setName(e).addTextArea(o=>{o.setValue(n).onChange(s=>{this.command.settings[e]=s,this.onCommandChange?.()}).setPlaceholder(i??""),o.inputEl.addClass("qa-user-script-argument-textarea")})}addToggle(e,n){return new Tn.Setting(this.contentEl).setName(e).addToggle(i=>i.setValue(n).onChange(o=>{this.command.settings[e]=o,this.onCommandChange?.()}))}addDropdown(e,n,i){return new Tn.Setting(this.contentEl).setName(e).addDropdown(o=>{n.forEach(s=>{o.addOption(s,s)}),o.setValue(i),o.onChange(s=>{this.command.settings[e]=s,this.onCommandChange?.()})})}addFormatInput(e,n,i){let o=new Tn.Setting(this.contentEl).setName(e),s=l8(n),a=new Tn.TextAreaComponent(this.contentEl);new sn(this.app,a.inputEl,zr()),Lh(a.inputEl,{passThroughUntilUsed:!0}),a.inputEl.addClass("qa-user-script-format-textarea"),a.inputEl.setAttribute("aria-label",e);let l=NV(this.contentEl,{app:this.app,plugin:zr(),value:s});return this.previewHandles.push(l),a.setValue(s).onChange(c=>{this.command.settings[e]=c,l.setValue(c),this.onCommandChange?.()}).setPlaceholder(i??""),o}destroyPreviews(){for(let e of this.previewHandles)e.destroy();this.previewHandles=[]}onClose(){this.destroyPreviews(),super.onClose()}async migrateSecretSettings(){await QC(this.app,this.command,this.settings)&&(this.onCommandChange?.(),this.display())}};ye();eu();var T8=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function UI(r,t){ie(t,!0);var e=T8(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let c=k(()=>`Configure ${t.command.name}`);Et(s,{iconId:"settings",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onConfigureAssistant(t.command)})}var a=E(s,2);{let c=k(()=>`Delete ${t.command.name}`);Et(a,{iconId:"trash-2",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var l=E(a,2);{let c=k(()=>`Reorder ${t.command.name}`);qr(l,{get label(){return f(c)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(()=>ee(i,t.command.name)),A(r,e),oe()}var ii=require("obsidian");var _8="QuickAdd sends the system prompt to the model as written - format syntax like {{DATE}} is not resolved here. Only the prompt template is formatted.",k8=0;function sx(r,t,e){let n=r.createDiv({text:_8,cls:"qa-literal-format-note"}),i=`qa-literal-format-note-${++k8}`;n.id=i;let o=s=>{let a=s.includes("{{");n.classList.toggle("qa-literal-format-note--shown",a),a?t.setAttribute("aria-describedby",i):t.removeAttribute("aria-describedby")};return o(e),o}gi();je();zs();Nv();var rU=require("obsidian");Dm();var B9=[{key:"temperature",name:"Temperature",desc:"Sampling temperature (0-1, the range every provider accepts). Higher values like 0.8 make the output more random; lower values like 0.2 make it more focused and deterministic.",min:0,max:1,step:.1,fallback:1},{key:"top_p",name:"Top P",desc:"Nucleus sampling - an alternative to temperature. The model considers only the tokens comprising the top P probability mass, so 0.1 means the top 10%.",min:0,max:1,step:.1,fallback:1},{key:"frequency_penalty",name:"Frequency penalty",desc:"Positive values penalize tokens by how often they already appear, reducing verbatim repetition; negative values encourage it. Only sent to providers that support it.",min:-2,max:2,step:.1,fallback:0},{key:"presence_penalty",name:"Presence penalty",desc:"Positive values penalize tokens that have appeared at all, encouraging new topics; negative values do the opposite. Only sent to providers that support it.",min:-2,max:2,step:.1,fallback:0}];function nU(r,t,e,n){let i=tu(e,{silent:!0})?.model;i?.supportsTemperature===!1&&r.createDiv({text:`${i.name} uses fixed sampling, so these settings are not sent to it.`,cls:"setting-item-description"});for(let o of B9){let s=typeof t[o.key]=="number";new rU.Setting(r).setName(o.name).setDesc(s?o.desc:`${o.desc} Currently using the provider's default.`).addSlider(a=>{a.setLimits(o.min,o.max,o.step),a.setValue(t[o.key]??o.fallback),a.onChange(l=>{t[o.key]=l})}).addExtraButton(a=>{a.setIcon("rotate-ccw"),a.setTooltip("Reset to provider default"),a.setDisabled(!s),a.onClick(()=>{delete t[o.key],n()})})}}Dm();fi();je();var Om="Ask me",$x="__qa-missing-model__";function Fx(r,t,e){let n=U.getState().ai.providers,i=r.selectEl;t={model:t.model,modelRef:$l(t.model,t.modelRef)},r.addOption(Om,Om);let o=new Map,s=0;for(let l of n){if(l.models.length===0)continue;let c=i.createEl("optgroup");c.label=l.name;for(let d of np(l.models)){let u=`${l.id??l.name}/${d.name}:${s++}`;o.set(u,{providerId:l.id,modelName:d.name}),c.createEl("option",{value:u,text:d.deprecated?`${d.name} (retired)`:d.name})}}let a=U9(t,o);if(a)r.setValue(a);else{let l=t.modelRef?`${t.modelRef.providerId}/${t.modelRef.name}`:t.model;r.addOption($x,`(missing) ${l}`);let c=Array.from(i.options).find(d=>d.value===$x);c&&(c.disabled=!0),r.setValue($x)}r.onChange(l=>{if(l===$x)return;if(l===Om){e({model:Om,modelRef:void 0});return}let c=o.get(l);c&&e({model:c.modelName,modelRef:c.providerId?{providerId:c.providerId,name:c.modelName}:void 0})})}function U9(r,t){if(!r.model||r.model===Om)return Om;let e=r.modelRef?void 0:tu(r.model,{silent:!0}),n=r.modelRef??(e&&{providerId:e.provider.id,name:e.model.name});if(n){for(let[i,o]of t)if(o.providerId===n.providerId&&o.modelName===n.name)return i}}fi();var Mx=class extends ii.Modal{constructor(e,n){super(e);this.isResolved=!1;this.showAdvancedSettings=!1;this.settings=n,this.originalSettings=this.cloneSettings(n),this.waitForClose=new Promise((i,o)=>{this.rejectPromise=o,this.resolvePromise=i}),this.open(),this.display()}get systemPromptTokenLength(){return Ci(this.settings.systemPrompt)}resolve(e){this.isResolved||(this.isResolved=!0,this.resolvePromise(e))}cloneSettings(e){return{...e,promptTemplate:{...e.promptTemplate},modelParameters:{...e.modelParameters}}}restoreOriginal(){let e=this.cloneSettings(this.originalSettings);Object.assign(this.settings,e),this.settings.promptTemplate=e.promptTemplate,this.settings.modelParameters=e.modelParameters}display(){let e=this.contentEl.createEl("h2");e.addClass("qa-clickable-modal-title"),e.createEl("button",{cls:"qa-rename-title-button",text:`${this.settings.name} settings`,attr:{type:"button","aria-label":`Rename ${this.settings.name}`}}).addEventListener("click",()=>{(async()=>{try{let i=await ir.Prompt(this.app,"New name",this.settings.name,this.settings.name);i&&i!==this.settings.name&&(this.settings.name=i,this.reload())}catch{}})()}),this.addPromptTemplateSetting(this.contentEl),this.addModelSetting(this.contentEl),this.addOutputVariableNameSetting(this.contentEl),this.addShowAdvancedSettingsToggle(this.contentEl),this.showAdvancedSettings&&(this.settings.modelParameters||(this.settings.modelParameters={}),nU(this.contentEl,this.settings.modelParameters,$l(this.settings.model,this.settings.modelRef)??this.settings.model,()=>this.reload())),this.addSystemPromptSetting(this.contentEl),this.addButtonBar(this.contentEl)}addButtonBar(e){let n=e.createDiv({cls:"qa-command-button-row"});new ii.ButtonComponent(n).setButtonText("Cancel").onClick(()=>{this.restoreOriginal(),this.resolve(null),this.close()}),new ii.ButtonComponent(n).setButtonText("Save").setCta().onClick(()=>{this.resolve(this.settings),this.close()})}reload(){this.contentEl.empty(),this.display()}addPromptTemplateSetting(e){let n=U.getState().ai.promptTemplatesFolderPath,i=Xo(this.app,n).map(o=>o.name);new ii.Setting(e).setName("Prompt template").setDesc("Enabling this will have the assistant use the prompt template you specify. If disable, the assistant will ask you for a prompt template to use.").addToggle(o=>{o.setValue(this.settings.promptTemplate.enable),o.onChange(s=>{this.settings.promptTemplate.enable=s})}).addText(o=>{o.setValue(this.settings.promptTemplate.name).onChange(s=>{this.settings.promptTemplate.name=s}),new hi(this.app,o.inputEl,i)})}addModelSetting(e){new ii.Setting(e).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(n=>{Fx(n,this.settings,i=>{this.settings.model=i.model,this.settings.modelRef=i.modelRef,this.reload()})})}addOutputVariableNameSetting(e){new ii.Setting(e).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(n=>{n.setValue(this.settings.outputVariableName).onChange(i=>{this.settings.outputVariableName=i})})}addSystemPromptSetting(e){new ii.Setting(e).setName("System prompt").setDesc("The system prompt for the AI Assistant");let n=this.contentEl.createDiv(),i=n.createSpan({cls:"qa-ai-token-count"}),o=n.createDiv({text:"Estimated locally. Providers enforce exact context limits.",cls:"qa-ai-token-note"});n.appendChild(i),n.appendChild(o);let s=new ii.TextAreaComponent(e);s.inputEl.addClass("qa-ai-prompt-textarea"),s.inputEl.setAttribute("aria-label","System prompt");let a=sx(e,s.inputEl,this.settings.systemPrompt??""),l=(0,ii.debounce)(()=>{i.innerText=`Estimated tokens: ${this.systemPromptTokenLength}`},50);s.setValue(this.settings.systemPrompt).onChange(c=>{this.settings.systemPrompt=c,a(c),l()}),l()}addShowAdvancedSettingsToggle(e){new ii.Setting(e).setName("Show advanced settings").setDesc("Sampling settings such as temperature and top p. Untouched settings use the provider's defaults.").addToggle(n=>{n.setValue(this.showAdvancedSettings),n.onChange(i=>{this.showAdvancedSettings=i,this.reload()})})}onClose(){this.isResolved||(this.restoreOriginal(),this.resolve(null)),super.onClose()}};var q9=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function yP(r,t){ie(t,!0);var e=q9(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let c=k(()=>`Configure ${t.command.name}`);Et(s,{iconId:"settings",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onConfigureOpenFile(t.command)})}var a=E(s,2);{let c=k(()=>`Delete ${t.command.name}`);Et(a,{iconId:"trash-2",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var l=E(a,2);{let c=k(()=>`Reorder ${t.command.name}`);qr(l,{get label(){return f(c)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(()=>ee(i,t.command.name)),A(r,e),oe()}var Hs=require("obsidian");Rx();Zt();var Dx=class extends Hs.Modal{constructor(e,n){super(e);this.isResolved=!1;this.originalCommand=n,this.command={...n,type:"OpenFile"},this.command.focus=this.command.focus??!0,this.command.location=this.command.location??this.deriveLocation(),this.syncLegacyFlagsFromLocation(this.command.location),this.waitForClose=new Promise(i=>{this.resolvePromise=i}),this.display(),this.open()}onClose(){super.onClose(),this.isResolved||(this.resolvePromise(null),this.isResolved=!0)}resolveWithGuard(e){this.isResolved||(this.resolvePromise(e),this.isResolved=!0)}display(){this.containerEl.addClass("quickAddModal","openFileCommandSettingsModal"),this.contentEl.empty();let e=this.contentEl.createEl("h2");e.textContent="Open file command settings",e.addClass("qa-modal-title"),this.addFilePathSetting(),this.addOpenLocationSetting(),this.addFocusSetting(),this.addButtonBar()}addFilePathSetting(){new Hs.Setting(this.contentEl).setName("File path").setDesc("Path to the file. Supports formatting like {{DATE}}, {{VALUE}}, etc.").addText(e=>e.setPlaceholder("{{DATE}}todo.md").setValue(this.command.filePath).onChange(n=>{this.command.filePath=n,this.command.name=`Open file: ${n}`}))}addOpenLocationSetting(){let e=[{value:"reuse",label:"Reuse active tab"},{value:"tab",label:"New tab"},{value:"split",label:"Split"},{value:"window",label:"New window"},{value:"left-sidebar",label:"Left sidebar"},{value:"right-sidebar",label:"Right sidebar"}];new Hs.Setting(this.contentEl).setName("Where to open").setDesc("Choose tab, split, window, or sidebar").addDropdown(n=>{for(let{value:i,label:o}of e)n.addOption(i,o);n.setValue(this.deriveLocation()).onChange(i=>{this.command.location=i,this.syncLegacyFlagsFromLocation(i),this.reload()})}),this.deriveLocation()==="split"&&this.addDirectionSetting()}syncLegacyFlagsFromLocation(e){switch(e){case"split":this.command.openInNewTab=!0,this.command.direction||(this.command.direction="vertical");break;case"tab":case"reuse":this.command.openInNewTab=!1,this.command.direction=void 0;break;default:this.command.openInNewTab=!0,this.command.direction=void 0;break}}addDirectionSetting(){new Hs.Setting(this.contentEl).setName("Split direction").setDesc("How to arrange the new pane relative to the current one").addDropdown(e=>{e.addOption("vertical","Split right").addOption("horizontal","Split down").setValue(this.command.direction??"vertical").onChange(n=>{this.command.direction=n})})}addFocusSetting(){new Hs.Setting(this.contentEl).setName("Focus opened file").setDesc("Bring the opened file to the foreground").addToggle(e=>e.setValue(this.command.focus??!0).onChange(n=>{this.command.focus=n}))}deriveLocation(){return this.command.location?this.command.location:this.command.openInNewTab?"split":"reuse"}addButtonBar(){let e=this.contentEl.createDiv({cls:"qa-command-button-row qa-command-button-row-compact"});new Hs.ButtonComponent(e).setButtonText("Cancel").onClick(()=>{this.resolveWithGuard(null),this.close()}),new Hs.ButtonComponent(e).setButtonText("Save").setCta().onClick(()=>{this.resolveWithGuard(this.command),this.close()})}reload(){this.display()}};Hl();Hr();var z9=F('<li class="quickAddCommandListItem conditionalCommand svelte-3d0n7s"><div class="quickAddCommandLabel"><div class="conditionalSummary svelte-3d0n7s"> </div> <div class="conditionalBranches svelte-3d0n7s"><span> </span> <span> </span></div></div> <div class="quickAddCommandControls"><!> <!> <!> <!> <!></div></li>'),H9={hash:"svelte-3d0n7s",code:".conditionalCommand.svelte-3d0n7s {flex-wrap:wrap;}.conditionalSummary.svelte-3d0n7s {font-weight:600;margin-bottom:4px;}.conditionalBranches.svelte-3d0n7s {display:flex;gap:12px;font-size:0.9em;opacity:0.8;}"};function bP(r,t){ie(t,!0),Ae(r,H9);let e=k(()=>zl(t.command.condition)),n=k(()=>Mt(t.command.thenCommands).length),i=k(()=>Mt(t.command.elseCommands).length);var o=z9(),s=R(o),a=R(s),l=re(a,!0),c=E(a,2),d=R(c),u=re(d),p=E(d,2),m=re(p);$(c),$(s);var h=E(s,2),g=R(h);{let w=k(()=>`Edit condition for ${f(e)}`);Et(g,{iconId:"settings",get label(){return f(w)},extraClass:"clickable",onclick:()=>t.onConfigureCondition(t.command)})}var v=E(g,2);{let w=k(()=>`Edit then branch for ${f(e)}`);Et(v,{iconId:"corner-down-right",get label(){return f(w)},extraClass:"clickable",onclick:()=>t.onEditThenBranch(t.command)})}var b=E(v,2);{let w=k(()=>`Edit else branch for ${f(e)}`);Et(b,{iconId:"corner-down-left",get label(){return f(w)},extraClass:"clickable",onclick:()=>t.onEditElseBranch(t.command)})}var y=E(b,2);{let w=k(()=>`Delete ${t.command.name}`);Et(y,{iconId:"trash-2",get label(){return f(w)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var C=E(y,2);{let w=k(()=>`Reorder ${t.command.name}`);qr(C,{get label(){return f(w)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(h),$(o),Q(()=>{ee(l,f(e)),ee(u,`Then: ${f(n)??""}`),ee(m,`Else: ${f(i)??""}`)}),A(r,o),oe()}var W9=F("<ol></ol>"),G9={hash:"svelte-15ra1ch",code:`.quickAddCommandList.svelte-15ra1ch {display:grid;grid-template-columns:auto;width:auto;border:0 solid black;overflow-y:auto;height:auto;margin-bottom:8px;padding:20px;}
- /* A macro without steps shows no blank list area. The zone type is unique
- to this list, so an empty list is never a drop target. */.quickAddCommandList.is-empty.svelte-15ra1ch {display:none;}`};function wP(r,t){let e=$i();ie(t,!0),Ae(r,G9);let n=X(t,"commands",31,()=>Ze([])),i=k(()=>{let M=new Set;return Array.isArray(n())?n().filter(B=>{if(typeof B!="object"||B===null)return!1;let J=B.id;return typeof J!="string"||J===""||M.has(J)?!1:(M.add(J),!0)}):[]}),o=`command:${e}`,s=oU.Platform.isMobile,a=ym(),l=k(()=>!s&&!a.armed),c=pe(void 0),d=M=>M,u=M=>M,p=M=>M,m=M=>M,h=M=>M,g=M=>M;function v(){t.saveCommands(Ui(n()))}let b=null,y=pe(!1);function C(M){a.markStarted(),q(y,M.detail.info.trigger!==hr.DRAG_STOPPED),gm(M,wc);let B=M.detail.items;b=fm(B,M.detail.info.id)??b,n(bi(B))}function w(M){let B=bi(M.detail.items),J=M.detail.info.id;b?.item.id===J&&!B.some(te=>te.id===J)&&(B=[...B],B.splice(Math.min(b.index,B.length),0,b.item)),b=null,q(y,!1),n(B),M.detail.info.source===pn.POINTER&&a.reset(),v()}let T=()=>{a.startDrag()};function P(M,B){let J=document.activeElement?.getAttribute("aria-label"),te=bi(f(i)),W=hm(te,M,B);if(!W)return;let Z=W.findIndex(ce=>ce.id===M),se=W[Z];n(W),v(),Xd(`Moved ${wc(se)} to position ${Z+1} of ${W.length}`),J&&bm(f(c),J)}function _(M){n(PV(f(i),{...M})),v()}async function I(M){await t.onConfigureCondition?.(M)&&_(M)}function O(M){t.onEditThenBranch?.(M,()=>_(M))}function N(M){t.onEditElseBranch?.(M,()=>_(M))}function K(M){let B=te=>{let W={...M,choice:te,name:te.name};_(W)},J=M.choice;J.type==="Template"?new wm(t.app,J,t.plugin,B).open():J.type==="Capture"&&new rm(t.app,J,t.plugin,B).open()}async function ne(M){let B;try{B=await Zd(M,t.app)}catch(te){if(ix(te))return;throw te}if(!B?.script){S.logWarning(`${M.name} could not be loaded.`);return}let J=B.settings??{};new tx(t.app,M,J,()=>v()).open()}async function H(M){await new Mx(t.app,M).waitForClose&&_(M)}async function D(M){let B=await new Dx(t.app,M).waitForClose;B&&_(B)}var G=W9();let V;gt(G,21,()=>bi(f(i)),M=>M.id,(M,B)=>{var J=bt(),te=ae(J);{var W=he=>{{let Re=k(()=>d(f(B)));AI(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onUpdateCommand:_,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},Z=he=>{{let Re=k(()=>u(f(B)));II(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureChoice:K,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},se=he=>{{let Re=k(()=>p(f(B)));PI(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureScript:ne,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},ce=he=>{{let Re=k(()=>m(f(B)));UI(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureAssistant:H,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},$e=he=>{{let Re=k(()=>h(f(B)));yP(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureOpenFile:D,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},Xe=he=>{{let Re=k(()=>g(f(B)));bP(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureCondition:I,onEditThenBranch:O,onEditElseBranch:N,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},Ye=he=>{SI(he,{get command(){return f(B)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})};z(te,he=>{f(B).type==="Wait"?he(W):f(B).type==="NestedChoice"?he(Z,1):f(B).type==="UserScript"?he(se,2):f(B).type==="AIAssistant"?he(ce,3):f(B).type==="OpenFile"?he($e,4):f(B).type==="Conditional"?he(Xe,5):he(Ye,-1)})}A(M,J)}),$(G),Cn(G,M=>q(c,M),()=>f(c)),Ft(G,(M,B)=>mm?.(M,B),()=>vm({items:f(i),dragDisabled:f(l),type:o,resolveLabel:wc})),Q(()=>V=Ge(G,1,"quickAddCommandList svelte-15ra1ch",null,V,{"is-empty":f(i).length===0&&!f(y)})),Yn("consider",G,C),Yn("finalize",G,w),A(r,G),oe()}Wi();CP();xP();EP();TP();_P();kP();SP();AP();IP();PP();var $P=new Map(Object.entries({Copy:Lm,Cut:Nm,Paste:Vm,"Paste with format":Bm,"Select active line":Um,"Select link on active line":qm,"Move cursor to file start":zm,"Move cursor to file end":Hm,"Move cursor to line start":Wm,"Move cursor to line end":Gm}));function aU(r){return Ze(r)}rl();Zt();jo();var Bv=class extends fn{constructor(e,n){super(e,"Obsidian");this.generateId=()=>this.id=Vt();this.commandId=n}};rl();Zt();var Ox=class extends fn{constructor(t,e){super(t,"Choice"),this.choiceId=e}};rl();Zt();var Lx=class extends fn{constructor(t){super("Wait","Wait"),this.time=t}};Zt();rl();var Nx=class extends fn{constructor(t){super(t.name,"NestedChoice"),this.choice=t}};jo();var Ws=class{constructor(t,e){this.id=Vt(),this.name=t,this.type=e,this.command=!1,this.onePageInput=void 0}};Ve();function Vx(r){if(!r||typeof r!="object"||!("property"in r)||!r.property||typeof r.property!="object"||!("kind"in r.property)||!("action"in r)||r.action!=="set"&&r.action!=="addToList"||!("createIfMissing"in r)||typeof r.createIfMissing!="boolean")throw new Error("Invalid property capture settings. Choose a property and action in the Capture settings.");let t=r.property;if(t.kind==="prompt")return{property:{kind:"prompt"},action:r.action,createIfMissing:r.createIfMissing};if(t.kind==="named"&&"format"in t&&typeof t.format=="string")return{property:{kind:"named",format:t.format},action:r.action,createIfMissing:r.createIfMissing};throw new Error("Invalid property capture selector.")}var Tc=class extends Ws{constructor(t){super(t,"Capture"),this.appendLink=!1,this.copyLinkToClipboard=!1,this.captureTo="",this.captureToActiveFile=!1,this.captureToCanvasNodeId="",this.activeFileWritePosition="cursor",this.createFileIfItDoesntExist={enabled:!1,createWithTemplate:!1,template:""},this.format={enabled:!1,format:""},this.insertAfter={enabled:!1,after:"",insertAtEnd:!0,considerSubsections:!1,createIfNotFound:!0,createIfNotFoundLocation:"top",inline:!1,replaceExisting:!1,blankLineAfterMatchMode:"auto",promptHeading:!1},this.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"},this.newLineCapture={enabled:!1,direction:"below"},this.prepend=!1,this.task=!1,this.openFile=!1,this.fileOpening=en(),this.templater={afterCapture:"none"}}static Load(t){let e=t;return e.propertyCapture!==void 0&&(e.propertyCapture=Vx(e.propertyCapture)),e.activeFileWritePosition!=="cursor"&&e.activeFileWritePosition!=="top"&&e.activeFileWritePosition!=="bottom"&&(e.activeFileWritePosition="cursor"),typeof e.captureToCanvasNodeId!="string"&&(e.captureToCanvasNodeId=""),e.insertBefore||(e.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"}),e.captureToActiveFile&&e.prepend&&!e.insertAfter?.enabled&&!e.insertBefore.enabled&&!e.newLineCapture?.enabled&&(e.activeFileWritePosition!=="top"&&(e.activeFileWritePosition="bottom"),e.prepend=!1),e.templater||(e.templater={afterCapture:"none"}),e.templater.afterCapture!=="wholeFile"&&(e.templater.afterCapture="none"),e.insertAfter&&!e.insertAfter.blankLineAfterMatchMode&&(e.insertAfter.blankLineAfterMatchMode="auto"),e.insertAfter&&e.insertAfter.inline===void 0&&(e.insertAfter.inline=!1),e.insertAfter&&e.insertAfter.replaceExisting===void 0&&(e.insertAfter.replaceExisting=!1),e.insertAfter&&e.insertAfter.promptHeading===void 0&&(e.insertAfter.promptHeading=!1),e.insertAfter?.createIfNotFoundLocation===Wo&&(e.insertAfter.createIfNotFound&&!e.insertAfter.orderBy&&(e.insertAfter.orderBy={by:"insertion",direction:"desc",unparseable:"bottom"}),e.insertAfter.inline=!1),e}};var Gs=class extends Ws{constructor(t){super(t,"Template"),this.templatePath="",this.fileNameFormat={enabled:!1,format:""},this.discoverExistingNotesBeforeCreate=!1,this.folder={enabled:!1,folders:[],chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1,chooseFromSubfolders:!1},this.appendLink=!1,this.copyLinkToClipboard=!1,this.openFile=!1,this.fileOpening=en(),this.fileExistsBehavior={kind:"prompt"}}static Load(t){return t}};var lU=require("obsidian");Ve();Cm();function Bx(r){let t=[];for(let e of r.vault.getFiles())Sh.test(e.path)?t.push({file:e,isMarkdown:!1}):xt.test(e.path)&&j9(r,e)&&t.push({file:e,isMarkdown:!0});return t}function j9(r,t){return r.metadataCache.getFileCache(t)?.sections?.some(n=>n.type==="code")??!1}function cU(r,t,e){let n=t.find(s=>s.file.path===e);if(n)return n;let i=t.find(s=>!s.isMarkdown&&s.file.basename===e);if(i)return i;let o=r.vault.getAbstractFileByPath(e);if(o instanceof lU.TFile){if(Sh.test(o.path))return{file:o,isMarkdown:!1};if(xt.test(o.path))return{file:o,isMarkdown:!0}}return null}async function Uv(r,t){let e=await r.vault.read(t),{code:n,error:i}=qs(e);return n!==null&&n.length>0?null:i??"No ```js code block found in the note."}function FP(r){let t=new Set(r.map(({file:n})=>n.path)),e=new Map;for(let{file:n,isMarkdown:i}of r)i||e.set(n.basename,(e.get(n.basename)??0)+1);return r.map(({file:n,isMarkdown:i})=>i||e.get(n.basename)>1||t.has(n.basename)?n.path:n.basename)}rl();Zt();var qv=class extends fn{constructor(t,e){super(t,"UserScript"),this.path=e,this.settings={}}};Ka();var dU=require("obsidian");function Ux(r){let e=new dU.Notice("",1e4).messageEl;e.replaceChildren(),e.createDiv({text:"No scripts found",cls:"quickadd-notice-title"});let n=e.createDiv();n.createDiv({text:"QuickAdd cannot find any .js files or notes with a ```js code block in your vault."}),n.createEl("br"),n.createDiv({text:"Please make sure your scripts are:"}),n.createDiv({text:`\u2713 In your vault (not in ${r.vault.configDir} folder)`}),n.createDiv({text:"\u2713 Not in hidden folders (starting with a dot)"}),n.createDiv({text:"\u2713 A .js file, or a note containing a ```js code block"}),n.createEl("br"),Kw(n,es.userScripts,"View documentation")}nl();var zv=require("obsidian");Ln();on();function Ym(r,t,e,n){let i=t.lastIndexOf("/"),o=i>=0?t.slice(0,i):"",s=Jb(i>=0?t.slice(i+1):t),a=e?.vault.getAbstractFileByPath(t),l=e&&a instanceof zv.TFile?Ms([a],h=>e.metadataCache.getFileCache(h))[0]:null,c=l?.primary??s,d=l?.secondary??o;r.addClass("mod-complex");let u=r.createDiv({cls:"suggestion-content"}),p=u.createDiv({cls:"suggestion-title"});if(n?(0,zv.renderMatches)(p,c,n.matches):p.setText(c),!d)return;let m=u.createDiv({cls:"suggestion-note"});n&&d===t?(0,zv.renderMatches)(m,d,n.matches,-n.pathOffset):m.setText(d)}Ln();ye();nt();rl();Zt();je();fi();var qx=class extends fn{constructor(){super("AI Assistant","AIAssistant");let t=U.getState().ai;this.model=t.defaultModel;let e=$l(t.defaultModel,t.defaultModelRef);this.modelRef=e?{...e}:void 0,this.systemPrompt=t.defaultSystemPrompt,this.outputVariableName="output",this.promptTemplate={enable:!1,name:""},this.modelParameters={}}};je();Zt();jo();Rx();var zx=class{constructor(t="{{DATE}}.md",e=!1,n,i,o=!0){this.filePath=t;this.type="OpenFile";this.id=Vt();this.openInNewTab=e,this.direction=n,this.location=i,this.focus=o,this.name=`Open file: ${this.filePath}`,this.applyLegacyFromLocation()}applyLegacyFromLocation(){if(this.location)switch(this.location){case"split":this.openInNewTab=!0,this.direction||(this.direction="vertical");break;case"tab":case"reuse":this.openInNewTab=!1,this.direction=void 0;break;default:this.openInNewTab=!0,this.direction=void 0;break}}};eu();rl();Zt();function Y9(){return{mode:"variable",variableName:"",operator:"isTruthy",valueType:"string"}}function K9(r){return r.mode==="variable"?{...r}:{...r}}var Hx=class extends fn{constructor(t){super(t?.name??"If condition","Conditional"),this.condition=t?.condition?K9(t.condition):Y9(),this.thenCommands=t?.thenCommands?[...t.thenCommands]:[],this.elseCommands=t?.elseCommands?[...t.elseCommands]:[]}};Xa();Hr();var Q9=F(`<div class="qaDataUnreadable svelte-sorpfp"><div class="qaDataUnreadableHead svelte-sorpfp"><!> <span class="qaDataUnreadableTitle svelte-sorpfp"> </span></div> <p class="qaDataUnreadableBody svelte-sorpfp">The saved value isn't in a shape QuickAdd understands, so it can't be shown
- or edited here. Nothing has been changed or deleted, and QuickAdd will not
- overwrite it.</p> <p class="qaDataUnreadableBody svelte-sorpfp">It's stored in <code>.obsidian/plugins/quickadd/data.json</code> inside this
- vault. Make a copy of that file before editing it.</p></div>`),X9={hash:"svelte-sorpfp",code:".qaDataUnreadable.svelte-sorpfp {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);padding:12px 14px;margin:4px 0 8px;background:var(--background-secondary);}.qaDataUnreadableHead.svelte-sorpfp {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaDataUnreadableTitle.svelte-sorpfp {font-weight:var(--font-semibold);color:var(--text-normal);}.qaDataUnreadableBody.svelte-sorpfp {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}"};function RP(r,t){Ae(r,X9);var e=Q9(),n=R(e),i=R(n);Qe(i,{iconId:"alert-triangle",size:16});var o=E(i,2),s=re(o);$(n),Xt(4),$(e),Q(()=>ee(s,`QuickAdd couldn't read ${t.what??""}`)),A(r,e)}var Km=class{constructor(t){this.obsidianCommands=[];this.scriptCandidates=[];this.commandListHandle=null;this.commandListProps=null;this.containerEl=null;this.unreadableCardHandle=null;this.app=t.app,this.plugin=t.plugin,this.unreadable=Wt(t.commands),this.commandsRef=FI(t.commands).commands,this.choices=t.choices,this.onCommandsChange=t.onCommandsChange,this.conditionalHandlers=t.conditionalHandlers,this.loadObsidianCommands(),this.loadScriptCandidates()}render(t){return this.destroy(),this.containerEl=t,t.empty(),t.addClass("quickAddCommandEditor"),this.unreadable?(this.renderUnreadableCard(t),!1):this.renderCommandList(t)?(this.renderCommandBar(t),this.renderAddObsidianCommandSetting(t),this.renderAddEditorCommandSetting(t),this.renderAddUserScriptSetting(t),this.renderAddChoiceSetting(t),!0):!1}renderUnreadableCard(t){let e=t.createDiv("commandList");this.unreadableCardHandle=vi(e,RP,{what:"this macro's commands"},{what:"this macro's commands"})}destroy(){this.commandListHandle?.destroy(),this.commandListHandle=null,this.commandListProps=null,this.unreadableCardHandle?.destroy(),this.unreadableCardHandle=null}loadObsidianCommands(){Object.keys(this.app.commands.commands).forEach(t=>{let e=this.app.commands.commands[t];this.obsidianCommands.push(new Bv(e.name,e.id))})}loadScriptCandidates(){this.scriptCandidates=Bx(this.app)}renderCommandList(t){let e=t.createDiv("commandList");return this.commandListProps=aU({app:this.app,plugin:this.plugin,commands:this.commandsRef,deleteCommand:async n=>{let i=this.commandsRef.find(a=>a.id===n);if(!i)throw S.logError("command not found"),new Error("command not found");if(!await wi(this.app,{title:`Delete '${i.name}'?`,message:"The command will be removed from this macro.",action:"Delete"}))return;if(!await JC(this.app,i)){new xi.Notice("Could not clear user script secrets. Command was not deleted.");return}this.commandsRef=this.commandsRef.filter(a=>a.id!==n),this.emitCommandsChanged()},saveCommands:n=>{this.commandsRef=n,this.onCommandsChange?.(n)},onConfigureCondition:this.conditionalHandlers?.configureCondition,onEditThenBranch:this.conditionalHandlers?.editThenBranch,onEditElseBranch:this.conditionalHandlers?.editElseBranch}),this.commandListHandle=vi(e,wP,this.commandListProps,{what:"this macro's commands"}),this.commandListHandle.ok}renderCommandBar(t){let e=t.createDiv("quickCommandContainer");this.addChoiceButton(e,"Capture",Tc),this.addChoiceButton(e,"Template",Gs),this.addCommandButton(e,"file-search","Add open file command",()=>new zx),this.addCommandButton(e,"clock","Add wait command",()=>new Lx(100)),this.addCommandButton(e,"git-branch","Add conditional command",()=>new Hx),U.getState().disableOnlineFeatures||this.addCommandButton(e,"bot","Add AI Assistant command",()=>new qx)}renderAddObsidianCommandSetting(t){let e,n=()=>{let i=e.getValue();if(!i.trim())return;let o=this.obsidianCommands.find(a=>a.name===i);if(!o){S.logError(`Could not find Obsidian command with name "${i}"`);return}let s=new Bv(o.name,o.commandId);s.generateId(),this.addCommand(s),e.setValue("")};new xi.Setting(t).setName("Obsidian command").setDesc("Add an Obsidian command").addText(i=>{e=this.configureSuggestedInput(i,"Obsidian command",this.obsidianCommands.map(o=>o.name),n)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}renderAddEditorCommandSetting(t){let e,n=()=>{if(!e.getValue())return;let i=$P.get(e.getValue());if(!i)throw S.logError("invalid editor command type"),new Error("invalid editor command type");this.addCommand(new i),e.setValue("")};new xi.Setting(t).setName("Editor commands").setDesc("Add editor command").addDropdown(i=>{e=i,i.selectEl.addClass("qa-command-sequence-input"),i.addOption("","Select command");for(let o of $P.keys())i.addOption(o,o)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}renderAddUserScriptSetting(t){let e,n=null,i=async()=>{this.loadScriptCandidates();let o=e.getValue().trim();if(!o)return;let s=Am(o).basename??o,a=cU(this.app,this.scriptCandidates,s);if(!a){new xi.Notice(`QuickAdd: No script or js-block note named "${o}" found.`);return}if(a.isMarkdown){let l=await Uv(this.app,a.file);if(l){new xi.Notice(`QuickAdd: "${a.file.path}" \u2014 ${l}`);return}}this.addCommand(new qv(o,a.file.path)),e.setValue(""),n&&n.buttonEl.addClass("qa-hidden")};new xi.Setting(t).setName("User scripts").setDesc("Add a .js file or a note with a ```js code block - type the name or click Browse").addText(o=>{e=this.configureSuggestedInput(o,"Start typing script name...",FP(this.scriptCandidates),i)}).addButton(o=>o.setButtonText("Browse").setTooltip("Browse and select a script (.js file or note)").onClick(As("Couldn't add that script",async()=>{let s=await this.showScriptPicker();s&&this.addCommand(s)}))).addButton(o=>{n=o,o.setButtonText("Add").setCta().onClick(()=>{i()}),o.buttonEl.addClass("qa-hidden")}),e.onChange(o=>{n&&n.buttonEl.toggleClass("qa-hidden",o.trim().length===0)})}renderAddChoiceSetting(t){let e,n=()=>{let i=e.getValue();if(!i.trim())return;let o=this.choices.find(s=>s.name===i);if(!o){new xi.Notice(`QuickAdd: No choice named "${i}".`);return}this.addCommand(new Ox(o.name,o.id)),e.setValue("")};new xi.Setting(t).setName("Choices").setDesc("Add existing choice").addText(i=>{e=this.configureSuggestedInput(i,"Choice",this.choices.map(o=>o.name),n)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}configureSuggestedInput(t,e,n,i){return t.inputEl.addClass("qa-command-sequence-input"),t.setPlaceholder(e),new hi(this.app,t.inputEl,n),t.inputEl.addEventListener("keypress",o=>{o.key==="Enter"&&i()}),t}addChoiceButton(t,e,n){new xi.ButtonComponent(t).setButtonText(e).setTooltip(`Add ${e} choice`).onClick(()=>{let o=new n(`Untitled ${e} Choice`);this.addCommand(new Nx(o))})}addCommandButton(t,e,n,i){new xi.ButtonComponent(t).setIcon(e).setTooltip(n).onClick(()=>this.addCommand(i()))}async showScriptPicker(){if(this.loadScriptCandidates(),this.scriptCandidates.length===0)return Ux(this.app),null;let t=this.scriptCandidates.map(a=>a.file.path),e=FP(this.scriptCandidates),n=Ms(this.scriptCandidates.map(a=>a.file),a=>this.app.metadataCache.getFileCache(a)),i=await gr.Suggest(this.app,e,t,{placeholder:"Select a script (.js file or note with a ```js block)",renderItem:(a,l,c)=>Ym(l,a,this.app,{matches:c,pathOffset:n[t.indexOf(a)].primary.length+1}),searchItems:t.map((a,l)=>`${n[l].primary} ${a}`),allowCustomValue:!1}),o=t.indexOf(i);if(o===-1)return null;let s=this.scriptCandidates[o];if(s.isMarkdown){let a=await Uv(this.app,s.file);if(a)return new xi.Notice(`QuickAdd: "${s.file.path}" \u2014 ${a}`),null}return new qv(e[o],s.file.path)}addCommand(t){this.commandsRef=[...this.commandsRef,t],this.emitCommandsChanged()}emitCommandsChanged(){this.commandListProps&&(this.commandListProps.commands=[...this.commandsRef]),this.onCommandsChange?.(this.commandsRef)}};var hn=require("obsidian");Hl();nl();nt();function pU(r){return r.mode==="variable"?{...r}:{...r}}function J9(){return{mode:"variable",variableName:"",operator:"isTruthy",valueType:"boolean"}}function Z9(){return{mode:"script",scriptPath:""}}var Wx=class extends hn.Modal{constructor(e,n){super(e);this.isResolved=!1;this.scriptCandidates=[];this.originalCommand=n,this.workingCommand={...n,condition:pU(n.condition)},this.waitForClose=new Promise(i=>{this.resolvePromise=i}),this.loadScriptCandidates(),this.display(),this.open()}onClose(){super.onClose(),this.isResolved||this.resolve(null)}resolve(e){this.isResolved||(this.isResolved=!0,this.resolvePromise(e))}loadScriptCandidates(){this.scriptCandidates=Bx(this.app)}reload(){this.display()}display(){this.containerEl.addClass("quickAddModal","conditionalSettingsModal"),this.contentEl.empty(),this.contentEl.createEl("h2",{text:"Configure conditional command"}).addClass("qa-modal-title"),this.renderModeSelector(),this.workingCommand.condition.mode==="variable"?this.renderVariableConfiguration(this.workingCommand.condition):this.renderScriptConfiguration(this.workingCommand.condition),this.renderButtonBar()}renderModeSelector(){new hn.Setting(this.contentEl).setName("Condition type").setDesc("Choose how this condition should be evaluated.").addDropdown(e=>{e.addOption("variable","Macro variable").addOption("script","Run script").setValue(this.workingCommand.condition.mode).onChange(n=>{n!==this.workingCommand.condition.mode&&(this.workingCommand.condition=n==="variable"?J9():Z9(),this.reload())})})}renderVariableConfiguration(e){this.renderVariableNameSetting(e),this.renderOperatorSetting(e),this.renderValueTypeSetting(e),ql(e.operator)&&this.renderExpectedValueSetting(e)}renderVariableNameSetting(e){new hn.Setting(this.contentEl).setName("Variable name").setDesc("Name of the macro variable to inspect (without the $ prefix).").addText(n=>n.setPlaceholder("e.g. projectStatus").setValue(e.variableName).onChange(i=>{e.variableName=i.trim()}))}renderOperatorSetting(e){let n=[{value:"equals",label:"Equals"},{value:"notEquals",label:"Does not equal"},{value:"lessThan",label:"Less than"},{value:"lessThanOrEqual",label:"Less than or equal"},{value:"greaterThan",label:"Greater than"},{value:"greaterThanOrEqual",label:"Greater than or equal"},{value:"contains",label:"Contains"},{value:"notContains",label:"Does not contain"},{value:"isTruthy",label:"Is truthy"},{value:"isFalsy",label:"Is falsy"}];new hn.Setting(this.contentEl).setName("Operator").setDesc("How to compare the variable value.").addDropdown(i=>{i.addOptions(n.reduce((o,s)=>(o[s.value]=s.label,o),{})),i.setValue(e.operator),i.onChange(o=>{e.operator=o,e.valueType=y0(e.operator),ql(e.operator)||delete e.expectedValue,this.reload()})})}renderValueTypeSetting(e){new hn.Setting(this.contentEl).setName("Value type").setDesc("How to interpret the comparison value.").addDropdown(n=>{n.addOption("string","Text").addOption("number","Number").addOption("boolean","Boolean").setValue(e.valueType).onChange(i=>{e.valueType=i,this.reload()})})}renderExpectedValueSetting(e){if(e.valueType==="boolean"){new hn.Setting(this.contentEl).setName("Expected value").setDesc("Choose true or false.").addDropdown(n=>{n.addOption("true","True").addOption("false","False").setValue(e.expectedValue??"true").onChange(i=>{e.expectedValue=i})});return}new hn.Setting(this.contentEl).setName("Expected value").setDesc("Value to compare against.").addText(n=>{n.setPlaceholder("Enter comparison value").setValue(e.expectedValue??"").onChange(i=>{e.expectedValue=i})})}renderScriptConfiguration(e){this.renderScriptPathSetting(e),this.renderScriptExportSetting(e)}renderScriptPathSetting(e){let n;new hn.Setting(this.contentEl).setName("Script path").setDesc("Vault-relative path to a .js file or a note with a ```js code block.").addText(i=>{n=i,i.setPlaceholder("scripts/myCheck.js or Notes/myCheck.md").setValue(e.scriptPath).onChange(o=>{e.scriptPath=o.trim()})}).addButton(i=>i.setButtonText("Browse").setTooltip("Select a script (.js file or note)").onClick(As("Couldn't select that script",async()=>{if(this.loadScriptCandidates(),this.scriptCandidates.length===0){Ux(this.app);return}let o=this.scriptCandidates.map(l=>l.file.path),s=await gr.Suggest(this.app,o,o,{placeholder:"Select a script (.js file or note with a ```js block)",emptyStateText:"No scripts found in your vault"});if(!s)return;let a=this.scriptCandidates.find(l=>l.file.path===s);if(a?.isMarkdown){let l=await Uv(this.app,a.file);if(l){new hn.Notice(`QuickAdd: "${a.file.path}" \u2014 ${l}`);return}}e.scriptPath=s,n.setValue(s)})))}renderScriptExportSetting(e){new hn.Setting(this.contentEl).setName("Export name").setDesc("Optional export or member to call (use :: to access nested members).").addText(n=>n.setPlaceholder("default").setValue(e.exportName??"").onChange(i=>{e.exportName=i.trim()||void 0}))}renderButtonBar(){let e=this.contentEl.createDiv({cls:"qa-command-button-row"});new hn.ButtonComponent(e).setButtonText("Cancel").onClick(()=>{this.resolve(null),this.close()}),new hn.ButtonComponent(e).setCta().setButtonText("Save").onClick(()=>{this.validateCondition()&&(this.applyChanges(),this.resolve(this.originalCommand),this.close())})}validateCondition(){let e=this.workingCommand.condition;return e.mode==="variable"?e.variableName.trim()?!0:(new hn.Notice("QuickAdd: Enter a variable name before saving."),!1):e.scriptPath.trim()?!0:(new hn.Notice("QuickAdd: Enter a script path before saving."),!1)}applyChanges(){this.originalCommand.condition=pU(this.workingCommand.condition);let e=zl(this.originalCommand.condition);this.originalCommand.name=`If ${e}`}};var mU=require("obsidian");Zr();Hr();var Gx=class extends _o{constructor(e){super(e.app,e.title,e.onSave);this.commandEditor=null;this.edited=!1;this.plugin=e.plugin,this.choices=e.choices,this.conditionalHandlers=e.conditionalHandlers,this.workingCommands=ke(e.commands),this.containerEl.addClass("conditionalBranchPage")}render(e){this.commandEditor=new Km({app:this.app,plugin:this.plugin,commands:this.workingCommands,choices:this.choices,onCommandsChange:i=>{this.workingCommands=i,this.edited=!0},conditionalHandlers:this.conditionalHandlers});let n=new mU.SettingGroup(e).setHeading("Commands").listEl;this.commandEditor.render(n.createDiv("branchCommandEditor"))}result(){return this.edited?Mt(this.workingCommands):null}destroy(){this.commandEditor?.destroy(),this.commandEditor=null}};Hl();var jx=require("obsidian");lt();Go();function e7(r){let t=r.trim();return t||void 0}function t7(r){return(typeof r.icon=="string"?r.icon.trim():"")||cp(r.type)}function Yx(r,t,e,n){let i=cp(e.type),o=new jx.Setting(t).setName("Icon").setDesc(`Lucide/Obsidian icon id. Leave empty to use ${i}.`);o.settingEl.addClass("qa-choice-icon-setting");let s=At(t,"span");s.classList.add("qa-choice-icon-setting-preview"),s.setAttribute("aria-hidden","true"),o.controlEl.appendChild(s);function a(){s.replaceChildren(),(0,jx.setIcon)(s,t7(e))}o.addText(l=>{l.setPlaceholder(i),l.setValue(typeof e.icon=="string"?e.icon:""),l.inputEl.addClass("qa-choice-icon-input"),l.inputEl.setAttribute("aria-label","Choice icon"),new hi(r,l.inputEl,hC,50),l.onChange(c=>{let d=e7(c);e.icon=d,n(d),a()})}),a()}lt();Hr();jo();jp();lc();function r7(r){let t=[],e=n=>{n.forEach(i=>{Ee(i)&&(i.type==="Multi"?e(Le(i)):t.push(i))})};return e(pr(r)),t}var Kx=class extends _o{constructor(e,n,i,o,s){super(e,i.name,s);this.choices=[];this.commandEditor=null;this.pickDaySetting=null;this.choice=i,this.macro=i.macro,this.openedName=i.name,this.choices=r7(o).filter(a=>a.id!==i.id),this.plugin=n,this.containerEl.addClass("macroBuilder")}result(){let e=em(this.choice.name,this.openedName);return this.choice.name=e,Qa(this.macro)&&(this.macro.name=e),this.choice}destroy(){this.commandEditor?.destroy(),this.commandEditor=null}render(e){this.addNameSetting(e,this.choice.name,this.openedName,i=>{this.choice.name=i,Qa(this.macro)&&(this.macro.name=i),this.pickDaySetting?.setName(Kp(i.trim()||this.openedName))}),this.addCommandEditor(this.addGroup(e,"Commands"));let n=this.addGroup(e,"Behavior");this.addOnePageInputSetting(n),this.addDateOriginSetting(n),this.addRunOnStartupSetting(n),this.addCommandPaletteSettings(n),this.addIconSetting(n)}addGroup(e,n){return new ls.SettingGroup(e).setHeading(n).listEl}addOnePageInputSetting(e){new ls.Setting(e).setName("One-page input override").addDropdown(n=>{n.addOption("","Follow global setting").addOption("always","Always").addOption("never","Never").setValue(this.choice.onePageInput??"").onChange(i=>{this.choice.onePageInput=i==="always"||i==="never"?i:void 0})})}addDateOriginSetting(e){let n=this.choice.dateOrigin,i=Wa(n);if(new ls.Setting(e).setName(Qw).setDesc(Xw).addDropdown(o=>{for(let s of rC)o.addOption(s.value,s.label);o.setValue(i),o.onChange(s=>{iC(s)&&(this.choice.dateOrigin=oC({preset:s,previous:this.choice.dateOrigin}),this.reload())})}),i==="ask"){let o=n?.kind==="ask"?n.defaultValue:void 0;new ls.Setting(e).setName(Jw).setDesc(Zw).addDropdown(s=>{for(let a of sC(o))s.addOption(a.value,a.label);s.setValue(ov(o)),s.onChange(a=>{let l=aC(a,o);this.choice.dateOrigin=l?{kind:"ask",defaultValue:l}:{kind:"ask"}})})}if(i==="custom"&&n?.kind==="relative"&&new ls.Setting(e).setName(nv).setDesc(eC).addText(o=>{o.setValue(String(n.offset)),o.setPlaceholder("-2"),o.onChange(s=>{let a=this.choice.dateOrigin;if(a?.kind!=="relative")return;let l=s.trim();/^[+-]?\d+$/.test(l)&&(this.choice.dateOrigin={...a,offset:Number(l)})})}).addDropdown(o=>{for(let s of tv)o.addOption(s,s);o.setValue(n.unit),o.onChange(s=>{let a=this.choice.dateOrigin;a?.kind==="relative"&&rv(s)&&(this.choice.dateOrigin={...a,unit:s})})}),i==="variable"){let o=n?.kind==="variable"?n.name:"";new ls.Setting(e).setName(iv).setDesc(tC).addText(s=>{s.setValue(o),s.setPlaceholder("day"),s.onChange(a=>{this.choice.dateOrigin={kind:"variable",name:a}})})}}addCommandPaletteSettings(e){new ls.Setting(e).setName(av).setDesc(lC).addToggle(n=>{n.setValue(this.choice.command).onChange(i=>{this.choice.command=i,this.reload()})}),this.pickDaySetting=null,this.choice.command&&lv(this.choice.dateOrigin)&&(this.pickDaySetting=new ls.Setting(e).setName(Kp(this.choice.name)).setDesc(cC).addToggle(n=>{n.setValue(this.choice.pickDayCommand??!1).onChange(i=>{this.choice.pickDayCommand=i})}))}addRunOnStartupSetting(e){new ls.Setting(e).setName("Run on startup").setDesc("Execute this macro when Obsidian starts").addToggle(n=>n.setValue(this.choice.runOnStartup).onChange(i=>{this.choice.runOnStartup=i}))}addIconSetting(e){Yx(this.app,e,this.choice,n=>{this.choice.icon=n})}reload(){this.destroy(),this.containerEl.empty(),this.render(this.containerEl)}macroCommandsValue(){return dr(this.macro)}setMacroCommands(e){if(!Qa(this.macro)){this.macro={id:Vt(),name:this.choice.name,commands:e},this.choice.macro=this.macro;return}this.macro.commands=e}addCommandEditor(e){let n=e.createDiv("macroBuilder__editor");this.commandEditor=new Km({app:this.app,plugin:this.plugin,commands:this.macroCommandsValue(),choices:this.choices,onCommandsChange:i=>{this.setMacroCommands(i)},conditionalHandlers:this.buildConditionalHandlers()}),this.commandEditor.render(n)}buildConditionalHandlers(){return{configureCondition:e=>this.configureConditionalCondition(e),editThenBranch:(e,n)=>this.openBranchPage(e,"then",n),editElseBranch:(e,n)=>this.openBranchPage(e,"else",n)}}async configureConditionalCondition(e){return await new Wx(this.app,e).waitForClose!==null}openBranchPage(e,n,i){new Gx({app:this.app,plugin:this.plugin,choices:this.choices,title:`${n==="then"?"Then":"Else"}: ${zl(e.condition)}`,commands:n==="then"?e.thenCommands:e.elseCommands,conditionalHandlers:this.buildConditionalHandlers(),onSave:o=>{o&&(n==="then"?e.thenCommands=o:e.elseCommands=o,i())}}).open()}};var Qx=class extends _o{constructor(e,n,i){super(e,n.name,i);this.choice=n;this.name=n.name,this.placeholder=n.placeholder??"",this.icon=typeof n.icon=="string"?n.icon:void 0,this.containerEl.addClass("qaMultiChoiceBuilder")}render(e){let n=o=>{},i=this.addNameSetting(e,this.name,this.choice.name,o=>{this.name=o,n(o.trim()||this.choice.name)});i.addSetting(o=>{o.setName("Placeholder").setDesc("Shown in the choice picker search box when this folder opens. Leave blank to use the folder name.").addText(s=>{n=a=>{s.setPlaceholder(a)},s.setPlaceholder(this.name),s.setValue(this.placeholder).onChange(a=>{this.placeholder=a})})}),Yx(this.app,i.listEl,{type:this.choice.type,icon:this.icon},o=>{this.icon=o})}result(){let e=this.placeholder.trim();return{...this.choice,name:em(this.name,this.choice.name),placeholder:e||void 0,icon:this.icon}}};je();jo();var Xx=class{constructor(t){this.name=t,this.id=Vt(),this.commands=[]}};var Qm=class extends Ws{constructor(e){super(e,"Macro");this.runOnStartup=!1;this.macro=new Xx(e)}};var Xm=class extends Ws{constructor(e){super(e,"Multi");this.choices=[];this.collapsed=!1}addChoice(e){return this.choices.push(e),this}addChoices(e){return this.choices.push(...e),this}};Hr();lt();function ru(r){return r==="Multi"?"folder":"choice"}function fU(r){return r==="Multi"?"Folder":"Choice"}Zr();function DP(r,t){let e=ke(r);for(let n of t)delete e[n];return e}Zr();Xa();ye();Hi();var n7={Template:Gs,Capture:Tc,Macro:Qm,Multi:Xm};function LP(r,t){let e=n7[r];if(!e)throw new Error(`Unknown choice type: ${r}`);return new e(t)}function gU(r,t){let e=LP(r.type,`${r.name} (copy)`);if(r.type==="Multi"){let n=e,i=r;return Object.assign(n,DP(i,["id","name","choices"])),Aa(i)?n.choices=Le(i).filter(Ee).map(o=>gU(o,t)):n.choices=i.choices,n}return Object.assign(e,DP(r,["id","name"])),r.type==="Macro"&&(e.macro=ke(r.macro),HV(e.macro),ZC(e,t)),e}async function vU(r,t){let e=await i7(t,r);return gU(r,{secretOptionNamesByPath:e,stripUnknownStringSettings:!0})}function yU(r){return r!==null&&typeof r=="object"}function OP(r,t){if(yU(r)){if(r.type==="UserScript"&&typeof r.path=="string"&&t.add(r.path),Array.isArray(r.thenCommands))for(let e of r.thenCommands)OP(e,t);if(Array.isArray(r.elseCommands))for(let e of r.elseCommands)OP(e,t);NP(r.choice,t)}}function NP(r,t){if(yU(r)){if(r.type==="Macro"){let e=dr(r.macro);if(Array.isArray(e))for(let n of e)OP(n,t)}if(r.type==="Multi"&&Array.isArray(r.choices))for(let e of r.choices)NP(e,t)}}async function i7(r,t){let e=new Set;NP(t,e);let n=new Map;for(let i of e)try{if(Ut(i)||!await r.vault.adapter.exists(i))continue;let s=Iv(await r.vault.adapter.read(i),i);n.set(i,s.foundSecretOptions&&s.names.size===0?null:s.names)}catch(o){S.logWarning(`QuickAdd could not inspect user-script settings '${i}' while duplicating choice: ${o?.message??o}`)}return n}function o7(r,t,e,n){switch(r.type){case"Template":return new wm(t,r,e,n);case"Capture":return new rm(t,r,e,n);case"Macro":return new Kx(t,e,r,U.getState().choices,n);case"Multi":return new Qx(t,r,n);default:throw new Error("Invalid choice type")}}async function bU(r,t){let e=r.type==="Multi",n=r.type==="Macro",i=l=>{if(mo(l))return"QuickAdd couldn't read this folder's contents. Deleting it also deletes whatever is still stored under it in data.json.";let c=Jt(Le(l));if(c.length===0)return"";let d=c.filter(m=>m.type==="Multi").length,u=c.length-d,p=[];return u>0&&p.push(`${u} ${u===1?"choice":"choices"}`),d>0&&p.push(`${d} ${d===1?"folder":"folders"}`),`Deleting this folder will also delete everything inside it: ${p.join(" and ")}.`},o=l=>Wt(dr(l.macro))?"QuickAdd couldn't read this macro's commands. Deleting it also deletes whatever is still stored under it in data.json.":"Deleting this choice will also delete its macro commands.",s=[`Are you sure you want to delete '${r.name}'?`,e?i(r):"",n?o(r):""].filter(Boolean).join(" ");return await wi(t,{title:`Delete ${ru(r.type)}`,message:s,action:"Delete"})?(n||e)&&!await JC(t,{type:"NestedChoice",choice:r})?(new hU.Notice(`Could not clear user script secrets. The ${ru(r.type)} was not deleted.`),!1):!0:!1}function wU(r,t,e,n){let i=o7(r,t,e,s=>{let a=Ui(s);n(a,o),o=a}),o=Ui(r);return i.open()}function CU(r){return{...r,command:!r.command}}var Jx=class{constructor(t){this.plugin=t}enableCommand(t){this.plugin.addCommandForChoice(t)}disableCommand(t,e){e?this.plugin.removeCommandForChoice(t,e):this.plugin.removeCommandForChoice(t)}updateCommand(t,e){this.plugin.removeCommandForChoice(t),this.plugin.addCommandForChoice(e)}};function xU(r,t,e){if(!t||!e)return r;let n=nu(r,t),i=nu(r,e);if(!n||!i||i.type!=="Multi"||n.type==="Multi"&&(n.id===i.id||s7(n).has(i.id)))return r;let{updated:o,removed:s}=Hv(r,t);return s?VP(o,e,s)??r:r}function EU(r,t){if(!t||r.some(i=>Ee(i)&&i.id===t))return r;let{updated:e,removed:n}=Hv(r,t);return n?[...e,n]:r}function nu(r,t){for(let e of r){if(!Ee(e))continue;if(e.id===t)return e;let n=nu(Le(e),t);if(n)return n}}function s7(r){let t=new Set,e=n=>{Ee(n)&&(t.add(n.id),Le(n).forEach(e))};return Le(r).forEach(e),t}function Hv(r,t){let e;return{updated:r.map(i=>{if(!Ee(i))return i;if(i.id===t){e=i;return}if(!Aa(i))return i;let o=Hv(Le(i),t);return o.removed&&(e=o.removed),o.removed?{...i,choices:o.updated}:i}).filter(Boolean),removed:e}}function VP(r,t,e){let n=!1,i=r.map(o=>{if(!Ee(o))return o;if(o.id===t&&o.type==="Multi"){if(mo(o))return o;n=!0;let a=o;return{...a,choices:[...Le(a),e]}}if(!Aa(o))return o;let s=VP(Le(o),t,e);return s?(n=!0,{...o,choices:s}):o});return n?i:void 0}function BP(r,t,e){let n=r.findIndex(s=>Ee(s)&&s.id===t);if(n!==-1){let s=[...r];return s.splice(n+1,0,e),s}let i=!1,o=r.map(s=>{if(!Ee(s)||!Aa(s))return s;let a=BP(Le(s),t,e);return a?(i=!0,{...s,choices:a}):s});return i?o:void 0}function TU(r,t,e){if(!e)return[...r,t];let n=VP(r,e,t)??[...r,t];return a7(n,e)}function UP(r,t,e){return r.map(n=>{if(!Ee(n)||n.type!=="Multi")return n;let i=n;return i.id===t?e(i):Aa(i)?{...i,choices:UP(Le(i),t,e)}:n})}function qP(r,t,e){return UP(r,t,n=>({...n,collapsed:e}))}function a7(r,t){return qP(r,t,!1)}function _U(r,t,e){return UP(r,t,n=>({...n,choices:e}))}var eE=require("obsidian");lt();var kU=[{type:"Template",label:"Template",description:"Create a note from a template file.",iconId:"file-text"},{type:"Capture",label:"Capture",description:"Add text to a note \u2014 append, prepend, or insert.",iconId:"pencil"},{type:"Macro",label:"Macro",description:"Run a sequence of commands and scripts.",iconId:"terminal"}];function Zx(r){switch(r){case"Template":return"New template";case"Capture":return"New capture";case"Macro":return"New macro";case"Multi":return"New folder"}}function SU(r,t){let e=Zx(r),n=new Set(Jt(t).map(o=>o.name));if(!n.has(e))return e;let i=2;for(;n.has(`${e} ${i}`);)i++;return`${e} ${i}`}var l7=F('<div><button type="button" class="qaNewFolderBtn svelte-jvakpr"><!> <span> </span></button> <button type="button" aria-haspopup="menu"><!> <span> </span> <!></button></div>'),c7={hash:"svelte-jvakpr",code:`.qaAddChoiceControls.svelte-jvakpr {display:flex;flex-direction:row;align-items:center;gap:0.5rem;}.qaAddChoiceControls.svelte-jvakpr button:where(.svelte-jvakpr) {display:inline-flex;align-items:center;gap:0.35em;}
- /* The chevron sits tighter to the label than the leading plus. */.qaNewChoiceBtn.svelte-jvakpr svg:last-child {margin-left:-0.1em;opacity:0.85;}
- /* Per-folder ("compact") controls render as quiet, clickable text links \u2014 not
- filled buttons \u2014 so they read as "add inside this folder" affordances and
- don't compete with the global primary CTA, especially when repeated across
- nested folders. */.qaAddChoiceControls.compact.svelte-jvakpr {gap:1rem;}.qaAddChoiceControls.compact.svelte-jvakpr button:where(.svelte-jvakpr) {font-size:var(--font-ui-smaller);padding:2px 0;gap:0.25em;background:transparent;border:none;box-shadow:none;color:var(--text-muted);}.qaAddChoiceControls.compact.svelte-jvakpr button:where(.svelte-jvakpr):hover {color:var(--text-accent);text-decoration:underline;}
- /* Mobile/touch: stretch so the two buttons fill the bar width instead of
- cramming to the right. Driven by \`fill\` (Platform.isMobile from the bottom
- bar) because viewport media queries don't fire under desktop mobile-emulation. */.qaAddChoiceControls.fill.svelte-jvakpr {flex:1;}.qaAddChoiceControls.fill.svelte-jvakpr button:where(.svelte-jvakpr) {flex:1;justify-content:center;}
- /* Narrow desktop windows stack the non-compact controls. Filled controls (the
- mobile bottom bar) are excluded so this can't override \`.fill\`'s side-by-side
- 50/50 layout on a phone-width viewport (Platform.isMobile + width <= 800px). */
- @media (max-width: 800px) {.qaAddChoiceControls.svelte-jvakpr:not(.compact):not(.fill) {flex-direction:column;align-items:stretch;}
- }`};function Jm(r,t){ie(t,!0),Ae(r,c7);let e=X(t,"targetFolderId",3,void 0),n=X(t,"targetFolderName",3,void 0),i=X(t,"compact",3,!1),o=X(t,"fill",3,!1),s=pe(!1);function a(N){let K=new eE.Menu;for(let H of kU)K.addItem(D=>D.setTitle(eE.Platform.isPhone?H.label:`${H.label} \u2014 ${H.description}`).setIcon(H.iconId).onClick(G=>{let V=G.altKey===!0;t.onAddChoice(Zx(H.type),H.type,e(),V)}));q(s,!0),K.onHide(()=>{q(s,!1)});let ne=N.target?.closest("button");if(ne){let H=ne.getBoundingClientRect();K.showAtPosition({x:H.left,y:H.bottom+4,width:H.width,overlap:!0,left:!i()})}else K.showAtMouseEvent(N)}function l(){t.onAddChoice(Zx("Multi"),"Multi",e(),!0)}let c=k(()=>i()?"Add choice":"New choice"),d=k(()=>i()?"Add folder":"New folder"),u=k(()=>n()?`Add choice to ${n()}`:f(c)),p=k(()=>n()?`Add folder to ${n()}`:f(d));var m=l7();let h;var g=R(m),v=R(g);Qe(v,{iconId:"folder-plus",size:14});var b=E(v,2),y=re(b,!0);$(g);var C=E(g,2);let w;var T=R(C);Qe(T,{iconId:"plus",size:14});var P=E(T,2),_=re(P,!0),I=E(P,2);{var O=N=>{Qe(N,{iconId:"chevron-down",size:12})};z(I,N=>{i()||N(O)})}$(C),$(m),Q(()=>{h=Ge(m,1,"qaAddChoiceControls svelte-jvakpr",null,h,{compact:i(),fill:o()&&!i()}),le(g,"aria-label",f(p)),le(g,"title",i()?f(p):void 0),ee(y,f(d)),w=Ge(C,1,"qaNewChoiceBtn svelte-jvakpr",null,w,{"mod-cta":!i()}),le(C,"aria-expanded",f(s)),le(C,"aria-label",f(u)),le(C,"title",i()?f(u):void 0),ee(_,f(c))}),ge("click",g,l),ge("click",C,a),A(r,m),oe()}He(["click"]);var d7=F('<div class="rightButtonsContainer svelte-1tlf1y8"><!> <!> <!> <!> <!> <!></div>'),u7={hash:"svelte-1tlf1y8",code:`.rightButtonsContainer.svelte-1tlf1y8 {display:flex;align-items:center;
- /* Icons carry their own 3px padding inside the choice rows (24px hit
- boxes), so a tight gap keeps the cluster compact without touching. */gap:2px;flex:0 0 auto;}`};function Wv(r,t){ie(t,!0),Ae(r,u7);let e=X(t,"showConfigureButton",3,!0),n=X(t,"showDuplicateButton",3,!0),i=X(t,"commandEnabled",3,!1),o=X(t,"choiceName",3,"");var s=d7(),a=R(s);{var l=v=>{{let b=k(()=>`Configure${o()?" "+o():""}`);Et(v,{iconId:"settings",get label(){return f(b)},extraClass:"qa-row-secondary-action",get onclick(){return t.onConfigureChoice}})}};z(a,v=>{e()&&v(l)})}var c=E(a,2);{var d=v=>{{let b=k(()=>`Duplicate${o()?" "+o():""}`);Et(v,{iconId:"copy",get label(){return f(b)},extraClass:"qa-row-secondary-action",get onclick(){return t.onDuplicateChoice}})}};z(c,v=>{n()&&v(d)})}var u=E(c,2);{let v=k(()=>`Delete${o()?" "+o():""}`);Et(u,{iconId:"trash-2",get label(){return f(v)},extraClass:"qa-row-secondary-action",get onclick(){return t.onDeleteChoice}})}var p=E(u,2);{var m=v=>{{let b=k(()=>`More options${o()?" for "+o():""}`);Et(v,{iconId:"more-vertical",ariaHasPopup:"menu",get label(){return f(b)},onclick:y=>t.onOpenMenu?.(y.currentTarget)})}};z(p,v=>{t.onOpenMenu&&v(m)})}var h=E(p,2);{let v=k(()=>`Command palette${o()?": "+o():""}`);Et(h,{iconId:"zap",get ariaPressed(){return i()},get label(){return f(v)},extraClass:"qa-row-secondary-action",get onclick(){return t.onToggleCommand}})}var g=E(h,2);{let v=k(()=>`Reorder${o()?" "+o():""}`);qr(g,{get label(){return f(v)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.onDragHandleDown},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(s),A(r,s),oe()}var iE=require("obsidian");var AU=require("obsidian");lt();var zP="quickadd:move-to-root";function p7(r,t){let e=pr(t);if(e.some(i=>Ee(i)&&i.id===r.id))return!1;let n=i=>{for(let o of i){if(!Ee(o))continue;let s=Le(o);if(s.some(a=>a?.id===r.id)||n(s))return!0}return!1};return n(e)}function m7(r,t){let e=[],n=Array.isArray(t)?t:[],i=(o,s=[])=>{for(let a of o){if(!Ee(a))continue;let l=a.name??"";if(a.type==="Multi"){let c=[...s,l];f7(r,a)||e.push({id:a.id,path:c.join(" / ")}),i(Le(a),[...s,l])}}};return i(n,[]),e}function f7(r,t){if(t.type!=="Multi"||r.id===t.id||mo(t))return!0;if(r.type==="Multi"){let e=new Set,n=i=>{Ee(i)&&(e.add(i.id),Le(i).forEach(n))};if(Le(r).forEach(n),e.has(t.id))return!0}return!1}function Zm(r,t){return{onRename:()=>t.onRenameChoice(r),onToggle:()=>t.onToggleCommand(r),onConfigure:()=>t.onConfigureChoice(r),onDuplicate:()=>t.onDuplicateChoice(r),onDelete:()=>t.onDeleteChoice(r),onMove:e=>t.onMoveChoice(r,e)}}function IU(r,t,e,n){let i=new AU.Menu;i.addItem(s=>s.setTitle(t.command?"Disable in command palette":"Enable in command palette").setIcon("zap").onClick(n.onToggle)).addItem(s=>s.setTitle("Rename").setIcon("pencil").onClick(n.onRename)).addItem(s=>s.setTitle("Configure").setIcon("settings").onClick(n.onConfigure)).addItem(s=>s.setTitle("Duplicate").setIcon("copy").onClick(n.onDuplicate)).addItem(s=>s.setTitle("Delete").setIcon("trash-2").onClick(n.onDelete)).addSeparator(),p7(t,e)&&i.addItem(s=>s.setTitle("Move to: (root)").setIcon("folder-up").onClick(()=>n.onMove(zP)));let o=m7(t,e);return o.length===0?i.addItem(s=>s.setTitle("Move to: (no folders)").setDisabled(!0).setIcon("folder")):o.forEach(s=>i.addItem(a=>a.setTitle(`Move to: ${s.path}`).setIcon("folder-open").onClick(()=>n.onMove(s.id)))),i}function tE(r,t,e,n,i){t.preventDefault(),IU(r,e,n,i).showAtMouseEvent(t)}function rE(r,t,e,n,i){let o=t.getBoundingClientRect();IU(r,e,n,i).showAtPosition({x:o.left,y:o.bottom})}var PU=require("obsidian");function nE(r,t,e,n){t.replaceChildren(),PU.MarkdownRenderer.render(n,r,t,"/",e)}lt();var h7=F('<div class="choiceListItem"><span class="qaChoiceRowIcon" aria-hidden="true"><!></span> <span class="choiceListItemName"></span> <!></div>'),g7={hash:"svelte-1xw9zlu",code:""};function HP(r,t){ie(t,!0),Ae(r,g7);let e=!0,n=pe(void 0),i=new iE.Component;Ot(()=>{f(n)&&nE(t.choice.name,f(n),i,t.app)}),Ot(()=>()=>i.unload());function o(p){tE(t.app,p,t.choice,t.roots,Zm(t.choice,t.actions))}function s(p){rE(t.app,p,t.choice,t.roots,Zm(t.choice,t.actions))}var a=h7(),l=R(a),c=R(l);{let p=k(()=>Ed(t.choice));Qe(c,{get iconId(){return f(p)},size:15})}$(l);var d=E(l,2);Cn(d,p=>q(n,p),()=>f(n));var u=E(d,2);Wv(u,{get onDragHandleDown(){return t.startDrag},onDeleteChoice:()=>t.actions.onDeleteChoice(t.choice),onConfigureChoice:()=>t.actions.onConfigureChoice(t.choice),onToggleCommand:()=>t.actions.onToggleCommand(t.choice),onDuplicateChoice:()=>t.actions.onDuplicateChoice(t.choice),onOpenMenu:s,get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown},get choiceName(){return t.choice.name},get commandEnabled(){return t.choice.command},showConfigureButton:e,get dragDisabled(){return t.dragDisabled},showDuplicateButton:!0}),$(a),Q(()=>le(a,"data-choice-id",t.choice.id)),ge("contextmenu",a,o),ge("dblclick",a,p=>{iE.Platform.isMobile||p.target.closest("button, a")||t.actions.onConfigureChoice(t.choice)}),A(r,a),oe()}He(["contextmenu","dblclick"]);var oE=require("obsidian");lt();var v7=F('<span class="qaFolderCount svelte-gckzoy" aria-hidden="true"> </span>'),y7=F(`<p class="qaUnreadableFolder svelte-gckzoy">QuickAdd couldn't read this folder's contents. They're still
- in <code class="svelte-gckzoy">data.json</code>.</p>`),b7=F('<div class="nestedAddRow svelte-gckzoy"><!></div>'),w7=F("<!> <!>",1),C7=F('<div class="nestedChoiceList svelte-gckzoy"><!></div>'),x7=F('<div><div class="multiChoiceListItem"><button type="button" class="multiChoiceListItemName svelte-gckzoy"><span aria-hidden="true"><!></span> <span class="choiceListItemName"></span> <!></button> <!></div> <!></div>'),E7={hash:"svelte-gckzoy",code:`
- /* Row surface (min-height, padding, radius, hover, rhythm) is shared with
- leaf rows and lives in styles.css \u2014 see "Choice list rows". Only the
- folder-specific pieces stay here. */
- /* Base icon = chevron-down (expanded); collapsed rotates to point RIGHT,
- matching Obsidian's own collapse grammar (file explorer, outline). */.multiChoiceCollapseIcon.svelte-gckzoy {transition:transform 150ms ease;}.multiChoiceCollapseIcon.is-collapsed.svelte-gckzoy {transform:rotate(-90deg);}
- @media (prefers-reduced-motion: reduce) {.multiChoiceCollapseIcon.svelte-gckzoy {transition:none;}
- }
- /* Full-width collapse toggle: reset native <button> chrome while keeping
- native keyboard activation + aria-expanded. It hosts the shared icon
- column (the chevron), so the folder NAME lands on the exact leaf-name x
- for free \u2014 same 8px column gap as the leaf rows. */.multiChoiceListItemName.svelte-gckzoy {flex:1 1 auto;min-width:0;align-self:stretch;display:flex;align-items:center;
- /* Obsidian's base button centers flex content; the name must not rely
- on a growing child to stay left (it stopped growing for the count). */justify-content:flex-start;gap:8px;background:transparent;border:none;box-shadow:none;padding:0;
- /* Obsidian's base button rule sets height: var(--input-height) (30px),
- which would make folder rows 4px taller than leaf rows \u2014 the exact
- rhythm break this redesign removes. */height:auto;min-height:0;font:inherit;color:inherit;text-align:left;cursor:pointer;
- /* Suppress double-tap-zoom + its click delay on touch \u2014 proper touch hygiene
- for a tap target, and reduces the ghost-click the dedupe above also guards. */touch-action:manipulation;}
- /* The count reads as part of the label ("Misc \xB7 12"), so the name must not
- grow \u2014 it keeps its ellipsis via flex-shrink + the shared min-width: 0. */.multiChoiceListItemName.svelte-gckzoy .choiceListItemName {flex:0 1 auto;}
- /* Same slot, weight and colour as the empty-folder hint in ChoiceList, so a
- folder we cannot read reads as a variation of "empty" rather than an alarm. */.qaUnreadableFolder.svelte-gckzoy {margin:0;padding:6px 8px 8px;color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);line-height:1.4;}.qaUnreadableFolder.svelte-gckzoy code:where(.svelte-gckzoy) {font-size:inherit;}.qaFolderCount.svelte-gckzoy {flex:0 0 auto;color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);font-variant-numeric:tabular-nums;line-height:1;}.multiChoiceListItemName.svelte-gckzoy:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:1px;border-radius:var(--radius-s, 4px);}
- /* Just the indent \u2014 the drop-into-folder ring is drawn on the ACTUAL dndzone
- (.choiceList, in ChoiceList.svelte) so the highlighted area equals the
- droppable area (WYSIWYG); it is NOT drawn on this wrapper, which extends past
- the zone to the add-row/hint. The ::before is an indent GUIDE under the
- parent's icon column (x = row padding 8px + half the 18px column, minus
- half the line), clarifying what belongs to the open folder. */.nestedChoiceList.svelte-gckzoy {position:relative;padding-left:26px;}.nestedChoiceList.svelte-gckzoy::before {content:"";position:absolute;left:16px;top:3px;bottom:3px;width:1px;background:var(--background-modifier-border);pointer-events:none;}
- /* The per-folder add-row reads as a ghost row of the folder: aligned to the
- child rows' padding, one tight step (4px) below the last child. */.nestedAddRow.svelte-gckzoy {margin:2px 0 4px 0;padding:0 8px;}`};function WP(r,t){ie(t,!0),Ae(r,E7);let e=X(t,"choice",7),n=X(t,"forceDragDisabled",3,!1),i=k(()=>Le(e())),o=k(()=>mo(e())),s=!0,a=pe(void 0),l=new oE.Component;Ot(()=>{f(a)&&nE(e().name,f(a),l,t.app)}),Ot(()=>()=>l.unload());function c(O){tE(t.app,O,e(),t.roots,Zm(e(),t.actions))}function d(O){rE(t.app,O,e(),t.roots,Zm(e(),t.actions))}let u={...pt(()=>t.actions),onReorderChoices:O=>{e().choices=O,t.actions.onCommitFolder(e().id,O)}};function p(){n()||t.actions.onToggleCollapsed(e())}var m=x7(),h=R(m),g=R(h),v=R(g);let b;var y=R(v);Qe(y,{iconId:"chevron-down",size:16}),$(v);var C=E(v,2);Cn(C,O=>q(a,O),()=>f(a));var w=E(C,2);{var T=O=>{var N=v7(),K=re(N,!0);Q(()=>ee(K,f(i).length)),A(O,N)};z(w,O=>{e().collapsed&&f(i).length>0&&O(T)})}$(g),Ft(g,O=>NC?.(O));var P=E(g,2);Wv(P,{get onDragHandleDown(){return t.startDrag},onDeleteChoice:()=>t.actions.onDeleteChoice(e()),onConfigureChoice:()=>t.actions.onConfigureChoice(e()),onToggleCommand:()=>t.actions.onToggleCommand(e()),onDuplicateChoice:()=>t.actions.onDuplicateChoice(e()),onOpenMenu:d,get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown},showConfigureButton:s,get dragDisabled(){return t.dragDisabled},get choiceName(){return e().name},get commandEnabled(){return e().command},showDuplicateButton:!0}),$(h);var _=E(h,2);{var I=O=>{var N=bt(),K=ae(N);{var ne=H=>{var D=C7(),G=R(D);{var V=B=>{var J=y7();A(B,J)},M=B=>{var J=w7(),te=ae(J);{let se=k(()=>f(i).length===0),ce=k(()=>t.rootReorder??t.actions.onReorderChoices);ef(te,{get app(){return t.app},get roots(){return t.roots},get choices(){return f(i)},nested:!0,get isEmptyFolder(){return f(se)},get forceDragDisabled(){return n()},get rootReorder(){return f(ce)},get actions(){return u}})}var W=E(te,2);{var Z=se=>{var ce=b7(),$e=R(ce);Jm($e,{compact:!0,get targetFolderId(){return e().id},get targetFolderName(){return e().name},get onAddChoice(){return t.actions.onAddChoice}}),$(ce),A(se,ce)};z(W,se=>{n()||se(Z)})}A(B,J)};z(G,B=>{f(o)?B(V):B(M,-1)})}$(D),A(H,D)};z(K,H=>{e().collapsed||H(ne)})}A(O,N)};z(_,O=>{(!t.collapseId||t.collapseId&&e().id!==t.collapseId)&&O(I)})}$(m),Q(()=>{le(h,"data-choice-id",e().id),le(g,"aria-expanded",!e().collapsed),le(g,"aria-label",`Toggle ${e().name}`),b=Ge(v,1,"qaChoiceRowIcon multiChoiceCollapseIcon svelte-gckzoy",null,b,{"is-collapsed":e().collapsed})}),ge("contextmenu",h,c),ge("click",h,O=>{oE.Platform.isMobile||O.target.closest("button, a")||p()}),ge("click",g,p),A(r,m),oe()}He(["contextmenu","click"]);var $U=require("obsidian");lt();var T7=F("<div><!></div>"),_7=F("<div></div>"),k7={hash:"svelte-10tg5sy",code:`.choiceList.svelte-10tg5sy {width:auto;}
- /* Root (non-nested) empty list keeps a little bottom breathing room. The only way to
- render it empty is a zero-match filter \u2014 a truly empty tree shows the hero state. */.choiceList.qa-empty.svelte-10tg5sy:not(.qa-nested) {padding-bottom:0.5rem;}.choiceList.qa-nested.svelte-10tg5sy {
- /* Own the 2px name->first-row gap so the empty drop band sits the same distance
- below the folder name as a populated folder's first row (collapses with the
- row's own margin-top, so populated folders look identical). */margin-top:2px;position:relative; /* anchor the ring (::before) */border-radius:var(--radius-m);transition:background-color 120ms ease;}
- /* The drop ring is drawn a few px OUTSIDE the content as an absolutely-positioned
- ::before (adds no layout) \u2014 "synthetically" bigger than the rows so it doesn't
- clamp straight against the choice names. The right edge stays at the content edge:
- the settings pane is overflow-x:hidden, so extending the ring right would clip it. */.choiceList.qa-nested.svelte-10tg5sy::before {content:"";position:absolute;inset:-4px 0 -4px -6px;border-radius:var(--radius-m);border:2px dashed transparent;pointer-events:none;transition:border-color 120ms ease;}.choiceList.qa-nested.svelte-10tg5sy.qa-folder-droptarget {background-color:var(--background-modifier-hover);}.choiceList.qa-nested.svelte-10tg5sy.qa-folder-droptarget::before {border-color:var(--interactive-accent);}
- /* Empty folder: a GENEROUS, STABLE drop target. The band is sized by the folder's
- PERSISTED emptiness (qa-folder-empty), NOT the live \`choices\` length \u2014 so when a
- dragged item is previewed into the zone (filling \`choices\`, toggling qa-empty off)
- the band keeps its height instead of collapsing/expanding under the cursor (the
- "jumps all over the place"). Only persisted-empty folders get it, so populated
- folders never heave at drag start. */.choiceList.qa-nested.qa-folder-empty.svelte-10tg5sy {min-height:3rem;display:flex;align-items:center;}
- /* Hint shows only when the folder is persisted-empty AND nothing is previewed in it
- (qa-empty = live \`choices\` empty), so it cleanly swaps out for the previewed row
- without changing the band's size. */.choiceList.qa-nested.qa-folder-empty.qa-empty.svelte-10tg5sy::after {content:"Empty \u2014 add a choice or drag one here.";color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);line-height:1.3;padding-left:8px; /* align with the child rows' own left padding */pointer-events:none;user-select:none;}
- @media (prefers-reduced-motion: reduce) {.choiceList.qa-nested.svelte-10tg5sy,
- .choiceList.qa-nested.svelte-10tg5sy::before {transition:none;}
- }`};function ef(r,t){ie(t,!0),Ae(r,k7);let e=X(t,"choices",31,()=>Ze([])),n=X(t,"forceDragDisabled",3,!1),i=X(t,"isEmptyFolder",3,!1),o=X(t,"nested",3,!1),s=k(()=>{let w=new Set;return pr(e()).filter(T=>{if(!Ee(T))return!1;let P=T.id;return typeof P!="string"||P===""||w.has(P)?!1:(w.add(P),!0)})}),a=k(()=>t.rootReorder??t.actions.onReorderChoices),l=$U.Platform.isMobile,c=pe(""),d=ym(),u=k(()=>n()||!l&&!d.armed),p=pe(void 0),m=null;function h(w){if(n())return;d.markStarted(),gm(w);let T=w.detail.items;m=fm(T,w.detail.info.id)??m,q(c,w.detail.info.id,!0),e(bi(T))}function g(w){if(n())return;q(c,"");let T=bi(w.detail.items),P=w.detail.info.id;w.detail.info.trigger===hr.DROPPED_INTO_ANOTHER?T=T.filter(_=>_.id!==P):m?.item.id===P&&!T.some(_=>_.id===P)&&(T=[...T],T.splice(Math.min(m.index,T.length),0,m.item)),m=null,e(T),d.reset(),t.actions.onReorderChoices(e())}let v=()=>{n()||d.startDrag()};function b(w,T){if(n())return;let P=document.activeElement?.getAttribute("aria-label"),_=bi(f(s)),I=hm(_,w.id,T);if(!I)return;let O=I.findIndex(N=>N.id===w.id);e(I),t.actions.onReorderChoices(e()),Xd(`Moved ${w.name} to position ${O+1} of ${I.length}`),P&&bm(f(p),P)}var y=_7();let C;gt(y,21,()=>bi(f(s)),w=>w.id,(w,T)=>{var P=T7(),_=R(P);{var I=N=>{{let K=k(()=>t.roots??e()),ne=k(()=>n()?void 0:()=>b(f(T),-1)),H=k(()=>n()?void 0:()=>b(f(T),1));HP(N,{get app(){return t.app},get roots(){return f(K)},get dragDisabled(){return f(u)},startDrag:v,get actions(){return t.actions},get choice(){return f(T)},get onMoveUp(){return f(ne)},get onMoveDown(){return f(H)}})}},O=N=>{{let K=k(()=>t.roots??e()),ne=k(()=>n()?void 0:()=>b(f(T),-1)),H=k(()=>n()?void 0:()=>b(f(T),1));WP(N,{get app(){return t.app},get roots(){return f(K)},get dragDisabled(){return f(u)},startDrag:v,get actions(){return t.actions},get collapseId(){return f(c)},get forceDragDisabled(){return n()},get rootReorder(){return f(a)},get choice(){return f(T)},get onMoveUp(){return f(ne)},get onMoveDown(){return f(H)}})}};z(_,N=>{f(T).type!=="Multi"?N(I):N(O,-1)})}$(P),A(w,P)}),$(y),Cn(y,w=>q(p,w),()=>f(p)),Ft(y,(w,T)=>mm?.(w,T),()=>vm({items:f(s),dragDisabled:f(u),dropTargetClasses:o()?["qa-folder-droptarget"]:[]})),Q(()=>C=Ge(y,1,"choiceList svelte-10tg5sy",null,C,{"qa-nested":o(),"qa-folder-empty":i(),"qa-empty":f(s).length===0})),Yn("consider",y,h),Yn("finalize",y,g),A(r,y),oe()}var S7=F('<pre class="qaChoicesUnavailableDetail svelte-1t3kvu9"> </pre>'),A7=F(`<div class="qaChoicesUnavailable svelte-1t3kvu9"><div class="qaChoicesUnavailableHead svelte-1t3kvu9"><!> <span class="qaChoicesUnavailableTitle svelte-1t3kvu9"> </span></div> <p class="qaChoicesUnavailableBody svelte-1t3kvu9">Something in this vault's QuickAdd settings could not be read. Your choices
- have not been changed or deleted, and QuickAdd will not overwrite them.</p> <p class="qaChoicesUnavailableBody svelte-1t3kvu9">They are stored in <code>.obsidian/plugins/quickadd/data.json</code> inside this vault. Make a
- copy of that file before editing it.</p> <!></div>`),I7={hash:"svelte-1t3kvu9",code:".qaChoicesUnavailable.svelte-1t3kvu9 {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);padding:12px 14px;margin:4px 0 8px;background:var(--background-secondary);}.qaChoicesUnavailableHead.svelte-1t3kvu9 {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaChoicesUnavailableTitle.svelte-1t3kvu9 {font-weight:var(--font-semibold);color:var(--text-normal);}.qaChoicesUnavailableBody.svelte-1t3kvu9 {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}.qaChoicesUnavailableDetail.svelte-1t3kvu9 {margin:10px 0 0;padding:8px 10px;border-radius:var(--radius-s);background:var(--background-primary);color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);white-space:pre-wrap;word-break:break-word;user-select:text;}"};function tf(r,t){Ae(r,I7);let e=X(t,"what",3,"your choices"),n=X(t,"detail",3,"");var i=A7(),o=R(i),s=R(o);Qe(s,{iconId:"alert-triangle",size:16});var a=E(s,2),l=re(a);$(o);var c=E(o,6);{var d=u=>{var p=S7(),m=re(p,!0);Q(()=>ee(m,n())),A(u,p)};z(c,u=>{n()&&u(d)})}$(i),Q(()=>ee(l,`QuickAdd couldn't display ${e()??""}`)),A(r,i)}var sE=require("obsidian");ye();nt();zs();ye();nt();function P7(r){return`${fU(r)} name`}async function FU(r,t,e){try{let i=(await ir.Prompt(r,P7(e),void 0,t)).trim();return!i||i===t?null:i}catch(n){return Be(n)||S.logError(ka(n,"Could not rename")),null}}var DU=require("obsidian");lt();ye();lt();var GP=new WeakMap;function MU(r){let t=GP.get(r);if(t)return t;let e=HO(r);return GP.set(r,e),e}function RU(r){return GP.has(r)}function jP(r,t){if(!Array.isArray(r))return r;let e=RU(r),{choices:n,repaired:i}=MU(r);if(e)return n;for(let{choice:o}of i)if(o.command)try{t.enableCommand(o)}catch(s){S.logError(`Could not register a command for the repaired choice "${o.name}": ${s instanceof Error?s.message:String(s)}`)}return n}function OU(r,t){let e=t.trim();if(!e)return r;let n=(0,DU.prepareFuzzySearch)(e),i=e.toLowerCase(),o=(s,a=!1)=>{if(!Ee(s))return null;let l=typeof s.name=="string"?s.name:"";if(s.type!=="Multi")return a||n(l)?s:null;let c=a||l.toLowerCase().includes(i),d=p=>Le(s).map(m=>o(m,p)).filter(m=>m!==null),u=d(a);return c&&u.length===0&&(u=d(!0)),c||u.length>0?{...s,collapsed:!1,choices:u}:null};return r.map(s=>o(s)).filter(s=>s!==null)}function YP(r){return Ee(r)?r.command?!0:Le(r).some(YP):!1}function Gv(r,t){if(!Ee(r))return r;if(r.id===t.id)return{...r,...t};if(Aa(r)){let e=Le(r).map(i=>Gv(i,t));return{...r,choices:e}}return r}Zr();function _r(r,t){if(Object.is(r,t))return!0;if(r===null||t===null)return r===t;if(typeof r!=typeof t)return!1;if(Array.isArray(r)||Array.isArray(t))return!Array.isArray(r)||!Array.isArray(t)||r.length!==t.length?!1:r.every((e,n)=>_r(e,t[n]));if(typeof r=="object"&&typeof t=="object"){let e=r,n=t,i=Object.keys(e),o=Object.keys(n);return i.length!==o.length?!1:i.every(s=>Object.prototype.hasOwnProperty.call(n,s)&&_r(e[s],n[s]))}return!1}function il(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)&&Object.getPrototypeOf(r)===Object.prototype}function $7(r){return il(r)&&typeof r.name=="string"&&Array.isArray(r.models)}function F7(r){return il(r)&&typeof r.name=="string"&&typeof r.maxTokens=="number"&&!Array.isArray(r.models)}function M7(r){if(typeof r.id=="string"&&r.id.trim().length>0)return`id:${r.id.trim().toLowerCase()}`;let t=String(r.name??"").trim().toLowerCase(),e=String(r.endpoint??"").trim().toLowerCase().replace(/\/+$/,"");return`name:${t}\0${e}`}function R7(r){return il(r)&&typeof r.id=="string"&&r.id.trim().length>0}function D7(r){return`id:${String(r.id).trim()}`}function O7(r){return String(r.name??"").trim().toLowerCase()}function LU(r,t){let e=new Map;for(let n of r){if(!il(n))continue;let i=t(n);!i||i==="id:"||i==="name:\0"||e.has(i)||e.set(i,n)}return e}function L7(r,t,e,n,i){let o=LU(r??[],n),s=LU(e,n),a=[],l=new Set;for(let c of t){if(!il(c)){a.push(ke(c));continue}let d=n(c);if(l.has(d))continue;l.add(d);let u=o.get(d),p=s.get(d);if(!s.has(d)){(!o.has(d)||!_r(c,u))&&a.push(ke(c));continue}a.push(ol(u,c,p,i))}for(let c of e){if(!il(c))continue;let d=n(c);l.has(d)||(l.add(d),o.has(d)||a.push(ke(c)))}return a}function ol(r,t,e,n=[]){if(_r(t,e))return ke(t);if(_r(t,r))return ke(e);if(_r(e,r))return ke(t);if(il(r)&&il(t)&&il(e)){let a=new Set([...Object.keys(r),...Object.keys(t),...Object.keys(e)]),l={};for(let c of a)l[c]=ol(r[c],t[c],e[c],[...n,c]);return l}let i=Array.isArray(r)?r:void 0,o=Array.isArray(t)?t:void 0,s=Array.isArray(e)?e:void 0;if(o&&s){let a=n[n.length-1],l=[...o,...s,...i??[]],c=a==="providers"&&l.every($7)?M7:a==="models"&&l.every(F7)?O7:a==="choices"&&l.every(R7)?D7:void 0;if(c)return L7(i,o,s,c,n)}return ke(t)}function N7(r,t){return!_r(r,t)}function V7(r,t,e){return r==null||e==null?{toWrite:t,didMerge:!1}:N7(r,e)?{toWrite:ol(r,t,e),didMerge:!0}:{toWrite:t,didMerge:!1}}function NU(r){let t=r.local,{toWrite:e,didMerge:n}=V7(r.base,t,r.disk);_r(r.currentStore,t)||(e=ol(t,r.currentStore,e),t=r.currentStore,n=!0);let i=n&&_r(r.currentStore,t)&&!_r(e,r.currentStore);return{toWrite:e,didMerge:n,local:t,shouldReplaceStore:i}}function VU(r,t,e){return!_r(r,t)&&_r(t,e)}je();function BU(r){function t(){r.saveChoices(Ui(r.choices))}async function e(v,b,y,C=!1){let w=SU(b,r.choices),T=LP(b,w);if(r.choices=TU(r.choices,T,y),!y&&r.filterQuery.trim().length>0&&(r.filterQuery=""),t(),b==="Multi")await l(T);else if(!C)try{if(s(T))return}catch(P){S.logError(`Failed to configure the new choice: ${P instanceof Error?P.message:String(P)}`),t()}await n(T.id)}async function n(v){await ys();try{document.querySelector(`[data-choice-id="${v}"]`)?.scrollIntoView({block:"nearest"})}catch{}}function i(v){return nu(r.choices,v.id)??v}async function o(v){let b=i(v);await bU(b,r.app)&&(r.choices=Hv(r.choices,v.id).updated,r.commandRegistry.disableCommand(b,{recursive:!0}),t())}function s(v){let b=!1;return wU(i(v),r.app,r.plugin,(y,C)=>As(`Couldn't save the ${ru(C.type)} \u201C${C.name}\u201D`,()=>{a(C,y)||b||(b=!0,new sE.Notice(`QuickAdd: \u201C${C.name}\u201D was deleted elsewhere, so your changes to it were not saved.`))})())}function a(v,b){let y=U.getState().choices,C=nu(y,v.id);if(!C)return!1;let w=ol(v,b,Ui(C));return r.saveChoices(Ui(y.map(T=>Gv(T,w)))),r.commandRegistry.updateCommand(C,w),!0}async function l(v){if(!v)return;let b=await FU(r.app,v.name,v.type);if(!b)return;let y=nu(r.choices,v.id);if(!y){new sE.Notice(`QuickAdd: \u201C${v.name}\u201D was deleted elsewhere, so it was not renamed.`);return}let C={...y,name:b};r.choices=r.choices.map(w=>Gv(w,C)),r.commandRegistry.updateCommand(y,C),t()}function c(v){let b=CU(i(v));r.choices=r.choices.map(y=>Gv(y,b)),b.command?r.commandRegistry.enableCommand(b):r.commandRegistry.disableCommand(b),t()}async function d(v){let b=await vU(i(v),r.app);r.choices=BP(r.choices,v.id,b)??[...r.choices,b],YP(b)&&r.commandRegistry.enableCommand(b),t(),new sE.Notice(`Duplicated "${v.name}".`),await n(b.id)}function u(v,b){r.choices=b===zP?EU(r.choices,v.id):xU(r.choices,v.id,b),t()}function p(v){r.choices=v,t()}function m(v,b){r.choices=_U(r.choices,v,b),t()}function h(v){r.choices=qP(r.choices,v.id,!v.collapsed),t()}function g(v,b){return(y,...C)=>{let w=ru(y?.type),T=y?.name?`the ${w} \u201C${y.name}\u201D`:`that ${w}`;As(`Couldn't ${v} ${T}`,b)(y,...C)}}return{onDeleteChoice:g("delete",o),onConfigureChoice:g("open the settings for",s),onToggleCommand:g("update the command palette entry for",c),onDuplicateChoice:g("duplicate",d),onRenameChoice:g("rename",l),onMoveChoice:g("move",u),onToggleCollapsed:g("open or close",h),onReorderChoices:As("Couldn't save the new order",p),onCommitFolder:As("Couldn't save that folder's contents",m),onAddChoice:(v,b,y,C)=>As(`Couldn't add that ${ru(b)}`,e)(v,b,y,C)}}var B7=F('<button type="button" class="qaAIAssistantBtn qaAIAssistantEmptyBtn clickable-icon svelte-i6fsu8" aria-label="Configure AI Assistant"><!> <span>Configure AI Assistant</span></button>'),U7=F(`<div class="choiceEmptyState svelte-i6fsu8"><!> <div class="choiceEmptyTitle svelte-i6fsu8">No choices yet</div> <p class="choiceEmptyBody svelte-i6fsu8">A choice is an action QuickAdd can run: create a note, capture
- text, or run a macro. Group them with folders. <a class="quickadd-docs-link" target="_blank" rel="noopener noreferrer">Learn more</a></p> <div class="choiceEmptyActions svelte-i6fsu8"><!></div> <!></div>`),q7=F('<button class="search-input-clear-button qaFilterClearButton svelte-i6fsu8" aria-label="Clear filter"></button>'),z7=F('<div class="choiceFilterEmpty svelte-i6fsu8">No choices match your filter.</div>'),H7=F('<button type="button" class="qaAIAssistantBtn clickable-icon svelte-i6fsu8" aria-label="Configure AI Assistant" title="Configure AI Assistant"><!></button>'),W7=F('<div class="choiceFilterBar svelte-i6fsu8"><div class="search-input-container choiceFilterInput svelte-i6fsu8"><input type="search" placeholder="Filter choices..." autocapitalize="off" autocorrect="off" enterkeyhint="search"/> <!></div></div> <!> <div class="choiceViewBottomBar svelte-i6fsu8"><!> <!></div>',1),G7=F("<div><!></div>"),j7={hash:"svelte-i6fsu8",code:`.qaAIAssistantEmptyBtn.svelte-i6fsu8 {display:inline-flex;align-items:center;gap:0.375rem;margin-top:0.75rem;width:auto;color:var(--text-muted);font-size:var(--font-ui-small);}.choiceViewBottomBar.svelte-i6fsu8 {display:flex;flex-direction:row;align-items:center;justify-content:flex-end; /* pack right; "New choice" (primary) is the terminal action */flex-wrap:wrap;gap:0.5rem;margin-top:0.75rem;}
- /* AI Assistant as a quiet icon button (matches the per-row action icons),
- leading the right cluster so the bar's width barely changes when AI/online
- features toggle. */.qaAIAssistantBtn.svelte-i6fsu8 {flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;color:var(--text-muted);}.qaAIAssistantBtn.svelte-i6fsu8:hover {color:var(--text-normal);}.choiceEmptyState.svelte-i6fsu8 {display:flex;flex-direction:column;align-items:center;text-align:center;gap:0.5rem;padding:2.5rem 1rem;color:var(--text-muted);}.choiceEmptyTitle.svelte-i6fsu8 {font-weight:var(--font-semibold);color:var(--text-normal);}.choiceEmptyBody.svelte-i6fsu8 {margin:0;max-width:42ch;}.choiceEmptyActions.svelte-i6fsu8 {margin-top:0.5rem;}.choiceFilterBar.svelte-i6fsu8 {margin-bottom:8px;}
- /* The native container is inline-block by default in some contexts; span
- the full row so the filter aligns with the list edges. */.choiceFilterInput.svelte-i6fsu8 {width:100%;}
- /* Obsidian styles .search-input-clear-button (position, the \xD7 glyph, hover)
- \u2014 we only reset the <button> chrome so that styling shows through. A real
- <button> (Obsidian uses a div) keeps it keyboard-operable. */.qaFilterClearButton.svelte-i6fsu8 {background:transparent;border:none;box-shadow:none;padding:0;margin:0;cursor:var(--cursor, pointer);}.choiceFilterEmpty.svelte-i6fsu8 {color:var(--text-faint);font-size:var(--font-ui-small, 13px);padding:12px 8px 16px;}`};function KP(r,t){ie(t,!0),Ae(r,j7);let e=X(t,"choices",31,()=>Ze([])),n=pe(""),i=k(()=>!Array.isArray(e())),o=k(()=>`The "choices" value in data.json is ${e()===null?"null":`of type "${typeof e()}"`}, but QuickAdd expects a list.`),s=UU.Platform.isMobile,a=pe(Ze(U.getState().disableOnlineFeatures)),l=new Jx(pt(()=>t.plugin));e(jP(e(),l)),Ot(()=>{let h=U.subscribe(g=>{e(jP(g.choices,l)),q(a,g.disableOnlineFeatures,!0)});return()=>h()});let c=BU({get app(){return t.app},get plugin(){return t.plugin},get choices(){return e()},set choices(h){e(h)},get filterQuery(){return f(n)},set filterQuery(h){q(n,h,!0)},commandRegistry:l,saveChoices:h=>t.saveChoices(h)});var d=G7(),u=R(d);{var p=h=>{tf(h,{get detail(){return f(o)}})},m=h=>{var g=bt(),v=ae(g);hh(v,{onerror:y=>S.logError(`QuickAdd could not render the choice list: ${y instanceof Error?y.message:String(y)}`),failed:(y,C=$t)=>{{let w=k(()=>C()instanceof Error?C().message:String(C()));tf(y,{get detail(){return f(w)}})}}},y=>{var C=bt(),w=ae(C);{var T=I=>{var O=U7(),N=R(O);Qe(N,{iconId:"folder-plus",size:28});var K=E(N,4),ne=E(R(K));$(K);var H=E(K,2),D=R(H);Jm(D,{get onAddChoice(){return c.onAddChoice}}),$(H);var G=E(H,2);{var V=M=>{var B=B7(),J=R(B);Qe(J,{iconId:"sparkles",size:16}),Xt(2),$(B),ge("click",B,function(...te){t.openAISettings?.apply(this,te)}),A(M,B)};z(G,M=>{f(a)||M(V)})}$(O),Q(()=>le(ne,"href",es.gettingStarted)),A(I,O)},P=k(()=>e().length===0&&f(n).trim().length===0),_=I=>{var O=W7(),N=ae(O),K=R(N),ne=R(K);Ct(ne),le(ne,"spellcheck",!1);var H=E(ne,2);{var D=se=>{var ce=q7();ge("click",ce,()=>q(n,"")),A(se,ce)};z(H,se=>{f(n)&&se(D)})}$(K),$(N);var G=E(N,2);{var V=se=>{ef(se,{get app(){return t.app},get roots(){return e()},get actions(){return c},get choices(){return e()},set choices(ce){e(ce)}})},M=k(()=>f(n).trim().length===0),B=se=>{let ce=k(()=>OU(e(),f(n)));var $e=bt(),Xe=ae($e);{var Ye=Re=>{var Je=z7();A(Re,Je)},he=Re=>{ef(Re,{get app(){return t.app},get roots(){return e()},get choices(){return f(ce)},forceDragDisabled:!0,get actions(){return c}})};z(Xe,Re=>{f(ce).length===0?Re(Ye):Re(he,-1)})}A(se,$e)};z(G,se=>{f(M)?se(V):se(B,-1)})}var J=E(G,2),te=R(J);{var W=se=>{var ce=H7(),$e=R(ce);Qe($e,{iconId:"sparkles",size:16}),$(ce),ge("click",ce,function(...Xe){t.openAISettings?.apply(this,Xe)}),A(se,ce)};z(te,se=>{f(a)||se(W)})}var Z=E(te,2);Jm(Z,{get onAddChoice(){return c.onAddChoice},get fill(){return s}}),$(J),ge("keydown",ne,se=>{se.key==="Escape"&&f(n)&&(q(n,""),se.stopPropagation())}),Jn(ne,()=>f(n),se=>q(n,se)),A(I,O)};z(w,I=>{f(P)?I(T):I(_,-1)})}A(y,C)}),A(h,g)};z(u,h=>{f(i)?h(p):h(m,-1)})}$(d),A(r,d),oe()}He(["click","keydown"]);Gi();je();Nh();var Y7=F('<div class="qa-gv__empty svelte-it20w4">No global variables yet.</div>'),K7=F('<div class="qa-gv__row qa-gv__row--head svelte-it20w4"><div class="qa-gv__cell qa-gv__name">Name</div> <div class="qa-gv__cell qa-gv__value">Value</div> <div class="qa-gv__cell qa-gv__ops svelte-it20w4">Actions</div></div>'),Q7=F('<div class="qa-gv__row svelte-it20w4"><div class="qa-gv__cell qa-gv__name svelte-it20w4"><input type="text" placeholder="Name" class="svelte-it20w4"/></div> <div class="qa-gv__cell qa-gv__value svelte-it20w4"><textarea rows="2" placeholder="Snippet value (supports QuickAdd tokens)" class="svelte-it20w4"></textarea></div> <div class="qa-gv__cell qa-gv__ops svelte-it20w4"><button class="qa-gv__btn danger svelte-it20w4" title="Delete">Delete</button></div></div>'),X7=F('<div class="qa-gv svelte-it20w4"><div class="qa-gv__desc svelte-it20w4">Define reusable snippets referenced as <code>{{GLOBAL_VAR:<name>}}</code>. Snippets support other QuickAdd tokens and expand before VALUE/VDATE/etc.</div> <div class="qa-gv__table svelte-it20w4"><!> <!></div> <div class="qa-gv__actions svelte-it20w4"><button class="mod-cta">Add variable</button></div></div>'),J7={hash:"svelte-it20w4",code:`.qa-gv.svelte-it20w4 {display:flex;flex-direction:column;gap:8px;}
- /* Keeps "Add variable" right-aligned now that it is the row's only child. */.qa-gv__actions.svelte-it20w4 {display:flex;justify-content:flex-end;}.qa-gv__desc.svelte-it20w4 {color:var(--text-muted);font-size:12px;}.qa-gv__empty.svelte-it20w4 {color:var(--text-muted);font-size:var(--font-ui-smaller);padding:6px 0;}.qa-gv__table.svelte-it20w4 {display:grid;gap:8px;}.qa-gv__row.svelte-it20w4 {display:grid;grid-template-columns:180px 1fr 140px;gap:8px;align-items:start;}.qa-gv__row--head.svelte-it20w4 {font-weight:600;color:var(--text-muted);}.qa-gv__cell.svelte-it20w4 input[type="text"]:where(.svelte-it20w4) {width:100%;}.qa-gv__cell.svelte-it20w4 textarea:where(.svelte-it20w4) {width:100%;resize:vertical;}.qa-gv__ops.svelte-it20w4 {display:flex;gap:6px;align-items:center;}.qa-gv__btn.svelte-it20w4 {padding:4px 8px;}.qa-gv__btn.danger.svelte-it20w4 {color:var(--text-error);}
- @media (max-width: 900px) {.qa-gv__row.svelte-it20w4 {grid-template-columns:1fr;}.qa-gv__row--head.svelte-it20w4 {display:none;}
- }`};function QP(r,t){ie(t,!0),Ae(r,J7);let e=pe(Ze([]));function n(w,T){if(!T.has(w))return w;let P=1;for(;T.has(`${w}${P}`);)P++;return`${w}${P}`}function i(){let T=U.getState().globalVariables||{};q(e,Object.keys(T).map(P=>({name:P,value:T[P]??""})),!0)}let o=!1;function s(){let w=f(e).map(I=>I.name.trim()),T=w.some(I=>!I),P=new Set(w).size!==w.length;if(T||P)return;let _={};for(let I of f(e))_[I.name.trim()]=I.value??"";o=!0;try{U.setState({globalVariables:_})}finally{o=!1}}function a(){let w=new Set(f(e).map(P=>P.name)),T=n("NewVar",w);q(e,[...f(e),{name:T,value:""}],!0),s()}function l(w){q(e,f(e).filter((T,P)=>P!==w),!0),s()}function c(w){return new sn(t.app,w,t.plugin),{destroy(){}}}let d;function u(w){d!==void 0&&window.clearTimeout(d),d=window.setTimeout(()=>{d=void 0,s()},200)}Ot(()=>{let w=U.subscribe(()=>{o||i()});return i(),()=>{d!==void 0&&(window.clearTimeout(d),s()),w()}});var p=X7(),m=E(R(p),2),h=R(m);{var g=w=>{var T=Y7();A(w,T)},v=w=>{var T=K7();A(w,T)};z(h,w=>{f(e).length===0?w(g):w(v,-1)})}var b=E(h,2);gt(b,17,()=>f(e),fd,(w,T,P)=>{var _=Q7(),I=R(_),O=R(I);Ct(O),Ft(O,D=>c?.(D)),wr(()=>Jn(O,()=>f(T).name,D=>f(T).name=D)),$(I);var N=E(I,2),K=R(N);Jc(K),Ft(K,D=>c?.(D)),Ft(K,D=>nw?.(D)),wr(()=>Jn(K,()=>f(T).value,D=>f(T).value=D)),$(N);var ne=E(N,2),H=re(ne);$(_),ge("input",O,()=>{u(f(T))}),ge("input",K,()=>u(f(T))),ge("click",H,()=>l(f(e).indexOf(f(T)))),A(w,_)}),$(m);var y=E(m,2),C=re(y);$(p),ge("click",C,a),A(r,p),oe()}He(["input","click"]);je();gi();tr();var cq=require("obsidian");al();lt();Hr();tr();ou();Zt();var tJ=new Set;function XP(r,t,e){return r?t.has(r.id)?e.has(r.id):!0:!1}function rJ(r,t,e,n){switch(r.type){case"Choice":{let i=r;if(!e.has(i.choiceId))return!0;let o=t.get(i.choiceId);return o&&XP(o.choice,t,e)&&n(o.choice),!0}case"NestedChoice":{let i=r;return i.choice&&XP(i.choice,t,e)&&n(i.choice),!0}default:return!1}}function nJ(r){let t=new Map,e=(n,i,o)=>{for(let s of n){if(!Ee(s))continue;let a=[...o,s.name];t.set(s.id,{choice:s,parentId:i,path:a}),iu(s)&&Array.isArray(s.choices)&&e(s.choices,s.id,a)}};return e(pr(r),null,[]),t}function HU(r){let t=new Set;for(let e of Le(r))Ee(e)&&t.add(e.id);return ji(r)&&JP(r.macro?.commands,t),t}function JP(r,t){for(let e of Mt(r))if(Tr(e))switch(e.type){case"Choice":{let n=e;n.choiceId&&t.add(n.choiceId);break}case"Conditional":{let n=e;JP(n.thenCommands,t),JP(n.elseCommands,t);break}case"NestedChoice":{let i=e.choice;if(!i)break;let o=HU(i);for(let s of o)t.add(s);break}default:break}}function lE(r,t,e){let n=nJ(r),i=new Set,o=new Set,s=e?.excludedChoiceIds??tJ,a=t.filter(c=>!s.has(c)),l=[];for(;a.length>0;){let c=a.shift();if(i.has(c))continue;if(s.has(c)){i.add(c);continue}let d=n.get(c);if(!d){o.add(c);continue}i.add(c),l.push(c);let u=HU(d.choice);for(let p of u){if(!n.has(p)){o.add(p);continue}s.has(p)||a.push(p)}}return{catalog:n,choiceIds:l,missingChoiceIds:Array.from(o)}}function WU(r,t,e,n){let i=new Set(t),o=new Set,s=l=>{!l||!XP(l,r,i)||o.has(l.id)||(o.add(l.id),e(l),iu(l)&&Array.isArray(l.choices)&&l.choices.forEach(s),ji(l)&&a(l.macro?.commands))},a=l=>{for(let c of Mt(l))if(Tr(c)&&!rJ(c,r,i,s)&&(n(c),c.type==="Conditional")){let d=c;a(d.thenCommands),a(d.elseCommands)}};for(let l of t){let c=r.get(l);c&&s(c.choice)}}function cE(r,t){let e=new Set,n=new Set;return WU(r,t,()=>{},i=>{if(i.type==="UserScript"){let o=i;o.path&&e.add(o.path)}else if(i.type==="Conditional"){let{condition:o}=i;o.mode==="script"&&o.scriptPath&&n.add(o.scriptPath)}}),{userScriptPaths:e,conditionalScriptPaths:n}}function dE(r,t){let e=new Set,n=new Set,i=new Set;return WU(r,t,o=>{if(Un(o)&&o.templatePath&&e.add(xn(o.templatePath)),sl(o)){let s=o.createFileIfItDoesntExist;s?.enabled&&s.createWithTemplate&&s.template&&n.add(xn(s.template));for(let a of ZP(o))i.add(a)}},()=>{}),{templatePaths:e,captureTemplatePaths:n,includePaths:i}}function ZP(r){let t=r.format;return!t?.enabled||typeof t.format!="string"?new Set:_c(t.format)}function GU(r,t){let e=t.trim().toLowerCase();return e?r.filter(n=>`${n.path.join(" ")} ${n.choice.type}`.toLowerCase().includes(e)):r}function jU(r,t){let e=[];for(let n of r)t.has(n.id)&&(!n.parentId||!t.has(n.parentId))&&e.push(n.id);return e}function YU(r,t,e){if(t.length===0)return{rootCount:0,totalChoices:0,dependencyCount:0,missingChoiceIds:[],userScripts:0,conditionalScripts:0,templateFiles:0,captureTemplates:0};let n=lE(r,t,{excludedChoiceIds:e}),i=cE(n.catalog,n.choiceIds),o=dE(n.catalog,n.choiceIds);return{rootCount:t.length,totalChoices:n.choiceIds.length,dependencyCount:Math.max(n.choiceIds.length-t.length,0),missingChoiceIds:n.missingChoiceIds,userScripts:i.userScriptPaths.size,conditionalScripts:i.conditionalScriptPaths.size,templateFiles:o.templatePaths.size,captureTemplates:o.captureTemplatePaths.size}}var cs=require("obsidian");lt();var KU=typeof TextEncoder<"u"?new TextEncoder:void 0,QU=typeof TextDecoder<"u"?new TextDecoder:void 0;function XU(r){return typeof window>"u"?!1:typeof window[r]=="function"}function JU(){if(!(typeof Buffer>"u"))return Buffer}function ZU(r){if(KU&&XU("btoa")){let e=KU.encode(r),n="";for(let i=0;i<e.length;i++)n+=String.fromCharCode(e[i]);return window.btoa(n)}let t=JU();if(t)return t.from(r,"utf8").toString("base64");throw new Error("Base64 encoding is not supported in this environment.")}function Ys(r){if(QU&&XU("atob")){let e=window.atob(r),n=Uint8Array.from(e,i=>i.charCodeAt(0));return QU.decode(n)}let t=JU();if(t)return t.from(r,"base64").toString("utf8");throw new Error("Base64 decoding is not supported in this environment.")}Xa();ye();function uE(r,t){let e=new Map;for(let n of r)if(n.kind==="user-script")try{let i=Iv(Ys(n.content),n.originalPath);e.set(n.originalPath,i.foundSecretOptions&&i.names.size===0?null:i.names)}catch(i){S.logWarning(`QuickAdd ${t} could not inspect user-script settings '${n.originalPath}': ${i?.message??i}`)}return e}var nq=require("obsidian");Ka();ye();function pE(r){return!!r&&typeof r=="object"}function eq(r){return Array.isArray(r)&&r.every(t=>typeof t=="string")}function iJ(r){return pE(r)?typeof r.id=="string"&&typeof r.name=="string"&&typeof r.type=="string":!1}function oJ(r){return pE(r)?iJ(r.choice)&&eq(r.pathHint)&&(r.parentChoiceId===null||typeof r.parentChoiceId=="string"):!1}function sJ(r){if(!pE(r))return!1;let{kind:t,originalPath:e,contentEncoding:n,content:i}=r;return(t==="user-script"||t==="conditional-script"||t==="template"||t==="capture-template")&&typeof e=="string"&&n==="base64"&&typeof i=="string"}function tq(r){if(!pE(r))return!1;let{schemaVersion:t,quickAddVersion:e,createdAt:n,rootChoiceIds:i,choices:o,assets:s}=r;return typeof t=="number"&&Number.isInteger(t)&&t>=1&&typeof e=="string"&&typeof n=="string"&&eq(i)&&Array.isArray(o)&&o.every(oJ)&&Array.isArray(s)&&s.every(sJ)}lt();Zr();async function mE(r,t){let e=t.lastIndexOf("/");if(e<0)return;let n=t.slice(0,e);if(!n)return;let i=n.split("/").filter(Boolean),o="";for(let s of i)o=o?`${o}/${s}`:s,await r.vault.adapter.exists(o)||await r.vault.createFolder(o)}tr();ou();Hi();Xa();function iq(){return`QuickAdd Packages/quickadd-package-${new Date().toISOString().replace(/[:.]/g,"-")}.quickadd.json`}async function oq(r,t){let{choices:e,rootChoiceIds:n,quickAddVersion:i}=t,o=new Set(t.excludedChoiceIds??[]),s=t.createdAt??new Date().toISOString(),a=lE(e,n,{excludedChoiceIds:o}),l=new Set(a.choiceIds),c=cE(a.catalog,a.choiceIds),d=dE(a.catalog,a.choiceIds),u=aJ(c,d),p=await sq(r,u);await cJ(r,p);let m=uE(p.encodedAssets,"export"),h=a.choiceIds.map(b=>{let y=a.catalog.get(b);if(!y)throw new Error(`Choice '${b}' missing from catalog.`);let C=ke(y.choice);return aq(C,l),ZC(C,{secretOptionNamesByPath:m,stripUnknownStringSettings:!0}),{choice:C,pathHint:[...y.path],parentChoiceId:y.parentId}}),g=n.filter(b=>l.has(b));return{pkg:{schemaVersion:1,quickAddVersion:i,createdAt:s,rootChoiceIds:[...g],choices:h,assets:p.encodedAssets},missingChoiceIds:a.missingChoiceIds,missingAssets:p.missingAssets}}function aJ(r,t){let e=new Map;for(let n of r.userScriptPaths)n&&e.set(n,"user-script");for(let n of r.conditionalScriptPaths)n&&e.set(n,"conditional-script");for(let n of t.templatePaths)n&&(e.has(n)||e.set(n,"template"));for(let n of t.captureTemplatePaths)n&&(e.has(n)||e.set(n,"capture-template"));for(let n of t.includePaths)n&&(e.has(n)||e.set(n,"template"));return Array.from(e.entries()).map(([n,i])=>({path:n,kind:i}))}var lJ=10;async function cJ(r,t){let e=new Set(t.encodedAssets.map(i=>i.originalPath));for(let i of t.missingAssets)e.add(i.path);let n=t.encodedAssets.filter(rq);for(let i=0;i<lJ&&n.length>0;i++){let o=[];for(let a of n)for(let l of _c(Ys(a.content)))e.has(l)||(e.add(l),o.push({path:l,kind:"template"}));if(o.length===0)break;let s=await sq(r,o);t.encodedAssets.push(...s.encodedAssets),t.missingAssets.push(...s.missingAssets),n=s.encodedAssets.filter(rq)}}function rq(r){return(r.kind==="template"||r.kind==="capture-template")&&Ss(r.originalPath)}async function sq(r,t){let e=[],n=[];for(let{path:i,kind:o}of t){if(Ut(i)){n.push({path:i,kind:o}),S.logWarning(`QuickAdd export skipped ${o} outside the vault: ${i}`);continue}try{if(!await r.vault.adapter.exists(i)){n.push({path:i,kind:o}),S.logWarning(`QuickAdd export skipped missing ${o}: ${i}`);continue}let a=await r.vault.adapter.read(i);e.push({kind:o,originalPath:i,contentEncoding:"base64",content:ZU(a)})}catch(s){n.push({path:i,kind:o}),S.logWarning(`QuickAdd export failed to read ${o} '${i}': ${s?.message??s}`)}}return{encodedAssets:e,missingAssets:n}}function aq(r,t){if(r.type!=="Multi")return;let e=r;if(!Array.isArray(e.choices)||e.choices.length===0){e.choices=[];return}e.choices=e.choices.filter(n=>Ee(n)&&t.has(n.id)).map(n=>(aq(n,t),n))}async function dJ(r,t){return wi(r,{title:"Overwrite existing file?",message:`A file already exists at '${t}'. Saving the package will overwrite it.`,action:"Overwrite"})}async function lq(r,t,e,n={}){let i=(0,nq.normalizePath)(e.trim());if(!i)throw new Error("Output path cannot be empty.");let o=await r.vault.adapter.exists(i);if(o&&!await(n.confirmOverwrite??(c=>dJ(r,c)))(i))throw new Error(`Save cancelled: '${i}' already exists.`);await mE(r,i);let s=JSON.stringify(t,null,2);return await r.vault.adapter.write(i,s),{overwritten:o}}var uJ=F('<div class="setting-item mod-empty-state"><div class="setting-item-info"><div class="setting-item-name">No choices match the current filter.</div></div></div>'),pJ=F('<span class="qa-export-choice-path svelte-1way66v"> </span>'),mJ=F('<label class="qa-export-choice svelte-1way66v"><input type="checkbox" class="svelte-1way66v"/> <span class="qa-export-choice-name svelte-1way66v"> </span> <!> <span class="flair qa-export-choice-type svelte-1way66v"> </span></label>'),fJ=F('<div class="setting-item"><div class="setting-item-info"><div class="setting-item-name"> </div></div> <div class="setting-item-control"><span class="setting-item-value qa-export-count svelte-1way66v"> </span></div></div>'),hJ=F('<section class="callout qa-export-callout svelte-1way66v" data-callout="warning"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner">Missing dependencies detected</div></div> <div class="callout-content svelte-1way66v"><p class="svelte-1way66v"> </p></div></section>'),gJ=F('<p class="svelte-1way66v"> </p>'),vJ=F('<li><code class="svelte-1way66v"> </code> <span class="qa-export-asset-kind svelte-1way66v"> </span></li>'),yJ=F('<p class="svelte-1way66v">Missing assets:</p> <ul class="svelte-1way66v"></ul>',1),bJ=F('<section class="callout qa-export-callout svelte-1way66v" data-callout="warning"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner">Warnings</div></div> <div class="callout-content svelte-1way66v"><!> <!></div></section>'),wJ=F('<div class="qa-package-dialog"><div class="qa-package-body"><section class="qa-export-select svelte-1way66v"><div class="qa-export-controls svelte-1way66v"><div class="search-input-container svelte-1way66v"><label class="qa-visually-hidden" for="qa-export-filter">Filter choices</label> <input id="qa-export-filter" type="search" enterkeyhint="search" placeholder="Filter choices..." autocapitalize="off" autocorrect="off"/></div> <button type="button">Select visible</button> <button type="button">Clear selection</button></div> <div class="setting-group"><div class="setting-items qa-export-list svelte-1way66v"><!></div></div></section> <section class="setting-group mod-list"><div class="setting-item setting-item-heading"><div class="setting-item-name">Package summary</div></div> <div class="setting-items"></div></section> <!> <!> <section class="setting-group qa-export-save-group svelte-1way66v"><div class="setting-items"><div class="setting-item qa-export-save svelte-1way66v"><div class="setting-item-info svelte-1way66v"><label class="setting-item-name" for="qa-export-path">Save to file</label></div> <div class="setting-item-control svelte-1way66v"><input id="qa-export-path" type="text" placeholder="QuickAdd Packages/quickadd-package-YYYY-MM-DD.quickadd.json" class="svelte-1way66v"/> <button type="button"><!></button></div></div></div></section></div> <div class="modal-button-container"><button type="button">Cancel</button> <button type="button"><!></button></div></div>'),CJ={hash:"svelte-1way66v",code:`.qa-export-select.svelte-1way66v {display:flex;flex-direction:column;gap:var(--size-4-3);}.qa-export-controls.svelte-1way66v {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-2);}.qa-export-controls.svelte-1way66v .search-input-container:where(.svelte-1way66v) {flex:1 1 12rem;}.qa-export-list.svelte-1way66v {max-height:260px;overflow-y:auto;padding:var(--size-4-1);}
- /* List padding + row padding lands on the 16px inset of the mod-list rows
- below, so every row in the modal starts on the same edge. */.qa-export-choice.svelte-1way66v {display:flex;align-items:center;gap:var(--size-4-2);padding:var(--size-4-1) var(--size-4-3);padding-inline-start:calc(
- var(--size-4-3) + var(--qa-export-depth, 0) * var(--size-4-4)
- );font-size:var(--font-ui-small);border-radius:var(--radius-s);cursor:var(--cursor);}.qa-export-choice.svelte-1way66v:hover {background-color:var(--background-modifier-hover);}.qa-export-choice.svelte-1way66v input:where(.svelte-1way66v) {flex-shrink:0;margin:0;}.qa-export-choice-name.svelte-1way66v {min-width:0;overflow-wrap:anywhere;}.qa-export-choice-path.svelte-1way66v {min-width:0;color:var(--text-muted);font-size:var(--font-ui-smaller);overflow-wrap:anywhere;}.qa-export-choice-type.svelte-1way66v {margin-inline-start:auto;}.qa-export-count.svelte-1way66v {color:var(--text-normal);font-variant-numeric:tabular-nums;}.qa-export-callout.svelte-1way66v {margin:0;}.qa-export-callout.svelte-1way66v .callout-content:where(.svelte-1way66v) {font-size:var(--font-ui-small);}.qa-export-callout.svelte-1way66v p:where(.svelte-1way66v) {margin:var(--size-4-2) 0 0;}.qa-export-callout.svelte-1way66v ul:where(.svelte-1way66v) {margin:var(--size-4-1) 0 0;padding-inline-start:var(--size-4-5);}.qa-export-callout.svelte-1way66v code:where(.svelte-1way66v) {font-family:var(--font-monospace);font-size:var(--code-size);background-color:var(--code-background);border-radius:var(--code-radius);padding:0.1em 0.25em;overflow-wrap:anywhere;}.qa-export-asset-kind.svelte-1way66v {margin-inline-start:var(--size-4-1);color:var(--text-muted);font-size:var(--font-ui-smaller);}
- /* Same inset as the mod-list summary rows above. Not mod-list itself:
- Obsidian keeps mod-list rows horizontal on phones, where this row needs
- to stack. */.qa-export-save-group.svelte-1way66v {--setting-items-padding-x: var(--size-4-4);--setting-items-padding-y: var(--size-4-3);}
- /* The path is the point of this row: let the input take the width the
- short name leaves over. */.qa-export-save.svelte-1way66v {align-items:center;}
- /* Phones stack the row and make controls full width; wrap so the path
- and Save each get a full line. */.is-phone .qa-export-save.svelte-1way66v .setting-item-control:where(.svelte-1way66v) {flex-wrap:wrap;}.qa-export-save.svelte-1way66v .setting-item-info:where(.svelte-1way66v) {flex:0 0 auto;}.qa-export-save.svelte-1way66v input:where(.svelte-1way66v) {flex:1 1 auto;min-width:0;}`};function e$(r,t){ie(t,!0),Ae(r,CJ);let e={"user-script":"User script","conditional-script":"Conditional script",template:"Template file","capture-template":"Capture template"},n=pe(""),i=pe(Ze(new Set)),o=pe(Ze(new Set)),s=pe(Ze(iq())),a=pe(null),l=pe(null),c=k(()=>Td(t.allChoices)),d=k(()=>GU(f(c),f(n))),u=k(()=>jU(f(c),f(i))),p=k(()=>YU(t.allChoices,f(u),f(o))),m=k(()=>new Map(f(c).map(me=>[me.id,me.path.join(" / ")])));function h(me){let Fe=[];for(let ut of Le(me))Ee(ut)&&Fe.push(ut.id,...h(ut));return Fe}function g(me,Fe){let ut=[me.id,...h(me)],Yt=new Set(f(i)),Kt=new Set(f(o));for(let qt of ut)Fe?(Yt.add(qt),Kt.delete(qt)):(Yt.delete(qt),Kt.add(qt));q(i,Yt,!0),(!Fe||f(o).size>0)&&q(o,Kt,!0)}function v(me){let Fe=f(c).find(Yt=>Yt.id===me);if(!Fe)return;let ut=f(i).has(me);g(Fe.choice,!ut),q(a,null)}function b(){for(let me of f(d))g(me.choice,!0);q(a,null)}function y(){q(i,new Set,!0),q(o,new Set,!0),q(a,null)}function C(me){let{missingChoiceIds:Fe,missingAssets:ut}=me;return Fe.length===0&&ut.length===0?null:{missingChoices:Fe,missingAssets:ut}}async function w(){if(f(u).length===0)return new cs.Notice("Select at least one choice to export."),null;try{let me=await oq(t.app,{choices:t.allChoices,rootChoiceIds:f(u),excludedChoiceIds:Array.from(f(o)),quickAddVersion:t.plugin.manifest.version});return q(a,C(me),!0),me}catch(me){return console.error(me),q(a,null),new cs.Notice(`Export failed: ${me?.message??String(me)}`),null}}async function T(){if(!f(l)){q(l,"copy");try{let me=await w();if(!me)return;let Fe=JSON.stringify(me.pkg,null,2);await navigator.clipboard.writeText(Fe),new cs.Notice(`Copied package (${me.pkg.choices.length} choice${me.pkg.choices.length===1?"":"s"}) to clipboard.`),f(a)?new cs.Notice("Package copied with warnings. Review details below."):t.close()}catch(me){console.error(me),new cs.Notice(`Copy failed: ${me?.message??String(me)}`)}finally{q(l,null)}}}async function P(){if(f(l))return;let me=f(s).trim();if(!me){new cs.Notice("Enter a file path before saving.");return}q(l,"save");try{let Fe=await w();if(!Fe)return;let{overwritten:ut}=await lq(t.app,Fe.pkg,me),Yt=Fe.pkg.choices.length,Kt=`${Yt} choice${Yt===1?"":"s"}`;new cs.Notice(ut?`Overwrote package (${Kt}) at '${me}'.`:`Saved package (${Kt}) to '${me}'.`),f(a)?new cs.Notice("Package saved with warnings. Review details below."):t.close()}catch(Fe){let ut=Fe?.message??String(Fe);if(ut.startsWith("Save cancelled:")){new cs.Notice("Save cancelled.");return}console.error(Fe),new cs.Notice(`Save failed: ${ut}`)}finally{q(l,null)}}var _=wJ(),I=R(_),O=R(I),N=R(O),K=R(N),ne=E(R(K),2);Ct(ne),le(ne,"spellcheck",!1),$(K);var H=E(K,2),D=E(H,2);$(N);var G=E(N,2),V=R(G),M=R(V);{var B=me=>{var Fe=uJ();A(me,Fe)},J=me=>{var Fe=bt(),ut=ae(Fe);gt(ut,17,()=>f(d),Yt=>Yt.id,(Yt,Kt)=>{var qt=mJ(),Qt=R(qt);Ct(Qt);var Se=E(Qt,2),st=re(Se,!0),vr=E(Se,2);{var zt=An=>{var la=pJ(),Y=re(la,!0);Q(de=>ee(Y,de),[()=>f(Kt).path.slice(0,-1).join(" \u203A ")]),A(An,la)};z(vr,An=>{f(Kt).path.length>1&&An(zt)})}var Mo=E(vr,2),vl=re(Mo,!0);$(qt),Q((An,la)=>{tp(qt,`--qa-export-depth: ${f(Kt).depth}`),hd(Qt,An),ee(st,la),ee(vl,f(Kt).choice.type)},[()=>f(i).has(f(Kt).id),()=>f(Kt).path.at(-1)]),ge("change",Qt,()=>v(f(Kt).id)),A(Yt,qt)}),A(me,Fe)};z(M,me=>{f(d).length===0?me(B):me(J,-1)})}$(V),$(G),$(O);var te=E(O,2),W=E(R(te),2);gt(W,21,()=>[["Selected choices",f(p).rootCount],["Total packaged",f(p).totalChoices],["Auto-included",f(p).dependencyCount],["Scripts embedded",f(p).userScripts+f(p).conditionalScripts],["Templates embedded",f(p).templateFiles+f(p).captureTemplates]],([me,Fe])=>me,(me,Fe)=>{var ut=k(()=>ak(f(Fe),2));let Yt=()=>f(ut)[0],Kt=()=>f(ut)[1];var qt=fJ(),Qt=R(qt),Se=R(Qt),st=re(Se,!0);$(Qt);var vr=E(Qt,2),zt=R(vr),Mo=re(zt,!0);$(vr),$(qt),Q(()=>{ee(st,Yt()),ee(Mo,Kt())}),A(me,qt)}),$(W),$(te);var Z=E(te,2);{var se=me=>{var Fe=hJ(),ut=R(Fe),Yt=R(ut),Kt=R(Yt);Qe(Kt,{iconId:"alert-triangle"}),$(Yt),Xt(2),$(ut);var qt=E(ut,2),Qt=R(qt),Se=re(Qt);$(qt),$(Fe),Q(st=>ee(Se,`The following choice IDs were referenced but not found:
- ${st??""}`),[()=>f(p).missingChoiceIds.join(", ")]),A(me,Fe)};z(Z,me=>{f(p).missingChoiceIds.length>0&&me(se)})}var ce=E(Z,2);{var $e=me=>{var Fe=bJ(),ut=R(Fe),Yt=R(ut),Kt=R(Yt);Qe(Kt,{iconId:"alert-triangle"}),$(Yt),Xt(2),$(ut);var qt=E(ut,2),Qt=R(qt);{var Se=zt=>{var Mo=gJ(),vl=re(Mo);Q(An=>ee(vl,`Missing choices:
- ${An??""}`),[()=>f(a).missingChoices.map(An=>f(m).get(An)??An).join(", ")]),A(zt,Mo)};z(Qt,zt=>{f(a).missingChoices.length>0&&zt(Se)})}var st=E(Qt,2);{var vr=zt=>{var Mo=yJ(),vl=E(ae(Mo),2);gt(vl,21,()=>f(a).missingAssets,An=>An.path,(An,la)=>{var Y=vJ(),de=R(Y),Pt=re(de,!0),yr=E(de,2),Ro=re(yr,!0);$(Y),Q(()=>{ee(Pt,f(la).path),ee(Ro,e[f(la).kind])}),A(An,Y)}),$(vl),A(zt,Mo)};z(st,zt=>{f(a).missingAssets.length>0&&zt(vr)})}$(qt),$(Fe),A(me,Fe)};z(ce,me=>{f(a)&&me($e)})}var Xe=E(ce,2),Ye=R(Xe),he=R(Ye),Re=E(R(he),2),Je=R(Re);Ct(Je);var ve=E(Je,2),Ne=R(ve);{var Ie=me=>{var Fe=bs("Saving\u2026");A(me,Fe)},ze=me=>{var Fe=bs("Save");A(me,Fe)};z(Ne,me=>{f(l)==="save"?me(Ie):me(ze,-1)})}$(ve),$(Re),$(he),$(Ye),$(Xe),$(I);var ct=E(I,2),Ke=R(ct),ot=E(Ke,2),or=R(ot);{var Ar=me=>{var Fe=bs("Copying\u2026");A(me,Fe)},zn=me=>{var Fe=bs("Copy JSON");A(me,Fe)};z(or,me=>{f(l)==="copy"?me(Ar):me(zn,-1)})}$(ot),$(ct),$(_),Q(()=>{ve.disabled=f(l)!==null,Ke.disabled=f(l)!==null,ot.disabled=f(l)!==null}),Jn(ne,()=>f(n),me=>q(n,me)),ge("click",H,b),ge("click",D,y),Jn(Je,()=>f(s),me=>q(s,me)),ge("click",ve,P),ge("click",Ke,function(...me){t.close?.apply(this,me)}),ge("click",ot,T),A(r,_),oe()}He(["click","change"]);var hE=class extends cq.Modal{constructor(e,n,i){super(e);this.plugin=n;this.choices=i;this.handle=null}onOpen(){this.modalEl.addClass("quickAddModal","qa-package-modal","packageExportModal"),this.setTitle("Export QuickAdd package"),this.handle=vi(this.contentEl,e$,{app:this.app,plugin:this.plugin,allChoices:this.choices,close:()=>this.close()},{what:"the package exporter"})}onClose(){this.handle?.destroy(),this.handle=null}};var Nq=require("obsidian");var Zv=require("obsidian");je();var E$=require("obsidian");tn();jo();Zt();al();Zt();lt();Hr();function vE(r,t,e){if(!(!r||typeof r!="object")){if(Array.isArray(r)){t.onUnreadable?.();return}if(!e.has(r)){if(e.add(r),t.onChoice?.(r),iu(r))if(Array.isArray(r.choices))for(let n of r.choices)vE(n,t,e);else Wt(r.choices)&&t.onUnreadable?.();ji(r)&&gE(dr(r.macro),t,e)}}}function gE(r,t,e){if(!Array.isArray(r)){Wt(r)&&t.onUnreadable?.();return}for(let n of r){if(!n||typeof n!="object")continue;if(Array.isArray(n)){t.onUnreadable?.();continue}t.onCommand?.(n);let i=n;(n.type==="Conditional"||Array.isArray(i.thenCommands)||Array.isArray(i.elseCommands))&&(gE(i.thenCommands,t,e),gE(i.elseCommands,t,e));let s=n,a=n.type==="NestedChoice"||s.choice&&typeof s.choice=="object"?s.choice:void 0;a&&vE(a,t,e)}}function t$(r,t){let e=new Set;if(Array.isArray(r.choices))for(let i of r.choices)vE(i,t,e);else t.onUnreadable?.();let n=r.macros;if(Array.isArray(n))for(let i of n)gE(dr(i),t,e);else Wt(n)&&t.onUnreadable?.()}function rf(r){let t=!1;return t$(r,{onUnreadable:()=>{t=!0}}),t}function dq(r,t){vE(r,{onChoice:t},new Set)}function nf(r,t){r$(r.settings,t)}function r$(r,t){t$(r,{onChoice:t})}function yE(r,t){t$(r,{onCommand:t})}function xJ(r){return r.type==="AIAssistant"}function bE(r,t,e){let n=0;return yE({choices:r},i=>{if(!xJ(i)||i.modelRef&&i.modelRef.name===i.model&&t.find(l=>l.id===i.modelRef?.providerId)?.models.some(l=>l.name===i.model)||!i.model||i.model==="Ask me")return;let o=t.find(a=>a.models.some(l=>l.name===i.model));if(!o?.id)return;let s={providerId:o.id,name:i.model};i.modelRef=s,n++,e?.(i,s)}),n}ye();Ve();lt();Zr();Cm();tr();ou();Hi();i$();jo();tn();tr();ja();function wE(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="Template"}function TJ(r){return r.fileExistsBehavior?r.fileExistsBehavior:r.setFileExistsBehavior?{kind:"apply",mode:G1(r.fileExistsMode)??"increment"}:r.incrementFileName?{kind:"apply",mode:"increment"}:{kind:"prompt"}}function CE(r){r.fileExistsBehavior=TJ(r),delete r.incrementFileName,delete r.setFileExistsBehavior,delete r.fileExistsMode}function sf(r){if(r==null)return null;if(typeof r=="boolean")return{enabled:r};if(typeof r!="object")return null;let t=r;return{enabled:typeof t.enabled=="boolean"?t.enabled:void 0,direction:t.direction==="horizontal"||t.direction==="vertical"?t.direction:void 0,focus:typeof t.focus=="boolean"?t.focus:void 0}}function af(r,t){let e=r.direction==="horizontal"?"horizontal":"vertical",n=typeof t=="string"&&t!=="default"?t:"default";return en({location:r.enabled?"split":"tab",direction:e,focus:r.focus??!0,mode:n})}Zt();lt();Hr();ou();Xa();function o$(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function mq(r){if(wE(r)&&CE(r),r.type==="Capture"||r.type==="Template"){let i=r,o=sf(i.openFileInNewTab);!i.fileOpening&&o&&(i.fileOpening=af(o,i.openFileInMode))}let t=r.insertAfter;r.type==="Capture"&&o$(t)&&(t.insertAtEnd??(t.insertAtEnd=!1),t.createIfNotFound??(t.createIfNotFound=!1));let e=r.type==="Capture"?new Tc(r.name):r.type==="Template"?new Gs(r.name):void 0;if(!e)return;let n=r;for(let[i,o]of Object.entries(e)){if(o===void 0)continue;let s=n[i];s===void 0?n[i]=o:o$(s)&&o$(o)&&(n[i]={...o,...s})}rw(r)}function EE(r,t,e,n){mq(r);let i=r.id,o=t.get(i)??i;r.id=o;let s=o!==i;if(r.type==="Macro"){let a=r;s&&Qa(a.macro)&&(a.macro.id=Vt()),s$(dr(a.macro),t,e,s,n)}if(r.type==="Multi"){let a=r;Array.isArray(a.choices)&&(a.choices=a.choices.filter(l=>Ee(l)&&e.has(l.id)).map(l=>EE(l,t,e,n)))}return r}function s$(r,t,e,n,i){for(let o of Mt(r))if(Tr(o))switch(ZV(o,i),n&&(o.id=Vt()),o.type){case"Choice":{let s=o,a=t.get(s.choiceId);a&&(s.choiceId=a);break}case"Conditional":{let s=o;s$(s.thenCommands,t,e,n,i),s$(s.elseCommands,t,e,n,i);break}case"NestedChoice":{let s=o;s.choice&&e.has(s.choice.id)?s.choice=EE(s.choice,t,e,i):Ee(s.choice)&&dq(s.choice,mq);break}default:break}}function TE(r,t){for(let e of r){if(!Ee(e))continue;if(e.id===t)return e;let n=TE(Le(e),t);if(n)return n}}function fq(r,t,e){let n=TE(r,t);return n!==void 0&&Le(n).some(i=>Ee(i)&&i.id===e)}function xE(r,t,e){if(!Array.isArray(t.choices)||r&&!Array.isArray(r.choices))return;let n=new Map;for(let o of t.choices)Ee(o)&&n.set(o.id,o);let i=[];for(let o of r?.choices??[]){let s=Ee(o)?n.get(o.id):void 0;if(!s){i.push(o);continue}o.type==="Multi"&&s.type==="Multi"&&xE(o,s,e),i.push(s),n.delete(s.id)}for(let o of n.values()){let s=e.get(o.id);o.type==="Multi"&&xE(s?.type==="Multi"?s:void 0,o,e),i.push(o)}t.choices=i}function l$(r,t){for(let e=0;e<r.length;e++){let n=r[e];if(Ee(n)){if(n.id===t.id)return r.splice(e,1,t),!0;if(l$(Le(n),t))return!0}}return!1}function c$(r,t){for(let e=0;e<r.length;e++){let n=r[e];if(!Ee(n))continue;if(n.id===t)return r.splice(e,1),n;let i=c$(Le(n),t);if(i)return i}}function d$(r,t,e){for(let n of r)if(Ee(n)){if(n.id===t&&n.type==="Multi")return u$(n,e);if(d$(Le(n),t,e))return!0}return!1}function u$(r,t){if(!Array.isArray(r.choices)){if(mo(r))return!1;r.choices=[]}let e=r.choices.findIndex(n=>Ee(n)&&n.id===t.id);return e!==-1?r.choices.splice(e,1,t):r.choices.push(t),!0}function hq(r,t){if(t.length===0)return null;let e=r,n=null;for(let i of t){let o=e.find(s=>Ee(s)&&s.type==="Multi"&&s.name===i);if(!o)return null;n=o,e=Le(o)}return n}function _E(r,t){switch(r.type){case"Macro":{a$(dr(r.macro),t);break}case"Template":{let e=r,n=t.get(xn(e.templatePath))??t.get(e.templatePath);n&&(e.templatePath=n);break}case"Capture":{let e=r,n=e.createFileIfItDoesntExist?.template;if(n){let o=t.get(xn(n))??t.get(n);o&&(e.createFileIfItDoesntExist={...e.createFileIfItDoesntExist,template:o})}let i=e.format;if(i&&typeof i.format=="string"){let o=aE(i.format,t);o!==i.format&&(e.format={...i,format:o})}break}case"Multi":{r.choices?.forEach(n=>_E(n,t));break}default:break}}function pq(r,t){let e=po(r),n=t.get(r)??t.get(e)??e;return n===r?void 0:n}function a$(r,t){for(let e of Mt(r))if(Tr(e))switch(e.type){case"UserScript":{let n=e,i=pq(n.path,t);i&&(n.name===n.path?n.name=i:n.name.startsWith(`${n.path}::`)&&(n.name=i+n.name.slice(n.path.length)),n.path=i);break}case"Conditional":{let n=e;if(n.condition.mode==="script"&&n.condition.scriptPath){let i=pq(n.condition.scriptPath,t);i&&(n.condition={...n.condition,scriptPath:i})}a$(n.thenCommands,t),a$(n.elseCommands,t);break}case"NestedChoice":{let n=e;n.choice&&_E(n.choice,t);break}default:break}}var p$={"user-script":{severity:"critical",label:"SCRIPT",description:"Runs custom JavaScript with full access to your vault and the network."},"conditional-script":{severity:"critical",label:"CONDITIONAL",description:"Runs custom JavaScript to decide which branch executes."},"bundled-script":{severity:"critical",label:"SCRIPT FILE",description:"Bundles a file that will be written to your vault and can be run as code."},"run-on-startup":{severity:"critical",label:"STARTUP",description:"Runs automatically every time Obsidian starts."},"mislabeled-executable":{severity:"critical",label:"EXECUTABLE",description:"A bundled file is run as code even though it is labeled a template."},"registers-command":{severity:"warning",label:"COMMAND",description:"Adds a command to the command palette."},"obsidian-command":{severity:"warning",label:"OBSIDIAN",description:"Triggers another Obsidian command."},ai:{severity:"warning",label:"AI",description:"Sends note content to your AI provider over the network."},"ai-tools":{severity:"critical",label:"AI TOOLS",description:"Lets an AI model read and write your vault: the script gives the model tools (functions) it calls with model-chosen arguments."},"capture-writes":{severity:"warning",label:"WRITES",description:"Writes captured text into your notes."},"template-write":{severity:"warning",label:"TEMPLATE",description:"Creates notes from a bundled template."},"overwrites-existing-choice":{severity:"warning",label:"OVERWRITES",description:"Replaces a choice that already exists in your vault."},"overwrites-existing-file":{severity:"warning",label:"OVERWRITES",description:"Overwrites a file that already exists in your vault."},"missing-reference":{severity:"warning",label:"MISSING",description:"References a file that is not bundled in this package."},"unknown-command":{severity:"warning",label:"UNKNOWN",description:"An unrecognised command type. Review it manually."},"editor-command":{severity:"info",label:"EDITOR",description:"Runs a built-in editor command."},"open-file":{severity:"info",label:"OPEN FILE",description:"Opens a file in your vault."}};function lf(r){return p$[r].severity}function m$(r){return p$[r].label}function f$(r){return p$[r].description}Ve();Wl();lt();Cm();tn();Hi();tr();ou();Wl();tn();tr();al();Zt();lt();Hr();var _J=new Set(Object.values(jt));function Ei(r){return r.filter(t=>!!t).join(" \u203A ")}function g$(r,t){return r.split("::")[0].trim()===t}function gq(r,t,e){return g$(t,e)?Ei(r):`${Ei(r)} (${e})`}function kJ(r){let t=r.name?.trim();return t&&t.length>0?t:String(r.type)}function SJ(r){if(r.mode==="script")return`script: ${r.scriptPath}${r.exportName?` (${r.exportName})`:""}`;let t=r.expectedValue!==void 0?` ${r.expectedValue}`:"";return`${r.variableName} ${r.operator}${t}`}function AJ(r){if(Un(r)){let t=Array.isArray(r.folder?.folders)?r.folder.folders:[];return[["file name format",r.fileNameFormat?.format],...t.map(e=>["folder",e])]}if(sl(r)){let t=r.propertyCapture?.property;return[["capture to",r.captureTo],["capture format",r.format?.format],["insert after",r.insertAfter?.after],["insert before",r.insertBefore?.before],["property name",t?.kind==="named"?t.format:void 0]]}return[]}function vq(r){return typeof r=="string"&&xw(r).length>0}function yq(r,t,e,n=!0){r.inlineScripts.push({setting:Ei(t.slice(1)),text:e}),n&&(r.flags.add("user-script"),r.rows.push({flag:"user-script",severity:"critical",title:"Runs custom JavaScript written into a choice setting",detail:Ei(t)}))}function IJ(r){let t=r.fileExistsBehavior;return!t||t.kind!=="apply"?!1:t.mode==="overwrite"||t.mode==="appendTop"||t.mode==="appendBottom"}function v$(r){let t=[],e=new Set(r.choices.map(n=>n.choice.id));for(let n of r.choices){let i=n.choice,o=Ei(n.pathHint.slice(0,-1))||"Root",s={choiceId:i.id,name:i.name,type:i.type,location:o,registersCommand:!1,flags:new Set,commands:[],usages:[],rows:[],inlineScripts:[]};y$(i,s,[i.name],e,0),t.push(s)}return{choiceWalks:t}}function y$(r,t,e,n,i){if(r.command&&(t.registersCommand=!0,t.flags.add("registers-command")),ji(r)&&(r.runOnStartup&&(t.flags.add("run-on-startup"),t.rows.push({flag:"run-on-startup",severity:"critical",title:"Runs automatically every time Obsidian starts",detail:Ei(e)})),h$(dr(r.macro),t,e,n,i)),Un(r)&&(r.templatePath&&t.usages.push({choiceId:t.choiceId,path:xn(r.templatePath),asScript:!1,impliedKind:"template",breadcrumb:Ei([...e,"template"])}),IJ(r)&&t.flags.add("template-write")),sl(r)){t.flags.add("capture-writes");let s=r.createFileIfItDoesntExist;s?.enabled&&s.createWithTemplate&&s.template&&t.usages.push({choiceId:t.choiceId,path:xn(s.template),asScript:!1,impliedKind:"capture-template",breadcrumb:Ei([...e,"new-file template"])});for(let a of ZP(r))t.usages.push({choiceId:t.choiceId,path:a,asScript:!1,impliedKind:"template",breadcrumb:Ei([...e,"{{TEMPLATE}} include"])})}let o=new Set;for(let[s,a]of AJ(r))vq(a)&&(yq(t,[...e,s],a,!o.has(s)),o.add(s));if(iu(r)&&Array.isArray(r.choices))for(let s of r.choices)Ee(s)&&(n.has(s.id)||y$(s,t,[...e,s.name],n,i))}function h$(r,t,e,n,i){for(let o of Mt(r)){if(!Tr(o))continue;let s=kJ(o),a=[...e,s],l={name:s,type:o.type,depth:i};switch(t.commands.push(l),o.type){case"UserScript":{let c=o;t.flags.add("user-script"),Object.assign(l,{flag:"user-script",scriptPath:c.path}),c.path&&(t.usages.push({choiceId:t.choiceId,path:po(c.path),asScript:!0,impliedKind:"user-script",breadcrumb:Ei(a)}),t.rows.push({flag:"user-script",severity:"critical",title:"Runs custom JavaScript with full access to your vault and the network",detail:gq(a,s,c.path),scriptPath:c.path}));break}case"Conditional":{let c=o,d=c.condition,u=d?SJ(d):void 0,p=d?.mode==="script"&&!!d.scriptPath;if(Object.assign(l,{flag:p?"conditional-script":void 0,scriptPath:p?d.scriptPath:void 0,summary:u}),p){let m=d.scriptPath;t.flags.add("conditional-script"),t.usages.push({choiceId:t.choiceId,path:po(m),asScript:!0,impliedKind:"conditional-script",breadcrumb:Ei(a)}),t.rows.push({flag:"conditional-script",severity:"critical",title:"Runs custom JavaScript chosen by a condition",detail:gq(a,s,m),scriptPath:m})}h$(c.thenCommands??[],t,[...a,"then"],n,i+1),h$(c.elseCommands??[],t,[...a,"else"],n,i+1);break}case"NestedChoice":{let c=o;c.choice&&y$(c.choice,t,[...a,c.choice.name],n,i+1);break}case"Obsidian":{let c=o;t.flags.add("obsidian-command"),t.rows.push({flag:"obsidian-command",severity:"warning",title:"Triggers another Obsidian command",detail:`${Ei(a)}${c.commandId?` (${c.commandId})`:""}`});break}case"AIAssistant":{t.flags.add("ai"),t.rows.push({flag:"ai",severity:"warning",title:"Sends note content to your AI provider over the network",detail:Ei(a)});break}case"EditorCommand":{t.flags.add("editor-command");break}case"OpenFile":{t.flags.add("open-file");let c=o.filePath;vq(c)&&(l.flag="user-script",yq(t,[...a,"file path"],c));break}case"Choice":case"Wait":break;default:{l.type=String(o.type),_J.has(String(o.type))||(t.flags.add("unknown-command"),l.flag="unknown-command",t.rows.push({flag:"unknown-command",severity:"warning",title:"Unknown capability. Review it manually.",detail:`${Ei(a)} (${String(o.type)})`}));break}}}}function PJ(r){return r==="user-script"||r==="conditional-script"}var $J=/\.[cm]?js$/i;function FJ(r,t){let e;try{e=Ys(t)}catch{return null}if($J.test(r))return e;if(!Ss(r))return null;let n=[];if(xt.test(r)){let{code:i}=qs(e);i&&n.push(i)}for(let i of xw(e))n.push(i);return n.length>0?n.join(`
- `):null}var MJ=/\bai\s*\.\s*(?:tools|agent|tool)\b|\btools\s*\.\s*(?:vault|workspace|system)\s*\(/;function RJ(r){return MJ.test(r)}var kE={critical:0,warning:1,info:2};function wq(r){return Array.from(Eq(r,v$(r).choiceWalks).keys())}var DJ=10;function Cq(r){return xr(r.originalPath)}function b$(r){let t=Cq(r),e=po(r.originalPath);return e===t?[t]:[t,e]}function xq(r){return r.assets.filter(t=>yx(t.originalPath))}function Eq(r,t){let e=new Map,n=a=>{if(!a.path)return;let l=e.get(a.path)??[];l.push(a),e.set(a.path,l)};for(let a of t)for(let l of a.usages)n(l);let i=new Map(xq(r).flatMap(a=>b$(a).map(l=>[l,a]))),o=new Set,s=Array.from(e.keys());for(let a=0;a<DJ&&s.length>0;a++){let l=[];for(let c of s){if(o.has(c))continue;let d=i.get(c);if(!d||!Ss(c))continue;let u=(e.get(c)??[]).filter(g=>!g.asScript);if(u.length===0)continue;o.add(c);let p;try{p=Ys(d.content)}catch{continue}let m=_c(p);if(m.size===0)continue;let h=new Map;for(let g of u)h.has(g.choiceId)||h.set(g.choiceId,g);for(let g of m){for(let v of h.values())n({choiceId:v.choiceId,path:g,asScript:!1,impliedKind:"template",breadcrumb:`${v.breadcrumb} \u203A {{TEMPLATE}} include`});o.has(g)||l.push(g)}}s=l}return e}function OJ(r){let t=r.length;if(t===0)return 0;let e=0;return r.endsWith("==")?e=2:r.endsWith("=")&&(e=1),Math.max(0,Math.floor(t*3/4)-e)}function LJ(r,t){return kE[lf(r)]-kE[lf(t)]}function Tq(r,t,e){let{choiceWalks:n}=v$(t),i=new Set(Jt(r).map(_=>_.id)),o=Eq(t,n),s=new Set;for(let[_,I]of o)I.some(O=>O.asScript)&&s.add(_);let a=new Set(xq(t).flatMap(b$)),l=new Map(t.assets.map(_=>[_.originalPath,FJ(Cq(_),_.content)])),c=t.assets.map(_=>{let I=b$(_),O=a.has(I[0]),N=O?I.flatMap(H=>o.get(H)??[]):[],K=I.some(H=>s.has(H)),ne=K||l.get(_.originalPath)!=null;return{originalPath:_.originalPath,kind:_.kind,bundled:!0,executable:K,requiresReview:ne,exists:O&&(I.some(H=>e.has(H))||e.has(_.originalPath)),sizeBytes:OJ(_.content),orphan:N.length===0,referencedBy:N}}),d=n.map(_=>{let I=i.has(_.choiceId),O=Array.from(_.flags);return I&&O.push("overwrites-existing-choice"),O.sort(LJ),{choiceId:_.choiceId,name:_.name,type:_.type,location:_.location,exists:I,registersCommand:_.registersCommand,flags:O,commands:_.commands,inlineScripts:_.inlineScripts}}),u=[];for(let[_,I]of o){if(a.has(_)||e.has(_))continue;let O=I.some(N=>N.asScript);u.push({path:_,asScript:O,breadcrumb:I[0]?.breadcrumb??_})}let p=c.filter(_=>_.orphan).map(_=>_.originalPath),m=[];for(let _ of n)for(let I of _.rows)m.push(I);for(let _ of c)_.executable&&(PJ(_.kind)||m.push({flag:"mislabeled-executable",severity:"critical",title:"Runs a file as code even though it is labeled a template",detail:_.originalPath,scriptPath:_.originalPath}));for(let _ of c)_.requiresReview&&(_.executable||m.push({flag:"bundled-script",severity:"critical",title:"Bundles a file that will be written to your vault and can be run as code",detail:_.originalPath,scriptPath:_.originalPath}));for(let _ of c){let I=l.get(_.originalPath);!I||!RJ(I)||m.push({flag:"ai-tools",severity:"critical",title:"Lets an AI model read and write your vault",detail:_.originalPath,scriptPath:_.originalPath})}let h=d.filter(_=>_.registersCommand).length;h>0&&m.push({flag:"registers-command",severity:"warning",title:"Adds commands to the command palette",detail:`${h} choice${h===1?"":"s"}`});let g=d.filter(_=>_.exists).length;g>0&&m.push({flag:"overwrites-existing-choice",severity:"warning",title:"Replaces choices that already exist in your vault",detail:`${g} choice${g===1?"":"s"}`});let v=c.filter(_=>_.exists).length;if(v>0&&m.push({flag:"overwrites-existing-file",severity:"warning",title:"Overwrites existing files in your vault",detail:`${v} file${v===1?"":"s"}`}),u.length>0){let _=u.filter(I=>I.asScript).length;m.push({flag:"missing-reference",severity:_>0?"critical":"warning",title:_>0?"References scripts that are not bundled, so they run from whatever exists at those paths after import":"References files that are not bundled and not in your vault",detail:`${u.length} reference${u.length===1?"":"s"}`})}m.sort((_,I)=>kE[_.severity]-kE[I.severity]);let b=c.filter(_=>_.requiresReview).map(_=>_.originalPath),y=s.size,C=n.some(_=>_.flags.has("run-on-startup")),w=m.filter(_=>_.severity==="critical").length,T=m.filter(_=>_.severity==="warning").length,P={hasCritical:w>0,hasWarning:T>0,criticalCount:w,warningCount:T,runsOnStartup:C,scriptCount:y,registersCommandCount:h,overwritesChoices:g,overwritesFiles:v,missingCount:u.length};return{quickAddVersion:t.quickAddVersion,createdAt:t.createdAt,choiceCount:t.choices.length,fileCount:t.assets.length,choices:d,files:c,capabilityRows:m,missingReferences:u,orphanAssets:p,criticalScriptPaths:b,summary:P}}var bq=1e5;function NJ(r){return typeof TextEncoder<"u"?new TextEncoder().encode(r).length:r.length}function VJ(r){if(r.length<1e3)return!1;let t=0,e=1,n=0;for(let o=0;o<r.length;o++)r[o]===`
- `?(n>t&&(t=n),n=0,e++):n++;n>t&&(t=n);let i=r.length/e;return t>1e3||i>250}function w$(r){let t=r.length>bq,e=t?r.slice(0,bq):r;return{found:!0,text:e,truncated:t,sizeBytes:NJ(r),looksMinified:VJ(e)}}function SE(r,t){let e=r.assets.find(n=>n.originalPath===t);if(!e)return{found:!1,text:"",truncated:!1,sizeBytes:0,looksMinified:!1,error:"File is not bundled in this package."};try{return w$(Ys(e.content))}catch(n){return{found:!0,text:"",truncated:!1,sizeBytes:0,looksMinified:!1,error:n instanceof Error?n.message:String(n)}}}function AE(r){return r.summary.hasCritical}function _q(r,t,e){let n=r.criticalScriptPaths.filter(o=>!t.has(o)).length,i=r.choices.filter(o=>o.inlineScripts.length>0&&!e.has(o.choiceId)).length;return n+i}Hr();tn();Zt();lt();function Yv(r){let t;try{t=JSON.parse(r)}catch(o){throw new Error(`Package content is not valid JSON: ${o?.message??o}`)}if(!tq(t))throw new Error("Content is not a valid QuickAdd package.");if(t.schemaVersion>1)throw new Error(`Package schema version ${t.schemaVersion} is newer than this plugin supports (${1}).`);let e=BJ(t.assets);if(e!==null)throw new Error(`Package contains duplicate asset path "${e}". Each asset must have a unique path.`);let n=UJ(t.choices);if(n!==null)throw new Error(`Package contains conflicting definitions for choice "${n}". Each choice id must describe the same choice everywhere it appears.`);let i=qJ(t.choices);if(i!==null)throw new Error(`Package choice "${i}" names a parent that does not list it as a child. Each parented choice must appear inside its parent.`);return t}function BJ(r){let t=new Set;for(let e of r){let n=xr(e.originalPath??"");if(t.has(n))return e.originalPath;t.add(n)}return null}function UJ(r){let t=new Map,e=null,n=i=>{if(e!==null||!i||typeof i!="object")return;let o=i.id;if(typeof o=="string"){let s=x$(i),a=t.get(o);if(a===void 0)t.set(o,s);else if(a!==s){e=o;return}}if(i.type==="Multi"){let s=i;if(Array.isArray(s.choices))for(let a of s.choices)n(a)}i.type==="Macro"&&C$(Mt(dr(i.macro)),n)};for(let i of r){if(e!==null)break;n(i?.choice)}return e}function C$(r,t){if(Array.isArray(r)){for(let e of r)if(e){if(e.type==="NestedChoice")t(e.choice);else if(e.type==="Conditional"){let n=e;C$(n.thenCommands,t),C$(n.elseCommands,t)}}}}function x$(r){if(r===null||typeof r!="object"){let n=JSON.stringify(r);return n===void 0?"\0undefined":n}if(Array.isArray(r))return`[${r.map(x$).join(",")}]`;let t=r;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${x$(t[n])}`).join(",")}}`}function qJ(r){let t=new Map(r.map(e=>[e.choice.id,e]));for(let e of r){let n=e.parentChoiceId;if(n===null)continue;let i=t.get(n);if(!i)continue;let o=i.choice;if(!Le(o).some(a=>a?.id===e.choice.id))return e.choice.id}return null}async function IE(r,t){if(Ut(t))throw new Error(`Refusing to read a package outside the vault: "${t}".`);let e=(0,E$.normalizePath)(t.trim());if(!e)throw new Error("Package path cannot be empty.");if(!await r.vault.adapter.exists(e))throw new Error(`Package file not found: ${e}`);let i=await r.vault.adapter.read(e);return{pkg:Yv(i),path:e}}async function PE(r,t,e){let n=new Map(Jt(t).map(s=>[s.id,s])),i=e.choices.map(s=>({choiceId:s.choice.id,name:s.choice.name,parentChoiceId:s.parentChoiceId,pathHint:s.pathHint??[],exists:n.has(s.choice.id)})),o=[];for(let s of e.assets){let a=Ut(s.originalPath)?!1:await r.vault.adapter.exists(s.originalPath);o.push({originalPath:s.originalPath,exists:a,kind:s.kind})}return{choiceConflicts:i,assetConflicts:o}}async function cf(r,t,e){let n=new Set([...e.assets.flatMap(a=>yx(a.originalPath)?[a.originalPath,xr(a.originalPath)]:[]),...wq(e)]),i=new Set;await Promise.all(Array.from(n,async a=>{a&&(Ut(a)||await kq(r,a)&&i.add(a))}));let o=Tq(t,e,i),{summary:s}=o;return S.logMessage(`QuickAdd import preview: choices=${o.choiceCount} files=${o.fileCount} scripts=${s.scriptCount} runOnStartup=${s.runsOnStartup} registersCommands=${s.registersCommandCount} overwritesChoices=${s.overwritesChoices} overwritesFiles=${s.overwritesFiles} missing=${s.missingCount} critical=${s.criticalCount} warning=${s.warningCount}`),o}function zJ(r){let e=(r??"").trim();if(!e)throw new Error("Package asset has an empty destination path.");let n=e.replace(/\\/g,"/");if(n.startsWith("/")||/^[a-zA-Z]:/.test(n))throw new Error(`Refusing to import asset to an absolute path outside the vault: "${n}".`);let i=(0,E$.normalizePath)(e);if(!i||i.trim()==="")throw new Error("Package asset has an empty destination path.");let o=i.split("/").filter(a=>a.length>0);if(o.some(a=>a===".."))throw new Error(`Refusing to import asset with a path-traversal segment ("..") in: "${i}".`);if(o.find(a=>a.startsWith(".")&&!a.startsWith("..%")))throw new Error(`Refusing to import asset into a config directory: "${i}".`);return i}async function $E(r){let{app:t,existingChoices:e,pkg:n}=r,i=new Map(r.choiceDecisions.map(D=>[D.choiceId,D.mode])),o=new Map(r.assetDecisions.map(D=>[D.originalPath,D])),s=new Map(n.choices.map(D=>[D.choice.id,D])),a=uE(n.assets,"import"),l=new Set(n.choices.filter(D=>i.get(D.choice.id)!=="skip").map(D=>D.choice.id)),c=new Map,d=new Set,u=new Map,p=D=>{if(!l.has(D))return!1;let G=c.get(D);if(G!==void 0)return G;if(d.has(D))return c.set(D,!1),!1;d.add(D);try{let V=s.get(D)?.parentChoiceId,M=i.get(D)==="duplicate"||!!(V&&(i.get(V)==="duplicate"||l.has(V)&&p(V)));return c.set(D,M),M}finally{d.delete(D)}};for(let D of n.choices){if(!l.has(D.choice.id))continue;let V=p(D.choice.id)?Vt():D.choice.id;u.set(D.choice.id,V)}let m=new Set(Jt(e).map(D=>D.id)),h=n.choices.filter(D=>l.has(D.choice.id)&&(i.get(D.choice.id)??"import")==="import"&&u.get(D.choice.id)===D.choice.id&&m.has(D.choice.id));if(h.length>0){let D=h.map(G=>`"${G.choice.name}"`).join(", ");throw new Error(`Already in this vault: ${D}. Import only adds new choices, so choose overwrite, duplicate or skip for ${h.length===1?"it":"them"}.`)}let g=ke(e),v=[],b=[],y=[],C=new Map;for(let D of n.choices){if(!l.has(D.choice.id)){y.push(D.choice.id);continue}let G=ke(D.choice),V=EE(G,u,l,{secretOptionNamesByPath:a,stripUnknownStringSettings:!0});C.set(D.choice.id,V)}let w=n.assets.map(D=>{let V=o.get(D.originalPath)?.destinationPath?.trim(),M=zJ(V||D.originalPath);return{asset:D,destinationPath:M}}),T=new Map;for(let{asset:D,destinationPath:G}of w)T.set(D.originalPath,G),T.set(xr(D.originalPath),G);for(let D of C.values())_E(D,T);r.aiProviders?.length&&bE(Array.from(C.values()),r.aiProviders);let P=new Set,_=[],I=new Map;for(let D of n.choices){let G=D.choice.id,V=D.parentChoiceId;if(!l.has(G)||!V||!l.has(V))continue;let M=u.get(G)??G,B=u.get(V)??V;if(fq(g,B,M))continue;let J=c$(g,M);J?.type==="Multi"&&I.set(M,J)}for(let D of n.choices){let G=D.choice.id;if(!l.has(G)||P.has(G))continue;let V=C.get(G);if(!V)continue;let M=V.id,B=i.get(G)??"import",J=D.parentChoiceId;if(J&&l.has(J)?C.get(J):null){P.add(G),_.push({finalId:M});continue}if(V.type==="Multi"){let Z=TE(g,M);xE(Z?.type==="Multi"?Z:void 0,V,I)}if((B==="overwrite"||B==="import")&&l$(g,V)){b.push(M),P.add(G);continue}if(J){let Z=u.get(J)??J;if(d$(g,Z,V)){v.push(M),P.add(G);continue}let ce=hq(g,D.pathHint.slice(0,-1));if(ce&&u$(ce,V)){v.push(M),P.add(G);continue}S.logWarning(`QuickAdd import: could not locate parent for '${D.choice.name}'. Adding to root.`)}let W=g.findIndex(Z=>Ee(Z)&&Z.id===M);W!==-1?(g.splice(W,1,V),b.push(M)):(g.push(V),v.push(M)),P.add(G)}for(let{finalId:D}of _)m.has(D)?b.push(D):v.push(D);let O=[],N=[],K=await WJ(t),ne=new Map;for(let{asset:D,destinationPath:G}of w){if(o.get(D.originalPath)?.mode==="skip")continue;let V=K?G.toLowerCase():G,M=ne.get(V);if(M)throw new Error(`Refusing to import: assets "${M.originalPath}" and "${D.originalPath}" resolve to the same destination ("${G}"). Rename one so each imported file is unique.`);ne.set(V,{originalPath:D.originalPath,destinationPath:G})}for(let{destinationPath:D}of w)await of(t,D);let H=[];for(let{asset:D,destinationPath:G}of w){let V=o.get(D.originalPath),M=await kq(t,G);if((V?.mode??(M?"overwrite":"write"))==="skip"){N.push(G);continue}if(M&&(await t.vault.adapter.stat(G))?.type==="folder")throw new Error(`Refusing to import: "${G}" is a folder. Choose a file path for "${D.originalPath}".`);H.push({asset:D,destinationPath:G})}for(let{asset:D,destinationPath:G}of H){await mE(t,G);let V=HJ(D,G,T);await t.vault.adapter.write(G,V),O.push(G)}return{updatedChoices:g,addedChoiceIds:v,overwrittenChoiceIds:b,skippedChoiceIds:y,writtenAssets:O,skippedAssets:N}}function HJ(r,t,e){let n=Ys(r.content);return!(r.kind==="template"||r.kind==="capture-template")||!Ss(t)||xt.test(t)&&qs(n).code?n:aE(n,e)}async function kq(r,t){try{return await r.vault.adapter.exists(t)}catch{return!1}}async function WJ(r){let t=r.vault.configDir;if(!t)return!1;let e=t===t.toLowerCase()?t.toUpperCase():t.toLowerCase();if(e===t)return!1;try{return await r.vault.adapter.exists(e)}catch{return!1}}var FE=require("obsidian");function Kv(r,t){return t&&(0,FE.setTooltip)(r,t),{update(e){(0,FE.setTooltip)(r,e??"")},destroy(){(0,FE.setTooltip)(r,"")}}}var GJ=F("<span> </span>"),jJ={hash:"svelte-vwgq2t",code:".qa-capability-flair.svelte-vwgq2t {margin-inline-start:0;cursor:help;}"};function Qv(r,t){ie(t,!0),Ae(r,jJ);let e=k(()=>lf(t.flag)),n=k(()=>m$(t.flag)),i=k(()=>f$(t.flag));var o=GJ();let s;var a=re(o,!0);Ft(o,(l,c)=>Kv?.(l,c),()=>f(i)),Q(()=>{s=Ge(o,1,"flair qa-capability-flair svelte-vwgq2t",null,s,{"qa-flair-critical":f(e)==="critical","qa-flair-warning":f(e)==="warning"}),ee(a,f(n))}),A(r,o),oe()}var YJ=F('<span class="qa-import-banner-detail svelte-1l3m8bg"> </span>'),KJ=F('<li class="svelte-1l3m8bg"><!> <span class="qa-import-banner-title svelte-1l3m8bg"> </span> <!></li>'),QJ=F(`<p class="qa-import-banner-note svelte-1l3m8bg">Importing doesn't run startup macros. They first run the next time
- Obsidian starts or you reload QuickAdd.</p>`),XJ=F('<section class="callout qa-import-banner svelte-1l3m8bg" aria-labelledby="qa-import-banner-title"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner" id="qa-import-banner-title">What this package can do</div></div> <div class="callout-content svelte-1l3m8bg"><ul class="qa-import-banner-rows svelte-1l3m8bg"></ul> <!></div></section>'),JJ={hash:"svelte-1l3m8bg",code:`.qa-import-banner.svelte-1l3m8bg {margin:0;}
- /* Setting-row text size, so the callout sits level with the cards. */.qa-import-banner.svelte-1l3m8bg .callout-content:where(.svelte-1l3m8bg) {padding-top:var(--size-4-2);font-size:var(--font-ui-small);}.qa-import-banner-rows.svelte-1l3m8bg {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:var(--size-4-2);}
- /* The flair is an inline lead-in to the sentence, so long titles wrap
- full-width under it instead of leaving a dead column beside it. */.qa-import-banner-rows.svelte-1l3m8bg li:where(.svelte-1l3m8bg) {line-height:var(--line-height-tight);}.qa-import-banner-title.svelte-1l3m8bg {margin-inline-start:var(--size-4-1);}.qa-import-banner-detail.svelte-1l3m8bg {display:block;margin-top:var(--size-2-1);font-size:var(--font-ui-smaller);color:var(--text-muted);overflow-wrap:anywhere;}.qa-import-banner-note.svelte-1l3m8bg {margin:var(--size-4-3) 0 0;font-size:var(--font-ui-smaller);color:var(--text-muted);}`};function T$(r,t){ie(t,!0),Ae(r,JJ);let e=k(()=>t.preview.summary.hasCritical);var n=XJ(),i=R(n),o=R(i),s=R(o);{let u=k(()=>f(e)?"zap":"alert-triangle");Qe(s,{get iconId(){return f(u)}})}$(o),Xt(2),$(i);var a=E(i,2),l=R(a);gt(l,21,()=>t.preview.capabilityRows,u=>u.flag+u.detail,(u,p)=>{var m=KJ(),h=R(m);Qv(h,{get flag(){return f(p).flag}});var g=E(h,2),v=re(g,!0),b=E(g,2);{var y=C=>{var w=YJ(),T=re(w,!0);Q(()=>ee(T,f(p).detail)),A(C,w)};z(b,C=>{f(p).detail&&C(y)})}$(m),Q(()=>ee(v,f(p).title)),A(u,m)}),$(l);var c=E(l,2);{var d=u=>{var p=QJ();A(u,p)};z(c,u=>{t.preview.summary.runsOnStartup&&u(d)})}$(a),$(n),Q(()=>le(n,"data-callout",f(e)?"danger":"warning")),A(r,n),oe()}var ZJ=F('<p class="qa-code-preview-note mod-error svelte-azzakv"> </p>'),eZ=F(`<p class="qa-code-preview-note mod-warning svelte-azzakv">Minified: cannot be visually reviewed. Import only if you trust
- the source.</p>`),tZ=F('<p class="qa-code-preview-note mod-warning svelte-azzakv"> </p>'),rZ=F('<!> <span class="qa-visually-hidden"> </span> <pre tabindex="0" role="region"> </pre> <!>',1),nZ=F('<div class="qa-code-preview svelte-azzakv"><!></div>'),iZ={hash:"svelte-azzakv",code:`.qa-code-preview.svelte-azzakv {display:flex;flex-direction:column;gap:var(--size-4-2);}.qa-code-preview-note.svelte-azzakv {margin:0;font-size:var(--font-ui-smaller);}.qa-code-preview-note.mod-error.svelte-azzakv {color:var(--text-error);}
- /* Obsidian's code-block look. The card already uses --code-background, so
- the block sits on the modal background instead to stay distinct. */.qa-code-preview-code.svelte-azzakv {margin:0;max-height:240px;overflow:auto;padding:var(--size-4-3) var(--size-4-4);border-radius:var(--code-radius);background-color:var(--background-primary);color:var(--code-normal);font-family:var(--font-monospace);font-size:var(--code-size);line-height:var(--line-height-normal);white-space:pre;tab-size:4;user-select:text;}.qa-code-preview-code.mod-wrap.svelte-azzakv {white-space:pre-wrap;overflow-wrap:anywhere;}.qa-code-preview-code.svelte-azzakv:focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:-2px;}`};function Xv(r,t){let e=$i();ie(t,!0),Ae(r,iZ);let n=X(t,"wrap",3,!1),i=`${e}-label`;var o=nZ(),s=R(o);{var a=c=>{var d=ZJ(),u=re(d);Q(()=>ee(u,`Preview unavailable: ${t.content.error??""}`)),A(c,d)},l=c=>{var d=rZ(),u=ae(d);{var p=w=>{var T=eZ();A(w,T)};z(u,w=>{t.content.looksMinified&&w(p)})}var m=E(u,2),h=re(m,!0),g=E(m,2);let v;var b=re(g,!0),y=E(g,2);{var C=w=>{var T=tZ(),P=re(T);Q(()=>ee(P,`Preview truncated. The full ${t.executable?"script will run":"file will be imported"}.`)),A(w,T)};z(y,w=>{t.content.truncated&&w(C)})}Q(()=>{le(m,"id",i),ee(h,t.label),v=Ge(g,1,"qa-code-preview-code svelte-azzakv",null,v,{"mod-wrap":n()}),le(g,"aria-labelledby",i),ee(b,t.content.text)}),A(c,d)};z(s,c=>{t.content.error?c(a):c(l,-1)})}$(o),A(r,o),oe()}var oZ=F('<span class="flair qa-import-file-flair qa-flair-critical svelte-4j5ctu">Executable</span>'),sZ=F('<span class="flair qa-import-file-flair svelte-4j5ctu">Unused</span>'),aZ=F('<span class="qa-import-reviewed"><!> Reviewed</span>'),lZ=F('<span class="qa-import-file-folder svelte-4j5ctu">The destination is a folder. Add a file name.</span>'),cZ=F("<span> </span>"),dZ=F(`<div class="setting-item-description mod-warning" role="note">Won't be written. Any choice that uses this script will run
- whatever file already exists at this path after import, not the
- contents you reviewed.</div>`),uZ=F("<option>Overwrite</option>"),pZ=F('<div class="qa-import-file-preview svelte-4j5ctu"><!></div>'),mZ=F('<div class="setting-items qa-import-file"><div class="setting-item qa-import-file-main svelte-4j5ctu"><div class="setting-item-info"><div class="setting-item-name qa-import-file-name svelte-4j5ctu"><span class="qa-import-file-icon svelte-4j5ctu"><!></span> <span class="qa-import-file-label svelte-4j5ctu"> </span> <!> <!> <!></div> <div class="setting-item-description"><!> </div> <!> <button type="button" class="qa-link-button qa-import-file-toggle svelte-4j5ctu"><span><!></span> <span> </span></button></div> <div class="setting-item-control"><label class="qa-visually-hidden"> </label> <select class="dropdown"><option>Write</option><!><option>Skip</option></select></div> <div><div class="qa-import-file-preview-inner svelte-4j5ctu"><!></div></div></div> <div class="setting-item qa-import-file-destination svelte-4j5ctu"><div class="setting-item-info svelte-4j5ctu"><label class="setting-item-name">Destination <span class="qa-visually-hidden"> </span></label></div> <div class="setting-item-control"><input type="text" placeholder="vault/path/to/file" class="svelte-4j5ctu"/></div></div></div>'),fZ={hash:"svelte-4j5ctu",code:`.qa-import-file-name.svelte-4j5ctu {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-1) var(--size-4-2);}.qa-import-file-icon.svelte-4j5ctu {display:inline-flex;color:var(--text-muted);--icon-size: var(--icon-s);}.qa-import-file-label.svelte-4j5ctu {min-width:0;overflow-wrap:anywhere;}.qa-import-file-flair.svelte-4j5ctu {margin-inline-start:0;cursor:help;}.qa-import-file-folder.svelte-4j5ctu {color:var(--text-error);}
- /* The path is the point of this row: let the input take the width the
- short "Destination" name leaves over. */.qa-import-file-destination.svelte-4j5ctu {align-items:center;}.qa-import-file-destination.svelte-4j5ctu .setting-item-info:where(.svelte-4j5ctu) {flex:0 0 auto;}.qa-import-file-destination.svelte-4j5ctu input:where(.svelte-4j5ctu) {flex:1 1 auto;min-width:0;}.qa-import-file-destination.svelte-4j5ctu input:where(.svelte-4j5ctu):disabled {opacity:0.5;cursor:not-allowed;}
- /* The preview opens under the row at full width. No row gap, so the
- collapsed preview adds no space; the preview pads itself instead. */.qa-import-file-main.svelte-4j5ctu {flex-wrap:wrap;row-gap:0;}.qa-import-file-toggle.svelte-4j5ctu {margin-top:var(--size-4-1);font-size:var(--font-ui-smaller);}.qa-import-file-preview-wrap.svelte-4j5ctu {flex-basis:100%;min-width:0;}
- /* Pulls the glyph's built-in side bearing back to the text edge. */.qa-import-file-chevron.svelte-4j5ctu {display:inline-flex;margin-inline-start:-3px;transition:transform 150ms ease;}.qa-import-file-chevron.open.svelte-4j5ctu {transform:rotate(90deg);}.qa-import-file-preview-wrap.svelte-4j5ctu {display:grid;grid-template-rows:0fr;transition:grid-template-rows 200ms ease;}.qa-import-file-preview-wrap.open.svelte-4j5ctu {grid-template-rows:1fr;}.qa-import-file-preview-inner.svelte-4j5ctu {overflow:hidden;min-height:0;}.qa-import-file-preview.svelte-4j5ctu {padding-top:var(--size-4-3);}
- @media (prefers-reduced-motion: reduce) {.qa-import-file-chevron.svelte-4j5ctu,
- .qa-import-file-preview-wrap.svelte-4j5ctu {transition:none;}
- }`};function _$(r,t){let e=$i();ie(t,!0),Ae(r,fZ);let n=X(t,"destinationIsFolder",3,!1),i=X(t,"reviewed",3,!1),o=pe(!1),s=k(()=>f(o)?SE(t.pkg,t.file.originalPath):null),a=`${e}-preview`,l=`${e}-destination`,c=`${e}-action`,d=`${e}-folder`,u=k(()=>t.file.originalPath.split("/").pop()??t.file.originalPath);function p(Se){return Se<1024?`${Se} B`:Se<1024*1024?`${(Se/1024).toFixed(1)} KB`:`${(Se/(1024*1024)).toFixed(1)} MB`}function m(){q(o,!f(o)),f(o)&&t.file.requiresReview&&t.onReviewed(t.file.originalPath)}function h(Se){t.onPathInput(Se.currentTarget.value)}function g(Se){t.onModeChange(Se.currentTarget.value)}var v=mZ(),b=R(v),y=R(b),C=R(y),w=R(C),T=R(w);{let Se=k(()=>t.destinationExists?"file-warning":"file-plus");Qe(T,{get iconId(){return f(Se)}})}$(w);var P=E(w,2),_=re(P,!0),I=E(P,2);{var O=Se=>{var st=oZ();Ft(st,(vr,zt)=>Kv?.(vr,zt),()=>"Runs as code when its choice runs. It can read, change, or delete files in your vault and access the network."),A(Se,st)};z(I,Se=>{t.file.executable&&Se(O)})}var N=E(I,2);{var K=Se=>{var st=sZ();Ft(st,(vr,zt)=>Kv?.(vr,zt),()=>"Bundled in this package but not referenced by any choice."),A(Se,st)};z(N,Se=>{t.file.orphan&&Se(K)})}var ne=E(N,2);{var H=Se=>{var st=aZ(),vr=R(st);Qe(vr,{iconId:"check",size:14}),Xt(),$(st),A(Se,st)};z(ne,Se=>{i()&&t.mode!=="skip"&&t.file.requiresReview&&Se(H)})}$(C);var D=E(C,2),G=R(D);{var V=Se=>{var st=lZ();Q(()=>le(st,"id",d)),A(Se,st)},M=Se=>{var st=cZ();let vr;var zt=re(st,!0);Q(()=>{vr=Ge(st,1,"",null,vr,{"mod-warning":t.destinationExists}),ee(zt,t.destinationExists?"Will overwrite":"New file")}),A(Se,st)};z(G,Se=>{n()?Se(V):Se(M,-1)})}var B=E(G);$(D);var J=E(D,2);{var te=Se=>{var st=dZ();A(Se,st)};z(J,Se=>{t.file.requiresReview&&t.mode==="skip"&&Se(te)})}var W=E(J,2),Z=R(W);let se;var ce=R(Z);Qe(ce,{iconId:"chevron-right",size:14}),$(Z);var $e=E(Z,2),Xe=re($e,!0);$(W),$(y);var Ye=E(y,2),he=R(Ye),Re=re(he),Je=E(he,2),ve=R(Je);ve.value=ve.__value="write";var Ne=E(ve);{var Ie=Se=>{var st=uZ();st.value=st.__value="overwrite",A(Se,st)};z(Ne,Se=>{t.destinationExists&&Se(Ie)})}var ze=E(Ne);ze.value=ze.__value="skip",$(Je);var ct;Pl(Je),$(Ye);var Ke=E(Ye,2);let ot;var or=R(Ke),Ar=R(or);{var zn=Se=>{var st=pZ(),vr=R(st);{let zt=k(()=>`Contents of ${t.file.originalPath}`);Xv(vr,{get content(){return f(s)},get label(){return f(zt)},get executable(){return t.file.executable}})}$(st),A(Se,st)};z(Ar,Se=>{f(s)&&Se(zn)})}$(or),$(Ke),$(b);var me=E(b,2),Fe=R(me),ut=R(Fe),Yt=E(R(ut)),Kt=re(Yt);$(ut),$(Fe);var qt=E(Fe,2),Qt=R(qt);Ct(Qt),$(qt),$(me),$(v),Q(Se=>{ee(_,f(u)),ee(B,` \xB7 ${Se??""}`),le(W,"aria-expanded",f(o)),le(W,"aria-controls",a),se=Ge(Z,1,"qa-import-file-chevron svelte-4j5ctu",null,se,{open:f(o)}),ee(Xe,f(o)?"Hide contents":"View contents"),le(he,"for",c),ee(Re,`Action for ${t.file.originalPath??""}`),le(Je,"id",c),ct!==(ct=t.mode)&&(Je.value=(Je.__value=ct)??"",Il(Je,ct)),ot=Ge(Ke,1,"qa-import-file-preview-wrap svelte-4j5ctu",null,ot,{open:f(o)}),le(Ke,"id",a),le(ut,"for",l),ee(Kt,`for ${t.file.originalPath??""}`),le(Qt,"id",l),Xn(Qt,t.destinationPath),le(Qt,"aria-invalid",n()),le(Qt,"aria-describedby",n()?d:void 0),Qt.disabled=t.mode==="skip"},[()=>p(t.file.sizeBytes)]),ge("click",W,m),ge("change",Je,g),ge("input",Qt,h),A(r,v),oe()}He(["click","change","input"]);var hZ=F('<section class="qa-import-ack"><label><input id="qa-import-ack-checkbox" type="checkbox" class="svelte-w06gp4"/> <span> </span></label></section>'),gZ={hash:"svelte-w06gp4",code:".qa-import-ack-label.svelte-w06gp4 {display:flex;align-items:flex-start;gap:var(--size-4-2);font-size:var(--font-ui-small);line-height:var(--line-height-tight);cursor:var(--cursor);}.qa-import-ack-label.is-disabled.svelte-w06gp4 {cursor:not-allowed;color:var(--text-muted);}.qa-import-ack-label.svelte-w06gp4 input:where(.svelte-w06gp4) {flex-shrink:0;margin:0;}"};function k$(r,t){ie(t,!0),Ae(r,gZ);let e=X(t,"acknowledged",15,!1),n=k(()=>(t.preview?.criticalScriptPaths.length??0)+(t.preview?.choices.filter(p=>p.inlineScripts.length>0).length??0)),i=k(()=>t.preview?.missingReferences.some(p=>p.asScript)??!1),o=k(()=>f(n)>0?f(i)?"I have reviewed each script shown above and trust the source, including scripts that are not included and cannot be shown.":"I have reviewed each script above and trust the source.":f(i)?"This package runs scripts that are not included and cannot be reviewed. I trust the source.":"I understand this package can run code, and I trust the source.");var s=hZ(),a=R(s);let l;var c=R(a);Ct(c);var d=E(c,2),u=re(d,!0);$(a),$(s),Q(()=>{l=Ge(a,1,"qa-import-ack-label svelte-w06gp4",null,l,{"is-disabled":!t.fullyReviewed}),hd(c,e()),c.disabled=!t.fullyReviewed,le(c,"aria-describedby",t.reasonId),ee(u,f(o))}),ge("change",c,p=>e(p.currentTarget.checked)),A(r,s),oe()}He(["change"]);var su=require("obsidian");tr();Hi();function RE(r,t){return r==="skip"?r:t&&r==="write"?"overwrite":!t&&r==="overwrite"?"write":r}function Jv(r,t){return!t&&r==="overwrite"?"import":r}function DE(r,t){let[e]=ei(t),n=r.kind==="template"||r.kind==="capture-template";if(e&&n){let i=r.originalPath.split("/").pop()??r.originalPath;return`${e}/${i}`}return r.originalPath}function Sq(r,t,e){let n=t(r),i=r.exists||e(n);return{mode:i?"overwrite":"write",destinationPath:n,destinationExists:i}}function Aq(r,t){let e=t(r);return{mode:e?"overwrite":"write",destinationPath:r,destinationExists:e}}function Iq(r,t,e){let n=new Map;for(let i of r)n.set(i.originalPath,Sq(i,t,e));return n}function Pq(r,t,e,n){return r.get(t.originalPath)??Sq(t,e,n)}function $q(r){let t=new Map;for(let e of r)t.set(e.choiceId,e.exists?"overwrite":"import");return t}function Fq(r,t,e){let n=new Map(r);return n.set(t,e),n}function Mq(r,t,e,n){let i=r.get(t)??Aq(t,n),o=new Map(r);return o.set(t,{...i,mode:e}),o}function Rq(r,t,e,n){let i=r.get(t)??Aq(t,n),o=e.trim(),s=o||t,a=o||e,l=n(s),c=new Map(r);return c.set(t,{...i,mode:RE(i.mode,l),destinationPath:a,destinationExists:l}),{decisions:c,effectivePath:s}}function Dq(r,t,e){let n=r.get(t);if(!n||n.destinationExists===e)return r;let i=new Map(r);return i.set(t,{...n,destinationExists:e,mode:RE(n.mode,e)}),i}function Oq(r,t){return r.map(e=>({choiceId:e.choiceId,mode:Jv(t.get(e.choiceId)??"import",e.exists)}))}function Lq(r,t,e){return r.map(n=>{let i=t.get(n.originalPath),o=i?.destinationPath?.trim()||n.originalPath,s=i?.destinationExists??(n.exists||e(o)),a=i?.mode??(s?"overwrite":"write");return{originalPath:n.originalPath,destinationPath:o,mode:a}})}var ME=class{constructor(t){this.app=t;this.tokens=new Map}indexed(t){let e=t.trim();return!e||Ut(e)?null:this.app.vault.getAbstractFileByPath((0,su.normalizePath)(e))}optimistic(t){return this.indexed(t)instanceof su.TFile}isFolder(t){return this.indexed(t)instanceof su.TFolder}async resolve(t){let e=t.trim();if(!e||Ut(e))return!1;try{return(await this.app.vault.adapter.stat((0,su.normalizePath)(e)))?.type==="file"}catch{return!1}}schedule(t,e,n){let i=(this.tokens.get(t)??0)+1;this.tokens.set(t,i),this.resolve(e).then(o=>{this.tokens.get(t)===i&&n(o)})}};var vZ=F('<span class="qa-macro-command-type svelte-131fx5e"> </span>'),yZ=F('<code class="svelte-131fx5e"> </code>'),bZ=F('<span class="qa-macro-command-summary svelte-131fx5e"> </span>'),wZ=F('<li class="svelte-131fx5e"><span class="qa-macro-command-name"> </span> <!> <!></li>'),CZ=F('<ul class="qa-macro-commands svelte-131fx5e"></ul>'),xZ={hash:"svelte-131fx5e",code:`
- /* Obsidian's outline/file-tree indentation guide on the left. */.qa-macro-commands.svelte-131fx5e {list-style:none;margin:0;padding:0 0 0 var(--size-4-3);border-inline-start:var(--nav-indentation-guide-width, 1px) solid
- var(--nav-indentation-guide-color, var(--background-modifier-border));display:flex;flex-direction:column;gap:var(--size-4-1);}.qa-macro-commands.svelte-131fx5e li:where(.svelte-131fx5e) {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-1) var(--size-4-2);padding-inline-start:calc(var(--qa-macro-depth, 0) * var(--size-4-4));font-size:var(--font-ui-smaller);line-height:var(--line-height-tight);}.qa-macro-command-type.svelte-131fx5e,
- .qa-macro-command-summary.svelte-131fx5e {color:var(--text-muted);}.qa-macro-commands.svelte-131fx5e code:where(.svelte-131fx5e) {font-family:var(--font-monospace);font-size:var(--code-size);color:var(--text-muted);overflow-wrap:anywhere;}`};function S$(r,t){ie(t,!0),Ae(r,xZ);let e={UserScript:"User script",Conditional:"Conditional",NestedChoice:"Nested choice",Obsidian:"Obsidian command",Choice:"Choice",Wait:"Wait",EditorCommand:"Editor command",AIAssistant:"AI assistant",OpenFile:"Open file"};function n(o){return e[o]??o}var i=CZ();gt(i,21,()=>t.commands,fd,(o,s)=>{var a=wZ(),l=R(a),c=re(l,!0),d=E(l,2);{var u=v=>{Qv(v,{get flag(){return f(s).flag}})},p=v=>{var b=vZ(),y=re(b,!0);Q(C=>ee(y,C),[()=>n(f(s).type)]),A(v,b)};z(d,v=>{f(s).flag?v(u):v(p,-1)})}var m=E(d,2);{var h=v=>{var b=bt(),y=ae(b);{var C=T=>{var P=yZ(),_=re(P,!0);Q(()=>ee(_,f(s).scriptPath)),A(T,P)},w=k(()=>!g$(f(s).name,f(s).scriptPath));z(y,T=>{f(w)&&T(C)})}A(v,b)},g=v=>{var b=bZ(),y=re(b,!0);Q(()=>ee(y,f(s).summary)),A(v,b)};z(m,v=>{f(s).scriptPath?v(h):f(s).summary&&v(g,1)})}$(a),Q(()=>{tp(a,`--qa-macro-depth: ${f(s).depth}`),ee(c,f(s).name)}),A(o,a)}),$(i),A(r,i),oe()}var EZ=F('<div class="setting-item mod-empty-state svelte-1vg70zw"><div class="setting-item-info"><div class="setting-item-name svelte-1vg70zw">No choices found in this package.</div></div></div>'),TZ=F('<span class="qa-import-reviewed"><!> Reviewed</span>'),_Z=F('<div class="setting-item-description"> </div>'),kZ=F('<button type="button" class="qa-link-button svelte-1vg70zw"><span><!></span> <span> </span></button>'),SZ=F('<div><button type="button" class="qa-link-button svelte-1vg70zw"><span><!></span> <span> </span></button></div>'),AZ=F("<option>Overwrite</option>"),IZ=F("<option>Import</option>"),PZ=F('<div class="qa-import-choice-macro svelte-1vg70zw"><!></div>'),$Z=F('<div class="qa-import-choice-code-setting svelte-1vg70zw"> </div> <!>',1),FZ=F('<div class="qa-import-choice-code svelte-1vg70zw"></div>'),MZ=F('<div class="setting-item svelte-1vg70zw"><div class="setting-item-info"><div class="setting-item-name qa-import-choice-name svelte-1vg70zw"><span> </span> <!></div> <!> <!> <!></div> <div class="setting-item-control"><label class="qa-visually-hidden"> </label> <select class="dropdown"><!><option>Duplicate</option><option>Skip</option></select></div> <!> <!></div>'),RZ=F('<section class="setting-group qa-import-choices svelte-1vg70zw"><div class="setting-item setting-item-heading svelte-1vg70zw"><div class="setting-item-name svelte-1vg70zw">Choices</div></div> <div class="setting-items"><!> <!></div></section>'),DZ={hash:"svelte-1vg70zw",code:`.qa-import-choices.svelte-1vg70zw .setting-item:where(.svelte-1vg70zw) {flex-wrap:wrap;}.qa-import-choices.svelte-1vg70zw .setting-item-name:where(.svelte-1vg70zw) {overflow-wrap:anywhere;}.qa-import-choice-name.svelte-1vg70zw {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-1) var(--size-4-2);}.qa-import-choices.svelte-1vg70zw .qa-link-button:where(.svelte-1vg70zw) {margin-top:var(--size-4-1);font-size:var(--font-ui-smaller);}
- /* Pulls the glyph's built-in side bearing back to the text edge. */.qa-import-choice-chevron.svelte-1vg70zw {display:inline-flex;margin-inline-start:-3px;transition:transform 150ms ease;}.qa-import-choice-chevron.open.svelte-1vg70zw {transform:rotate(90deg);}.qa-import-choice-macro.svelte-1vg70zw {flex-basis:100%;min-width:0;}
- /* Opens under the row at full width, like a file's contents. */.qa-import-choice-code.svelte-1vg70zw {flex-basis:100%;min-width:0;display:flex;flex-direction:column;gap:var(--size-4-2);}.qa-import-choice-code-setting.svelte-1vg70zw {font-size:var(--font-ui-smaller);color:var(--text-muted);}
- @media (prefers-reduced-motion: reduce) {.qa-import-choice-chevron.svelte-1vg70zw {transition:none;}
- }`};function A$(r,t){let e=$i();ie(t,!0),Ae(r,DZ);function n(c){let d=(c.pathHint??[]).slice(0,-1),u=[];return d.length>0&&u.push(`In ${d.join(" \u203A ")}`),c.exists&&u.push("Already in vault"),u.join(" \xB7 ")}var i=RZ(),o=E(R(i),2),s=R(o);{var a=c=>{var d=EZ();A(c,d)};z(s,c=>{t.conflicts.length===0&&c(a)})}var l=E(s,2);gt(l,19,()=>t.conflicts,c=>c.choiceId,(c,d,u)=>{let p=k(()=>Jv(t.choiceDecisions.get(f(d).choiceId)??"import",f(d).exists)),m=k(()=>t.previewChoiceById.get(f(d).choiceId)),h=k(()=>(f(m)?.commands?.length??0)>0),g=k(()=>f(h)&&t.expandedMacros.has(f(d).choiceId)),v=k(()=>f(m)?.inlineScripts??[]),b=k(()=>f(v).length>0&&t.expandedCode.has(f(d).choiceId)),y=k(()=>n(f(d)));var C=MZ(),w=R(C),T=R(w),P=R(T),_=re(P,!0),I=E(P,2);{var O=ve=>{var Ne=TZ(),Ie=R(Ne);Qe(Ie,{iconId:"check",size:14}),Xt(),$(Ne),A(ve,Ne)},N=k(()=>t.reviewedChoiceIds.has(f(d).choiceId)&&f(p)!=="skip");z(I,ve=>{f(N)&&ve(O)})}$(T);var K=E(T,2);{var ne=ve=>{var Ne=_Z(),Ie=re(Ne,!0);Q(()=>ee(Ie,f(y))),A(ve,Ne)};z(K,ve=>{f(y)&&ve(ne)})}var H=E(K,2);{var D=ve=>{var Ne=kZ(),Ie=R(Ne);let ze;var ct=R(Ie);Qe(ct,{iconId:"chevron-right",size:14}),$(Ie);var Ke=E(Ie,2),ot=re(Ke,!0);$(Ne),Q(()=>{le(Ne,"aria-expanded",f(g)),ze=Ge(Ie,1,"qa-import-choice-chevron svelte-1vg70zw",null,ze,{open:f(g)}),ee(ot,f(g)?"Hide macro":"Show macro")}),ge("click",Ne,()=>t.toggleMacro(f(d).choiceId)),A(ve,Ne)};z(H,ve=>{f(h)&&ve(D)})}var G=E(H,2);{var V=ve=>{var Ne=SZ(),Ie=R(Ne),ze=R(Ie);let ct;var Ke=R(ze);Qe(Ke,{iconId:"chevron-right",size:14}),$(ze);var ot=E(ze,2),or=re(ot,!0);$(Ie),$(Ne),Q(()=>{le(Ie,"aria-expanded",f(b)),ct=Ge(ze,1,"qa-import-choice-chevron svelte-1vg70zw",null,ct,{open:f(b)}),ee(or,f(b)?"Hide code":"View code")}),ge("click",Ie,()=>t.toggleCode(f(d).choiceId)),A(ve,Ne)};z(G,ve=>{f(v).length>0&&ve(V)})}$(w);var M=E(w,2),B=R(M),J=re(B),te=E(B,2),W=R(te);{var Z=ve=>{var Ne=AZ();Ne.value=Ne.__value="overwrite",A(ve,Ne)},se=ve=>{var Ne=IZ();Ne.value=Ne.__value="import",A(ve,Ne)};z(W,ve=>{f(d).exists?ve(Z):ve(se,-1)})}var ce=E(W);ce.value=ce.__value="duplicate";var $e=E(ce);$e.value=$e.__value="skip",$(te);var Xe;Pl(te),$(M);var Ye=E(M,2);{var he=ve=>{var Ne=PZ(),Ie=R(Ne);{let ze=k(()=>f(m)?.commands??[]);S$(Ie,{get commands(){return f(ze)}})}$(Ne),A(ve,Ne)};z(Ye,ve=>{f(g)&&ve(he)})}var Re=E(Ye,2);{var Je=ve=>{var Ne=FZ();gt(Ne,21,()=>f(v),fd,(Ie,ze)=>{var ct=$Z(),Ke=ae(ct),ot=re(Ke,!0),or=E(Ke,2);{let Ar=k(()=>w$(f(ze).text)),zn=k(()=>`${f(d).name} \u203A ${f(ze).setting}`);Xv(or,{get content(){return f(Ar)},get label(){return f(zn)},executable:!0,wrap:!0})}Q(()=>ee(ot,f(ze).setting)),A(Ie,ct)}),$(Ne),A(ve,Ne)};z(Re,ve=>{f(b)&&ve(Je)})}$(C),Q(()=>{ee(_,f(d).name),le(B,"for",`${e}-action-${f(u)}`),ee(J,`Action for ${f(d).name??""}`),le(te,"id",`${e}-action-${f(u)}`),Xe!==(Xe=f(p))&&(te.value=(te.__value=Xe)??"",Il(te,Xe))}),ge("change",te,ve=>t.onChoiceModeChange(f(d).choiceId,ve)),A(c,C)}),$(o),$(i),A(r,i),oe()}He(["click","change"]);var OZ=F('<li class="svelte-88pyz9"><code class="svelte-88pyz9"> </code> <span class="qa-package-callout-loc svelte-88pyz9"> </span></li>'),LZ=F('<section class="callout qa-package-callout svelte-88pyz9"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner">Missing files</div></div> <div class="callout-content svelte-88pyz9"><ul class="svelte-88pyz9"></ul></div></section>'),NZ=F('<li class="svelte-88pyz9"><code class="svelte-88pyz9"> </code>: bundled but not used by any choice</li>'),VZ=F('<section class="callout qa-package-callout svelte-88pyz9" data-callout="info"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner">Unreferenced files</div></div> <div class="callout-content svelte-88pyz9"><ul class="svelte-88pyz9"></ul></div></section>'),BZ=F("<!> <!>",1),UZ={hash:"svelte-88pyz9",code:`.qa-package-callout.svelte-88pyz9 {margin:0;}.qa-package-callout.svelte-88pyz9 .callout-content:where(.svelte-88pyz9) {font-size:var(--font-ui-small);}.qa-package-callout.svelte-88pyz9 ul:where(.svelte-88pyz9) {margin:var(--size-4-2) 0 0;padding-inline-start:var(--size-4-5);display:flex;flex-direction:column;gap:var(--size-4-1);}.qa-package-callout.svelte-88pyz9 li:where(.svelte-88pyz9) {overflow-wrap:anywhere;line-height:var(--line-height-tight);}
- /* Obsidian's inline-code look, which is otherwise scoped to rendered notes. */.qa-package-callout.svelte-88pyz9 code:where(.svelte-88pyz9) {font-family:var(--font-monospace);font-size:var(--code-size);background-color:var(--code-background);border-radius:var(--code-radius);padding:0.1em 0.25em;}.qa-package-callout-loc.svelte-88pyz9 {display:block;color:var(--text-muted);font-size:var(--font-ui-smaller);}`};function I$(r,t){ie(t,!0),Ae(r,UZ);let e=k(()=>t.preview?.missingReferences.some(l=>l.asScript)??!1);var n=BZ(),i=ae(n);{var o=l=>{var c=LZ(),d=R(c),u=R(d),p=R(u);{let g=k(()=>f(e)?"zap":"alert-triangle");Qe(p,{get iconId(){return f(g)}})}$(u),Xt(2),$(d);var m=E(d,2),h=R(m);gt(h,21,()=>t.preview.missingReferences,g=>g.path,(g,v)=>{var b=OZ(),y=R(b),C=re(y,!0),w=E(y),T=E(w),P=re(T,!0);$(b),Q(()=>{ee(C,f(v).path),ee(w,`:
- ${f(v).asScript?"not bundled, so it runs from whatever file exists at that path after import":"not bundled and not in your vault"} `),ee(P,f(v).breadcrumb)}),A(g,b)}),$(h),$(m),$(c),Q(()=>le(c,"data-callout",f(e)?"danger":"warning")),A(l,c)};z(i,l=>{t.preview&&t.preview.missingReferences.length>0&&l(o)})}var s=E(i,2);{var a=l=>{var c=VZ(),d=R(c),u=R(d),p=R(u);Qe(p,{iconId:"info"}),$(u),Xt(2),$(d);var m=E(d,2),h=R(m);gt(h,20,()=>t.preview.orphanAssets,g=>g,(g,v)=>{var b=NZ(),y=R(b),C=re(y,!0);Xt(),$(b),Q(()=>ee(C,v)),A(g,b)}),$(h),$(m),$(c),A(l,c)};z(s,l=>{t.preview&&t.preview.orphanAssets.length>0&&l(a)})}A(r,n),oe()}var qZ=F('<p class="qa-import-status mod-error svelte-dvnvtv"> </p>'),zZ=F('<p class="qa-import-status svelte-dvnvtv">Analyzing package\u2026</p>'),HZ=F('<p class="qa-import-status svelte-dvnvtv"> </p>'),WZ=F('<div class="setting-items"><div class="setting-item mod-empty-state"><div class="setting-item-info"><div class="setting-item-name">No files bundled with this package.</div></div></div></div>'),GZ=F("<h4> </h4> <!>",1),jZ=F('<section class="callout qa-import-summary svelte-dvnvtv" data-callout="success" role="status"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner"> </div></div></section>'),YZ=F('<!> <!> <section class="setting-group qa-import-files svelte-dvnvtv"><div class="setting-item setting-item-heading svelte-dvnvtv"><div class="setting-item-name">Files</div></div> <!></section> <!> <!>',1),KZ=F('<p id="qa-import-reason" class="qa-import-reason svelte-dvnvtv"> </p>'),QZ=F('<button type="button">Cancel</button>'),XZ=F('<div class="qa-package-dialog"><div class="qa-package-body"><section class="qa-import-paste svelte-dvnvtv"><label class="qa-visually-hidden" for="qa-import-json">Package JSON</label> <textarea id="qa-import-json" placeholder="Paste the contents of a .quickadd.json package here" rows="8" class="svelte-dvnvtv"></textarea> <!></section> <!> <!></div> <div class="modal-button-container"><!> <!> <button type="button" class="mod-cta"><!></button></div></div>'),JZ={hash:"svelte-dvnvtv",code:`.qa-import-paste.svelte-dvnvtv {display:flex;flex-direction:column;gap:var(--size-4-2);}.qa-import-paste.svelte-dvnvtv textarea:where(.svelte-dvnvtv) {width:100%;font-family:var(--font-monospace);font-size:var(--font-ui-small);resize:vertical;}.qa-import-status.svelte-dvnvtv {margin:0;font-size:var(--font-ui-smaller);color:var(--text-muted);overflow-wrap:anywhere;}.qa-import-status.mod-error.svelte-dvnvtv {color:var(--text-error);}.qa-import-files.svelte-dvnvtv {display:flex;flex-direction:column;gap:var(--size-4-3);}.qa-import-files.svelte-dvnvtv .setting-item-heading:where(.svelte-dvnvtv) {margin-bottom:var(--size-4-1);}
- /* Small muted group label, like Obsidian's settings sidebar sections. */.qa-import-files-group.svelte-dvnvtv {margin:var(--size-4-2) 0 0;padding:0 var(--size-4-4);font-size:var(--font-ui-smaller);font-weight:var(--font-semibold);color:var(--text-muted);}.qa-import-files-group.svelte-dvnvtv:first-of-type {margin-top:0;}.qa-import-files-group.mod-warning.svelte-dvnvtv {color:var(--text-warning);}.qa-import-summary.svelte-dvnvtv {margin:0;}
- /* Left of the buttons; the text wraps before they do. */.qa-import-reason.svelte-dvnvtv {flex:1 1 0;align-self:center;margin:0;font-size:var(--font-ui-smaller);color:var(--text-muted);}
- /* The phone footer stacks its buttons bottom-up; put the reason on top. */.is-phone .qa-import-reason.svelte-dvnvtv {flex:none;order:1;text-align:center;}`};function P$(r,t){ie(t,!0),Ae(r,JZ);let e;function n(){return e??(e=new ME(t.app))}let i=pe(null),o=pe(null),s=pe(null),a=pe(!1),l=pe(Ze(new Set)),c=pe(Ze(new Set)),d=pe(Ze(new Set)),u=pe(Ze(new Set)),p=pe(null),m=pe(!1),h=pe(null),g=pe(Ze(new Map)),v=pe(Ze(new Map)),b=pe(Ze(new Set)),y=pe(""),C=pe(!1),w=pe(0),T=pe(!1),P=pe(null),_=k(()=>f(s)?AE(f(s)):!1),I=k(()=>f(s)?_q(f(s),f(l),f(c)):0),O=k(()=>f(I)===0),N=k(()=>new Map((f(s)?.choices??[]).map(Y=>[Y.choiceId,Y]))),K=k(()=>new Map((f(s)?.files??[]).map(Y=>[Y.originalPath,Y]))),ne=k(()=>!!(f(s)&&(f(s).summary.hasCritical||f(s).summary.hasWarning))),H=k(()=>{let Y=f(h);if(!Y)return"";let de=[];Y.added&&de.push(`${Y.added} choice${Y.added===1?"":"s"} added`),Y.overwritten&&de.push(`${Y.overwritten} overwritten`),Y.assetsWritten&&de.push(`${Y.assetsWritten} file${Y.assetsWritten===1?"":"s"} written`);let Pt=Y.skipped+Y.assetsSkipped;return Pt&&de.push(`${Pt} skipped`),de.length?`Imported: ${de.join(", ")}.`:"Nothing was imported."});function D(Y){if(f(l).has(Y))return;let de=new Set(f(l));de.add(Y),q(l,de,!0)}function G(Y){let de=new Set(f(d));de.has(Y)?de.delete(Y):de.add(Y),q(d,de,!0)}function V(Y){let de=new Set(f(u));de.has(Y)?de.delete(Y):de.add(Y),q(u,de,!0),de.has(Y)&&!f(c).has(Y)&&q(c,new Set(f(c)).add(Y),!0)}let M=Y=>n().optimistic(Y),B=k(()=>(f(o)?.assetConflicts??[]).map(Y=>{let de=Pq(f(v),Y,se,M);return{conflict:Y,state:de,destinationIsFolder:de.mode!=="skip"&&n().isFolder(de.destinationPath),file:f(K).get(Y.originalPath)}})),J=k(()=>f(B).filter(Y=>!f(b).has(Y.conflict.originalPath))),te=k(()=>f(B).filter(Y=>f(b).has(Y.conflict.originalPath))),W=k(()=>!!(f(i)&&f(o))&&!f(C)&&!f(B).some(Y=>Y.destinationIsFolder)&&(!f(_)||f(a)&&f(O))),Z=k(()=>!f(i)||!f(o)||f(C)||f(T)?"":f(_)&&!f(O)?`View ${f(I)} script${f(I)===1?"":"s"} above to import.`:f(_)&&!f(a)?"Confirm the acknowledgement above to import.":f(B).some(Y=>Y.destinationIsFolder)?"A destination above is a folder. Add a file name to import.":"");function se(Y){return DE(Y,U.getState().templateFolderPaths)}function ce(Y,de,Pt=!1){n().schedule(Y,de,yr=>{if(q(v,Dq(f(v),Y,yr),!0),Pt&&yr!==f(b).has(Y)){let Ro=new Set(f(b));yr?Ro.add(Y):Ro.delete(Y),q(b,Ro,!0)}})}function $e(){if(!f(o)){q(g,new Map,!0),q(v,new Map,!0),q(b,new Set,!0);return}q(g,$q(f(o).choiceConflicts),!0),q(v,Iq(f(o).assetConflicts,se,M),!0),q(b,new Set(f(o).assetConflicts.filter(Y=>f(v).get(Y.originalPath)?.destinationExists).map(Y=>Y.originalPath)),!0);for(let Y of f(o).assetConflicts){let de=f(v).get(Y.originalPath);de&&ce(Y.originalPath,de.destinationPath,!0)}}function Xe(Y,de){q(g,Fq(f(g),Y,de),!0)}function Ye(Y,de){q(v,Mq(f(v),Y,de,M),!0)}function he(Y,de){let{decisions:Pt,effectivePath:yr}=Rq(f(v),Y.originalPath,de,M);q(v,Pt,!0),ce(Y.originalPath,yr)}function Re(Y,de){let yr=de.currentTarget.value;Xe(Y,yr)}function Je(){q(s,null),q(a,!1),q(l,new Set,!0),q(c,new Set,!0),q(d,new Set,!0),q(u,new Set,!0)}async function ve(Y){let de=Y.trim(),Pt=Ak(w);if(q(h,null),q(T,!1),!de){q(i,null),q(o,null),q(g,new Map,!0),q(v,new Map,!0),Je(),q(p,null);return}q(C,!0);try{let yr=Yv(de),Ro=U.getState().choices,qf=await PE(t.app,Ro,yr),Q_=await cf(t.app,Ro,yr);if(Pt!==f(w))return;q(i,{pkg:yr,path:"[pasted]"},!0),q(o,qf,!0),Je(),q(s,Q_,!0),q(p,null),$e()}catch(yr){if(Pt!==f(w))return;q(p,yr?.message??String(yr),!0),q(i,null),q(o,null),q(g,new Map,!0),q(v,new Map,!0),Je()}finally{Pt===f(w)&&q(C,!1)}}function Ne(Y){let de=Y.currentTarget.value;q(y,de,!0),ve(de)}async function Ie(){if(f(T)){new Zv.Notice("This package has already been imported.");return}if(!f(i)||!f(o)){new Zv.Notice("Load a package before importing.");return}q(m,!0),q(h,null);try{let Y=U.getState().choices,de=await $E({app:t.app,existingChoices:Y,aiProviders:U.getState().ai.providers,pkg:f(i).pkg,choiceDecisions:Oq(f(o).choiceConflicts,f(g)),assetDecisions:Lq(f(o).assetConflicts,f(v),M)});U.setState(Pt=>({...Pt,choices:de.updatedChoices})),t.onImported?.(de,Y),q(h,{added:de.addedChoiceIds.length,overwritten:de.overwrittenChoiceIds.length,skipped:de.skippedChoiceIds.length,assetsWritten:de.writtenAssets.length,assetsSkipped:de.skippedAssets.length},!0),q(T,!0),new Zv.Notice(`Imported ${de.addedChoiceIds.length+de.overwrittenChoiceIds.length} choice${de.addedChoiceIds.length+de.overwrittenChoiceIds.length===1?"":"s"} successfully.`)}catch(Y){console.error(Y),new Zv.Notice(`Import failed: ${Y?.message??Y}`)}finally{q(m,!1)}f(T)&&(await ys(),f(P)?.scrollIntoView({block:"nearest"}))}var ze=XZ(),ct=R(ze),Ke=R(ct),ot=E(R(Ke),2);Jc(ot);var or=E(ot,2);{var Ar=Y=>{var de=qZ(),Pt=re(de,!0);Q(()=>ee(Pt,f(p))),A(Y,de)},zn=Y=>{var de=zZ();A(Y,de)},me=Y=>{var de=HZ(),Pt=re(de);Q(yr=>ee(Pt,`Version ${f(i).pkg.quickAddVersion??""} \xB7 Created ${yr??""} \xB7 ${f(o).choiceConflicts.length??""} choice${f(o).choiceConflicts.length===1?"":"s"} \xB7 ${f(i).pkg.assets.length??""} file${f(i).pkg.assets.length===1?"":"s"}`),[()=>new Date(f(i).pkg.createdAt).toLocaleDateString()]),A(Y,de)};z(or,Y=>{f(p)?Y(Ar):f(C)?Y(zn,1):f(i)&&f(o)&&Y(me,2)})}$(Ke);var Fe=E(Ke,2);{var ut=Y=>{var de=YZ(),Pt=ae(de);{var yr=ai=>{T$(ai,{get preview(){return f(s)}})};z(Pt,ai=>{f(ne)&&f(s)&&ai(yr)})}var Ro=E(Pt,2);A$(Ro,{get conflicts(){return f(o).choiceConflicts},get choiceDecisions(){return f(g)},get previewChoiceById(){return f(N)},get expandedMacros(){return f(d)},toggleMacro:G,get expandedCode(){return f(u)},get reviewedChoiceIds(){return f(c)},toggleCode:V,onChoiceModeChange:Re});var qf=E(Ro,2),Q_=E(R(qf),2);{var Ej=ai=>{var ca=WZ();A(ai,ca)},Tj=ai=>{var ca=bt(),Jy=ae(ca);gt(Jy,17,()=>[{label:"Added",rows:f(J),overwrite:!1},{label:"Will overwrite",rows:f(te),overwrite:!0}],zc=>zc.label,(zc,Hc)=>{var Zy=bt(),X_=ae(Zy);{var J_=Z_=>{var ZM=GZ(),ek=ae(ZM);let eR;var Sj=re(ek),Aj=E(ek,2);gt(Aj,17,()=>f(Hc).rows,tk=>tk.conflict.originalPath,(tk,da)=>{var tR=bt(),Ij=ae(tR);{var Pj=rk=>{{let $j=k(()=>f(l).has(f(da).file.originalPath));_$(rk,{get file(){return f(da).file},get pkg(){return f(i).pkg},get mode(){return f(da).state.mode},get destinationPath(){return f(da).state.destinationPath},get destinationExists(){return f(da).state.destinationExists},get destinationIsFolder(){return f(da).destinationIsFolder},onPathInput:nk=>he(f(da).conflict,nk),onModeChange:nk=>Ye(f(da).conflict.originalPath,nk),get reviewed(){return f($j)},onReviewed:D})}};z(Ij,rk=>{f(da).file&&rk(Pj)})}A(tk,tR)}),Q(()=>{eR=Ge(ek,1,"qa-import-files-group svelte-dvnvtv",null,eR,{"mod-warning":f(Hc).overwrite}),ee(Sj,`${f(Hc).label??""} (${f(Hc).rows.length??""})`)}),A(Z_,ZM)};z(X_,Z_=>{f(Hc).rows.length>0&&Z_(J_)})}A(zc,Zy)}),A(ai,ca)};z(Q_,ai=>{f(B).length===0?ai(Ej):ai(Tj,-1)})}$(qf);var JM=E(qf,2);I$(JM,{get preview(){return f(s)}});var _j=E(JM,2);{var kj=ai=>{var ca=jZ(),Jy=R(ca),zc=R(Jy),Hc=R(zc);Qe(Hc,{iconId:"check"}),$(zc);var Zy=E(zc,2),X_=re(Zy,!0);$(Jy),$(ca),Cn(ca,J_=>q(P,J_),()=>f(P)),Q(()=>ee(X_,f(H))),A(ai,ca)};z(_j,ai=>{f(h)&&ai(kj)})}A(Y,de)};z(Fe,Y=>{f(i)&&f(o)&&Y(ut)})}var Yt=E(Fe,2);{var Kt=Y=>{{let de=k(()=>f(Z)?"qa-import-reason":void 0);k$(Y,{get preview(){return f(s)},get fullyReviewed(){return f(O)},get reasonId(){return f(de)},get acknowledged(){return f(a)},set acknowledged(Pt){q(a,Pt,!0)}})}};z(Yt,Y=>{f(i)&&f(_)&&!f(T)&&Y(Kt)})}$(ct);var qt=E(ct,2),Qt=R(qt);{var Se=Y=>{var de=KZ(),Pt=re(de,!0);Q(()=>ee(Pt,f(Z))),A(Y,de)};z(Qt,Y=>{f(Z)&&Y(Se)})}var st=E(Qt,2);{var vr=Y=>{var de=QZ();Q(()=>de.disabled=f(m)),ge("click",de,function(...Pt){t.close?.apply(this,Pt)}),A(Y,de)};z(st,Y=>{f(T)||Y(vr)})}var zt=E(st,2),Mo=R(zt);{var vl=Y=>{var de=bs("Importing\u2026");A(Y,de)},An=Y=>{var de=bs("Close");A(Y,de)},la=Y=>{var de=bs("Import package");A(Y,de)};z(Mo,Y=>{f(m)?Y(vl):f(T)?Y(An,1):Y(la,-1)})}$(zt),$(qt),$(ze),Q(()=>{zt.disabled=f(m)||!f(T)&&!f(W),le(zt,"aria-describedby",f(Z)?"qa-import-reason":void 0)}),ge("input",ot,Ne),Jn(ot,()=>f(y),Y=>q(y,Y)),ge("click",zt,function(...Y){(f(T)?t.close:Ie)?.apply(this,Y)}),A(r,ze),oe()}He(["input","click"]);var OE=class extends Nq.Modal{constructor(e,n={}){super(e);this.options=n;this.handle=null}onOpen(){this.modalEl.addClass("quickAddModal","qa-package-modal","packageImportModal"),this.setTitle("Import QuickAdd package"),this.handle=vi(this.contentEl,P$,{app:this.app,close:()=>this.close(),onImported:this.options.onImported},{what:"the package importer"})}onClose(){this.handle?.destroy(),this.handle=null}};lt();function LE(r,t,e){let n=new Map(Jt(t).map(c=>[c.id,c])),i=Td(e.updatedChoices),o=new Map(i.map(c=>[c.id,c.choice])),s=new Map(i.map(c=>[c.id,c.parentId])),a=new Set([...e.overwrittenChoiceIds,...e.addedChoiceIds]),l=c=>{for(let d=s.get(c);d;d=s.get(d))if(a.has(d))return!0;return!1};for(let c of e.overwrittenChoiceIds){let d=n.get(c);d&&r.removeCommandForChoice(d,{recursive:!0})}for(let c of a){if(l(c))continue;let d=o.get(c);d&&r.addCommandForChoice(d)}}Fm();gd();Go();function $$(r,t,e,n){let i=At(r,"div"),o=At(r,"strong");return o.textContent=t,i.appendChild(o),i.appendChild(Cd(r,` ${e}`)),n?.className&&i.classList.add(n.className),i.classList.add("qa-dev-info-row"),r.appendChild(i),i}function Vq(r,t){if(t.branch!==null&&$$(r,"Branch:",t.branch),t.commit!==null&&$$(r,"Commit:",t.commit),t.dirty!==null){let e=t.dirty?"Yes (uncommitted changes)":"No",n=t.dirty?"qa-dev-dirty-status":"qa-dev-clean-status";$$(r,"Uncommitted changes:",e,{className:n})}}var NE="Bundle or import QuickAdd automations as reusable packages.";function Bq(r,t,e,n){let i=[{type:"group",heading:"Choices & packages",extraButtons:[o=>o.setIcon("help-circle").setTooltip("QuickAdd documentation").onClick(()=>h1(es.gettingStarted,o.extraSettingsEl))],items:[{name:"Choices",render:r.choices},{name:"Packages",desc:NE,render:r.packages}]},{type:"group",heading:"Input",items:[{name:"Use multi-line input prompt",desc:"Use multi-line input prompt instead of single-line input prompt. Submit multi-line prompts with Ctrl/Cmd+Enter; Enter inserts a newline.",control:{type:"toggle",key:"inputPrompt"}},{name:"One-page input for choices",desc:F$("Collect a choice's inputs in one form before it runs, instead of one prompt at a time. Works with Template and Capture choices, and with Macros whose scripts declare inputs. Template and Capture choices can override this individually. ",es.onePageInputs,"Learn more about one-page inputs"),control:{type:"toggle",key:"onePageInputEnabled"}}]},...n?[n]:[],{type:"group",heading:"Notifications",items:[{name:"Announce updates",desc:"Display release notes when a new version is installed. This includes new features, demo videos, and bug fixes.",control:{type:"dropdown",key:"announceUpdates",defaultValue:"major",options:{all:"Every release",major:"Feature releases",none:"Never"}}},{name:"Show capture notifications",desc:"Display a notification when content is captured successfully to confirm the operation completed.",control:{type:"toggle",key:"showCaptureNotification"}}]},{type:"group",heading:"AI & online",items:[{name:"Disable AI & online features",desc:"This prevents the plugin from making requests to external providers like OpenAI. You can still use user scripts to execute arbitrary code, including contacting external providers. However, this setting disables plugin features like the AI Assistant from doing so. You need to disable this setting to use the AI Assistant.",control:{type:"toggle",key:"disableOnlineFeatures"}},...e?[e]:[]]},{type:"group",heading:"Appearance",items:[{name:"Show icon in sidebar",desc:"Add QuickAdd icon to the sidebar ribbon. Requires a reload.",control:{type:"toggle",key:"enableRibbonIcon"}}]},{type:"group",items:[ZZ(r)]}];return t&&i.push({type:"group",heading:"Developer",items:[{name:"Development information",desc:"Git information for developers.",render:r.developmentInfo}]}),i}function ZZ(r){return{type:"page",name:"Advanced",items:[{type:"group",heading:"Choice picker",items:[{name:"\u201CNew note from template\u201D in the launcher",desc:"Add a row to Run QuickAdd that lists templates from your configured template folder, so you can create a note from a template without a dedicated Template choice. Only appears when a template folder is configured; the command palette entry works regardless.",control:{type:"dropdown",key:"templateFolderLauncherRow",defaultValue:"bottom",options:{bottom:"Bottom",top:"Top",off:"Hidden"}}},{name:"Search nested choices",desc:"When searching in the choice picker, also match choices nested inside folders and show their path. Note that nested matches can outrank same-level ones. Disable to search only the open level.",control:{type:"toggle",key:"searchNestedChoices"}}]},{type:"group",heading:"Input",items:[{name:"Use editor selection as default Capture value",desc:"When enabled, Capture uses the current editor selection as {{VALUE}} and may skip the prompt. When disabled, Capture always prompts for {{VALUE}}.",control:{type:"toggle",key:"useSelectionAsCaptureValue"}},{name:"Name pasted images after the note title",desc:"When on, clipboard images saved by QuickAdd (pasting into a prompt, or {{CLIPBOARD}} with an image and no text) are named after the destination note. When the destination is not yet known, QuickAdd keeps the timestamp name. Duplicate names are handled by Obsidian's attachment folder setting.",control:{type:"toggle",key:"namePastedImagesAfterNoteTitle"}},{name:"Persist input prompt drafts",desc:"Keep drafts when closing input prompts so they can be restored on reopen. Drafts are stored only for this session.",control:{type:"toggle",key:"persistInputPromptDrafts"}},{name:"Date aliases",desc:"Shortcodes for natural language date parsing. One per line: alias = phrase. Example: tm = tomorrow.",render:r.dateAliases}]},{type:"group",heading:"Notifications",items:[{name:"Show input cancellation notifications",desc:"Display a notification when an input prompt is cancelled without submitting. Disable this to avoid extra notices when dismissing prompts.",control:{type:"toggle",key:"showInputCancellationNotification"}}]},{type:"group",heading:"Properties",items:[{name:"Convert string front matter variables to typed properties (Beta)",desc:'List/object values from scripts are always written as proper Obsidian properties (a list becomes a List). This toggle additionally converts string values into typed properties: a comma or bullet-list string becomes a List, "42" becomes a Number, "true" becomes a Checkbox, etc. Disabled by default; the string conversion is a beta heuristic that may have edge cases.',control:{type:"toggle",key:"enableTemplatePropertyTypes"}}]},{type:"group",heading:"Global variables",items:[{name:"Global variables",render:r.globalVariables}]},{type:"group",heading:"Obsidian URI",items:[{name:"Allow URI x-callback-url",desc:"When on, an obsidian://quickadd URI may open a callback URL (x-success / x-error / x-cancel) after a Template or Capture choice finishes \u2014 sending the outcome and the affected note's vault path and URL to that callback. While on, a URI that carries x-* callback params is restricted to Template and Capture choices (other choice types are warned and skipped). Off by default because the callback URL is set by whoever creates the obsidian:// link. Only shortcuts: and obsidian: callback URLs are permitted.",control:{type:"toggle",key:"enableUriCallbacks"}}]}]}}function F$(r,t,e="Learn more"){let n=createFragment();return n.append(document.createTextNode(r)),Kw(n,t,e),n}lt();fi();je();Ka();var VE=require("obsidian");function Uq(r,t,e){return M$(new VE.Setting(r),t,e)}function M$(r,t,e){return r.setName("API key").setDesc(e.hasLegacyKey?"A legacy API key is stored in plain text. Link a keychain secret to replace it.":"Link a secret from Settings \u2192 Keychain.").addComponent(n=>new VE.SecretComponent(t,n).setValue(e.value).onChange(e.onChange))}var Yi=require("obsidian");fi();ye();je();var Xq=require("obsidian");fi();var qq=require("obsidian");je();var BE=null,eee=1440*60*1e3,R$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function tee(r){if(!R$(r))return null;let t=Object.entries(r).filter(([,e])=>R$(e)&&R$(e.models));return t.length>0?Object.fromEntries(t):null}async function D$(){if(BE&&Date.now()-BE.fetchedAt<eee)return BE.data;if(U.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let r=await(0,qq.requestUrl)({url:"https://models.dev/api.json",method:"GET"}),t=tee(r.json);if(!t)throw new Error("models.dev returned an unexpected response.");return BE={data:t,fetchedAt:Date.now()},t}function ree(r){for(let t of[r,`https://${r}`])try{let e=new URL(t).hostname.toLowerCase();if(e)return e}catch{}return""}function ey(r){let t=r.toLowerCase(),e=ree(r),n=i=>e===i||e.endsWith(`.${i}`);return n("openai.com")?"openai":n("openrouter.ai")?"openrouter":n("generativelanguage.googleapis.com")?"google":t.includes("anthropic")?"anthropic":n("groq.com")?"groq":n("together.ai")||n("together.xyz")?"togetherai":t.includes("huggingface")?"huggingface":t.includes("github")&&t.includes("models")?"github-models":t.includes("bedrock")||t.includes("aws")?"amazon-bedrock":t.includes("modelscope")?"modelscope":t.includes("dashscope")?"alibaba":n("fireworks.ai")?"fireworks-ai":t.includes("vercel")?"vercel":n("inference.net")?"inference":n("z.ai")||t.includes("zhipu")?"zhipuai":n("deepseek.com")?"deepseek":n("mistral.ai")?"mistral":t.includes("cerebras")?"cerebras":n("venice.ai")?"venice":n("upstage.ai")?"upstage":n("llama.com")?"llama":t.includes("morphllm")?"morph":n("inceptionlabs.ai")?"inception":t.includes("deepinfra")?"deepinfra":n("opencode.ai")?"opencode":n("inference.wandb.ai")?"wandb":n("githubcopilot.com")?"github-copilot":null}var O$=/(whisper|-tts|tts-|embed|dall-e|image|moderation|transcribe|realtime|rerank)/i;function nee(r){let t=r.modalities?.output;if(Array.isArray(t)&&!t.includes("text"))return!1;let e=r.limit??{};if(typeof e.context=="number"&&e.context<=0||typeof e.output=="number"&&e.output<=1)return!1;let n=(r.family??"").toLowerCase(),i=r.id.toLowerCase();return!(n.includes("embedding")||i.includes("embedding")||O$.test(i))}function zq(r){return r.filter(nee).map(t=>{let e={name:t.id,maxTokens:Math.max(1,Math.floor(t.limit?.context??128e3))};return typeof t.limit?.output=="number"&&t.limit.output>0&&(e.maxOutputTokens=Math.floor(t.limit.output)),typeof t.temperature=="boolean"&&(e.supportsTemperature=t.temperature),Object.assign(e,Hq(t)),e})}function Hq(r){let t={};return r.status==="deprecated"&&(t.deprecated=!0),typeof r.release_date=="string"&&r.release_date&&(t.releaseDate=r.release_date),t}var iee=/^(.+)-(?:\d{4}-\d{2}-\d{2}|\d{8})$/;function Wq(r){let t=new Set(r.map(e=>e.name));return r.filter(e=>{let n=iee.exec(e.name)?.[1];return!n||!t.has(n)})}async function Gq(r,t){let e=ey(r);if(!e)return t;let n;try{n=await D$()}catch{return t}let i=n[e]?.models;return i?t.map(o=>{let s=i[o.name];if(!s)return o;let a={...o};return typeof s.limit?.context=="number"&&s.limit.context>0&&(a.maxTokens=Math.floor(s.limit.context)),a.maxOutputTokens===void 0&&typeof s.limit?.output=="number"&&s.limit.output>0&&(a.maxOutputTokens=Math.floor(s.limit.output)),a.supportsTemperature===void 0&&typeof s.temperature=="boolean"&&(a.supportsTemperature=s.temperature),Object.assign(a,Hq(s)),a}):t}function L$(r,t){let e=new Map(t.map(s=>[s.name,s])),n=r.map(s=>{let a=e.get(s.name);if(!a)return s;let l={...s,maxTokens:a.maxTokens,maxOutputTokens:a.maxOutputTokens??s.maxOutputTokens,supportsTemperature:a.supportsTemperature??s.supportsTemperature},c=a.releaseDate??s.releaseDate;c!==void 0&&(l.releaseDate=c);let d=a.deprecated??s.deprecated;return d!==void 0&&(l.deprecated=d),l}),i=new Set(r.map(s=>s.name)),o=t.filter(s=>!i.has(s.name));return n.concat(o)}function UE(r,t){let e=new Set(r.map(n=>n.name));return L$(r,t.filter(n=>e.has(n.name)||!n.deprecated))}df();je();var HE=128e3;async function uf(r,t){return Wq(await uee(r,t))}async function uee(r,t){let e=r.modelSource??"providerApi";if(e==="modelsDev")return Kq(r);if(e==="providerApi")return Qq(r,t);try{return await Qq(r,t)}catch(n){if(!ey(r.endpoint))throw n;return Kq(r,n)}}async function Kq(r,t){try{let e=await D$(),n=ey(r.endpoint);if(!n||!(n in e))throw new Error(`models.dev does not list a provider that matches ${r.endpoint}.`);let i=Object.values(e[n].models);return zq(i)}catch(e){throw t?new Error(`Provider API failed (${t.message}). Fallback to models.dev also failed: ${e.message}`):e}}async function Qq(r,t){let{disableOnlineFeatures:e}=U.getState();if(e)throw new Error("Online features are disabled \u2014 enable them to browse provider models.");if(!r.endpoint)throw new Error("Provider is missing an endpoint URL.");let n=t??r.apiKey??"",i=xh(r),o=i==="anthropic"?await fee(r,n):i==="gemini"?await hee(r,n):await mee(r,n);if(!o.length)throw new Error("The provider's models endpoint did not include any usable models.");let s=await Gq(r.endpoint,o);return pee(r.endpoint,s)}function pee(r,t){let e=ey(r);if(e!=="openai"&&e!=="google"&&e!=="anthropic")return t;let n=new Map(Eh[e].map(i=>[i.name,i]));return t.map(i=>{let o=n.get(i.name);return o?{...i,maxTokens:i.maxTokens===HE?o.maxTokens:i.maxTokens,maxOutputTokens:i.maxOutputTokens??o.maxOutputTokens,supportsTemperature:i.supportsTemperature??o.supportsTemperature}:i})}async function V$(r,t,e){try{let n=await(0,Xq.requestUrl)({url:t,headers:e,throw:!1});if(n.status>=400)throw zE(r.name,n);return await n.json}catch(n){throw new Error(`Provider rejected the models request: ${n.message}`)}}async function mee(r,t){let e=r.endpoint.replace(/\/+$/,""),n=e.endsWith("/v1")?`${e}/models`:`${e}/v1/models`,i={};t&&(i.Authorization=`Bearer ${t}`);let o=await V$(r,n,i),s=gee(o),a=[];for(let l of s){let c=vee(l);c&&!O$.test(c.name)&&a.push(c)}return a}async function fee(r,t){let e=r.endpoint.replace(/\/+$/,""),n={"anthropic-version":"2023-06-01"};t&&(n["x-api-key"]=t);let i=[],o=null;for(let s=0;s<10;s++){let a=`${e}/v1/models?limit=1000`+(o?`&after_id=${encodeURIComponent(o)}`:""),l=await V$(r,a,n);for(let c of l.data??[])c.id&&i.push({name:c.id,maxTokens:HE});if(!l.has_more||!l.last_id)break;o=l.last_id}return i}async function hee(r,t){let e=r.endpoint.replace(/\/+$/,""),n={};t&&(n["x-goog-api-key"]=t);let i=[],o=null;for(let s=0;s<10;s++){let a=`${e}/v1beta/models?pageSize=1000`+(o?`&pageToken=${encodeURIComponent(o)}`:""),l=await V$(r,a,n);for(let c of l.models??[]){if(!c.name)continue;let d=c.supportedGenerationMethods;if(Array.isArray(d)&&!d.includes("generateContent"))continue;let u={name:c.name.replace(/^models\//,""),maxTokens:typeof c.inputTokenLimit=="number"&&c.inputTokenLimit>0?c.inputTokenLimit:HE};typeof c.outputTokenLimit=="number"&&c.outputTokenLimit>0&&(u.maxOutputTokens=c.outputTokenLimit),i.push(u)}if(!l.nextPageToken)break;o=l.nextPageToken}return i}function gee(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"&&Array.isArray(r.data))return r.data;throw new Error("The provider's models response was not a list.")}function vee(r){let t=r.id??r.name;return t?{name:t,maxTokens:yee(r)}:null}function yee(r){let t=[r.context_length,r.contextLength,r.context_tokens,r.max_context_tokens,r.max_context_length,r.max_input_tokens,r.max_tokens,r.limit?.context];for(let e of t){let n=bee(e);if(n&&n>0)return Math.floor(n)}return HE}function bee(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let t=Number(r);if(Number.isFinite(t))return t}return null}kc();var Eee=1440*60*1e3;function U$(r,t){let e=new Map(r.map(o=>[o.name,JSON.stringify(o)])),n=0,i=0;for(let o of t){let s=e.get(o.name);s===void 0?n+=1:s!==JSON.stringify(o)&&(i+=1)}return{added:n,updated:i}}async function WE(r,t){let e;try{let i=await So(r,t);e=await uf(t,i)}catch(i){throw t.lastModelSync={at:Date.now(),error:ez(i)},i}let n=t.models;return t.models=UE(t.models,e),t.lastModelSync={at:Date.now()},{...U$(n,t.models),discovered:e}}async function q$(r,t){let e=U.getState().ai.providers.find(a=>a.id===t);if(!e)return null;let n={...e,models:e.models.map(a=>({...a}))},i,o;try{({discovered:i}=await WE(r,n))}catch(a){o={error:a}}let s=!1;if(U.setState(a=>({ai:{...a.ai,providers:a.ai.providers.map(l=>l.id!==t?l:(s=!0,{...l,models:i?UE(l.models,i):l.models,lastModelSync:n.lastModelSync}))}})),o)throw o.error;return s?i??[]:null}function ez(r){let t=r?.message;if(typeof t=="string"&&t.length>0)return t;let e=String(r);return e.length>0?e:"Unknown error"}function B$(r){return r.id?`id:${r.id}`:`ne:${(r.name??"").trim().toLowerCase()}\0${(r.endpoint??"").trim().toLowerCase().replace(/\/+$/,"")}`}async function tz(r,t={}){let e=U.getState();if(e.disableOnlineFeatures)return[];let n=e.ai.providers.filter(l=>l.autoSyncModels);if(n.length===0)return[];let i=e.ai.lastModelAutoSyncAt??0;if(!t.ignoreThrottle&&Date.now()-i<Eee)return[];let o=[],s=new Map;for(let l of n){let c={...l,models:l.models.map(d=>({...d}))};try{let{added:d,updated:u}=await WE(r,c);o.push({provider:c.name,added:d,updated:u}),s.set(B$(c),c)}catch(d){o.push({provider:c.name,added:0,updated:0,error:ez(d)}),s.set(B$(c),c)}}let a=o.some(l=>!l.error);U.setState(l=>({...l,ai:{...l.ai,providers:l.ai.providers.map(c=>{let d=s.get(B$(c));return d?{...c,models:d.lastModelSync?.error?c.models:UE(c.models,d.models),lastModelSync:d.lastModelSync}:c}),lastModelAutoSyncAt:a?Date.now():l.ai.lastModelAutoSyncAt}}));for(let l of o)l.error?S.logMessage(`[Model auto-sync] ${l.provider}: failed (${l.error})`):(l.added>0||l.updated>0)&&S.logMessage(`[Model auto-sync] ${l.provider}: ${l.added} new model(s), ${l.updated} updated.`);return o}var rz=[{id:"openai",name:"OpenAI",endpoint:"https://api.openai.com/v1",doc:"https://platform.openai.com/docs/models",kind:"openai",modelSource:"modelsDev",seedKey:"openai"},{id:"gemini",name:"Gemini",endpoint:"https://generativelanguage.googleapis.com",doc:"https://ai.google.dev/gemini-api/docs",kind:"gemini",modelSource:"auto",seedKey:"google"},{id:"anthropic",name:"Anthropic",endpoint:"https://api.anthropic.com",doc:"https://docs.anthropic.com/",kind:"anthropic",modelSource:"auto",seedKey:"anthropic"},{id:"groq",name:"Groq",endpoint:"https://api.groq.com/openai/v1",doc:"https://console.groq.com/docs/models",kind:"openai",modelSource:"auto"},{id:"togetherai",name:"TogetherAI",endpoint:"https://api.together.xyz/v1",doc:"https://docs.together.ai/docs/serverless-models",kind:"openai",modelSource:"auto"},{id:"openrouter",name:"OpenRouter",endpoint:"https://openrouter.ai/api/v1",doc:"https://openrouter.ai/models",kind:"openai",modelSource:"auto"},{id:"hugging-face",name:"Hugging Face",endpoint:"https://router.huggingface.co/v1",doc:"https://huggingface.co/docs/inference-providers",kind:"openai",modelSource:"auto"},{id:"mistral",name:"Mistral",endpoint:"https://api.mistral.ai/v1",doc:"https://docs.mistral.ai/getting-started/models/",kind:"openai",modelSource:"auto"},{id:"deepseek",name:"DeepSeek",endpoint:"https://api.deepseek.com",doc:"https://platform.deepseek.com/api-docs/",kind:"openai",modelSource:"auto"}];var GE=class extends Yi.Modal{constructor(t,e){super(t),this.providers=e,this.waitForClose=new Promise((n,i)=>{this.resolvePromise=n,this.rejectPromise=i}),this.open(),this.display()}addHeader(t){t.createEl("h2",{text:"Add a provider",cls:"qa-modal-title"})}display(){this.contentEl.empty(),this.modalEl.addClass("qa-ai-wide-modal"),this.contentEl.addClass("qa-ai-scroll-content"),this.addHeader(this.contentEl);let t=this.contentEl.createDiv({cls:"qa-provider-grid"});for(let e of rz){let n=t.createDiv({cls:"qa-provider-card"});if(n.createDiv({text:e.name,cls:"qa-provider-card-title"}),n.createDiv({text:e.endpoint,cls:"qa-provider-card-endpoint"}),e.doc){let s=n.createEl("a",{text:"Docs",href:e.doc});s.target="_blank",s.rel="noopener noreferrer"}let i="",o=Uq(n,this.app,{value:i,onChange:s=>{i=s}});o.settingEl.addClass("qa-provider-api-setting"),o.addButton(s=>{s.setButtonText("Connect").setCta().onClick(async()=>{try{let a=i.trim();try{new URL(e.endpoint)}catch{new Yi.Notice(`Invalid endpoint URL for ${e.name}.`);return}let l=e.endpoint.toLowerCase();if(["openai.com","generativelanguage.googleapis.com","anthropic","api.groq.com","together.xyz","openrouter.ai","router.huggingface.co","api.mistral.ai","api.deepseek.com"].some(h=>l.includes(h))&&!a){new Yi.Notice(`${e.name} requires an API key.`);return}let d=h=>h.trim().toLowerCase(),u=h=>h.trim().toLowerCase().replace(/\/+$/,"");if(this.providers.some(h=>d(h.name)===d(e.name)&&u(h.endpoint)===u(e.endpoint))){new Yi.Notice(`${e.name} is already configured.`);return}let m={name:e.name,endpoint:e.endpoint,id:Ub(e.id,this.providers),kind:e.kind,apiKey:"",apiKeyRef:a,models:[],modelSource:e.modelSource??"auto",autoSyncModels:!0};s.setButtonText("Connecting..."),s.setDisabled(!0),await this.importInitialModels(m,e),this.providers.push(m),this.close()}catch(a){s.setButtonText("Connect"),s.setDisabled(!1),new Yi.Notice(`Failed to add provider: ${a.message??a}`)}})})}new Yi.Setting(this.contentEl).setName("Custom provider").setDesc("Create any custom endpoint (OpenAI-compatible or otherwise)").addButton(e=>{e.setButtonText("Add custom...").onClick(()=>{let n={id:Ub("custom",this.providers),name:"Custom",endpoint:"",apiKey:"",apiKeyRef:"",models:[],modelSource:"providerApi"};this.providers.push(n),new Yi.Notice("Custom provider added. Open it in the list to configure it."),this.close()})})}async importInitialModels(t,e){try{await WE(this.app,t),new Yi.Notice(`${e.name} connected with ${t.models.length} models.`)}catch(n){let i=n.message??String(n);e.seedKey?(t.models=zb(e.seedKey),new Yi.Notice(`${e.name} added with its built-in model list. Live model loading failed: ${i}`)):new Yi.Notice(`${e.name} added, but loading models failed: ${i} Use "Sync now" in the provider's settings to retry.`)}}onClose(){this.resolvePromise(this.providers??null),super.onClose()}};var gn=require("obsidian");fi();kc();async function jE(r,t){let e="";try{return e=await So(r,t),{ok:!0,modelCount:(await uf({...t,modelSource:"providerApi"},e)).length,apiKeyLinked:!!e}}catch(n){return{ok:!1,error:n?.message||String(n)||"Unknown error",apiKeyLinked:!!e}}}function nz(r){return r.ok?`\u2713 Connected. The provider lists ${`${r.modelCount} model${r.modelCount===1?"":"s"}`}.`:`\u2717 ${r.error}${r.apiKeyLinked?"":" (No API key is linked.)"}`}je();zs();Ka();var Ks=require("obsidian");kc();var YE=class extends Ks.Modal{constructor(e,n){super(e);this.allModels=[];this.filtered=[];this.selectedIds=new Set;this.mode="add";this.resolved=!1;this.loadError=null;this.provider=n,this.waitForClose=new Promise((i,o)=>{this.resolvePromise=i,this.rejectPromise=o}),this.open(),this.loadData().then(()=>this.display())}async loadData(){try{let e=await So(this.app,this.provider);this.allModels=await uf(this.provider,e),this.filtered=this.allModels.slice(),this.loadError=null}catch(e){this.loadError=`${e.message??e}`,new Ks.Notice(`Failed to load model directory: ${this.loadError}`)}}display(){this.contentEl.empty(),this.modalEl.addClass("qa-ai-wide-modal"),this.contentEl.addClass("qa-ai-scroll-content"),this.contentEl.createEl("h2",{text:`Browse models for ${this.provider.name}`,cls:"qa-modal-title"}),new Ks.Setting(this.contentEl).setName("Search").addText(e=>{e.setPlaceholder("Filter by name").onChange(n=>{let i=n.trim().toLowerCase();this.filtered=this.allModels.filter(o=>o.name.toLowerCase().includes(i)),this.renderList()})}).addExtraButton(e=>{e.setIcon("check"),e.setTooltip("Select all"),e.onClick(()=>{this.filtered.forEach(n=>this.selectedIds.add(n.name)),this.renderList()})}).addExtraButton(e=>{e.setIcon("x"),e.setTooltip("Clear selection"),e.onClick(()=>{this.selectedIds.clear(),this.renderList()})}),new Ks.Setting(this.contentEl).setName("Import mode").setDesc("Add will append new models. Replace will overwrite existing models with the selected list.").addDropdown(e=>{e.addOption("add","Add only"),e.addOption("replace","Replace existing"),e.setValue(this.mode),e.onChange(n=>this.mode=n)}).addButton(e=>{e.setButtonText("Import selected").setCta().onClick(()=>this.importSelected())}),this.contentEl.createDiv({cls:"qa-model-directory"}),this.renderList()}renderList(){let e=this.contentEl.querySelector(".qa-model-directory");if(e){if(e.empty(),this.filtered.length===0){let n=this.loadError?`Couldn't load models: ${this.loadError}. Check the API key and endpoint.`:this.allModels.length===0?"No models available for this provider.":"No models match your filter.";e.createDiv({text:n,cls:"qa-model-directory-empty"});return}for(let n of this.filtered){let i=e.createEl("label",{cls:"qa-model-row"}),o=i.createEl("input",{type:"checkbox"});o.checked=this.selectedIds.has(n.name),o.onchange=()=>{o.checked?this.selectedIds.add(n.name):this.selectedIds.delete(n.name)},i.createDiv({text:n.name,cls:"qa-model-row-title"}),i.createDiv({text:`${n.maxTokens.toLocaleString()} tokens max`,cls:"qa-model-row-meta"})}}}importSelected(){if(this.selectedIds.size===0){new Ks.Notice("Select at least one model.");return}try{let n=this.allModels.filter(i=>this.selectedIds.has(i.name)).map(i=>({...i}));if(!n.length){new Ks.Notice("No models selected to import.");return}this.resolved=!0,this.resolvePromise({imported:n,mode:this.mode}),this.close()}catch(e){new Ks.Notice(`Import failed: ${e.message??e}`)}}onClose(){this.resolved||this.resolvePromise(null),super.onClose()}};je();function Ao(r=U.getState()){let t=r.ai?.providers;return Array.isArray(t)?t:[]}function z$(r){U.setState(t=>({ai:{...t.ai,...r}}))}function iz(r){return Ao().find(t=>t.id===r)}function oz(r,t){U.setState(e=>({ai:{...e.ai,providers:e.ai.providers.map(n=>n.id===r?t(n):n)}}))}function KE(r){U.setState(t=>({ai:{...t.ai,providers:t.ai.providers.filter(e=>e.id!==r)}}))}function sz(r){let t={...r};return delete t.lastModelSync,t}function az(r){let t=r.map(i=>i.name.trim()||"Untitled provider"),e=new Map;for(let i of t)e.set(i,(e.get(i)??0)+1);let n=new Set;return t.map((i,o)=>{let s=(e.get(i)??0)>1&&r[o].id?`${i} (${r[o].id})`:i;for(let a=2;n.has(s);a++)s=`${i} (${a})`;return n.add(s),s})}function ry(r){return`${r} model${r===1?"":"s"}`}function Tee(r,t){let e=Math.floor(Math.max(0,t-r)/6e4);if(e<1)return"just now";if(e<60)return`${e} minute${e===1?"":"s"} ago`;let n=Math.floor(e/60);if(n<24)return`${n} hour${n===1?"":"s"} ago`;let i=Math.floor(n/24);return`${i} day${i===1?"":"s"} ago`}function lz(r,t){let e=r.lastModelSync;if(!e)return"Not synced yet.";let n=Tee(e.at,t);return e.error?`Last sync failed ${n}: ${e.error}`:`Last synced ${n} \xB7 ${ry(r.models.length)}.`}function cz(r){switch(r.modelSource??"providerApi"){case"modelsDev":return"the models.dev directory";case"auto":return"the provider's models endpoint (falls back to models.dev)";default:return"the provider's models endpoint"}}function QE(r,t,e){r.setText(t),r.classList.toggle("mod-success",e==="success"),r.classList.toggle("mod-error",e==="error")}function _ee(r){let t=[`Context: ${r.maxTokens.toLocaleString()} tokens`];return r.maxOutputTokens&&t.push(`Output: ${r.maxOutputTokens.toLocaleString()} tokens`),r.supportsTemperature===!1&&t.push("Fixed sampling (no temperature)"),r.releaseDate&&t.push(`Released ${r.releaseDate}`),t.join(" \xB7 ")}var XE=class extends gn.SettingPage{constructor(e,n){super();this.app=e;this.providerId=n;this.unsubscribe=null;this.modelFilter="";this.modelListEl=null;this.syncStatusEl=null;this.connectionResultEl=null}get provider(){return iz(this.providerId)}display(){this.teardown(),this.containerEl.empty();let e=this.provider;if(!e){this.containerEl.createDiv({cls:"setting-item-description",text:"This provider no longer exists."});return}this.renderConnectionGroup(e),this.renderModelSyncGroup(e),this.renderModelsGroup(),this.renderDeleteGroup();let n=e;this.unsubscribe=U.subscribe(()=>{let i=this.provider;if(!i||i===n)return;let o=n;n=i,i.models!==o.models&&this.renderModelList(),(i.lastModelSync!==o.lastModelSync||i.models.length!==o.models.length)&&this.renderSyncStatus()}),this.syncOnOpen(e)}hide(){this.teardown(),super.hide()}teardown(){this.unsubscribe?.(),this.unsubscribe=null,this.modelListEl=null,this.syncStatusEl=null,this.connectionResultEl=null}async syncOnOpen(e){if(e.autoSyncModels&&!U.getState().disableOnlineFeatures)try{await q$(this.app,this.providerId)}catch{}}edit(e){oz(this.providerId,e)}editConnection(e){this.edit(n=>sz(e(n))),this.connectionResultEl&&QE(this.connectionResultEl,"")}close(){let e=this.app.setting;typeof e?.closePage=="function"?e.closePage():this.display()}renderConnectionGroup(e){let n=new gn.SettingGroup(this.containerEl);n.addSetting(i=>{i.setName("Name").setDesc(e.id?`ID: ${e.id}. Scripts can address this provider's models as "${e.id}/model-name".`:"The display name of the provider.").addText(o=>{o.setValue(e.name).onChange(s=>{this.edit(a=>({...a,name:s})),gC(this.app,this,s.trim()||"Untitled provider")})})}),n.addSetting(i=>{i.setName("Endpoint").setDesc("The base URL of the provider's API.").addText(o=>{o.setPlaceholder("https://api.example.com/v1"),o.setValue(e.endpoint).onChange(s=>{this.editConnection(a=>({...a,endpoint:s}))})})}),n.addSetting(i=>{i.setName("Provider type").setDesc("The request format this provider expects. Auto-detect recognizes the official Anthropic and Gemini endpoints and treats everything else as OpenAI-compatible; pick a type explicitly for a proxy or custom endpoint.").addDropdown(o=>{o.addOption("","Auto-detect"),o.addOption("openai","OpenAI-compatible"),o.addOption("anthropic","Anthropic"),o.addOption("gemini","Gemini"),o.setValue(e.kind??""),o.onChange(s=>{this.editConnection(a=>({...a,kind:s||void 0}))})})}),n.addSetting(i=>{M$(i,this.app,{value:e.apiKeyRef??"",hasLegacyKey:!!e.apiKey&&!e.apiKeyRef,onChange:o=>{this.editConnection(s=>({...s,apiKeyRef:o,apiKey:""}))}})}),n.addSetting(i=>{i.setName("Connection").setDesc("Check that QuickAdd can reach this provider's models endpoint with the linked key.");let o=i.descEl.createDiv({cls:"qa-ai-status-line"});this.connectionResultEl=o,i.addButton(s=>{s.setButtonText("Test connection").onClick(async()=>{let a=this.provider;if(a){s.setDisabled(!0),QE(o,"Testing\u2026");try{let l=await jE(this.app,a);QE(o,nz(l),l.ok?"success":"error")}finally{s.setDisabled(!1)}}})})})}renderModelSyncGroup(e){let n=cz(e),i=new gn.SettingGroup(this.containerEl).setHeading("Model sync");i.addSetting(o=>{o.setName("Model source").setDesc("Where QuickAdd looks when browsing or syncing models for this provider.").addDropdown(s=>{s.addOption("providerApi","Provider models endpoint (requires API key)"),s.addOption("modelsDev","models.dev directory"),s.addOption("auto","Automatic (try provider, fall back to models.dev)"),s.setValue(e.modelSource??"providerApi"),s.onChange(a=>{this.editConnection(l=>({...l,modelSource:a})),this.display()})})}),i.addSetting(o=>{o.setName("Auto-sync models").setDesc(`Import new models and refreshed context limits from ${n} once a day and when this page opens.`),this.syncStatusEl=o.descEl.createDiv({cls:"qa-ai-status-line"}),this.renderSyncStatus(),o.addToggle(s=>{s.setValue(!!e.autoSyncModels).onChange(a=>{this.edit(l=>({...l,autoSyncModels:a}))})}).addButton(s=>{s.setButtonText("Sync now").onClick(()=>this.syncNow(s))})}),i.addSetting(o=>{o.setName("Browse models").setDesc(`Pick models to import from ${n}.`).addButton(s=>{s.setButtonText("Browse\u2026").onClick(()=>this.browseModels())})})}async syncNow(e){let n=this.provider;if(!n)return;let i=cz(n),o=n.models.map(s=>({...s}));e.setDisabled(!0);try{let s=await q$(this.app,this.providerId),a=this.provider;if(!s||!a)return;let l=new Set(s.map(d=>d.name)),c=U$(o,a.models.filter(d=>l.has(d.name)));new gn.Notice(c.added>0||c.updated>0?`Synced from ${i}: ${c.added} new, ${c.updated} updated.`:`Synced from ${i}: already up to date.`)}catch(s){new gn.Notice(`Sync failed: ${s.message??String(s)}`)}finally{e.setDisabled(!1)}}async browseModels(){let e=this.provider;if(!e)return;let n=await new YE(this.app,e).waitForClose;if(!n)return;let{imported:i,mode:o}=n;this.edit(s=>({...s,models:o==="replace"?i:L$(s.models,i)})),new gn.Notice(`Imported ${ry(i.length)}${o==="replace"?" (replaced the list)":""}.`)}renderModelsGroup(){let e=new gn.SettingGroup(this.containerEl).setHeading("Models").addClass("mod-list","qa-ai-models-group");e.addSearch(n=>{n.setPlaceholder("Filter models").setValue(this.modelFilter).onChange(i=>{this.modelFilter=i,this.renderModelList()})}),e.addExtraButton(n=>{n.setIcon("plus").setTooltip("Add model").onClick(()=>{this.addModel()})}),this.modelListEl=e.listEl,this.renderModelList()}renderModelList(){let e=this.modelListEl,n=this.provider;if(!e||!n)return;e.empty();let i=n.models.filter(a=>a.deprecated);if(i.length>0){let a=new Set(i.map(c=>c.name));new gn.Setting(e).setName(`${ry(i.length)} retired by the provider`).setDesc("Requests to them may fail. Commands that use them need another model.").addButton(c=>{c.setButtonText("Remove retired").onClick(async()=>{await wi(this.app,{title:`Remove ${ry(a.size)} retired by the provider from ${n.name}?`,action:"Remove"})&&this.edit(u=>({...u,models:u.models.filter(p=>!a.has(p.name))}))})}).settingEl.addClass("qa-ai-retired-notice")}let o=this.modelFilter.trim().toLowerCase(),s=np(n.models).filter(a=>!o||a.name.toLowerCase().includes(o));if(s.length===0){new gn.Setting(e).setName(o?`No models match "${this.modelFilter.trim()}".`:"No models yet. Sync, browse, or add one.").settingEl.addClass("mod-empty-state");return}for(let a of s){let l=new gn.Setting(e).setName(a.name).setDesc(_ee(a));a.deprecated&&l.nameEl.createSpan({cls:"qa-ai-model-badge",text:"Retired"}),l.addExtraButton(c=>{c.setIcon("trash-2").setTooltip("Delete model").onClick(()=>{this.deleteModel(a.name)})})}}async deleteModel(e){await wi(this.app,{title:`Delete ${e}?`,action:"Delete"})&&this.edit(i=>({...i,models:i.models.filter(o=>o.name!==e)}))}async addModel(){let e,n;try{e=await ir.Prompt(this.app,"Model name"),n=await ir.Prompt(this.app,"Context window (tokens)")}catch{return}let i=e.trim();if(!i){new gn.Notice("Model name cannot be empty.");return}let o=n.trim();if(!/^[1-9]\d*$/.test(o)||!Number.isSafeInteger(Number(o))){new gn.Notice("The context window must be a positive whole number.");return}if(this.provider?.models.some(s=>s.name===i)){new gn.Notice(`${i} is already in the list.`);return}this.edit(s=>({...s,models:[...s.models,{name:i,maxTokens:Number(o)}]}))}renderSyncStatus(){let e=this.provider;!this.syncStatusEl||!e||QE(this.syncStatusEl,lz(e,Date.now()),e.lastModelSync?.error?"error":void 0)}renderDeleteGroup(){new gn.SettingGroup(this.containerEl).addSetting(e=>{e.setName("Delete provider").setDesc("Commands that use its models will need another model.").addButton(n=>{n.setButtonText("Delete").setDestructive().setCta().onClick(async()=>{let i=this.provider;!i||!await wi(this.app,{title:`Delete ${i.name.trim()||"this provider"}?`,message:"Commands that use its models will need another model.",action:"Delete"})||(KE(this.providerId),this.close())})})})}};var JE="AI Assistant";function kee(r){return r===0?"No providers":`${r} provider${r===1?"":"s"}`}function dz(r){return Ao().find(e=>e.id===r)?.models.filter(e=>e.deprecated).length??0}function uz(r){return JSON.stringify(r.map(t=>[t.id,t.name,t.endpoint]))}function pz(r){return{type:"page",name:JE,desc:"Providers, models, and defaults for AI commands.",displayValue:()=>kee(Ao().length),visible:()=>!U.getState().disableOnlineFeatures,items:[See(r),Pee()]}}function See(r){let t=Ao(),e=az(t);return{type:"list",heading:"Providers",emptyState:"No providers yet. Add one to use AI commands.",addItem:{name:"Add provider",action:()=>{Aee(r)}},onDelete:n=>{Iee(r,t[n])},items:t.map((n,i)=>({type:"page",name:e[i],desc:n.endpoint,displayValue:()=>{let o=dz(n.id);return o?`${o} retired`:""},status:()=>dz(n.id)?"warning":null,page:()=>new XE(r,n.id??"")}))}}async function Aee(r){let t=[...Ao()],e=t.length;await new GE(r,t).waitForClose;let n=t.slice(e);n.length!==0&&U.setState(i=>({ai:{...i.ai,providers:[...Ao(i),...n]}}))}async function Iee(r,t){if(!t?.id)return;await wi(r,{title:`Delete ${t.name.trim()||"this provider"}?`,message:"Commands that use its models will need another model.",action:"Delete"})&&KE(t.id)}function Pee(){return{type:"group",heading:"Defaults",items:[{name:"Default model",desc:"The model new AI commands start with. \u201CAsk me\u201D prompts you to choose a model each run.",aliases:["AI provider","provider","API key","LLM"],render:r=>$ee(r)},{name:"Prompt template folder",desc:"The folder QuickAdd reads prompt templates from.",control:{type:"folder",key:"ai.promptTemplatesFolderPath",placeholder:"prompts/"}},{name:"Show assistant",desc:"Show progress notices while the AI Assistant works.",control:{type:"toggle",key:"ai.showAssistant"}},{name:"Confirm AI tool calls",desc:"When an AI agent runs script-defined or built-in tools, ask before executing. A tool that requires approval is always confirmed.",control:{type:"dropdown",key:"ai.confirmToolCalls",defaultValue:"destructive",options:{destructive:"Destructive tools only (recommended)",always:"Always confirm every tool",never:"Never (use each tool's own setting)"}}},{name:"Default system prompt",desc:"The system prompt new AI commands start with.",render:r=>Fee(r)}]}}function $ee(r){let t=()=>{};return r.addDropdown(e=>{let n=()=>{let o=U.getState().ai;e.selectEl.empty(),Fx(e,{model:o.defaultModel,modelRef:o.defaultModelRef},s=>z$({defaultModel:s.model,defaultModelRef:s.modelRef}))};n();let i=Ao();t=U.subscribe(o=>{let s=Ao(o);s!==i&&(i=s,n())})}),()=>t()}function Fee(r){r.settingEl.addClass("qa-ai-system-prompt-setting");let t=U.getState().ai.defaultSystemPrompt??"";r.addTextArea(e=>{e.inputEl.addClass("qa-ai-system-prompt-input"),e.inputEl.setAttribute("aria-label","Default system prompt");let n=sx(r.controlEl,e.inputEl,t);e.setValue(t).onChange(i=>{z$({defaultSystemPrompt:i}),n(i)})})}nt();var ZE="ai.",tT=class extends ny.PluginSettingTab{constructor(e,n){super(e,n);this.choiceView=null;this.globalVariablesViewHandle=null;this.packagesUnsubscribe=null;this.plugin=n,this.icon="zap";let i=Ao().map(a=>({...a}));qb(i)&&U.setState(a=>({ai:{...a.ai,providers:i}}));let o=a=>JSON.stringify([uz(Ao(a)),ei(a.templateFolderPaths)]),s=o(U.getState());n.register(U.subscribe(a=>{let l=o(a);l!==s&&(s=l,this.update())}))}openAIAssistantPageFromCommand(){if(U.getState().disableOnlineFeatures){new ny.Notice("QuickAdd: Turn off \u201CDisable AI & online features\u201D in QuickAdd settings to use the AI Assistant.");return}dc(this.app,this.plugin.manifest.id)&&this.openAIAssistantPage()}openAIAssistantPage(){F1(this.app,this,[JE])||new ny.Notice(`QuickAdd: Open the ${JE} page under "AI & online" below.`)}getControlValue(e){let n=U.getState();if(e.startsWith(ZE)){let i=e.slice(ZE.length);return n.ai[i]}return e==="inputPrompt"?n.inputPrompt==="multi-line":n[e]}setControlValue(e,n){if(e.startsWith(ZE)){let i=e.slice(ZE.length);U.setState(o=>({ai:{...o.ai,[i]:n}}));return}if(e==="inputPrompt"){U.setState({inputPrompt:n?"multi-line":"single-line"});return}if(e==="persistInputPromptDrafts"){let i=!!n;U.setState({persistInputPromptDrafts:i}),i||Bn.getInstance().clearAll();return}U.setState({[e]:n})}getSettingDefinitions(){return Bq({choices:e=>this.renderChoicesView(e),packages:e=>this.renderPackages(e),dateAliases:e=>this.renderDateAliases(e),globalVariables:e=>this.renderGlobalVariablesView(e),developmentInfo:e=>this.renderDevInfo(e)},!1,pz(this.app),this.templateFoldersList())}templateFoldersList(){let e=eT(),n={name:"Add folder",action:()=>{this.addTemplateFolder()}},i=["Template folders"];return e.length===0?{type:"group",heading:"Template folders",items:[{...n,desc:"No folders yet. QuickAdd suggests templates from the whole vault.",aliases:i}]}:{type:"list",heading:"Template folders",addItem:n,onDelete:o=>{U.setState({templateFolderPaths:eT().filter(s=>s!==e[o])})},items:e.map(o=>({name:o,aliases:i}))}}async addTemplateFolder(){let e=new Set(eT()),n=Ga(La(this.app)).filter(s=>s!=="/"&&!e.has(s)),i;try{i=await It.Suggest(this.app,n,n,"Choose a template folder")}catch(s){if(Be(s))return;throw s}let o=eT();o.includes(i)||U.setState({templateFolderPaths:[...o,i]})}hide(){super.hide(),this.destroySettingViews()}destroySettingViews(){this.choiceView?.handle.destroy(),this.choiceView=null,this.globalVariablesViewHandle?.destroy(),this.globalVariablesViewHandle=null,this.packagesUnsubscribe?.(),this.packagesUnsubscribe=null}prepareFullWidthSetting(e){e.infoEl.remove(),e.settingEl.addClass("qa-setting-full-width"),e.controlEl.addClass("qa-setting-full-width-control")}mountView(e,n){this.prepareFullWidthSetting(e),this.globalVariablesViewHandle?.destroy();let i=n(e.controlEl);return this.globalVariablesViewHandle=i,()=>{i.destroy(),this.globalVariablesViewHandle===i&&(this.globalVariablesViewHandle=null)}}renderChoicesView(e){if(this.prepareFullWidthSetting(e),!this.choiceView){let i=createDiv(),o=this.mountChoiceView(i);if(!o.ok)return e.controlEl.appendChild(i),()=>o.destroy();this.choiceView={el:i,handle:o}}let{el:n}=this.choiceView;return e.controlEl.appendChild(n),()=>n.remove()}mountChoiceView(e){return vi(e,KP,{app:this.app,plugin:this.plugin,choices:U.getState().choices,saveChoices:n=>{U.setState({choices:n})},openAISettings:()=>this.openAIAssistantPage()},{what:"your choices",fallbackComponent:tf})}renderGlobalVariablesView(e){return this.mountView(e,n=>vi(n,QP,{app:this.app,plugin:this.plugin},{what:"your global variables"}))}packagesDesc(e){return F$(e?`${NE} Export becomes available once you have a choice. `:`${NE} `,es.packages,"Learn more about packages")}renderPackages(e){let n;e.addButton(a=>{n=a,a.setButtonText("Export package\u2026").onClick(()=>{let l=pr(U.getState().choices);new hE(this.app,this.plugin,l).open()})}),e.addButton(a=>a.setButtonText("Import package\u2026").onClick(()=>{new OE(this.app,{onImported:(l,c)=>LE(this.plugin,c,l)}).open()}));let i=a=>{e.setDesc(this.packagesDesc(a)),n&&(n.setDisabled(a),a?n.setTooltip("Nothing to export yet"):n.buttonEl.removeAttribute("aria-label"))},o=pr(U.getState().choices).length===0;i(o),this.packagesUnsubscribe?.();let s=U.subscribe(a=>{let l=pr(a.choices).length===0;l!==o&&(o=l,i(l))});return this.packagesUnsubscribe=s,()=>{s(),this.packagesUnsubscribe===s&&(this.packagesUnsubscribe=null)}}renderDateAliases(e){e.settingEl.addClass("qa-date-alias-setting"),e.controlEl.addClass("qa-date-alias-control");let n=null;e.addTextArea(i=>{n=i,i.setPlaceholder(`t = today
- tm = tomorrow
- yd = yesterday`).setValue(lS(U.getState().dateAliases)).onChange(o=>{U.setState({dateAliases:XD(o)})}),i.inputEl.addClass("qa-date-alias-input")}),e.addButton(i=>{i.setButtonText("Reset to defaults").onClick(()=>{U.setState({dateAliases:ip}),n?.setValue(lS(ip))}),i.buttonEl.addClass("qa-date-alias-reset")})}renderDevInfo(e){let n=e.settingEl.createDiv();n.addClass("qa-dev-info"),Vq(n,{branch:null,commit:null,dirty:null})}};function eT(){return ei(U.getState().templateFolderPaths)}cS();ye();Xb();nt();var iy=class extends Fp{constructor(){super(...arguments);this.ErrorLog=[]}logError(e,n,i){let o=this.getQuickAddError(e,"ERROR",n,i);this.addMessageToErrorLog(o);let s=i||new Error(e);console.error(this.formatOutputString(o),s)}logWarning(e,n,i){let o=this.getQuickAddError(e,"WARNING",n,i);this.addMessageToErrorLog(o);let s=i||new Error(e);console.warn(this.formatOutputString(o),s)}logMessage(e,n,i){let o=this.getQuickAddError(e,"LOG",n,i);this.addMessageToErrorLog(o)}addMessageToErrorLog(e){this.ErrorLog.push(e),this.ErrorLog.length>kS&&(this.ErrorLog=this.ErrorLog.slice(-kS))}clearErrorLog(){this.ErrorLog=[]}};var H$=require("obsidian");Xb();var rT=class extends Fp{constructor(e){super();this.plugin=e}logError(e,n,i){let o=this.getQuickAddError(e,"ERROR",n,i);new H$.Notice(this.formatOutputString(o),15e3)}logWarning(e,n,i){let o=this.getQuickAddError(e,"WARNING",n,i);new H$.Notice(this.formatOutputString(o))}logMessage(e,n,i){}};ye();nt();nt();var mz=1e4,fz=50,Mee=/plugin:([^\s:)]+)/;function Ree(r){let t=r.stack??"",e=`${r.name}: ${r.message}`;return(t.startsWith(e)?t.slice(e.length):t).split(`
- `)}function Dee(r){for(let t of Ree(r)){let e=Mee.exec(t);if(e)return{pluginId:e[1],frame:t.trim()}}return null}function Oee(r,t){return`${r.name}@${t}`}function hz(r,t=Date.now){let e=r.manifest.id,n=new Map;r.registerDomEvent(window,"unhandledrejection",i=>{let o=i.reason,s=o instanceof Error?Dee(o):null;if(s?.pluginId!==e)return;if(Be(o)){i.preventDefault();return}let a=o,l=Oee(a,s.frame),c=t(),d=n.get(l);if(n.set(l,c),!(d!==void 0&&c-d<mz)){if(n.size>=fz){for(let[u,p]of n)c-p>=mz&&n.delete(u);if(n.size>=fz){let u=n.keys().next();!u.done&&u.value!==l&&n.delete(u.value)}}Me(a,"A QuickAdd action failed")&&i.preventDefault()}})}by();lt();nt();var __=class{constructor(t,e,n,i){this.app=t;this.plugin=e;this.choices=n;this.choiceExecutor=i}async run(){let t=Jt(this.choices).filter(e=>e.type==="Macro"&&e.runOnStartup);for(let e of t)try{await new Xs(this.app,this.plugin,e,this.choiceExecutor,new Map).run()}catch(n){Me(n,`Startup macro '${e.name}' failed`)}}};var mG=require("obsidian");TT();ye();Ql();hu();E_();Ip();wy();function k_(r,t){return!t.enabled||t.destination.type!=="specifiedFile"||mg(r,t.destination)?null:`Append link target file not found or is not a Markdown file: ${t.destination.path}`}async function S_(r,t,e,n,i){e.enabled&&(e.destination?.type==="specifiedFile"?await Z0(r,t,e,i):n&&!Da(e.placement)?await _2(r,n,t):i?await FF(r,t,e,i):await FF(r,t,e))}async function A_(r){try{await eL(r)}catch(t){S.logWarning(`Could not copy link to clipboard for '${r.path}': ${t instanceof Error?t.message:String(t)}`)}}async function Df({app:r,file:t,opening:e,originLeaf:n,forceFocus:i}){let o=en(e),s=i??o.focus??!0;return NW(r,t,s)||await x_(r,t,{...o,...i===void 0?{}:{focus:i},originLeaf:n}),s}var Lf=require("obsidian");Rd();Ve();BT();Gi();ye();ja();var P_=require("obsidian");rr();ja();kf();var I_=class extends P_.FuzzySuggestModal{constructor(e,n,i){super(e);this.settled=!1;this.modalEl.addClass("qa-suggester"),this.rows=i.map(o=>({kind:"candidate",candidate:o})),this.action=uc(n.existingNoteAction),this.promise=new Promise((o,s)=>{this.resolvePromise=o,this.rejectPromise=s}).then(o=>o.kind==="candidate"?Dy(o.candidate.item):ra(o.title)),this.setPlaceholder(`Search notes or create ${n.name}`),this.open()}getItems(){return this.rows}getItemText(e){return e.kind==="candidate"?e.candidate.display:e.title}getSuggestions(e){let n=e.trim(),i=Xi(n),o=a=>a.kind==="candidate"&&a.candidate.exactKeys.includes(i),s=super.getSuggestions(n).sort((a,l)=>Number(o(l.item))-Number(o(a.item)));return n&&!this.rows.some(o)&&s.unshift({item:{kind:"create",title:n},match:{score:Number.NEGATIVE_INFINITY,matches:[]}}),s}renderSuggestion({item:e},n){if(e.kind==="candidate"&&e.candidate.renderPath){let o=e.candidate;Ym(n,e.candidate.renderPath),this.action!=="Open"&&n.querySelector(".suggestion-title")?.prepend(`${this.action}: `),o.renderAlias&&n.querySelector(".suggestion-content")?.createDiv({cls:"suggestion-note",text:`Alias: ${o.renderAlias}`});return}n.addClass("mod-complex");let i=n.createDiv({cls:"suggestion-content"});i.createDiv({cls:"suggestion-title",text:e.kind==="create"?`Create new note: ${e.title}`:e.candidate.unresolvedTitle??e.candidate.title}),e.kind==="create"?(0,P_.setIcon)(n.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"}),"file-plus"):i.createDiv({cls:"suggestion-note",text:"Unresolved link"})}selectSuggestion(e,n){this.settled=!0,super.selectSuggestion(e,n)}onChooseItem(e){this.settled=!0,this.resolvePromise(e)}onClose(){super.onClose(),this.settled||this.rejectPromise(rn())}};wu();Cu();kn();nt();rr();ja();kf();async function QW(r,t,e){let{candidates:n}=KT(r,t),i=`Search notes or create ${t.name}`,o=uc(t.existingNoteAction);try{let s=await Ki(e,{remote:async a=>{let l=await Qi(a,{items:n.map(c=>({value:Dy(c.item),title:c.renderPath&&o!=="Open"?`${o}: ${c.title}`:c.title})),placeholder:i,allowCustomInput:!0,what:"the note-discovery picker"});return typeof l=="string"?ra(l):l},headless:()=>{throw new ue(`'${t.name}' needs to ask which note to open or create, but this run is non-interactive. Pass the note name (e.g. value-value=<name>), or re-run with the ui flag.`)},app:()=>new I_(r,t,n).promise});return Oy(r,s)}catch(s){throw Be(s)?new et("Input cancelled by user"):s}}kf();Jd();If();wu();Cu();Ql();gi();Lc();hu();nt();var Of=class{constructor(t){this.executor=t;this.closed=!1}success(t,e){this.closed=!0,this.executor.recordExecutionResult?.({status:"success",file:t,effect:e})}failure(t){this.closed||this.executor.recordExecutionResult?.({status:"error",reason:t})}};function $_(r){return r instanceof Error?r.message||XW:String(r)||XW}var XW="Choice execution failed.";Qo();Fm();DT();VT();ti();kn();yy();tn();function F_(r,t){if(r.content!==t.before)return null;let e=[...t.edits].sort((s,a)=>s.from-a.from),n="",i=0;for(let s of e){if(s.from<i||s.to<s.from||s.to>t.before.length)return null;n+=t.before.slice(i,s.from)+s.text,i=s.to}if(n+=t.before.slice(i),n!==t.after)return null;let o=[];for(let s of r.offsets){let a=0;for(let l of e){let c=l.from!==l.to;if(c&&l.from<=s&&s<l.to)return null;(l.to<s||c&&l.to===s)&&(a+=l.text.length-(l.to-l.from))}o.push(s+a)}return{offsets:o,content:n}}tr();var M_=class extends Nc{constructor(e,n,i,o,s=null,a=[i]){super(e,n,o);this.originLeaf=s;this.chain=a;this.choiceExecutor=o,this.outcome=new Of(o),this.choice=i,this.formatter.setPromptRunContext({draftScopeId:i.id,choiceName:i.name}),this.formatter.choiceChain=a}async run(){this.cursorPlacement=null;let e=null,n=null,i=null;try{Lr(this.choice.templatePath,()=>`Invalid template path for ${this.choice.name}. ${this.choice.templatePath.length===0?"Template path is empty.":`Template path is not valid: ${this.choice.templatePath}`}`);let o=Kl(this.choice.appendLink);this.setLinkToCurrentFileBehavior(o.enabled&&!o.requireActiveFile?"optional":"required");let s=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:Cr;if(bc(this.choice,s,this.choiceExecutor.variables.get("value"))){let h=LH(this.choiceExecutor,this.choice.id),g=h?Oy(this.app,h):await QW(this.app,this.choice,this.choiceExecutor);if(g.kind==="existing"){let v=bC(this.choice.existingNoteAction);if(v==="open"){await this.openDiscoveredExistingNote(g.file),this.outcome.success(g.file,"unchanged");return}i={file:g.file,mode:v},e=this.setTemporaryValueVariable(g.file.basename)}else e=this.setTemporaryValueVariable(g.title),n=g.vaultRelativePath??null;await this.choiceExecutor.resolveDateOrigin?.(this.choice)}if(!this.validateAppendLinkDestination(o))return;let a=await this.resolveTemplateSourcePath(this.choice.templatePath);if(i&&Rn(this.app,a)?.path===i.file.path)throw new ue("Cannot apply a template to its own template source.");let l=i?.file.path??await this.resolveNewNotePath({templatePath:a,format:s,discoveryVaultRelativePath:n}),c,d=!1,u=!1,p="created";if(i){if(!Bc(a))throw new ue("Only Markdown templates can be applied to a selected note.");if(c=await this.applyExistingFileUpdate(i.mode,i.file,a,o),!c){this.failRun(this.lastTemplateFileFailure??`Could not apply template to '${l}'.`,"none");return}p="changed"}else if(await this.app.vault.adapter.exists(l)){let h=await this.getSelectedFileExistsMode(),g=nm(h);p=g.resolutionKind==="reuseExisting"?"unchanged":g.resolutionKind==="createNew"?"created":"changed";let v=g.requiresExistingFile?this.findExistingFile(l):null;if(g.requiresExistingFile&&(!(v instanceof Lf.TFile)||v.extension!=="md"&&v.extension!=="canvas"&&v.extension!=="base")){this.failRun(`'${l}' already exists but could not be resolved as a markdown, canvas, or base file.`);return}if({createdFile:c,shouldAutoOpen:d}=await this.applyFileExistsMode(h,l,v,a,o),!c){this.lastTemplateFileFailure?this.failRun(this.lastTemplateFileFailure,"none"):this.failRun(`Could not resolve file exists behavior for '${l}'.`,"warning");return}}else{if(c=await this.createFileWithTemplate(l,a),!c){this.failRun(this.lastTemplateFileFailure??`Could not create file '${l}'.`,"none");return}u=!0}this.outcome.success(c,p);let m=this.cursorPlacement;if(o.enabled&&c)try{await S_(this.app,c,o,this.choiceExecutor.focusedProperty,this.cursorPlacement?h=>{this.cursorPlacement&&h.filePath===c?.path&&(this.cursorPlacement=F_(this.cursorPlacement,h))}:void 0)}catch(h){if(h instanceof at)throw h;S.logWarning(`Created '${c.basename}' but could not insert the link: ${h instanceof Error?h.message:String(h)}`)}this.choice.copyLinkToClipboard&&c&&await A_(c),(this.choice.openFile||d)&&c?(await Df({app:this.app,file:c,opening:this.choice.fileOpening,originLeaf:this.originLeaf}),!this.templaterCursorHandled&&!await bu(this.app,c)&&this.placeCursor(c,m)):this.cursorPlacement&&Js(this.app,c)?!this.templaterCursorHandled&&!await bu(this.app,c)&&this.placeCursor(c,m):u&&!o.enabled&&!this.choice.copyLinkToClipboard&&new Lf.Notice(`Created '${c.basename}'.`)}catch(o){if(Mc(o,{logPrefix:"Template execution aborted",noticePrefix:"Template execution aborted",defaultReason:"Template execution aborted"})){this.choiceExecutor.signalAbort?.(o);return}Bn.getInstance().markExecutionScopeFailed(),this.outcome.failure($_(o)),Me(o,`Error running template choice "${this.choice.name}"`)}finally{e?.()}}failRun(e,n="error"){Bn.getInstance().markExecutionScopeFailed(),n==="warning"?S.logWarning(e):n==="error"&&S.logError(e),this.outcome.failure(e)}async resolveNewNotePath({templatePath:e,format:n,discoveryVaultRelativePath:i}){let o="";if(i)o=Zn(i);else if(this.choice.folder.enabled)o=await this.getFolderPath();else{let u=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");o=u===this.app.vault.getRoot()?"":u.path}this.formatter.setTargetFolderPath(o),this.choice.folder.enabled&&this.formatter.setPromptRunContext({destination:o,destinationKind:"folder"});let s=i||await this.formatter.formatFileName(n,"noteTitle"),a=Nr(s,"File name"),{fileName:l,strippedPrefix:c}=i?{fileName:a,strippedPrefix:!1}:this.stripDuplicateFolderPrefix(a,o),d=this.shouldTreatFormattedNameAsVaultRelativePath(a,c,this.choice.folder.enabled);return this.normalizeTemplateFilePath(i||d?"":o,l,e)}setTemporaryValueVariable(e){let n=this.choiceExecutor.variables,i=n.has("value"),o=n.get("value");return n.set("value",e),()=>{if(i){n.set("value",o);return}n.delete("value")}}validateAppendLinkDestination(e){let n=k_(this.app,e);return n?(this.failRun(n),!1):!0}async getSelectedFileExistsMode(){var i;if((i=this.choice).fileExistsBehavior??(i.fileExistsBehavior={kind:"prompt"}),this.choice.fileExistsBehavior.kind==="apply")return this.choice.fileExistsBehavior.mode;let e=z1(),n="If the target file already exists";return await Ki(this.choiceExecutor,{remote:o=>Qi(o,{items:e.map(s=>({value:s.id,title:s.label})),placeholder:n,what:'the "file already exists" chooser'}),headless:()=>{throw new ue(`'${this.choice.name}' needs to ask what to do because a note with that name already exists, but this run is non-interactive. Set the choice's "If the file already exists" behaviour to a specific action (e.g. Increment, Overwrite), or re-run with the ui flag.`)},app:()=>It.Suggest(this.app,e.map(o=>o.label),e.map(o=>o.id),n)})}async applyFileExistsMode(e,n,i,o,s){let a=nm(e);switch(a.resolutionKind){case"modifyExisting":return{createdFile:await this.applyExistingFileUpdate(a.id,i,o,s),shouldAutoOpen:!1};case"createNew":{let l=await j1(n,a.id,async d=>await this.app.vault.adapter.exists(d)),c=await this.createFileWithTemplate(l,o);return c&&l!==n&&!this.choice.openFile&&new Lf.Notice(`Created '${c.basename}'.`),{createdFile:c,shouldAutoOpen:!1}}case"reuseExisting":return S.logMessage(`Opening existing file: ${i.path}`),{createdFile:i,shouldAutoOpen:!0}}}async openDiscoveredExistingNote(e){await Df({app:this.app,file:e,opening:this.choice.fileOpening,originLeaf:this.originLeaf,forceFocus:!0})}async applyExistingFileUpdate(e,n,i,o){return e==="overwrite"?this.overwriteFileWithTemplate(n,i):this.appendToExistingFileWithTemplate(n,i,e==="appendTop"?"top":"bottom",o)}async appendToExistingFileWithTemplate(e,n,i,o){if(e.extension==="canvas"||e.extension==="base")return this.lastTemplateFileFailure=`Cannot append to '${e.path}': appending a template to a ${e.extension} file would corrupt it. Use the "Overwrite" file-exists option instead.`,Bn.getInstance().markExecutionScopeFailed(),S.logError(this.lastTemplateFileFailure),null;if(e.extension!=="md")return await this.appendToFileWithTemplate(e,n,i);let s=new Cf(this.app,this.plugin,e,n,i,this.choiceExecutor,n);s.setPromptRunContext({draftScopeId:this.choice.id,choiceName:this.choice.name,destination:e.path,destinationKind:"file"}),s.choiceChain=this.chain,s.setLinkToCurrentFileBehavior(o.enabled&&!o.requireActiveFile?"optional":"required");let a=await this.withAnonymousValueForInsertEngine(()=>s.apply());return this.cursorPlacement=s.getCursorPlacement(),a}async withAnonymousValueForInsertEngine(e){let n=this.formatter.getAnonymousValue(),i=this.choiceExecutor.variables;if(!(n!==void 0&&!i.has("value")))return await e();let s=this.setTemporaryValueVariable(n);try{return await e()}finally{s()}}findExistingFile(e){let n=this.app.vault.getAbstractFileByPath(e);if(n instanceof Lf.TFile)return n;if(n)return null;let i=e.toLowerCase(),o=this.app.vault.getFiles().filter(s=>s.path.toLowerCase()===i);if(o.length===1)return o[0];if(o.length>1){let s=o.map(a=>a.path).join(", ");S.logError(`Multiple files match '${e}' when ignoring case: ${s}`)}return null}async formatFolderPaths(e){let n=[];for(let i of e)n.push(await this.formatter.formatFolderPath(i));return n}async getFolderPath(){let e=(await this.formatFolderPaths([...this.choice.folder.folders])).map(l=>this.canonicalFolderPath(l)),n=this.getCurrentFolderSuggestion(),i=n?[n]:[],o=this.choice.folder,s=e,a=e;if(o?.chooseWhenCreatingNote)s=Ga(La(this.app)),a=void 0;else if(o?.createInSameFolderAsActiveFile){let l=this.app.workspace.getActiveFile();if(!l||!l.parent)return S.logWarning("No active file or active file has no parent. Cannot create file in same folder as active file. Creating in root folder."),"";s=[l.parent.path],a=void 0}else o?.chooseFromSubfolders&&(s=w1(Ga(La(this.app)),e));return this.getOrCreateFolder(s,{allowCreate:!0,allowedRoots:a,topItems:i,executor:this.choiceExecutor})}getCurrentFolderSuggestion(){let e=this.app.workspace.getActiveFile(),n=e?.parent;return!e||!n?null:{path:n.path??"",label:"<current folder>"}}};Pa();mf();hu();Ip();var ia=require("obsidian");is();nl();Rd();Ds();Ve();f_();Pa();_p();Rc();f_();mu();vM();v_();function JW({capture:r,targetString:t,fileContent:e,insertAfter:n,task:i}){let o=r.content,s=n?.orderBy??{by:"insertion",direction:"desc",unparseable:"bottom"},a=t.split(/\r?\n/,1)[0],l=oi([a])[0]?.level??0,c=Ia(r,`${t}
- `),d=()=>{let w=fu(e,c.content,{separateBlockquotes:!0});return Nl(c,w.content,w.insertedStartOffset===null||c.cursor.kind==="none"?null:w.insertedStartOffset+c.cursor.value)};if(l===0)return d();let u=jl(e),p=u.map(w=>w.replace(/\r$/,"")),m=CM(e),h=zy(p),g=a.replace(/\r$/,"").trimEnd(),v=h.findIndex((w,T)=>T>=m&&w.trimEnd()===g);if(v!==-1){let w=n?.insertAtEnd?Hy(h,hl(h,v,h_(!!n?.considerSubsections,h,v))??h.length-1,e,o):g_(h,v,e,n?.blankLineAfterMatchMode??"auto"),T=$f(o,e,w,i,r.cursor.kind==="offset"?r.cursor.value:void 0);return Nl(r,T.content,T.insertedEndOffset)}let b=typeof window<"u"?window.moment:void 0,y=eW(p,a,l,s,b,m);if(y.mode==="bodyStart")return d();let C=lW(u,y,c.content,e,c.cursor.kind==="offset"&&c.cursor.source==="marker"?c.cursor.value:void 0);return Nl(c,C.content,C.insertedEndOffset)}is();_p();Ve();Lc();kn();Pa();xu();mf();v_();Rc();tn();xx();var Hne=/^[ \t\r\n\f\v]*$/;function Wne(r){return Hne.test(r)}var R_=class extends _i{constructor(){super(...arguments);this.file=null;this.fileContent="";this.sourcePath=null;this.useSelectionAsCaptureValue=!0;this.clipboardImageFallbackEnabled=!1;this.createdClipboardAttachmentPaths=[];this.templaterProcessed=!1;this.insertAfterTargetOverride=null;this.lastResolvedInsertAfterHeading=null;this.linebreaksProcessed=!1;this.splitValueLines=!1}setDestinationFile(e){this.file=e,this.sourcePath=e.path,this.clipboardAttachmentLink=void 0,this.setTargetFolderPath(Zn(e.path)),this.setPromptRunContext({destination:e.path,destinationKind:"file"})}setDestinationSourcePath(e){this.sourcePath=e,this.file=null,this.clipboardAttachmentLink=void 0,this.setTargetFolderPath(Zn(e)),this.setPromptRunContext({destination:e,destinationKind:"file"})}setUseSelectionAsCaptureValue(e){this.useSelectionAsCaptureValue=e}setInsertAfterTargetOverride(e){this.insertAfterTargetOverride=e}getResolvedInsertAfterHeading(){return this.lastResolvedInsertAfterHeading}consumeCreatedClipboardAttachmentPaths(){let e=this.createdClipboardAttachmentPaths;return this.createdClipboardAttachmentPaths=[],e}shouldUseSelectionForValue(){return this.useSelectionAsCaptureValue}async getSelectedTextForValue(){let e=await this.getSelectedText();return e.trim().length>0?e:""}getLinkSourcePath(){return this.sourcePath??this.file?.path??null}async getClipboardContent(){let e=await super.getClipboardContent();return e.length>0||!this.clipboardImageFallbackEnabled?e:this.clipboardAttachmentLink!==void 0?this.clipboardAttachmentLink??"":(this.clipboardAttachmentLink=await this.saveClipboardImageAsAttachment(),this.clipboardAttachmentLink??"")}async withClipboardImageFallback(e){let n=this.clipboardImageFallbackEnabled;this.clipboardImageFallbackEnabled=!0;try{return await e()}finally{this.clipboardImageFallbackEnabled=n}}async saveClipboardImageAsAttachment(){let e=navigator.clipboard;if(typeof e?.read!="function")return null;let n,i;try{if(n=await this.getFirstClipboardImageItem(e),!n)return null;i=await(await n.clipboardItem.getType(n.mimeType)).arrayBuffer()}catch{return null}let o=this.getLinkSourcePath()??"",s=await wx(this.app,i,n.mimeType,o);return this.createdClipboardAttachmentPaths.push(s.path),Cx(this.app,s,o)}async getFirstClipboardImageItem(e){let n=await e.read();for(let i of n){let o=i.types.find(s=>Ja[s]!==void 0);if(o)return{clipboardItem:i,mimeType:o}}return null}getCurrentFileLink(){let e=this.app.workspace.getActiveFile();if(!e)return null;let n=this.sourcePath??this.file?.path??"";return this.app.fileManager.generateMarkdownLink(e,n)}async formatContentWithFile(e,n,i,o){return this.captureIntoFile(e,n,i,o,!0)}async insertFormattedContent(e,n,i,o){return this.captureIntoFile(e,n,i,o,!1)}async captureIntoFile(e,n,i,o,s){if(this.choice=n,this.file=o,this.fileContent=i,!n||!o||i===null){let l=Sn(e);return{content:l,captureContent:l,cursor:{kind:"none"}}}this.setTargetFolderPath(Zn(o.path));let a=n.insertAfter.enabled||!!n.insertBefore?.enabled||n.prepend||!n.captureToActiveFile||n.activeFileWritePosition==="top"||n.activeFileWritePosition==="bottom";return await this.formatCapture(e,a,s)}async formatContent(e,n){return this.choice=n,n?await this.formatFileContent(e):e}async formatFileContent(e,n=!0){return(await this.formatCapture(e,n)).content}async formatCapture(e,n,i=!0){let o=i?await this.withValueLines(!!this.choice?.eachLine,()=>this.withClipboardImageFallback(async()=>this.withPromptScope("captureText",e,async()=>this.withUserTextProtected(async()=>super.formatFileContent(await this.expandTemplateLinebreaksOnce(e)))))):e;if(n&&this.file&&!this.templaterProcessed){let l=await Oc(this.app,o,this.file);l&&(o=l),this.templaterProcessed=!0}let s=uT(up(o));return{...s.cursor.kind==="none"?{content:this.fileContent,cursor:s.cursor}:await this.insertCapture(s),captureContent:s.content,markerOnly:s.cursor.kind==="none"&&/{{CURSOR}}/i.test(o)}}async insertCapture(e){return this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom"?Ia(e,this.withLastLineEnded()):this.choice.insertAfter.enabled?this.insertAfterHandler(e):this.choice.insertBefore?.enabled?this.insertBeforeHandler(e):this.insertAtNoteBodyStartTracking(e)}withLastLineEnded(){let e=this.fileContent;return e.length>0&&!e.endsWith(`
- `)?`${e}
- `:e}async formatContentOnly(e,n={}){let i=await this.withValueLines(n.eachLine??!1,()=>this.withClipboardImageFallback(async()=>this.withPromptScope("captureText",e,async()=>this.withUserTextProtected(async()=>super.formatFileContent(await this.expandTemplateLinebreaksOnce(e))))));return Wne(i)?this.fileContent:i}async withValueLines(e,n){this.splitValueLines=e,this.defaultValueInputType=e?"multiline":void 0;try{return await n()}finally{this.splitValueLines=!1,this.defaultValueInputType=void 0}}async format(e){if(!this.splitValueLines)return super.format(e);this.splitValueLines=!1;let n=await this.expandCodeAndIncludes(e);if(!co.test(n))return this.formatScalarTokens(n);let i=await this.resolveValue(n),o=i.split(/\r\n|\r|\n/).map(d=>d.trim()).filter(Boolean);if(o.length===0){let d=this.valuePromptContext;if(!d?.defaultValue||d.optional)return"";o.push("")}let s=await this.replaceMathValueInString(n),a=this.hasConcreteVariable("value"),l=this.variables.get("value"),c=[];try{for(let d of o)this.value=d,a&&this.variables.set("value",d),c.push(await this.formatScalarTokens(s))}finally{this.value=i,a&&this.variables.set("value",l)}return c.map((d,u)=>u<c.length-1&&!d.endsWith(`
- `)?`${d}
- `:d).join("")}async expandTemplateLinebreaksOnce(e){return this.linebreaksProcessed?e:(this.linebreaksProcessed=!0,this.expandFormatTemplateEscapes(e))}async expandFormatTemplateEscapes(e){let n=await this.replaceGlobalVarInString(e);return this.expandLinebreakEscapesOutsideTokens(n)}async insertAfterHandler(e){let n=e.content,i=this.insertAfterTargetOverride;if(this.choice.insertAfter?.inline&&i===null){let m=await this.formatLocationString(await this.expandFormatTemplateEscapes(this.choice.insertAfter.after));return await this.insertAfterInlineHandler(e,m)}let o=i??await this.formatLocationString(await this.expandFormatTemplateEscapes(this.choice.insertAfter.after));if(i===null){let m=o.split(`
- `,1)[0];this.lastResolvedInsertAfterHeading=/^#+\s+\S/.test(m)?m.trim():null}let s=yM(o);if(bM(s))throw new ue("Insert-after target is empty after formatting.");let a=jl(this.fileContent),l=i!==null&&iW(i)?oW(a):this.isOrderedCreate()?sW(a,this.fileContent):a,{start:c,end:d}=wM(l,s);if(c===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(e,o);throw new ue(`Insert-after target not found: '${o}'.`)}let p;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let m=hl(a,c,this.considerSubsectionsForAnchor(a,c)),h=Math.max(m??a.length-1,d);p=Hy(a,h,this.fileContent,n)}else{let m=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";p=g_(a,d,this.fileContent,m)}return this.insertTextAfterPositionInBody(e,this.fileContent,p)}async insertBeforeHandler(e){let n=this.choice.insertBefore;if(!n)throw new ue("Insert-before settings are missing.");let i=await this.formatLocationString(await this.expandFormatTemplateEscapes(n.before)),o=yM(i);if(bM(o))throw new ue("Insert-before target is empty after formatting.");let s=jl(this.fileContent),{start:a}=wM(s,o);if(a===-1){if(n.createIfNotFound)return await this.createInsertBeforeIfNotFound(e,i);throw new ue(`Insert-before target not found: '${i}'.`)}return this.insertTextBeforePositionInBody(e,this.fileContent,a)}async insertAfterInlineHandler(e,n){if(rW(n))throw new ue("Inline insert-after target must be a single line \u2014 remove the line break (\\n) or turn off inline insertion.");let i=this.fileContent.indexOf(n);if(i===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInlineInsertAfterIfNotFound(e,n);throw new ue(`Inline insert-after target not found: '${n}'.`)}let o=i+n.length,s=this.choice.insertAfter?.replaceExisting?nW(this.fileContent,o):o;return Ia(e,this.fileContent.slice(0,o),this.fileContent.slice(s))}async createInsertAfterIfNotFound(e,n){let i=this.choice.insertAfter;if(i?.createIfNotFoundLocation===Wo)return this.createInsertAfterOrdered(e,n);let o=Ia(e,`${n}
- `);return this.createMissingTarget({payload:o,location:i?.createIfNotFoundLocation,rawTarget:i.after,insertAtCursor:s=>{let a=s;if(i?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let l=jl(this.fileContent),c=hl(l,s,this.considerSubsectionsForAnchor(l,s));a=Hy(l,c??l.length-1,this.fileContent,o.content)}return this.insertTextAfterPositionInBody(o,this.fileContent,a)}})}isOrderedCreate(){return!!this.choice.insertAfter?.createIfNotFound&&this.choice.insertAfter?.createIfNotFoundLocation===Wo}considerSubsectionsForAnchor(e,n){return h_(!!this.choice.insertAfter?.considerSubsections,e,n)}createInsertAfterOrdered(e,n){return JW({capture:e,targetString:n,fileContent:this.fileContent,insertAfter:this.choice.insertAfter,task:!!this.choice.task})}async createInsertBeforeIfNotFound(e,n){let i=this.choice.insertBefore;if(!i)throw new ue("Insert-before settings are missing.");let o=Ia(e,"",`${e.content.endsWith(`
- `)||e.content.length===0?"":`
- `}${n}`);return this.createMissingTarget({payload:o,location:i.createIfNotFoundLocation,rawTarget:i.before,insertAtCursor:s=>this.insertTextBeforePositionInBody(o,this.fileContent,s)})}async createInlineInsertAfterIfNotFound(e,n){let i=Ia(e,n);return this.createMissingTarget({payload:i,location:this.choice.insertAfter?.createIfNotFoundLocation,rawTarget:this.choice.insertAfter.after,insertAtCursor:o=>this.insertTextAfterPositionInBody(i,this.fileContent,o)})}createMissingTarget({payload:e,location:n,rawTarget:i,insertAtCursor:o}){switch(n){case Oi:return this.insertAtNoteBodyStartTracking(e,!0);case yd:{let s=this.withLastLineEnded();return Ia(e,s+AF(s,e.content))}case bd:{let s=mn(this.app);if(!s)throw new ue(`Unable to insert line '${i}' at cursor position: no active markdown editor.`);try{return o(s.editor.getCursor().line)}catch{throw new ue(`Unable to insert line '${i}' at cursor position.`)}}default:throw new ue(`Unknown createIfNotFoundLocation: ${n}`)}}insertAtNoteBodyStartTracking(e,n=!1){let i=fu(this.fileContent,e.content,{separateBlockquotes:n});return Nl(e,i.content,i.insertedStartOffset===null||e.cursor.kind==="none"?null:i.insertedStartOffset+e.cursor.value)}insertTextAfterPositionInBody(e,n,i){let o=$f(e.content,n,i,!!this.choice.task,e.cursor.kind==="offset"?e.cursor.value:void 0);return Nl(e,o.content,o.insertedEndOffset)}insertTextBeforePositionInBody(e,n,i){let o=aW(e.content,n,i,e.cursor.kind==="offset"?e.cursor.value:void 0);return Nl(e,o.content,o.insertedEndOffset)}};mu();_p();ye();hA();fp();Uh();gp();oM();GF();Ql();Lc();nt();wu();Cu();Fm();tn();var tG=require("obsidian");SM();Ve();gi();nl();Rd();cM();Qo();Hi();tn();wu();Cu();kn();rM();Ln();nM();var ZW=require("obsidian");Ve();kn();mC();pC();Qo();function eG(r,t){let e=r.trim().replace(/^\/+/,"");if(e==="")return{kind:"vault"};let n=Xp(e);if(n){if(!n.field)throw new ue("Property capture target needs a field name, e.g. property:type=draft");return{kind:"property",field:n.field,value:n.value,filter:n.filter}}let i=Qp(e);if(i){if(i.multiSelect)throw new ue("Capture target filters select one destination file. Use {{FILE:...|multi}} in the capture format for multi-value metadata.");return{kind:"filter",filter:i.filter}}let o=Nr(e,"Capture target file path");if(Mn.test(o))throw new ue(`Capture to '.base' files is not supported (${o}). Use a Template choice instead.`);let s=o.endsWith("/"),a=o.replace(/\/+$/,"");if(s)return{kind:"folder",folder:a};if(xt.test(o)||lr.test(o))return{kind:"file",path:o};let l=t.normalizeMarkdownFilePath("",a),d=t.getAbstractFileByPath(l)instanceof ZW.TFile;return t.isFolder(a)&&!d?{kind:"folder",folder:a}:{kind:"file",path:o}}var D_=class extends Rf{async getFormattedPathToCaptureTo(t){if(t){let s=this.app.workspace.getActiveFile();return Lr(s,"Cannot capture to active file - no active file."),s.path}let e=this.getPreselectedCaptureTargetPath();if(e!==void 0){let s=i_({isFolder:a=>vg(this.app,a),markdownFileExists:a=>this.app.vault.getAbstractFileByPath(n_(a))instanceof tG.TFile},this.choice.captureTo??"",!1);if(s){let a=this.confinePreselectedToScope(s,e);if(a!==null)return this.normalizeCaptureFilePath(a)}}let n=this.choice.captureTo,i=await this.formatter.formatFileName(n,"captureTarget");if(i===this.formatter.periodicNoteTarget?.path)return this.normalizeCaptureFilePath(`${i}.md`);let o=this.resolveCaptureTarget(i);switch(o.kind){case"vault":return this.selectFileInFolder("",!0);case"filter":return this.selectFileWithFilter(o.filter);case"property":return this.selectFileWithProperty(o.field,o.value,o.filter);case"folder":return this.selectFileInFolder(o.folder,!1);case"file":return this.normalizeCaptureFilePath(o.path)}}getPreselectedCaptureTargetPath(){return EH(this.choiceExecutor?.variables,this.choice.id)}confinePreselectedToScope(t,e){let n=this.stripLeadingSlash(e);if(t.kind==="folder")return t.folderPathSlash&&!n.startsWith(t.folderPathSlash)?`${t.folderPathSlash}${n}`:n;if(this.resolveScopeFiles(t).some(a=>a.path===n))return n;if(!(this.choice.createFileIfItDoesntExist?.enabled??!1))return null;let s=new Set(this.app.vault.getMarkdownFiles().map(a=>a.basename.toLowerCase()));return this.captureTargetAlreadyExists(n,s)?null:n}resolveScopeFiles(t){return t_(this.app,t)}resolveCaptureTarget(t){return eG(t,{getAbstractFileByPath:e=>this.app.vault.getAbstractFileByPath(e),isFolder:e=>vg(this.app,e),normalizeMarkdownFilePath:(e,n)=>this.normalizeMarkdownFilePath(e,n)})}captureTargetExists(t,e){let n=e.startsWith(t)?e:`${t}${e}`,i;try{i=Nr(n,"Capture target file path")}catch{return!1}let o=[i];return/\.(md|canvas)$/i.test(i)||o.push(`${i}.md`,`${i}.canvas`),o.some(s=>!!this.app.vault.getAbstractFileByPath(s))}async selectFileInFolder(t,e){let n=t.endsWith("/")||e?t:`${t}/`,i=Xo(this.app,n),o=this.choice.createFileIfItDoesntExist?.enabled??!1;Lr(o||i.length>0,`Folder ${n} is empty.`);let s=await this.chooseCaptureTarget(i,{allowCreate:o,nameIsTaken:l=>this.captureTargetExists(n,l)}),a=s.startsWith(`${n}`)?s:`${n}${s}`;return await this.formatFilePath(a)}async selectFileWithFilter(t){let e=Vw(this.app,t);return this.selectFileFromSet(e,"No files matched the capture target filters.")}async selectFileWithProperty(t,e,n){let i=Bw(this.app,t,e,n),o=e!==void 0?`${t}=${e}`:t;return this.selectFileFromSet(i,`No notes with property ${o}.`)}captureTargetAlreadyExists(t,e){let n=t.trim();if(!n)return!1;let i;try{i=Nr(n,"Capture target file path")}catch{return!1}let o=i.replace(/\.(md|canvas)$/i,"");if([i,`${o}.md`,`${o}.canvas`].some(l=>!!this.app.vault.getAbstractFileByPath(l)))return!0;let a=o.slice(o.lastIndexOf("/")+1);return e.has(a.toLowerCase())}async selectFileFromSet(t,e){let n=this.choice.createFileIfItDoesntExist?.enabled??!1;Lr(n||t.length>0,e);let i=new Set(this.app.vault.getMarkdownFiles().map(s=>s.basename.toLowerCase())),o=await this.chooseCaptureTarget(t,{allowCreate:n,nameIsTaken:s=>this.captureTargetAlreadyExists(s,i),restrictToScope:!0});return await this.formatFilePath(o)}async chooseCaptureTarget(t,e){let{paths:n,labels:i,aliases:o,search:s}=r_(this.app,t),a=new Set(i.map(m=>m.toLowerCase())),l=new Set(o.flat().map(m=>m.toLowerCase())),c=new Map(n.map((m,h)=>[m,s[h].length-m.length])),d=m=>a.has(m.toLowerCase())||e.nameIsTaken(m),u=e.allowCreate?"Choose a note or type to create one":void 0,p=String(await Ki(this.choiceExecutor,{remote:async m=>{let h=await Qi(m,{items:n.map((v,b)=>({value:v,title:i[b]??v})),placeholder:u,allowCustomInput:e.allowCreate,what:"the capture-target picker"}),g=n.includes(h)?void 0:Fd(n,o,h);if(g!==void 0)return g;if(e.restrictToScope&&!n.includes(h)&&d(h))throw new Error(`"${h}" already exists but is not one of the notes this capture targets. Pick one of the offered notes, or type a name that does not exist yet.`);return h},headless:()=>{throw this.assertInteractiveCaptureTarget(),new Error("unreachable")},app:()=>gr.Suggest(this.app,i,n,{placeholder:u,emptyStateText:e.allowCreate?"Type a note name to create it":void 0,renderItem:(m,h,g)=>Ym(h,m,this.app,{matches:g,pathOffset:c.get(m)??0}),searchItems:s,aliases:o,allowCustomValue:e.allowCreate,customValueLabel:m=>`Create new note: ${m}`,valueExists:m=>l.has(m.toLowerCase())||d(m)})}));return Lr(!!p&&p.length>0,"No file selected for capture."),p}async formatFilePath(t){let e=await this.formatter.formatFileName(t,"captureTarget");return this.normalizeCaptureFilePath(e)}normalizeCaptureFilePath(t){let e=Nr(this.stripLeadingSlash(t),"Capture target file path");if(Mn.test(e))throw new ue(`Capture to '.base' files is not supported (${e}). Use a Template choice instead.`);let n=this.normalizeCaptureFilePathExtension(e);if(!ks(n).trim())throw new ue(`Capture target file name is empty after formatting ('${n}'). Make sure the tokens in 'Capture to' produce a value.`);if(Ut(n))throw new ue(`Refusing to capture to a file outside the vault: "${n}".`);return n}normalizeCaptureFilePathExtension(t){for(let e of[xt,lr]){let n=t.match(e)?.[0];if(n)return`${Nr(t.replace(e,""),"Capture target file path")}${n}`}return this.normalizeMarkdownFilePath("",t)}assertInteractiveCaptureTarget(){if(this.choiceExecutor.interactive===!1)throw new ue(`'${this.choice.name}' needs to ask which note to capture into, but this run is non-interactive. Point "Capture to" at a specific file, or re-run with the ui flag.`)}};MT();kn();RT();HF();var rG=require("obsidian");Ve();kn();function IM(r){return r?.type==="text"?"text":r?.type==="file"||r?.file?"file":typeof r?.text=="string"?"text":"unsupported"}function Gne(r,t){let e=t.id;if(!e)return null;let n=r.getData?.();return n?.nodes?.length?n.nodes.find(i=>i.id===e)??null:null}function nG(r,t){if(r==="text"){if(t==="currentLine")return"Canvas capture does not support 'At cursor' for text cards. Use top, bottom, insert-after, or insert-before placement.";if(t==="newLineAbove"||t==="newLineBelow")return"Canvas capture does not support 'New line above/below cursor' for text cards. Use top, bottom, insert-after, or insert-before placement."}return r==="file"&&(t==="currentLine"||t==="newLineAbove"||t==="newLineBelow")?"Canvas file cards do not support cursor-based capture modes. Use top, bottom, insert-after, or insert-before modes.":null}function jne(r){let t=r.file;return t?typeof t=="string"?t:typeof t=="object"&&"path"in t&&typeof t.path=="string"?t.path:null:null}function PM(r){return!!r&&"path"in r&&"extension"in r}function Yne(r){let t=r.workspace.getActiveViewOfType(rG.View)??r.workspace.getMostRecentLeaf?.()?.view;return!t||t.getViewType?.()!=="canvas"?null:t}function Kne(r,t){let e=t.file??r.workspace.getActiveFile?.();if(!e)throw new ue("Cannot capture to Canvas because no active Canvas file is available.");return e}function Qne(r){let t=r.selection?Array.from(r.selection):[];if(t.length!==1)throw new ue("Canvas capture requires exactly one selected node.");return t[0]}function iG(r){let t=jne(r);if(!t)throw new ue("Selected Canvas file card does not have a valid linked file path.");if(!xt.test(t))throw new ue("Canvas file card targets markdown files only in this version.");return t}function Xne(r,t){let e=iG(t),n=r.vault.getAbstractFileByPath(e);if(!PM(n))throw new ue(`Selected Canvas file card target not found: ${e}`);return n}function Jne(r,t){let e=iG(t),n=r.vault.getAbstractFileByPath(e);if(!n)return{targetPath:e};if(!PM(n))throw new ue(`Selected Canvas file card target not found: ${e}`);return{targetPath:e,targetFile:n}}function Zne(r,t){let e;try{e=JSON.parse(r)}catch{throw new ue(`Canvas file is not valid JSON: ${t}`)}if(!e||typeof e!="object")throw new ue(`Canvas file has invalid structure: ${t}`);if(!Array.isArray(e.nodes))throw new ue(`Canvas file has no nodes array: ${t}`);return e}function oG(r,t){let e=r,n=Yne(e);if(!n)return null;let i=n.canvas;if(!i)throw new ue("Canvas capture is unavailable in this Obsidian version.");let o=Kne(e,n),s=Qne(i),a=Gne(i,s),l=IM(s);if(l==="unsupported"&&a&&(l=IM(a)),l==="unsupported")throw new ue("Canvas capture currently supports only text and file cards.");let c=nG(l,t);if(c)throw new ue(c);if(l==="text")return{kind:"text",source:"active",canvas:i,canvasFile:o,node:s,nodeData:a};let d=s.file||!a?.file?s:{...s,file:a.file};return{kind:"file",source:"active",canvasFile:o,node:d,targetFile:Xne(e,d)}}async function sG(r,t,e,n){let i=e.trim();if(!i)throw new ue("Canvas node id is required for Canvas node capture.");let o=r.vault.getAbstractFileByPath(t);if(!PM(o))throw new ue(`Canvas target not found: ${t}`);if(!lr.test(o.path))throw new ue("Canvas node capture requires the target path to be a .canvas file.");let s=await r.vault.read(o),a=Zne(s,o.path),l=a.nodes.findIndex(g=>g.id===i);if(l===-1)throw new ue(`Canvas node id '${i}' was not found in ${o.path}.`);let c=a.nodes[l],d=IM(c);if(d==="unsupported")throw new ue("Canvas capture currently supports only text and file cards.");let u=nG(d,n);if(u)throw new ue(u);if(d==="text")return{kind:"text",source:"configured",canvasFile:o,rawCanvas:s,canvasData:a,nodeData:c,nodeIndex:l};let p=r,{targetPath:m,targetFile:h}=Jne(p,c);return{kind:"file",source:"configured",canvasFile:o,nodeData:c,targetPath:m,targetFile:h}}function aG(r){return r.source==="active"?typeof r.node.text=="string"?r.node.text:typeof r.nodeData?.text=="string"?r.nodeData.text:"":typeof r.nodeData.text=="string"?r.nodeData.text:""}async function lG(r,t,e){if(t.source==="active"){typeof t.node.setText=="function"?t.node.setText(e):t.node.text=e,t.canvas.requestSave?.();return}if(await r.vault.read(t.canvasFile)!==t.rawCanvas)throw new ue("Canvas target changed while capture was running. Re-run capture to avoid overwriting newer Canvas edits.");t.nodeData.text=e,t.canvasData.nodes[t.nodeIndex]=t.nodeData,await r.vault.modify(t.canvasFile,JSON.stringify(t.canvasData,null," "))}yy();fA();var Nf=4e3,eie=/^[ \t\r\n\f\v]*$/;function cG(r){return eie.test(r)}var tie=/\{\{(?:VALUE|FILE|FIELD):[^}]*\|\s*multi\s*(?=[:}|]|$)[^}]*\}\}/gi,rie=/\|\s*format\s*:\s*(?:inline|spaced|yaml|markdown)\s*(?=\||}})/i;function nie(r){return Array.from(r.matchAll(tie)).some(t=>!rie.test(t[0]))}var O_=class extends D_{constructor(e,n,i,o,s=null,a=[i]){super(e);this.choiceExecutor=o;this.originLeaf=s;this.chain=a;this.capturePropertyVars=new Map;this.suppressFrontmatterCollection=!1;this.resolvedInsertAfterHeading=null;this.choice=i,this.plugin=n,this.outcome=new Of(o),this.formatter=new R_(e,n,o),this.formatter.choiceChain=a,this.formatter.setPromptRunContext({draftScopeId:i.id,choiceName:i.name})}captureResolvedOrderedHeading(){if(this.choice.insertAfter?.enabled&&this.choice.insertAfter.createIfNotFoundLocation===Wo){let e=this.formatter.getResolvedInsertAfterHeading();e&&(this.resolvedInsertAfterHeading=e)}}showSuccessNotice(e,{wasNewFile:n,action:i}){let o=`'${e.basename}'`;if(n){new ia.Notice(`Created and captured to ${o}`,Nf);return}let s=this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom",a="";switch(i){case"currentLine":a=`Captured to current line in ${o}`;break;case"newLineAbove":a=`Captured on a new line above cursor in ${o}`;break;case"newLineBelow":a=`Captured on a new line below cursor in ${o}`;break;case"activeFileTop":a=`Captured to top of ${o}`;break;case"prepend":case"append":a=s?`Captured to bottom of ${o}`:`Captured to top of ${o}`;break;case"insertAfter":{let l=this.resolvedInsertAfterHeading??this.choice.insertAfter.after;a=l?`Captured to ${o} under '${l}'`:`Captured to ${o}`;break}case"insertBefore":{let l=this.choice.insertBefore?.before;a=l?`Captured to ${o} before '${l}'`:`Captured to ${o}`;break}default:a=`Captured to ${o}`;break}new ia.Notice(a,Nf)}showNothingToCaptureNotice(e,{wasNewFile:n}){let i=`'${e.basename}'`;new ia.Notice(n?`Created ${i} \u2014 nothing to capture (no content)`:`Nothing to capture \u2014 ${i} unchanged`,Nf)}hasActiveMarkdownCaptureContext(){let e=!!this.app.workspace.getActiveFile(),n=!!mn(this.app);return e&&n}shouldSkipRequiredCanvasLinkInsertion(e,n){return n&&e.destination?.type!=="specifiedFile"&&e.requireActiveFile&&!this.hasActiveMarkdownCaptureContext()}async insertCaptureLink(e,n,{isCanvasTriggered:i,onEditorTextMutation:o}){if(n.enabled){if(n.destination?.type!=="specifiedFile"&&!Da(n.placement)&&this.shouldSkipRequiredCanvasLinkInsertion(n,i)){this.plugin.settings.showCaptureNotification&&new ia.Notice("Canvas capture skipped link insertion because no Markdown editor is focused.",Nf);return}await S_(this.app,e,n,this.choiceExecutor.focusedProperty,o)}}async copyCapturedFileLinkToClipboard(e){this.choice.copyLinkToClipboard&&await A_(e)}validateAppendLinkDestination(e){let n=k_(this.app,e);return n?(this.failRun(n),!1):!0}configureFormatter(e){this.formatter.setLinkToCurrentFileBehavior(e.enabled&&!e.requireActiveFile?"optional":"required");let n=this.choice.useSelectionAsCaptureValue,i=this.plugin.settings.useSelectionAsCaptureValue??!0,o=typeof n=="boolean"?n:i;this.formatter.setUseSelectionAsCaptureValue(o)}async resolveWriteTarget(e,n){let i=(this.choice.captureToActiveFile?oG(this.app,e):null)??await this.resolveConfiguredCanvasTarget(e);if(i?.kind==="text"){if(n)throw new ue("Property capture requires a Markdown note. Canvas text cards do not have note properties.");return{kind:"canvasText",canvas:i}}if(!n&&i?.kind==="file"&&this.createsMissingLineTargetAtCursor(e))throw new ue("Canvas file cards do not support creating missing line targets at cursor. Use top or bottom.");let o=i?.kind==="file"?i.source==="configured"?i.targetFile?.path??i.targetPath:i.targetFile.path:await this.getFormattedPathToCaptureTo(this.choice.captureToActiveFile);if(!i&&!this.choice.captureToActiveFile&&lr.test(o))throw new ue("Capture to a .canvas file requires a target canvas node id.");return{kind:"note",filePath:o,isCanvasTriggered:!!i}}createsMissingLineTargetAtCursor(e){let n=e==="insertAfter"?this.choice.insertAfter:e==="insertBefore"?this.choice.insertBefore:void 0;return!!n?.createIfNotFound&&n.createIfNotFoundLocation==="cursor"}async prepareNoteWrite(e,n){this.isInsertAfterHeadingMode()&&!lr.test(e)&&await this.maybeResolveInsertAfterHeading(await this.readNoteBodyForHeadingPicker(e,n));let i=!n&&!!this.choice?.createFileIfItDoesntExist?.enabled&&!this.choice?.createFileIfItDoesntExist?.createWithTemplate&&!this.periodicNoteFor(e)?.settings.template;if(this.suppressFrontmatterCollection=!i,this.suppressFrontmatterCollection&&nie(this.choice?.format?.format??"")&&S.logWarning("QuickAdd: {{VALUE:\u2026|multi}}, {{FILE:\u2026|multi}} and {{FIELD:\u2026|multi}} in this capture write comma-separated strings by default. Add |format:yaml, |format:markdown, |format:inline or |format:spaced to choose the output explicitly."),!n&&!this.choice?.createFileIfItDoesntExist?.enabled)throw new ue(`Target file missing: ${e}. Enable "Create file if it doesn't exist" or choose an existing file.`)}async run(){let e=!1;try{this.capturePropertyVars.clear();let n=Kl(this.choice.appendLink);if(this.configureFormatter(n),!this.validateAppendLinkDestination(n))return;let i=this.choice.propertyCapture===void 0?void 0:Vx(this.choice.propertyCapture),o=i?"append":A1(this.choice),s=await this.resolveWriteTarget(o,!!i);if(s.kind==="canvasText"){await this.handleCanvasTextCapture(s.canvas,o,n,()=>{e=!0});return}let{filePath:a,isCanvasTriggered:l}=s,c=this.getCaptureContent(),d=await this.fileExists(a);if(!d&&this.choice?.createFileIfItDoesntExist?.enabled&&Sy(a),i){await this.captureToProperty({filePath:a,fileAlreadyExists:d,config:i,linkOptions:n,isCanvasTriggered:l,onCommit:()=>{e=!0}});return}await this.prepareNoteWrite(a,d);let u=d?await this.onFileExists(a,c,o==="currentLine"||o==="newLineAbove"||o==="newLineBelow"):await this.onCreateFileIfItDoesntExist(a,c,n);if(u===null){this.plugin.settings.showCaptureNotification&&new ia.Notice("Nothing to capture (no content)",Nf),this.outcome.success(void 0,"unchanged");return}if(u.markerOnly){e=!d,this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(u.file,{wasNewFile:!d}),this.outcome.success(u.file,d?"unchanged":"created");return}this.captureResolvedOrderedHeading();let p=await this.commitCapture(u,{action:o,fileAlreadyExists:d,onCommit:()=>{e=!0}});if(!p)return;await this.finishCapture(u.file,{...p,action:o,wasNewFile:!d,linkOptions:n,isCanvasTriggered:l})}catch(n){if(e||await this.cleanupCreatedClipboardAttachments(),Mc(n,{logPrefix:"Capture execution aborted",noticePrefix:"Capture execution aborted",defaultReason:"Capture aborted"})){this.choiceExecutor.signalAbort?.(n);return}Bn.getInstance().markExecutionScopeFailed(),this.outcome.failure($_(n)),Me(n,`Error running capture choice "${this.choice.name}"`)}finally{e&&this.formatter.consumeCreatedClipboardAttachmentPaths()}}async finishCapture(e,n){let{captureIsNoOp:i,marked:o,action:s,wasNewFile:a,linkOptions:l,isCanvasTriggered:c}=n,d=n.cursor;this.outcome.success(e,n.effect),this.plugin.settings.showCaptureNotification&&(i?this.showNothingToCaptureNotice(e,{wasNewFile:a}):this.showSuccessNotice(e,{wasNewFile:a,action:s})),await this.copyCapturedFileLinkToClipboard(e),d&&l.enabled&&(l.destination.type==="specifiedFile"?mg(this.app,l.destination):Da(l.placement)?this.app.workspace.getActiveFile():this.choiceExecutor.focusedProperty?.file)?.path===e.path&&(d=null),await this.insertCaptureLink(e,l,{isCanvasTriggered:c,onEditorTextMutation:o&&d&&!Da(l.placement)?m=>{o&&d&&m.filePath===e.path&&(d=F_(d,m))}:void 0});let u=en(this.choice.fileOpening).focus??!0;this.choice.openFile&&(u=await Df({app:this.app,file:e,opening:this.choice.fileOpening,originLeaf:this.originLeaf}));let p=mn(this.app)?.file?.path===e.path;(this.choice.openFile||o&&p)&&!await bu(this.app,e)&&d&&(u||o&&p)&&(d.offsets.length===1?$2(this.app,e,d.offsets[0],d.content):Cy(this.app,e,d.offsets,d.content))}async commitCapture(e,n){let{file:i,captureContent:o,newFileContent:s,priorContent:a,cursor:l}=e,c=cG(o),{action:d}=n;if(d==="currentLine"||d==="newLineAbove"||d==="newLineBelow"){let y=c?o:await Oc(this.app,o,i),C=uT(up(y));if(C.cursor.kind==="none"&&/{{CURSOR}}/i.test(y))return this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(i,{wasNewFile:!n.fileAlreadyExists}),this.outcome.success(i,"unchanged"),null;c=cG(C.content);let w=C.cursor.kind==="offset"&&C.cursor.source==="marker",T=null;return!c&&!(w?(T=k2(C,this.app,i,d))!==null:(d==="currentLine"?S2:d==="newLineAbove"?I2:P2)(C.content,this.app))?(await this.cleanupCreatedClipboardAttachments(),this.failRun(`Capture "${this.choice.name}": no active Markdown editor to insert into.`),null):(n.onCommit(),{effect:c?"unchanged":"changed",captureIsNoOp:c,cursor:T,marked:w})}let{content:u,merged:p}=await X0(this.app,i,a,s);n.onCommit();let m=this.choice.templater?.afterCapture==="wholeFile";m&&(LT(`templater-whole-file:${this.choice.id}`,`'${this.choice.name}' uses "Run Templater on entire destination file after capture", which is deprecated and will be removed in a future release. QuickAdd already runs Templater in what it captures. Turn the option off in the Capture's settings.`),await yu(this.app,i));let h=await this.applyCapturePropertyVars(i),g=(m||h)&&await this.app.vault.read(i)!==u,v=n.fileAlreadyExists?s!==a||g?"changed":"unchanged":"created",b=!p&&!g&&l.kind==="offset"?{offsets:[l.value],content:s}:null;return{effect:v,captureIsNoOp:c,cursor:b,marked:l.kind==="offset"&&l.source==="marker"}}async captureToProperty(e){let{filePath:n,fileAlreadyExists:i,config:o,linkOptions:s}=e;if(!xt.test(n))throw new ue("Property capture requires a Markdown note.");if(!i&&!this.choice.createFileIfItDoesntExist.enabled)throw new ue(`Target file missing: ${n}. Enable "Create file if it doesn't exist" or choose an existing file.`);let a=i?this.getFileByPath(n):void 0;this.formatter.setTitle(ks(n)),this.formatter.setTargetFolderPath(Zn(n)),this.formatter.setDestinationSourcePath(n),a&&this.formatter.setDestinationFile(a),this.formatter.setPromptRunContext({draftScopeId:this.choice.id,choiceName:this.choice.name,destination:n,destinationKind:"file"});let l=!a&&this.choice.createFileIfItDoesntExist.createWithTemplate,c=a?await Od(this.app,a):l?"":await this.periodicNoteContent(n)??"",d=new Map;if(l){let y=new wf(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);y.setDestinationPath(n),y.setPromptRunContext({draftScopeId:`${this.choice.id}#${this.choice.createFileIfItDoesntExist.template}`,choiceName:this.choice.name,destination:n,destinationKind:"file"}),y.choiceChain=this.chain,s.enabled&&!s.requireActiveFile&&y.setLinkToCurrentFileBehavior("optional"),c=await y.run(),d=y.getAndClearTemplatePropertyVars()}let u=TL(c);for(let[y,C]of d)ky(u,y.split(Ni.PATH_SEPARATOR),hp(C));let p=fg(u,pL(o.property.kind==="named"?await this.formatter.formatPropertyName(o.property.format):await this.promptForCaptureProperty(u,o.createIfMissing))),m=$s(this.app,p,{registeredOnly:!0}),h=Object.prototype.hasOwnProperty.call(u,p)?u[p]:void 0,g=m??(typeof h=="number"?"number":typeof h=="boolean"?"checkbox":null),v=this.choice.format.enabled?this.choice.format.format:Cr,b=gL(this.choiceExecutor.variables);try{yL(this.choiceExecutor.variables,p,h),this.formatter.consumePropertyTokenExpanded();let y=await this.formatter.formatPropertyValue(o_(v,g),{listItems:xL({key:p,action:o.action,registeredType:m,existing:h})}),C=mL(v)||this.formatter.consumePropertyTokenExpanded(),w=I=>EL({frontmatter:I,key:p,value:y,config:o,registeredType:$s(this.app,p,{registeredOnly:!0}),compose:C}),T=w(u);if(o.action==="addToList"&&wL(y)){this.outcome.success(a,"unchanged");return}let P="";if(a)P=await Od(this.app,a),await this.app.fileManager.processFrontMatter(a,I=>{I[fg(I,p)]=w(I)});else{u[p]=T;let I=()=>this.createFileWithInput(n,_L(c,u),{suppressTemplaterOnCreate:l});a=l?await I():await LF(this.app,n,I)}e.onCommit(),!i&&(l||Ty(this.app))&&(l&&await yu(this.app,a),await this.app.fileManager.processFrontMatter(a,I=>{I[fg(I,p)]=w(I)}));let _=await this.app.vault.read(a);this.outcome.success(a,i?_===P?"unchanged":"changed":"created"),this.plugin.settings.showCaptureNotification&&new ia.Notice(`Captured to '${p}' in '${a.basename}'`,Nf),await this.copyCapturedFileLinkToClipboard(a),await this.insertCaptureLink(a,s,{isCanvasTriggered:e.isCanvasTriggered}),this.choice.openFile&&await Df({app:this.app,file:a,opening:this.choice.fileOpening,originLeaf:this.originLeaf})}finally{vL(this.choiceExecutor.variables,b)}}async promptForCaptureProperty(e,n){let i=Object.keys(e).filter(o=>o!=="__proto__").sort((o,s)=>o.localeCompare(s));if(!n&&i.length===0)throw new ue("The capture target has no properties. Enable 'Create property if missing' to add one.");return await Ki(this.choiceExecutor,{remote:o=>Qi(o,{items:i.map(s=>({value:s,title:s})),placeholder:"Property",allowCustomInput:n,what:"the property picker"}),headless:async()=>{throw new ue("Property capture needs a property selection. Configure a named property or run with the ui flag.")},app:()=>gr.Suggest(this.app,i,i,{placeholder:"Property",allowCustomValue:n,customValueLabel:o=>`Create property: ${o}`,valueExists:o=>i.some(s=>s.trim().toLowerCase()===o.trim().toLowerCase())})})}failRun(e){Bn.getInstance().markExecutionScopeFailed(),S.logError(e),this.outcome.failure(e)}async cleanupCreatedClipboardAttachments(){let e=this.formatter.consumeCreatedClipboardAttachmentPaths();for(let n of e)try{let i=this.app.vault.getAbstractFileByPath(n);i instanceof ia.TFile&&await this.app.fileManager.trashFile(i)}catch(i){S.logWarning(`QuickAdd: failed to clean up clipboard attachment '${n}': ${String(i)}`)}}async handleCanvasTextCapture(e,n,i,o){if(n==="currentLine"||n==="newLineAbove"||n==="newLineBelow")throw new ue("Canvas text cards support top, bottom, insert-after, and insert-before positions only.");if(this.createsMissingLineTargetAtCursor(n))throw new ue("Canvas text cards do not support creating missing line targets at cursor. Use top or bottom.");let s=e.canvasFile;this.formatter.setTitle(ks(s.basename)),this.formatter.setDestinationFile(s);let a=this.getCaptureContent(),l=aG(e);this.isInsertAfterHeadingMode()&&await this.maybeResolveInsertAfterHeading(l);let{content:c,markerOnly:d}=await this.formatter.formatContentWithFile(a,this.choice,l,s);if(d){this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(s,{wasNewFile:!1}),this.outcome.success(s,"unchanged");return}this.captureResolvedOrderedHeading();let u=c===l;u||await lG(this.app,e,c),o(),await this.finishCapture(s,{effect:u?"unchanged":"changed",captureIsNoOp:u,cursor:null,marked:!1,action:n,wasNewFile:!1,linkOptions:i,isCanvasTriggered:!0})}async resolveConfiguredCanvasTarget(e){if(this.choice.captureToActiveFile)return null;let n=this.choice.captureTo?.trim()??"",i=this.choice.captureToCanvasNodeId?.trim()??"";if(!n||!i)return null;let o=await this.formatFilePath(n);return lr.test(o)?await sG(this.app,o,i,e):null}async maybeResolveInsertAfterHeading(e){let n=this.choice.insertAfter;if(!n?.enabled||!n.promptHeading)return;let i=!!n.createIfNotFound,o=jl(e),s=oi(o).filter(m=>o[m.line].trim()!==m.heading),a=s.map(m=>o[m.line].trimStart().replace(/\r$/,"")),l=s.map(m=>`${" ".repeat(Math.max(0,m.level-1))}${m.heading}`),c=s.map(m=>m.heading),d="Choose a heading to insert under",u=String(await Ki(this.choiceExecutor,{remote:m=>Qi(m,{items:a.map((h,g)=>({value:h,title:l[g]??h})),placeholder:d,allowCustomInput:i,what:"the heading picker"}),headless:()=>{throw new ue(`'${this.choice.name}' needs to ask which heading to capture under, but this run is non-interactive. Turn off "Choose heading when capturing" and set a fixed heading, or re-run with the ui flag.`)},app:()=>gr.Suggest(this.app,l,a,{allowCustomValue:i,placeholder:d,emptyStateText:i?"No headings found \u2014 type a heading to create":"No headings found in the target note",customValueLabel:m=>`Insert after new line: ${m}`})}));Lr(!!u&&u.length>0,"No heading selected for capture."),this.formatter.setInsertAfterTargetOverride(u);let p=a.indexOf(u);this.resolvedInsertAfterHeading=p>=0?c[p]:u}isInsertAfterHeadingMode(){return!!this.choice.insertAfter?.enabled&&!!this.choice.insertAfter.promptHeading}async readNoteBodyForHeadingPicker(e,n){if(!n)return"";let i=this.app.vault.getAbstractFileByPath(e);return i instanceof ia.TFile?await Od(this.app,i):""}getCaptureContent(){let e;return this.choice.format.enabled?e=this.choice.format.format:e=Cr,this.choice.task&&(e=`- [ ] ${e}
- `),e}async onFileExists(e,n,i=!1){let o=this.getFileByPath(e);if(!o)throw new Error("File not found");this.formatter.setTitle(o.basename),this.formatter.setDestinationFile(o);let s=await this.collectIfFrontmatter(()=>this.formatter.formatContentOnly(n,{eachLine:this.choice.eachLine}));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let a=await Od(this.app,o);if(/{{CURSOR}}/i.test(s)&&up(s).cursor.kind==="none")return{file:o,newFileContent:a,captureContent:"",priorContent:a,cursor:{kind:"none"},markerOnly:!0};if(i)return{file:o,newFileContent:a,captureContent:s,priorContent:a,cursor:{kind:"none"}};let l=await this.collectIfFrontmatter(()=>this.formatter.insertFormattedContent(s,this.choice,a,o));return this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),l.markerOnly?{file:o,newFileContent:a,captureContent:l.captureContent,priorContent:a,cursor:l.cursor,markerOnly:!0}:{file:o,newFileContent:l.content,captureContent:l.captureContent,priorContent:a,cursor:l.cursor}}periodicNoteFor(e){if(this.choice.captureToActiveFile||this.choice.createFileIfItDoesntExist.createWithTemplate)return null;let n=this.formatter.periodicNoteTarget;return!n||`${n.path}.md`!==e?null:{period:n.period,settings:Dw(this.app,n.period)}}async periodicNoteContent(e){let n=this.periodicNoteFor(e);if(!n)return null;let i=await aL(this.app,n.settings,n.period);if(i===null)return null;let o=this.choiceExecutor.clocks;return lL(i,n.settings,n.period,window.moment(o?.date??o?.now),window.moment(o?.now))}async onCreateFileIfItDoesntExist(e,n,i){Sy(e);let o=ks(e);this.formatter.setTitle(o),this.formatter.setDestinationSourcePath(e);let s=await this.collectIfFrontmatter(()=>this.formatter.formatContentOnly(n,{eachLine:this.choice.eachLine}));if(this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),/{{CURSOR}}/i.test(s)&&up(s).cursor.kind==="none")return null;let a="";if(!this.choice.createFileIfItDoesntExist.createWithTemplate)a=await this.periodicNoteContent(e)??"";else{let m=new wf(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);i?.enabled&&!i.requireActiveFile&&m.setLinkToCurrentFileBehavior("optional"),m.setTargetFolderPath(Zn(e)),m.setPromptRunContext({draftScopeId:`${this.choice.id}#${this.choice.createFileIfItDoesntExist.template}`,choiceName:this.choice.name,destination:e,destinationKind:"file"}),m.choiceChain=this.chain,m.setKeepUserTextProtected(!0),a=await m.run();let h=m.getAndClearTemplatePropertyVars();S.logMessage(`CaptureChoiceEngine: Collected ${h.size} template property variables`),h.size>0&&S.logMessage(`Variables: ${Array.from(h.keys()).join(", ")}`),this.templatePropertyVars=h}let l=this.choice.createFileIfItDoesntExist.createWithTemplate,c=()=>this.createFileWithInput(e,a,{suppressTemplaterOnCreate:l}),d=l?await c():await LF(this.app,e,c);try{this.choice.createFileIfItDoesntExist.createWithTemplate&&this.templatePropertyVars&&yf(d,this.templatePropertyVars)&&await bf(this.app,d,this.templatePropertyVars),l&&a&&await yu(this.app,d)}finally{a&&await this.restoreUserTextInNote(d)}let u=await this.app.vault.read(d),p=await this.collectIfFrontmatter(()=>this.formatter.insertFormattedContent(s,this.choice,u,d));return this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),{file:d,newFileContent:p.content,captureContent:p.captureContent,priorContent:u,cursor:p.cursor,markerOnly:p.markerOnly}}async restoreUserTextInNote(e){let n=await this.app.vault.read(e);Sn(n)!==n&&await Co(this.app,e,Sn)}collectIfFrontmatter(e){return this.suppressFrontmatterCollection?e():this.formatter.withTemplatePropertyCollection(e)}mergeCapturePropertyVars(e){if(!(!e||e.size===0)){for(let[n,i]of e)this.capturePropertyVars.set(n,i);S.logMessage(`CaptureChoiceEngine: Accumulated ${this.capturePropertyVars.size} structured capture variables`)}}async applyCapturePropertyVars(e){return this.capturePropertyVars.size===0?!1:yf(e,this.capturePropertyVars)?(S.logMessage(`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`),await bf(this.app,e,this.capturePropertyVars),this.capturePropertyVars.clear(),!0):(this.capturePropertyVars.clear(),!1)}};by();var Ji=require("obsidian");on();nt();rr();je();lt();wy();var $M=require("obsidian");Ve();Gi();tr();nt();function dG(r){let t=r.split("/").pop()??r,e=t.lastIndexOf(".");return e>0?t.slice(0,e):t}function FM(r){let t=new Gs(dG(r));return t.id=`folder-template:${r}`,t.templatePath=r,t.openFile=!0,t.fileNameFormat={enabled:!0,format:Cr},t.discoverExistingNotesBeforeCreate=!0,t}function MM(r){return ei(r.settings.templateFolderPaths).length>0}function iie(r,t){let e=r.lastIndexOf("/"),n=e===-1?"":r.slice(0,e),i=t.createDiv({cls:"suggestion-content"});i.createDiv({cls:"suggestion-title",text:dG(r)}),n&&(t.classList.add("mod-complex"),i.createDiv({cls:"suggestion-note",text:n}))}async function oie(r,t){let n=[...t].sort((i,o)=>i.path.localeCompare(o.path)).map(i=>i.path);try{return await It.Suggest(r,n,n,"New note from template",(i,o)=>iie(i,o))}catch(i){if(Be(i))return null;throw i}}async function L_(r,t,e){try{let n=e.templatePath?.trim()||void 0;if(!n){if(!MM(t)){new $M.Notice("QuickAdd: Set a template folder in Settings \u2192 QuickAdd \u2192 Template folders to use \u201CNew note from template\u201D.",8e3),dc(r,t.manifest.id,{notice:!1});return}let i=t.getTemplateFiles();if(i.length===0){new $M.Notice("QuickAdd: No template files found in your configured template folder(s).");return}let o=await oie(r,i);if(!o)return;n=o}await e.choiceExecutor.execute(FM(n))}catch(n){if(Be(n))return;Me(n,"Error running template from folder")}}lt();Go();var sie="\u2190 Back",aie="Select a choice";function jy(r){return mo(r)?`QuickAdd couldn't read the contents of "${r.name}". They're still in data.json.`:`Folder "${r.name}" is empty.`}var lie="Empty",cie="Unreadable";function die(r){return RM(r)?mo(r)?cie:lie:""}var Gy="quickadd:run-template-from-folder",uie="New note from template\u2026",Vf="quickadd:back";function RM(r){return r.type==="Multi"&&r.id!==Vf&&Le(r).length===0}var pie=.5;function mie(r){return r.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/(\*\*|__)(.+?)\1/g,"$2").replace(/\*(.+?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/~~(.+?)~~/g,"$1")}function DM(r){return(r.settings.templateFolderLauncherRow??"bottom")!=="off"&&MM(r)}function fie(){return{id:Gy,name:uie,type:"Template",command:!1}}var Iu=class r extends Ji.FuzzySuggestModal{constructor(e,n,i){super(e.app);this.plugin=e;this.choices=n;this.focusedProperty=null;this.triggerContext=null;this.placeholderStack=[];this.selectionDispatched=!1;this.breadcrumbById=new Map;this.markdownComponent=new Ji.Component;this.warnRenderFailure=ap("Could not render a choice name as Markdown; showing it as plain text");if(this.modalEl.addClass("qa-choice-suggester"),this.choiceExecutor=i?.choiceExecutor??new Sr(this.app,this.plugin),this.focusedProperty=i&&"focusedProperty"in i?i.focusedProperty??null:kT(this.app),this.triggerContext=i&&"triggerContext"in i?i.triggerContext??null:{activeFile:this.app.workspace.getActiveFile()},this.placeholderStack=i?.placeholderStack??[],this.completion=i?.completion,this.ancestry=i?.ancestry,this.currentPlaceholder=i?.placeholder?.trim()||aie,this.setPlaceholder(this.currentPlaceholder),this.markdownComponent.load(),i?.includeTemplateFolderRow){let o=this.plugin.settings.templateFolderLauncherRow??"bottom";if(DM(this.plugin)){let s=fie();this.choices=o==="top"?[s,...this.choices]:[...this.choices,s]}}}static Open(e,n,i){new r(e,n,i).open()}onClose(){super.onClose(),this.markdownComponent.unload(),this.completion&&!this.selectionDispatched&&this.completion(rn())}getSuggestions(e){let n=e.trim();if(!n||!U.getState().searchNestedChoices)return super.getSuggestions(n);let i=(0,Ji.prepareFuzzySearch)(n),o=[];for(let s of this.getNestedSearchCandidates()){let a=i(s.text);a&&(s.nameOffset>0&&a.matches.length>0&&a.matches.every(([,l])=>l<=s.nameOffset)&&(a.score-=pie),o.push({item:s.choice,match:a}))}return o.sort((s,a)=>a.match.score-s.match.score),o}getNestedSearchCandidates(){if(!this.nestedSearchCandidates){let e=this.choices.filter(n=>n.id!==Vf&&n.id!==Gy);this.nestedSearchCandidates=Td(e).map(({choice:n,path:i})=>{let o=i.slice(0,-1);o.length>0&&this.breadcrumbById.set(n.id,o.map(mie).join(" / "));let s=i.join(" / ");return{choice:n,text:s,nameOffset:s.length-n.name.length}})}return this.nestedSearchCandidates}selectSuggestion(e,n){if(RM(e.item)){if("repeat"in n&&n.repeat)return;new Ji.Notice(jy(e.item)),this.inputEl.focus();return}this.selectionDispatched=!0,super.selectSuggestion(e,n)}renderSuggestion(e,n){n.empty(),n.classList.remove("mod-complex");let i=this.breadcrumbById.get(e.item.id),o=n.createDiv({cls:"quickadd-choice-suggestion-content"});this.renderChoiceIcon(e.item,o);let s;if(i){n.classList.add("mod-complex");let c=o.createDiv({cls:"suggestion-content quickadd-choice-suggestion-text"});s=c.createDiv({cls:"suggestion-title"}),c.createDiv({cls:"suggestion-note",text:i})}else s=o.createDiv({cls:"quickadd-choice-suggestion-title quickadd-choice-suggestion-text"});Ji.MarkdownRenderer.render(this.app,e.item.name,s,"",this.markdownComponent).catch(c=>{s.textContent=e.item.name,this.warnRenderFailure(c)}),n.classList.add("quickadd-choice-suggestion"),e.item.id===Vf&&n.classList.add("quickadd-choice-suggestion-back"),e.item.id===Gy&&n.classList.add("quickadd-choice-suggestion-run-template");let a=die(e.item),l=a!=="";if(n.classList.toggle("quickadd-choice-suggestion-empty",l),l){n.setAttribute("aria-disabled","true");let c=At(o,"span");c.classList.add("quickadd-choice-suggestion-empty-flair"),c.textContent=a,o.appendChild(c)}else n.removeAttribute("aria-disabled")}renderChoiceIcon(e,n){let i=this.getChoiceSuggestionIcon(e);if(!i)return;let o=At(n,"span");o.classList.add("quickadd-choice-icon"),o.setAttribute("aria-hidden","true"),n.appendChild(o),(0,Ji.setIcon)(o,i)}getChoiceSuggestionIcon(e){if(e.id!==Vf)return e.id===Gy?"file-plus":Ed(e)}getItemText(e){return e.name}getItems(){return this.choices}settleCompletion(e,n){e.then(()=>this.completion?.(),i=>{let o=typeof i=="string"&&Be(i)?rn():ka(i);xd(o,n),this.completion?.(o)})}onChooseItem(e,n){if(e.id===Gy){this.settleCompletion(L_(this.app,this.plugin,{choiceExecutor:this.choiceExecutor}),"Could not run a template from that folder");return}if(e.type==="Multi")this.onChooseMultiType(e);else{"shiftKey"in n&&n.shiftKey&&(this.choiceExecutor.pickDate=!0);let i=this.choiceExecutor.executeWithFocusedProperty?this.choiceExecutor.executeWithFocusedProperty(e,this.focusedProperty,this.triggerContext,this.ancestry):this.choiceExecutor.execute(e,this.ancestry);this.settleCompletion(i,`Could not run "${e.name}"`)}}onChooseMultiType(e){let n=e.id===Vf;if(!n&&RM(e)){new Ji.Notice(jy(e)),this.completion?.();return}let i=[...Le(e)];if(!n){let a=new Xm(sie).addChoices(this.choices);a.id=Vf,i.push(a)}let o=n?this.placeholderStack[this.placeholderStack.length-1]:e.placeholder?.trim()||e.name,s=n?this.placeholderStack.slice(0,-1):[...this.placeholderStack,this.currentPlaceholder];r.Open(this.plugin,i,{choiceExecutor:this.choiceExecutor,focusedProperty:this.focusedProperty,triggerContext:this.triggerContext,placeholder:o,placeholderStack:s,completion:this.completion,ancestry:this.ancestry})}};je();ti();ye();mM();Ln();VS();Vy();Ve();jp();lc();Tf();pM();If();function hie(r,t,e){let n=t.pickDate?Yp(Ha(r.dateOrigin)):Ha(r.dateOrigin),i=UT({setting:n,clocks:t.clocks,variables:new Map([...t.variables,...Object.entries(e)]),reservedSeed:n?.kind==="ask"?e[Ta]:void 0});return i.status!=="set"?t.clocks:{now:t.clocks?.now??new Date,date:i.date}}function uG(r,t){let e=r.trim();if(!e)return[];let n=Array.from(t.keys()).sort((s,a)=>a.length-s.length),i=[],o=e;for(;o.length>0;){let s=n.find(a=>o===a||o.startsWith(`${a}, `));if(!s)break;i.push(s),o=o===s?"":o.slice(s.length+2)}if(o.length>0)for(let s of o.split(",")){let a=s.trim();a&&i.push(a)}return i}function gie(r,t,e){let n=r.filter(o=>e||t.includes(o)),i=new Set(n);return[...t.filter(o=>i.has(o)),...n.filter((o,s)=>!t.includes(o)&&n.indexOf(o)===s)]}async function pG(r,t,e,n){try{if(OH(e,n.id))return!1;let i=e.promptProvider?null:await BH(r,t,e,n),o=i?.requirements??await na(r,t,e,n,{seedCaptureSelectionAsValue:!0,preloadedUserScripts:e.preloadedUserScripts});if(o.length===0)return!1;let s=ml(o,e.variables);if(s.length===0)return!1;let a=s.filter(g=>!g.runtimeOnly||i?.config.fieldUsages.has(g.id));if(a.length===0)return!1;let l=async g=>{try{let v=new Gp(r,t);v.setRunClocks(hie(n,e,g));let b=[];if(n.type==="Template"){let y=n;if(y.fileNameFormat?.enabled){v.setTargetFolderPath(BC(y.folder)??"Folder/Name");for(let[C,w]of Object.entries(g))v.variables.set(C,w);b.push({label:"File name",text:await v.format(y.fileNameFormat.format),diagnostics:v.diagnostics.list()})}}return b}catch{return[]}},c=e.promptProvider,d=null,u;c?u=await c.requestInputs(a):(d=new Pf(r,a,e.variables,l,i?.config),u=await d.waitForClose);let p=new Map,m=new Map;for(let g of d?.activeRequirements??a){if(g.id.startsWith(ag)){let v=g.options??[],b=g.displayOptions??v;p.set(g.id,{options:v,displayToValue:new Map(v.map((y,C)=>[(b[C]??y).trim(),y])),allowCustom:g.suggesterConfig?.allowCustomInput??!1,multiSelect:g.suggesterConfig?.multiSelect??!1})}if(g.suggesterConfig?.multiSelect&&!g.id.startsWith(ag)){let v=g.options??[],b=g.displayOptions??v,y=new Map;v.forEach((C,w)=>{y.set((b[w]??C).trim(),C)}),m.set(g.id,{emit:g.multiEmit??"text",allowCustom:g.suggesterConfig.allowCustomInput??!1,displayToValue:y})}}let h=i?new Map:e.variables;return Object.entries(u).forEach(([g,v])=>{let b=p.get(g);if(b!==void 0){let w=d?.fileSelections.get(g)??(Array.isArray(v)?v.map(String):void 0)??(b.multiSelect?uG(String(v),b.displayToValue).map(_=>b.displayToValue.get(_)??_):[String(v)]),P=gie(w,b.options,b.allowCustom).map(_=>O0(_,b.options));h.set(g,b.multiSelect?P:P[0]??"");return}let y=m.get(g);if(y!==void 0){let w=(d?.multiSelections.get(g)??uG(String(v),y.displayToValue)).filter(T=>y.allowCustom||y.displayToValue.has(T)).map(T=>y.displayToValue.get(T)??T);h.set(g,y.emit==="linklist"?w.map(hw):w);return}h.set(g,v)}),i&&d&&UH(e,i,h,d.discoverySelections),!0}catch(i){if(i instanceof at)throw i;return e.promptProvider||S.logWarning(`One-page input failed for choice "${n.name}"; falling back to step-by-step prompts: ${i instanceof Error?i.message:String(i)}`),!1}}ti();kn();rr();nt();E_();Fm();wy();jp();lc();lt();Ve();hT();Tf();ye();If();al();Jd();var Sr=class{constructor(t,e){this.app=t;this.plugin=e;this.variables=new Map;this.preparedInputs=FH();this.interactive=!0;this.preloadedUserScripts=new Map;this.focusedProperty=null;this.triggerContext=null;this.pickDate=!1;this.pendingAbort=null;this.pendingResult=null;this.executionDepth=0;this.dispatchAncestry=u2()}signalAbort(t){this.pendingAbort=t}consumeAbortSignal(){let t=this.pendingAbort;return this.pendingAbort=null,t??null}recordExecutionResult(t){this.pendingResult=t}beginExecutionContext(){this.executionDepth===0&&(this.focusedProperty=this.focusedPropertyOverride!==void 0?this.focusedPropertyOverride:kT(this.app),this.triggerContext=this.triggerContextOverride!==void 0?this.triggerContextOverride:{activeFile:this.app.workspace.getActiveFile()},this.clocks={now:this.clocks?.now??new Date,date:this.clocks?.date}),this.executionDepth++}endExecutionContext(){this.executionDepth=Math.max(0,this.executionDepth-1),this.executionDepth===0&&(this.focusedProperty=null,this.triggerContext=null,this.clocks=void 0,this.pickDate=!1,this.preloadedUserScripts.clear(),NH(this))}async execute(t,e=this.dispatchAncestry){let n=vy(t,e);this.pendingAbort=null;let i=this.pendingResult;this.beginExecutionContext();let o=C_(this.app),s=Bn.getInstance(),a=s.beginExecutionScope();try{await this.runOnePagePreflightIfEnabled(t),await By(this,t.id,async()=>{switch(await this.applyDateOrigin(t),t.type){case"Template":{let l=t;await this.onChooseTemplateType(l,o,n);break}case"Capture":{let l=t;await this.onChooseCaptureType(l,o,n);break}case"Macro":{let l=t;await this.onChooseMacroType(l,o,n);break}case"Multi":{let l=t;await this.onChooseMultiType(l,n);break}default:break}if(this.pendingAbort){s.rollbackExecutionScope(a);return}s.commitExecutionScope(a)})}catch(l){throw s.rollbackExecutionScope(a),l}finally{this.pendingResult=i,this.endExecutionContext()}}async executeWithFocusedProperty(t,e,n,i){let o=this.focusedPropertyOverride,s=this.triggerContextOverride;this.focusedPropertyOverride=e,this.triggerContextOverride=n;try{await this.execute(t,i)}finally{this.focusedPropertyOverride=o,this.triggerContextOverride=s}}async executeWithOutcome(t){let e=vy(t,this.dispatchAncestry);this.pendingAbort=null,this.pendingResult=null,this.beginExecutionContext();let n=C_(this.app),i=Bn.getInstance(),o=i.beginExecutionScope();try{return await this.runOnePagePreflightIfEnabled(t),await By(this,t.id,async()=>{if(await this.applyDateOrigin(t),t.type==="Template"?await this.onChooseTemplateType(t,n,e):await this.onChooseCaptureType(t,n,e),this.pendingAbort){i.rollbackExecutionScope(o);let a=this.consumeAbortSignal(),l=a instanceof et;return{status:"cancelled",cancelKind:l?"user":"aborted",reason:l?void 0:a?.message}}i.commitExecutionScope(o);let s=this.pendingResult;return this.pendingResult=null,s??{status:"error"}})}catch(s){return i.rollbackExecutionScope(o),s instanceof et?{status:"cancelled",cancelKind:"user"}:s instanceof at?{status:"cancelled",cancelKind:"aborted",reason:s.message}:(Me(s,"Error executing choice from URI"),{status:"error",reason:s instanceof Error?s.message:String(s)})}finally{this.endExecutionContext()}}async applyDateOrigin(t){Un(t)&&bc(t,t.fileNameFormat.enabled?t.fileNameFormat.format:Cr,this.variables.get("value"))||await this.resolveDateOrigin(t)}async resolveDateOrigin(t){let e=this.pickDate?Yp(Ha(t.dateOrigin)):Ha(t.dateOrigin),n=e?.kind==="ask"?this.variables.get(Ta):void 0,i=UT({setting:e,clocks:this.clocks,variables:this.variables,reservedSeed:n});if(i.status==="inherit")return;if(i.status==="error")throw S.logError(i.message),new ue(i.message);if(i.status==="set"){this.clocks={now:this.clocks?.now??new Date,date:i.date};return}if(this.interactive===!1&&!this.promptProvider)throw new ue(`"${t.name}" needs a date. Re-run with date= or the ui flag.`);let o=`Date for ${t.name}`;try{let s=this.promptProvider?await this.promptProvider.datePrompt(o,{defaultValue:i.defaultValue,dateFormat:"YYYY-MM-DD"}):await ll.Prompt(this.app,o,void 0,i.defaultValue,"YYYY-MM-DD"),a=Py(s);if(!a)throw new ue("Could not parse the date origin.");this.clocks={now:this.clocks?.now??new Date,date:a}}catch(s){throw Be(s)?new et("Date origin cancelled by user"):s}}async prepareMacroInputs(t,e){if(e.length===0)return;let n={...t,macro:{...t.macro,commands:e}};await this.runOnePagePreflightIfEnabled(n)}async runOnePagePreflightIfEnabled(t){let e=U.getState().onePageInputEnabled,n=t.onePageInput??this.macroOnePageInput,i=this.promptProvider!=null;if((n==="always"||n!=="never"&&(e||i))&&(t.type==="Template"||t.type==="Capture"||t.type==="Macro"))try{await pG(this.app,this.plugin,this,t)}catch(s){throw Be(s)?new et("One-page input cancelled by user"):s}}async onChooseTemplateType(t,e,n){await new M_(this.app,this.plugin,t,this,e,n).run()}async onChooseCaptureType(t,e,n){await new O_(this.app,this.plugin,t,this,e,n).run()}async onChooseMacroType(t,e,n){let i=new Xs(this.app,this.plugin,t,this,this.variables,this.preloadedUserScripts,void 0,e,n),o=this.macroOnePageInput;this.macroOnePageInput=t.onePageInput??o;try{await i.run()}finally{this.macroOnePageInput=o}Object.entries(i.params.variables).forEach(([s,a])=>{this.variables.set(s,a)})}async onChooseMultiType(t,e){let n=Le(t);if(this.promptProvider||this.interactive===!1){let i=this.promptProvider?"Run one of its choices directly.":"Run one of its choices directly, or re-run with the ui flag.";this.signalAbort(new ue(n.length===0?jy(t):`"${t.name}" is a folder of choices, and picking from it needs someone at the window. ${i}`));return}if(n.length===0){new mG.Notice(jy(t));return}await new Promise((i,o)=>{Iu.Open(this.plugin,n,{choiceExecutor:this,focusedProperty:this.focusedProperty,triggerContext:this.triggerContext,placeholder:t.placeholder?.trim()||t.name,ancestry:e,completion:s=>s===void 0?i():o(s)})})}};tr();var fG=require("obsidian");var vie="QuickAdd: No choices yet. Create your first one in Settings \u2192 QuickAdd.";function N_(r){let t=Array.isArray(r.settings.choices)?r.settings.choices:[];if(!(t.length>0||DM(r))){new fG.Notice(vie,8e3),dc(r.app,r.manifest.id,{notice:!1});return}Iu.Open(r,t,{includeTemplateFolderRow:!0})}kM();ye();ye();tr();var hG={description:"Use QuickAdd template folder instead of Obsidian templates plugin folder / Templater templates folder.",migrate:async r=>{try{let t=r.app.plugins.plugins.templater,e=r.app.internalPlugins.plugins.templates;if(!t&&!e){S.logMessage("No template plugin found. Skipping migration.");return}let n=[];if(e){let s=e.instance.options;s.folder&&(n.push(s.folder),S.logMessage("Migrated template folder path to Obsidian Templates' setting."))}if(t){let s=t.settings;s.template_folder&&(n.push(s.template_folder),S.logMessage("Migrated template folder path to Templaters setting."))}let i=ei(r.settings.templateFolderPaths),o=ei([...i,...n]);o.length>0&&(r.settings.templateFolderPaths=o)}catch(t){throw S.logError("Failed to migrate template folder path."),t}}};Zr();function V_(r){return r===null||typeof r!="object"||!("type"in r)||!("choices"in r)?!1:r.type==="Multi"&&Array.isArray(r.choices)}function B_(r){return r===null||typeof r!="object"||!("choice"in r)?!1:r.choice!==void 0}lt();Hr();function gG(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="Template"&&"incrementFileName"in r}function vG(r){for(let t of r)V_(t)&&(t.choices=vG(t.choices)),gG(t)&&(t.setFileExistsBehavior=!0,t.fileExistsMode="Increment the file name",delete t.incrementFileName);return r}function yie(r){for(let t of r)for(let e of Mt(dr(t)))B_(e)&&gG(e.choice)&&(e.choice.setFileExistsBehavior=!0,e.choice.fileExistsMode="Increment the file name",delete e.choice.incrementFileName);return r}var bie={description:"'Increment file name' setting moved to 'Set default behavior if file already exists' setting",migrate:async r=>{let t=r.settings,e=!lp(r.settings.choices)&&!Wt(t.macros);if(Array.isArray(r.settings.choices)){let o=ke(r.settings.choices);r.settings.choices=ke(vG(o))}let n=ke(xm(t.macros)),i=yie(n);if(Array.isArray(t.macros)&&(t.macros=i),!e)return{complete:!1}}},yG=bie;Zr();var wie={description:"Re-run template file collision normalization for users with older migration state",migrate:async r=>{let t=r.settings,e=!rf(t);if(Array.isArray(r.settings.choices)&&(r.settings.choices=ke(r.settings.choices)),Array.isArray(t.macros)&&(t.macros=ke(t.macros)),nf(r,n=>{wE(n)&&CE(n)}),!e)return{complete:!1}}},U_=wie;var Cie={description:"Repair template file collision settings that may have been left in legacy format",migrate:U_.migrate},bG=Cie;lt();function OM(r){return Ee(r)&&r.type==="Capture"}Zr();lt();Hr();function wG(r){for(let t of r)V_(t)&&(t.choices=wG(t.choices)),OM(t)&&t.insertAfter?.enabled&&t.prepend&&(t.prepend=!1);return r}function xie(r){for(let t of r)for(let e of Mt(dr(t)))B_(e)&&OM(e.choice)&&e.choice.insertAfter?.enabled&&e.choice.prepend&&(e.choice.prepend=!1);return r}var Eie={description:"Mutual exclusion of insertAfter and writeToBottomOfFile settings. If insertAfter is enabled, writeToBottomOfFile is disabled. To support changes in settings UI.",migrate:async r=>{let t=r.settings,e=!lp(r.settings.choices)&&!Wt(t.macros);if(Array.isArray(r.settings.choices)){let o=ke(r.settings.choices);r.settings.choices=wG(o)}let n=ke(xm(t.macros)),i=xie(n);if(Array.isArray(t.macros)&&(t.macros=i),!e)return{complete:!1}}},CG=Eie;je();var Tie={description:"Set version to the current plugin version.",migrate:async r=>{U.setState({version:r.manifest.version})}},xG=Tie;fi();je();Zr();var _ie={description:"Add default AI providers to the settings.",migrate:async r=>{let t=U.getState().ai,e=ke(Hb);if("OpenAIApiKey"in t&&typeof t.OpenAIApiKey=="string"){let n=e.find(i=>i.name==="OpenAI");n&&(n.apiKey=t.OpenAIApiKey)}"OpenAIApiKey"in t&&delete t.OpenAIApiKey,U.setState({ai:{...U.getState().ai,providers:e}})}},EG=_ie;ye();lt();Hr();var kie={description:"Remove macro indirection - embed macros directly in macro choices",migrate:async r=>{let t=r.settings;if(lp(t.choices))return S.logMessage("QuickAdd could not read part of the choice list, so legacy macros were left in place to be migrated later."),{complete:!1};if(!Array.isArray(t.choices))return S.logMessage("QuickAdd could not read the choice list, so legacy macros were left in place to be migrated later."),{complete:!1};if(Wt(t.macros))return S.logMessage("QuickAdd could not read the legacy macro list, so it was left in place to be migrated later."),{complete:!1};let e=xm(t.macros),n=new Map,i=Jt(t.choices);for(let o of i)if(o.type==="Macro"){let s=o;if(s.macroId){let a=s.macroId;n.has(a)||n.set(a,[]),n.get(a).push(s)}}for(let o of e){if(!o||typeof o!="object"||typeof o.id!="string"||o.id==="")continue;let s=n.get(o.id)??i.filter(a=>a.type==="Macro"&&a.macro?.id===o.id);if(s.length===0){let a=new Qm(o.name);a.macro={id:o.id,name:o.name,commands:o.commands||[]},a.runOnStartup=o.runOnStartup||!1,t.choices.push(a)}else for(let a of s)a.macro={id:o.id,name:o.name,commands:o.commands||[]},a.runOnStartup??(a.runOnStartup=o.runOnStartup??!1),delete a.macroId}for(let o of i)if(o.type==="Macro"){let s=o;s.macroId&&(S.logMessage(`Removing orphaned macroId reference: ${s.macroId}`),delete s.macroId)}"macros"in t&&delete t.macros}},TG=kie;ye();var Sie={description:"Migrate legacy openFileInNewTab settings to new fileOpening format",migrate:async r=>{S.logMessage("Starting migration of file opening settings...");let t=rf(r.settings),e=0;if(nf(r,i=>{if(i.type!=="Template"&&i.type!=="Capture")return;let o=i,s=o.openFileInNewTab,a=o.openFileInMode,l=sf(s);!o.fileOpening&&l&&(o.fileOpening=af(l,a),e++,S.logMessage(`Migrated file opening settings for choice: ${i.name}`))}),S.logMessage(`Migration complete. Migrated ${e} choices.`),t)return{complete:!1}}},_G=Sie;ye();var Aie={description:"Backfill missing file opening defaults for older choices",migrate:async r=>{S.logMessage("Starting file opening defaults backfill...");let t=rf(r.settings),e=0;if(nf(r,i=>{if(i.type!=="Template"&&i.type!=="Capture")return;let o=i,s=typeof o.fileOpening=="object"&&o.fileOpening!==null?o.fileOpening:void 0,a=o,l=a.openFileInNewTab,c=a.openFileInMode,d=sf(l);(!s||s.location==null||s.direction==null||s.mode==null||s.focus==null)&&(!s&&d?o.fileOpening=af(d,c):o.fileOpening=en(s),e++)}),S.logMessage(`File opening defaults backfill complete. Updated ${e} choice(s).`),t)return{complete:!1}}},kG=Aie;je();Zr();var Iie={description:"Ensure every AI provider has a discovery mode so browsing works without models.dev",migrate:async r=>{let e=U.getState().ai.providers??[],n=!1;for(let i of e)i.modelSource||(i.modelSource="auto",n=!0);n&&U.setState(i=>({...i,ai:{...i.ai,providers:ke(e)}}))}},SG=Iie;Zr();ye();je();Zr();kc();var Pie={description:"Move AI provider API keys into Obsidian SecretStorage",migrate:async r=>{let t=U.getState().ai.providers??[],e=()=>t.some(o=>(o.apiKey?.trim()??"")!==""),n=r.app?.secretStorage;if(!n?.getSecret||!n?.setSecret)return e()?(S.logWarning("SecretStorage unavailable; deferring AI provider API key migration until it is available."),{complete:!1}):void 0;let i=!1;for(let o of t){let s=o.apiKey?.trim(),a=o.apiKeyRef?.trim();if(a){try{let l=await Promise.resolve(n.getSecret(a));!l&&s?(await Promise.resolve(n.setSecret(a,s)),o.apiKey="",i=!0):l&&s&&(o.apiKey="",i=!0)}catch(l){S.logWarning(`Failed to migrate secret for ${o.name}: ${l.message??l}`)}continue}if(s)try{let l=await Zq(r.app,o,s);l&&(o.apiKeyRef=l,o.apiKey="",i=!0)}catch(l){S.logWarning(`Failed to store API key for ${o.name}: ${l.message??l}`)}}if(i&&U.setState(o=>({...o,ai:{...o.ai,providers:ke(t)}})),e())return{complete:!1}}},AG=Pie;tr();var IG={description:"Move the single template folder path into the multi-folder list.",migrate:async r=>{let t=r.settings,e=ei(t.templateFolderPaths);e.length>0?t.templateFolderPaths=e:t.templateFolderPaths=ei([t.templateFolderPath]),delete t.templateFolderPath}};fi();Zt();je();Zr();ye();function $ie(r){for(let t of[r,`https://${r}`])try{let e=new URL(t).hostname.toLowerCase();if(e)return e}catch{}return""}function Fie(r){let t=$ie(r.endpoint??"");return t==="api.openai.com"?"openai":t==="generativelanguage.googleapis.com"?"google":t==="api.anthropic.com"?"anthropic":null}function Mie(r,t,e){let n=new Set(t==="anthropic"?[]:KD[t]);r.models=r.models.filter(o=>!n.has(o.name));let i=new Map(r.models.map(o=>[o.name,o]));for(let o of Eh[t]){let s=i.get(o.name);s?(s.maxTokens=o.maxTokens,s.maxOutputTokens=o.maxOutputTokens,s.supportsTemperature=o.supportsTemperature):e.has(o.name)||r.models.push({...o})}}var Rie={temperature:1,top_p:1,frequency_penalty:0,presence_penalty:0};function Die(r){return r.type==="AIAssistant"}var Oie={description:"Refresh built-in AI provider model lists: drop retired models, add the current generation, and turn on auto-sync.",migrate:async r=>{let t=U.getState(),e=ke(t.ai.providers??[]),n=ke(t.choices??[]),i=new Set;for(let l of e){let c=Fie(l);if(!c)continue;let d=new Set(e.filter(m=>m!==l).flatMap(m=>m.models.map(h=>h.name))),u=l.models.map(m=>m.name);Mie(l,c,d);let p=new Set(l.models.map(m=>m.name));for(let m of u)p.has(m)||i.add(m);l.autoSyncModels=!0,c==="openai"&&(l.modelSource="modelsDev")}let o=new Set(e.flatMap(l=>l.models.map(c=>c.name))),s=new Set([...i].filter(l=>!o.has(l)));yE({choices:n},l=>{if(!Die(l))return;l.model&&s.has(l.model)&&(S.logMessage(`AI command "${l.name}" used ${l.model}, which its provider has retired. It now asks for a model when it runs.`),l.model="Ask me");let c=l.modelParameters;if(c&&typeof c=="object")for(let[d,u]of Object.entries(Rie))c[d]===u&&delete c[d]});let a=s.has(t.ai.defaultModel)?"Ask me":t.ai.defaultModel;U.setState({choices:n,ai:{...U.getState().ai,defaultModel:a,providers:e}})}},PG=Oie;fi();je();Zr();ye();function Lie(r,t){return r.find(e=>e.models.some(n=>n.name===t))}var Nie={description:"Pin AI commands' models to the provider they currently resolve to, and give every provider a stable id.",migrate:async r=>{let t=U.getState(),e=ke(t.ai.providers??[]),n=ke(t.choices??[]);qb(e),bE(n,e,(s,a)=>{S.logMessage(`Pinned AI command "${s.name}"'s model to ${a.providerId}/${a.name}.`)});let i,o=t.ai.defaultModel;if(t.ai.defaultModelRef&&t.ai.defaultModelRef.name===o)i=t.ai.defaultModelRef;else if(o&&o!=="Ask me"){let s=Lie(e,o);s?.id&&(i={providerId:s.id,name:o},S.logMessage(`Pinned the default model to ${s.id}/${o}.`))}U.setState({choices:n,ai:{...U.getState().ai,providers:e,...i?{defaultModelRef:i}:{}}})}},$G=Nie;je();var LM={useQuickAddTemplateFolder:hG,incrementFileNameSettingMoveToDefaultBehavior:yG,consolidateFileExistsBehavior:U_,repairTemplateFileExistsBehavior:bG,mutualExclusionInsertAfterAndWriteToBottomOfFile:CG,setVersionAfterUpdateModalRelease:xG,addDefaultAIProviders:EG,removeMacroIndirection:TG,migrateFileOpeningSettings:_G,backfillFileOpeningDefaults:kG,setProviderModelDiscoveryMode:SG,migrateProviderApiKeysToSecretStorage:AG,migrateToMultipleTemplateFolders:IG,refreshStaleDefaultModelSeeds:PG,pinAiModelRefs:$G};async function Vie(r){let t=Object.keys(LM).filter(e=>!r.settings.migrations[e]);if(t.length===0){S.logMessage("No migrations to run.");return}U.replaceState(ke(r.settings));for(let e of t){S.logMessage(`Running migration ${e}: ${LM[e].description}`);let n=ke(r.settings),i=U.getState();try{let o=await LM[e].migrate(r);U.getState()!==i&&(r.settings=ke(U.getState()));let s=o?.complete===!1;s||(r.settings.migrations[e]=!0),U.replaceState(ke(r.settings)),S.logMessage(s?`Migration ${e} incomplete; will retry on a later launch.`:`Migration ${e} successful.`)}catch(o){S.logError(`Migration '${e}' was unsuccessful. Please create an issue with the following error message:
- ${o}
- QuickAdd will now revert to backup.`),r.settings=n,U.replaceState(ke(r.settings))}}r.saveSettings()}var FG=Vie;je();var oa=require("obsidian");ye();function Bf(r){if(!r||typeof r!="string")return null;let t=r.split("-")[0]?.split("+")[0]?.trim();if(!t)return null;let e=t.split(".");if(e.length!==3)return null;let n=Number.parseInt(e[0]??"",10),i=Number.parseInt(e[1]??"",10),o=Number.parseInt(e[2]??"",10);return Number.isNaN(n)||Number.isNaN(i)||Number.isNaN(o)||n<0||i<0||o<0?null:{major:n,minor:i,patch:o}}function MG(r,t){return r.major-t.major||r.minor-t.minor||r.patch-t.patch}async function Bie(r,t,e){let n=await(0,oa.requestUrl)({url:`https://api.github.com/repos/${r}/${t}/releases?per_page=100`,throw:!1}),i=n.json;if(n.status>=400||!Array.isArray(i)){let s=typeof i=="object"&&i!==null&&"message"in i&&typeof i.message=="string"?i.message:"Unknown error";throw new Error(`Failed to fetch releases: ${s}`)}let o=Bf(e);if(!o)throw new Error(`Invalid version ${e}`);return i.filter(s=>{if(s.draft||s.prerelease)return!1;let a=Bf(s.tag_name);return a!==null&&MG(a,o)>0})}var NM=/^https:\/\/github\.com\/user-attachments\/assets\/[A-Za-z0-9-]+$/,RG=/^\[!\[[^\]]*\]\(([^)\s"]+)\)\]\((https:\/\/github\.com\/user-attachments\/assets\/[A-Za-z0-9-]+)\)$/,Uie=/^<!--\s*poster:\s*(https:\/\/[^\s"'>]+)\s*-->$/;function qie(r,t){let e=t?` poster="${t}"`:"";return`<video controls preload="metadata" playsinline style="width: 100%; border-radius: 8px;" src="${r}"${e}></video>`}function zie(r){let t=r.split(`
- `),e=new Set;for(let s of t){let a=s.trim();NM.test(a)&&e.add(a)}let n=new Map;for(let s of t){let a=s.trim().match(RG);a&&e.has(a[2])&&n.set(a[2],a[1])}let i=new Set;for(let s=0;s<t.length;s++)if(NM.test(t[s].trim()))for(let a of[1,-1]){let l=s+a;for(;l>=0&&l<t.length&&t[l].trim()==="";)l+=a;let c=l>=0&&l<t.length?t[l].trim().match(Uie):null;if(c){n.set(t[s].trim(),c[1]),i.add(l);break}}let o=[];for(let s=0;s<t.length;s++){let a=t[s],l=a.trim();if(i.has(s))continue;let c=l.match(RG);if(!(c&&e.has(c[2]))){if(NM.test(l)){o.push(qie(l,n.get(l)));continue}o.push(a)}}return o.join(`
- `)}var q_=class extends oa.Modal{constructor(e,n){super(e);this.markdownComponent=new oa.Component;this.isClosed=!1;this.previousVersion=n,this.releaseNotesPromise=Bie("chhoumann","quickadd",n),this.releaseNotesPromise.then(i=>{if(!this.isClosed){if(this.releases=i,this.releases.length===0){this.close();return}this.display()}}).catch(i=>{S.logError(`Failed to fetch release notes: ${i}`),this.isClosed||this.close()})}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h1",{text:"Fetching release notes..."}),this.addCloseFooter()}addCloseFooter(){let e=this.contentEl.createDiv("quickadd-update-modal-footer");new oa.ButtonComponent(e).setButtonText("Done").setCta().onClick(()=>this.close())}onClose(){let{contentEl:e}=this;this.isClosed=!0,this.markdownComponent.unload(),e.empty()}display(){let{contentEl:e}=this;e.empty(),e.classList.add("quickadd-update-modal-container");let n=`## New in QuickAdd v${this.releases[0].tag_name}
- `,i="Thank you for using QuickAdd! If you like the plugin, please consider supporting me by buying me a coffee. With your sponsorship, I'll be able to contribute more to my existing projects, start new ones, and be more responsive to issues & feature requests.",o='<div class="quickadd-bmac-container"><a href="https://www.buymeacoffee.com/chhoumann" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 144px !important;" ></a></div>',s=e.createDiv("quickadd-update-modal markdown-rendered"),a=this.releases.map(u=>zie(u.body??"")).join(`
- ---
- `),l=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,d=`${n}
- ${i}
- ${o}
- I'd love to get your feedback on QuickAdd! Please fill out this <a href="https://forms.gle/WRq1ewcKK8qmkqps6">feedback form</a> to let me know what you think.
- ${l}
- ---
- ${a}`;this.markdownComponent.load(),oa.MarkdownRenderer.render(this.app,d,s,this.app.vault.getRoot().path,this.markdownComponent),this.addCloseFooter()}};gT();Zr();function VM(r){if(r===!0||r==="true")return!0;if(r===!1||r==="false")return!1}function DG(r,t){if(t.cancelled!==void 0&&typeof t.cancelled!="boolean")return`The "cancelled" flag must be the literal true (or omitted). A cancel that is not recognised would otherwise be answered on the user's behalf.`;if(t.cancelled===!0)return null;if(r==="confirm"){let e=t.value;if(VM(e)===void 0)return`A confirm prompt needs a boolean reply, or {"cancelled": true} if the user dismissed it. Got ${BM(e)}.`}return null}function BM(r){return r===void 0?"no value":r===null?"null":typeof r=="string"?JSON.stringify(r.slice(0,40)):typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?"an array":typeof r}rr();kn();var Hie=25e3,Wie=6e4,Gie=3e4,jie=75e3,Yie=3e3,Kie=32;function Qie(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r.charCodeAt(n)^t.charCodeAt(n);return e===0}function Xie(r){if(r.origin||r.referer)return!1;let t=(r.host??"").split(":")[0];return t==="127.0.0.1"||t==="localhost"}function Jie(r){try{let t=window.require;return t?t(r):null}catch{return null}}function z_(){let r=window.crypto;if(r?.randomUUID)return r.randomUUID();if(r?.getRandomValues){let t=r.getRandomValues(new Uint8Array(16));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}throw new Error("Interactive prompts require a secure random source (crypto), which is unavailable here.")}var H_="No pending prompt for that requestId",UM="The interactive client disconnected, so the run was ended.",qM=class{constructor(){this.server=null;this.port=0;this.sessions=new Map;this.startPromise=null;this.generation=0}async ensureStarted(){if(this.server)return this.port;if(this.startPromise)return this.startPromise;let t=Jie("http");if(!t)throw new Error("Interactive prompts require desktop Obsidian (Node http is unavailable).");let e=this.generation;return this.startPromise=new Promise((n,i)=>{let o=t.createServer((s,a)=>{this.handle(s,a)});o.on("error",s=>{this.generation===e&&(this.startPromise=null),i(s)}),o.listen(0,"127.0.0.1",()=>{if(this.generation!==e){o.close(),i(new Error("Interactive server stopped during startup."));return}let s=o.address();this.port=typeof s=="object"&&s?s.port:0,this.server=o,n(this.port)})}),this.startPromise}createSession(){if(this.sessions.size>=Kie)throw new Error("Too many active interactive sessions.");let t=z_(),e=z_()+z_(),n={id:t,token:e,queue:[],waiter:null,waiterTimer:null,pending:new Map,finished:!1,aborted:!1,cleanupTimer:null,attached:!1,attachTimer:null,pollWatchdog:null,disconnectGrace:null};return n.attachTimer=window.setTimeout(()=>{!n.attached&&!n.finished&&this.finish(n.id,{kind:"error",error:"No client attached to the interactive session."})},Gie),this.sessions.set(t,n),{id:t,token:e}}emitPrompt(t,e){let n=this.sessions.get(t);if(!n)return Promise.reject(new Error("Unknown session"));if(n.finished)return Promise.reject(new ue(UM));if(n.aborted)return Promise.reject(new et(Dl));let i=z_();return new Promise((o,s)=>{n.pending.set(i,{resolve:o,reject:s,promptType:e.type}),this.push(n,{kind:"prompt",requestId:i,prompt:e})})}finish(t,e){let n=this.sessions.get(t);if(!(!n||n.finished)){n.finished=!0,n.attachTimer&&(window.clearTimeout(n.attachTimer),n.attachTimer=null),n.pollWatchdog&&(window.clearTimeout(n.pollWatchdog),n.pollWatchdog=null),n.disconnectGrace&&(window.clearTimeout(n.disconnectGrace),n.disconnectGrace=null);for(let[,i]of n.pending)i.reject(new ue(UM));n.pending.clear(),this.push(n,e),n.cleanupTimer=window.setTimeout(()=>this.destroySession(n),Wie)}}abortSession(t){let e=this.sessions.get(t);if(!e||e.finished)return null;e.aborted=!0;let n=[...e.pending.values()];e.pending.clear();for(let i of n)i.reject(new et(Dl));return e.queue=e.queue.filter(i=>i.kind!=="prompt"),n.length}stop(){this.generation++;for(let t of this.sessions.values()){this.clearSessionTimers(t);for(let[,e]of t.pending)e.reject(new ue("QuickAdd was unloaded during an interactive run."));if(t.waiter){let e=t.waiter;t.waiter=null,e({kind:"error",error:"QuickAdd unloaded"})}}this.sessions.clear(),this.server?.close(),this.server=null,this.port=0,this.startPromise=null}push(t,e){if(t.waiter){let n=t.waiter;t.waiter=null,t.waiterTimer&&(window.clearTimeout(t.waiterTimer),t.waiterTimer=null),n(e)}else t.queue.push(e)}clearSessionTimers(t){for(let e of[t.waiterTimer,t.cleanupTimer,t.attachTimer,t.pollWatchdog,t.disconnectGrace])e&&window.clearTimeout(e)}destroySession(t){this.clearSessionTimers(t);for(let[,e]of t.pending)e.reject(new ue(UM));t.pending.clear(),this.sessions.delete(t.id),this.sessions.size===0&&(this.server?.close(),this.server=null,this.port=0,this.startPromise=null)}authed(t,e){return!!t&&!!e&&Qie(t.token,e)}originAllowed(t){return Xie({origin:t.headers.origin,referer:t.headers.referer,host:t.headers.host})}submitReply(t,e,n,i=!1){let o=this.sessions.get(t);if(!o)return!1;let s=o.pending.get(e);return s?(o.pending.delete(e),i===!0?s.promptType==="info"?s.resolve(n):s.reject(new et(Dl)):s.resolve(n),!0):!1}pendingPromptType(t,e){return t.pending.get(e)?.promptType}send(t,e,n){let i=JSON.stringify(n);t.writeHead(e,{"content-type":"application/json","cache-control":"no-store"}),t.end(i)}async drainBody(t){let e=0;for await(let n of t)if(e+=n.length,e>1e6)throw new Error("Request body too large")}async readBody(t){let e=[],n=0;for await(let i of t){if(n+=i.length,n>1e6)throw new Error("Request body too large");e.push(i)}return e.length===0?{}:JSON.parse(Buffer.concat(e).toString("utf8"))}async handle(t,e){try{if(!this.originAllowed(t)){this.send(e,403,{ok:!1,error:"Forbidden"});return}let n=new URL(t.url??"/","http://127.0.0.1"),i=n.searchParams.get("session"),o=n.searchParams.get("token"),s=i?this.sessions.get(i):void 0;if(!this.authed(s,o)){this.send(e,404,{ok:!1,error:"Unknown session or token"});return}if(t.method==="GET"&&n.pathname==="/poll"){this.handlePoll(s,e);return}if(t.method==="POST"&&n.pathname==="/abort"){await this.drainBody(t);let a=this.abortSession(s.id);if(a===null){this.send(e,409,{ok:!1,error:"The interactive session has already ended"});return}this.send(e,200,{ok:!0,interrupted:a});return}if(t.method==="POST"&&n.pathname==="/reply"){let a=await this.readBody(t),l=this.submitWireReply(s.id,a);l.ok?this.send(e,200,{ok:!0}):this.send(e,l.status,{ok:!1,error:l.error});return}this.send(e,404,{ok:!1,error:"Not found"})}catch(n){this.send(e,400,{ok:!1,error:n instanceof Error?n.message:String(n)})}}handlePoll(t,e){t.attached||(t.attached=!0,t.attachTimer&&(window.clearTimeout(t.attachTimer),t.attachTimer=null)),t.pollWatchdog&&window.clearTimeout(t.pollWatchdog),t.pollWatchdog=window.setTimeout(()=>this.finishDisconnected(t),jie),t.disconnectGrace&&(window.clearTimeout(t.disconnectGrace),t.disconnectGrace=null);let n=t.queue.shift();if(n){this.send(e,200,n);return}if(t.waiter){this.send(e,200,{kind:"idle"});return}let i=o=>this.send(e,200,o);t.waiter=i,t.waiterTimer=window.setTimeout(()=>{t.waiter===i&&(t.waiter=null,t.waiterTimer=null,this.send(e,200,{kind:"idle"}))},Hie),e.on("close",()=>{t.waiter===i&&(t.waiterTimer&&window.clearTimeout(t.waiterTimer),t.waiter=null,t.waiterTimer=null,t.disconnectGrace&&window.clearTimeout(t.disconnectGrace),t.disconnectGrace=window.setTimeout(()=>this.finishDisconnected(t),Yie))})}finishDisconnected(t){this.finish(t.id,{kind:"error",error:"Interactive client disconnected."})}submitWireReply(t,e){let n=this.sessions.get(t);if(!n)return{ok:!1,status:409,error:H_};if(!e.requestId)return{ok:!1,status:409,error:H_};let i=this.pendingPromptType(n,e.requestId);if(!i)return{ok:!1,status:409,error:H_};let o=DG(i,e);return o?{ok:!1,status:400,error:o}:this.submitReply(n.id,e.requestId,e.value,e.cancelled)?{ok:!0}:{ok:!1,status:409,error:H_}}},gl=new qM;lt();ye();lt();Vy();var zM={choice:{value:"<name>",description:"Choice name"},id:{value:"<id>",description:"Choice id"}},HM={value:"<json>",description:"Variables object as JSON"},OG={description:"Allow interactive prompts"},LG={value:"<when>",description:"Day for {{DATE}} (YYYY-MM-DD, last week, last friday, ask, @date:ISO)"},W_={...zM,vars:HM,ui:OG,verify:{description:"Report the verified outcome for Template/Capture choices (file path and effect on success, honest failure when the engine swallows an error)"},date:LG},NG={type:{value:"<Template|Capture|Macro|Multi>",description:"Filter by choice type"},commands:{description:"Only include command-enabled choices"}},VG={kind:{value:"<links|tags>",description:"Which suggestions to list"},source:{value:"<vault-path>",description:"Note the link will be inserted in (link text follows the vault's link format from there)"}},WM={path:{value:"<vault-path>",description:"Path to a template file in the vault"},vars:HM,ui:OG,date:LG},GM={...zM,vars:HM,fields:{description:"Include full field metadata (options, defaults, widget config)"}},jM={...zM,vars:{value:"<json>",description:"Variables object as JSON (pre-seeded inputs)"}},BG={path:{value:"<vault-path>",description:"Path to a .quickadd.json package file in the vault"},decode:{description:"Inline decoded contents for each bundled file"}},UG=new Set(Object.keys(W_)),YM=new Set(Object.keys(WM)),qG=new Set(Object.keys(GM)),zG=new Set(Object.keys(jM));function sa(r){if(r===void 0)return!1;let t=r.toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}function Zie(r){let t;try{t=JSON.parse(r)}catch(e){throw new Error(`Invalid vars JSON: ${e instanceof Error?e.message:String(e)}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid vars JSON: expected an object");return t}function Uf(r,t){let e={};typeof r.vars=="string"&&Object.assign(e,Zie(r.vars));for(let[n,i]of Object.entries(r)){if(n.startsWith("value-")){let o=n.slice(6);o&&(e[o]=i);continue}t.has(n)||(e[n]=i)}return e}function Yy(r,t){if(typeof t.id=="string"&&t.id.trim().length>0)return r.getChoiceById(t.id);if(typeof t.choice=="string"&&t.choice.trim().length>0)return r.getChoiceByName(t.choice);throw new Error("Missing choice selector. Provide either choice=<name> or id=<id>")}function Ky(r){return{id:r.id,label:r.label,type:r.type,source:r.source??"collected",placeholder:r.placeholder,defaultValue:r.defaultValue,description:r.description,optionCount:r.options?.length??0}}function HG(r){return{...Ky(r),options:r.options,displayOptions:r.displayOptions,dateFormat:r.dateFormat,withTime:r.withTime,optional:r.optional,runtimeOnly:r.runtimeOnly,multiEmit:r.multiEmit,filters:r.filters,numericConfig:r.numericConfig,sliderConfig:r.sliderConfig,suggesterConfig:r.suggesterConfig}}function Qy(r,t){for(let[e,n]of Object.entries(t))r.variables.set(e,n)}function Pu(r){return{id:r.id,name:r.name,type:r.type}}var eoe=new Set(["template","capture","macro","multi"]);function toe(r){if(r.type==="Capture"){let t=r,e=fC(t),n={target:t.captureToActiveFile?"<active file>":t.captureTo,position:e==="activeTop"?"top":e==="top"&&t.captureToActiveFile?"cursor":e};if(e==="after"&&(n.line=t.insertAfter.promptHeading?"<ask>":t.insertAfter.after),e==="before"&&(n.line=t.insertBefore?.before??""),t.propertyCapture){let o=t.propertyCapture.property;n.property=o.kind==="named"?o.format:"<ask>"}n.format=t.format?.enabled?t.format.format:"{{VALUE}}",t.propertyCapture||(t.task&&(n.task=!0),t.eachLine&&(n.eachLine=!0));let i=t.createFileIfItDoesntExist;return i?.enabled&&i.createWithTemplate&&i.template&&(n.createWithTemplate=i.template),n}if(r.type==="Template"){let t=r,e=t.folder??{enabled:!1,folders:[]},n=VC(e);return{template:t.templatePath,folder:n==="obsidian-default"?"<default>":n==="active-file"?"<active file's folder>":n==="specified"&&e.folders?.length===1&&!e.chooseFromSubfolders?e.folders[0]:"<ask>",fileName:t.fileNameFormat?.enabled?t.fileNameFormat.format:"{{VALUE}}"}}}function WG(r,t=[]){let e=[];for(let n of pr(r)){if(!Ee(n))continue;let i=[...t,n.name],o=i.join(" / "),s=n.type==="Multi";e.push({id:n.id,name:n.name,type:n.type,command:n.command,path:o,runnable:!s,writes:toe(n)}),s&&e.push(...WG(Le(n),i))}return e}function GG(r,t){let e=typeof t.type=="string"?t.type.trim():"",n=e.toLowerCase();if(n&&!eoe.has(n))return{ok:!1,error:`Invalid type filter '${e}'.`};let i=WG(r.settings.choices).filter(o=>(!n||o.type.toLowerCase()===n)&&(!sa(t.commands)||o.command));return{ok:!0,count:i.length,choices:i}}async function jG(r,t){let e=Yy(r,t);if(e.type==="Multi")return{ok:!1,error:"Multi choices are interactive and cannot be checked via CLI.",choice:Pu(e)};let n=Uf(t,qG),i=new Sr(r.app,r);Qy(i,n);let o=await na(r.app,r,i,e),s=ml(o,i.variables),a=sa(t.fields)?HG:Ky;return{ok:s.length===0,choice:Pu(e),requiredInputCount:o.length,missingInputCount:s.length,missing:s.map(a),missingFlags:s.map(l=>`value-${l.id}=<value>`),...e.type==="Macro"?{deferred:$H(r,e,i.variables.get("value"))}:{}}}async function YG(r,t){let e=typeof t.path=="string"?t.path.trim():"";if(!e)return{ok:!1,error:"Missing package path. Provide path=<vault-path>."};let{pkg:n}=await IE(r.app,e),i=await cf(r.app,r.settings.choices,n),o={ok:!0,preview:i};return sa(t.decode)&&(o.contents=i.files.map(s=>({path:s.originalPath,...SE(n,s.originalPath)}))),o}function KG(r){let t=r.metadataCache;return{linkCandidates:e=>t.getLinkSuggestions?.().flatMap(({file:n,alias:i})=>n?[{path:n.path,mtime:n.stat.mtime,linktext:t.fileToLinktext(n,e),alias:i,excluded:t.isUserIgnored(n.path)}]:[])??null,tagCounts:()=>t.getTags()}}function QG(r,t){if(t.kind==="links"){let e=typeof t.source=="string"?t.source:"",n=r.linkCandidates(e);return n?{ok:!0,kind:"links",items:[...n].sort((o,s)=>Number(o.excluded)-Number(s.excluded)||s.mtime-o.mtime).map(({path:o,linktext:s,alias:a})=>a===void 0?{text:s,path:o}:{text:`${s}|${a}`,path:o,alias:a})}:{ok:!1,error:"This Obsidian version has no link suggestions API; update Obsidian."}}return t.kind==="tags"?{ok:!0,kind:"tags",items:Object.entries(r.tagCounts()).map(([n,i])=>({tag:n.replace(/^#/,""),count:i})).sort((n,i)=>i.count-n.count||n.tag.localeCompare(i.tag))}:{ok:!1,error:"kind must be links or tags"}}Ve();uu();var Xy="\0qa-idx:";function XG(r,t){let e=String(r);if(e.startsWith(Xy)){let n=Number(e.slice(Xy.length));if(Number.isInteger(n)&&n>=0&&n<t.length)return t[n]}return e}var G_=class{constructor(t,e=gl){this.sessionId=t;this.server=e}async suggester(t,e,n,i=!1){let o=typeof t=="function"?e.map((l,c,d)=>String(t(l,c,d))):t.map(l=>String(l)),s=e.map((l,c)=>({title:o[c]??String(l),value:`${Xy}${c}`})),a=await this.server.emitPrompt(this.sessionId,{type:"suggester",placeholder:n,allowCustomInput:i,items:s});return a==null?"":XG(a,e)}async suggesterMulti(t,e,n){let i=e.map((a,l)=>({title:t[l]??String(a),value:`${Xy}${l}`})),o=[];for(let a of n?.preselected??[]){let l=e.indexOf(a);if(l>=0)o.push(`${Xy}${l}`);else{let c=String(a);i.push({title:c,value:c}),o.push(c)}}let s=await this.server.emitPrompt(this.sessionId,{type:"multiselect",placeholder:n?.placeholder,allowCustomInput:n?.allowCustomInput??!1,items:i,preselected:o});return Array.isArray(s)?s.map(a=>XG(a,e)):[]}async inputPrompt(t,e,n){return this.textPrompt(t,e,n,!1)}async wideInputPrompt(t,e,n){return this.textPrompt(t,e,n,!0)}async textPrompt(t,e,n,i){let o=await this.server.emitPrompt(this.sessionId,{type:"input",header:t,placeholder:e,defaultValue:n,multiline:i});return o==null?"":String(o)}async datePrompt(t,e){let n=await this.server.emitPrompt(this.sessionId,{type:"date",header:t,placeholder:e?.placeholder,defaultValue:e?.defaultValue,dateFormat:e?.dateFormat,withTime:e?.withTime}),i=String(n??"");if(!i)return"";let o=i.startsWith("@date:")?i.slice(6):i,s=e?.dateFormat;return(s?Po(o,s):null)??o}async yesNoPrompt(t,e){let n=await this.server.emitPrompt(this.sessionId,{type:"confirm",header:t,text:e}),i=VM(n);if(i!==void 0)return i;throw new Error(`A confirm prompt needs a boolean reply, or {"cancelled": true} if the user dismissed it. Got ${BM(n)}.`)}async checkboxPrompt(t,e,n){let i=new Set(e??[]),o=await this.server.emitPrompt(this.sessionId,{type:"checkbox",header:n,items:t.map(s=>({title:String(s),value:String(s),checked:i.has(s)}))});return Array.isArray(o)?o.map(s=>String(s)):[]}async infoDialog(t,e){await this.server.emitPrompt(this.sessionId,{type:"info",header:t,text:Array.isArray(e)?e:[e]})}async requestInputs(t){let e=t.map(s=>({id:s.id,label:s.label??s.id,type:s.type==="file-picker"?"suggester":s.type,placeholder:s.placeholder,defaultValue:s.defaultValue,description:s.description,options:s.options,displayOptions:s.displayOptions,dateFormat:s.dateFormat,optional:s.optional,numericConfig:s.numericConfig,suggesterConfig:s.suggesterConfig?{allowCustomInput:s.suggesterConfig.allowCustomInput,multiSelect:s.suggesterConfig.multiSelect}:void 0,picker:s.type==="file-picker"?"file":void 0})),n=await this.server.emitPrompt(this.sessionId,{type:"form",fields:e});if(!n||typeof n!="object")return{};let i=new Set(t.filter(s=>s.type==="date").map(s=>s.id)),o={};for(let[s,a]of Object.entries(n)){if(Array.isArray(a)){o[s]=a.map(c=>String(c));continue}let l=a==null?"":String(a);l&&i.has(s)&&!l.startsWith("@date:")&&(l=`@date:${l}`),o[s]=l}return o}};Vy();tr();Tf();ti();async function KM(r,t,e){if(e&&(t.type==="Template"||t.type==="Capture")&&typeof r.executeWithOutcome=="function"){let i=await r.executeWithOutcome(t);switch(i.status){case"success":return{ok:!0,verified:!0,effect:i.effect,file:i.file?.path};case"cancelled":return{ok:!1,aborted:!0,error:i.reason||(i.cancelKind==="user"?"Execution cancelled by user":"Execution aborted")};case"error":return{ok:!1,error:i.reason||"Choice execution failed; no file was created."}}}let n;try{await r.execute(t),n=r.consumeAbortSignal?.()}catch(i){if(!(i instanceof at))throw i;n=i}return n?{ok:!1,aborted:!0,error:n.message||"Choice execution aborted"}:{ok:!0,verified:!1,effect:"unknown"}}async function JG(r,t,e,n,i){let o=Date.now(),s=Pu(e);if(e.type==="Multi")return{ok:!1,error:"Multi choices are interactive and cannot be run via CLI.",choice:s};let a=new Sr(r.app,r);if(Qy(a,Uf(t,n)),!Ef(a,t.date))return{ok:!1,error:`Could not parse date origin '${t.date}'.`,choice:s};if(a.interactive=sa(t.ui),!a.interactive){let c=await na(r.app,r,a,e,{preloadedUserScripts:a.preloadedUserScripts}),d=ml(c,a.variables);if(d.length)return{ok:!1,error:"Missing required inputs for non-interactive CLI run.",choice:s,missing:d.map(Ky),missingFlags:d.map(({id:u})=>u===Ta?"date=<when>":`value-${u}=<value>`)}}return{...await KM(a,e,i),choice:s,durationMs:Date.now()-o}}function QM(r,t){return JG(r,t,Yy(r,t),UG,sa(t.verify))}async function ZG(r,t){let e=typeof t.path=="string"?t.path.trim():"";if(!e)return{ok:!1,error:"Missing template path. Provide path=<vault-path>."};let n=Rn(r.app,e);if(!n)return{ok:!1,error:`No template file found at '${e}'.`};let i=FM(n.path);if(!sa(t.ui)){let{value:o}=Uf(t,YM);if(o==null||String(o).trim().length===0)return{ok:!1,error:"Missing required inputs for non-interactive CLI run.",choice:Pu(i),missing:[{id:"value",label:"New note name",type:"text",source:"collected",optionCount:0}],missingFlags:["value-value=<value>"]}}return JG(r,t,i,YM,!0)}async function ej(r,t){let e=Yy(r,t),n=Pu(e);if(e.type==="Multi")return{ok:!1,error:"Multi choices cannot be run interactively via CLI.",choice:n};let i=await gl.ensureStarted(),{id:o,token:s}=gl.createSession(),a=new Sr(r.app,r);return Qy(a,Uf(t,zG)),a.interactive=!0,a.promptProvider=new G_(o),KM(a,e,!0).then(l=>gl.finish(o,l.ok?{kind:"done",result:{...l,choice:n}}:{kind:"error",error:l.error})).catch(l=>gl.finish(o,{kind:"error",error:l instanceof Error?l.message:String(l)})),{ok:!0,choice:n,host:"127.0.0.1",port:i,sessionId:o,token:s,capabilities:["abort","outcome-effect"]}}je();var tj="quickadd:ai-test-connection",rj={provider:{value:"<id|name>",description:"AI provider id (e.g. openai) or name"}};async function nj(r,t){let e=String(t.provider??"").trim(),n=U.getState().ai.providers;if(!e)return{ok:!1,error:"Pass provider=<id|name>.",providers:n.map(a=>a.id??a.name)};let i=e.toLowerCase(),o=n.find(a=>a.id===e)??n.find(a=>a.name.trim().toLowerCase()===i);if(!o)return{ok:!1,error:`No AI provider matches "${e}".`,providers:n.map(a=>a.id??a.name)};let s=await jE(r.app,o);return{provider:o.id??o.name,...s}}xx();var j_="quickadd:save-clipboard-image",ij={sourcePath:{value:"<vault-path>",description:"Note path the image will live in (capture destination). Empty keeps a vault-root attachment."},nameAfterNoteTitle:{value:"<true|false>",description:"Override the Name pasted images after the note title setting for this save"}},roe=Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="),r=>r.charCodeAt(0));function noe(r){if(r===void 0||r==="")return;let t=r.toLowerCase();if(t==="true"||t==="1"||t==="yes"||t==="on")return!0;if(t==="false"||t==="0"||t==="no"||t==="off")return!1;throw new Error(`Invalid nameAfterNoteTitle: ${r}. Use true or false.`)}async function oj(r,t){try{let e=typeof t.sourcePath=="string"?t.sourcePath:"",n=noe(typeof t.nameAfterNoteTitle=="string"?t.nameAfterNoteTitle:void 0),i=await wx(r.app,roe.buffer,"image/png",e,n===void 0?void 0:{nameAfterNoteTitle:n});return JSON.stringify({ok:!0,command:j_,path:i.path,name:i.name,sourcePath:e||"",nameAfterNoteTitle:n??r.settings.namePastedImagesAfterNoteTitle})}catch(e){return JSON.stringify({ok:!1,command:j_,error:e instanceof Error?e.message:String(e)})}}je();lt();Hi();var lj="quickadd:package-import",cj={path:{value:"<vault-path>",description:"Path to a .quickadd.json package file in the vault"},acknowledge:{description:"Required when the package runs code: confirms you reviewed its scripts (see quickadd:package-preview)"},choices:{value:"import|overwrite|duplicate|skip",description:"Mode for every choice (default: overwrite when the id already exists, otherwise import). import refuses a package with a choice already in the vault"},files:{value:"write|overwrite|skip",description:"Mode for every bundled file (default: overwrite when the destination exists, otherwise write)"}},ioe=new Set(["import","overwrite","duplicate","skip"]),ooe=new Set(["write","overwrite","skip"]);function sj(r,t,e){let n=typeof r=="string"?r.trim().toLowerCase():"";if(n){if(!t.has(n))throw new Error(`Invalid ${e}=${r}. Use one of: ${Array.from(t).join(", ")}.`);return n}}function soe(r,t){let e=new Map(r.map(i=>[i.originalPath,DE(i,t)])),n=new Map;for(let i of e.values()){let o=i.toLowerCase();n.set(o,(n.get(o)??0)+1)}for(let[i,o]of e)(n.get(o.toLowerCase())??0)>1&&e.set(i,i);return e}var aj=Promise.resolve();function dj(r,t){let e=aj.then(()=>aoe(r,t));return aj=e.catch(()=>{}),e}async function aoe(r,t){let e=typeof t.path=="string"?t.path.trim():"";if(!e)return{ok:!1,error:"Missing package path. Provide path=<vault-path>."};let n=sj(t.choices,ioe,"choices"),i=sj(t.files,ooe,"files"),{app:o}=r,{pkg:s}=await IE(o,e),a=U.getState().choices,l=await PE(o,a,s),c=await cf(o,a,s);if(AE(c)&&!sa(t.acknowledge))return{ok:!1,error:"This package can run code. Review it with quickadd:package-preview, then pass acknowledge=true to import.",criticalScriptPaths:c.criticalScriptPaths,capabilities:c.capabilityRows.filter(v=>v.severity==="critical").map(v=>({flag:v.flag,title:v.title,detail:v.detail}))};let d=l.choiceConflicts.map(v=>({choiceId:v.choiceId,mode:Jv(n??(v.exists?"overwrite":"import"),v.exists)})),u=soe(l.assetConflicts,U.getState().templateFolderPaths),p=[];for(let v of l.assetConflicts){let b=u.get(v.originalPath)??v.originalPath,y=b===v.originalPath?v.exists:!Ut(b)&&await o.vault.adapter.exists(b);p.push({originalPath:v.originalPath,destinationPath:b,mode:RE(i??(y?"overwrite":"write"),y)})}let m=await $E({app:o,existingChoices:a,aiProviders:U.getState().ai.providers,pkg:s,choiceDecisions:d,assetDecisions:p});U.setState(v=>({...v,choices:m.updatedChoices})),LE(r,a,m),await r.saveSettings();let h=new Map(Jt(m.updatedChoices).map(v=>[v.id,v])),g=[...m.addedChoiceIds,...m.overwrittenChoiceIds].map(v=>h.get(v)).filter(v=>!!v).map(v=>({id:v.id,name:v.name,type:v.type}));return{ok:!0,added:m.addedChoiceIds,overwritten:m.overwrittenChoiceIds,skipped:m.skippedChoiceIds,writtenAssets:m.writtenAssets,skippedAssets:m.skippedAssets,choices:g}}var ds={runDefault:"quickadd",run:"quickadd:run",runTemplate:"quickadd:run-template",list:"quickadd:list",check:"quickadd:check",suggest:"quickadd:suggest",preview:"quickadd:package-preview",packageImport:lj,interactive:"quickadd:interactive",saveClipboardImage:j_,aiTestConnection:tj};function uj(r){let t=r;if(typeof t.registerCliHandler!="function")return S.logMessage("Skipping QuickAdd CLI handler registration: registerCliHandler is unavailable."),!1;let e=(n,i,o,s)=>t.registerCliHandler.call(t,n,i,o,async a=>{try{return JSON.stringify({command:n,...await s(a)})}catch(l){return JSON.stringify({ok:!1,command:n,error:l instanceof Error?l.message:String(l)})}});return e(ds.runDefault,"Run a QuickAdd choice (ok:true reports the choice ran without aborting; check verified to know QuickAdd confirmed the run, and effect to know whether the vault changed: created/changed/unchanged/unknown)",W_,n=>QM(r,n)),e(ds.run,"Run a QuickAdd choice (ok:true reports the choice ran without aborting; check verified to know QuickAdd confirmed the run, and effect to know whether the vault changed: created/changed/unchanged/unknown)",W_,n=>QM(r,n)),e(ds.runTemplate,"Create a new note from a template file (no Template choice required)",WM,n=>ZG(r,n)),e(ds.list,"List QuickAdd choices",NG,n=>GG(r,n)),e(ds.check,"Check missing inputs for a QuickAdd choice",GM,n=>jG(r,n)),e(ds.suggest,"List Obsidian's own [[ link or # tag suggestions for completion in another app",VG,n=>QG(KG(r.app),n)),e(ds.preview,"Preview a QuickAdd package before importing (files + capabilities)",BG,n=>YG(r,n)),e(ds.packageImport,"Import a QuickAdd package with the modal's default decisions (pass acknowledge=true after reviewing a package that runs code)",cj,n=>dj(r,n)),e(ds.interactive,"Run a choice interactively: forwards its runtime prompts to the caller over a local server (returns host/port/sessionId/token to attach)",jM,n=>ej(r,n)),e(ds.aiTestConnection,"Check an AI provider's models endpoint with its linked API key (reports the model count or the provider's error; never the key)",rj,n=>nj(r,n)),t.registerCliHandler.call(t,ds.saveClipboardImage,"Save a 1x1 PNG as a vault attachment using QuickAdd clipboard-image naming",ij,n=>oj(r,n)),S.logMessage("Registered QuickAdd CLI handlers."),!0}var aa={run:"Run",runTemplateFromFolder:"New note from template",applyTemplate:"Apply template to active note",reloadDev:"Reload (dev)",openSettings:"Open settings",openAISettings:"Open AI Assistant settings",resumePrompt:"Return to prompt"};Sx();kx();rs();ye();nt();fM();Tf();var loe=new Set(["shortcuts:","obsidian:"]);function Y_(r){return typeof r=="string"&&r.length>0?r:void 0}function pj(r){let t=Y_(r["x-success"]),e=Y_(r["x-error"]),n=Y_(r["x-cancel"]);if(t||e||n)return{success:t,error:e,cancel:n,any:!0};let i=Y_(r["x-callback-url"]);return i?{success:i,cancel:i,any:!0}:{any:!1}}function mj(r){return[r.success,r.error,r.cancel].filter(t=>typeof t=="string"&&t.length>0)}function XM(r){try{let t=new URL(r).protocol.toLowerCase();return loe.has(t)}catch{return!1}}function fj(r,t){let e=new URL(r);for(let[n,i]of Object.entries(t))e.searchParams.set(n,i);return e.toString()}function hj(r,t){return"obsidian://open?vault="+encodeURIComponent(r)+"&file="+encodeURIComponent(t)}function gj(r,t,e){r.registerObsidianProtocolHandler("quickadd",async c=>{let d=c,u=r.settings.enableUriCallbacks?pj(d):{any:!1};if(!u.any){await n(d);return}let p=mj(u).filter(v=>!XM(v));if(p.length>0){S.logWarning(`QuickAdd URI: ignoring disallowed callback URL(s): ${p.join(", ")}`),u.error&&XM(u.error)&&l(u.error,{status:"error",errorCode:"bad-callback-url"});return}if(!d.choice){S.logWarning("URI was executed without a `choice` parameter."),s(u,"choice-not-found");return}let m=t(d.choice);if(!m){S.logWarning(`URI could not find any choice named '${d.choice}'`),s(u,"choice-not-found");return}if(e(d.choice),m.type!=="Template"&&m.type!=="Capture"){S.logWarning(`QuickAdd URI x-callback supports Template and Capture choices only ('${m.name}' is ${m.type}). A URI with x-* callback params cannot run a ${m.type} choice while "Enable URI callbacks" is on; remove the x-* params to run it on the legacy path.`),s(u,"unsupported-choice-type");return}let h=new Sr(r.app,r);if(!i(h,d)){S.logWarning(`QuickAdd URI: could not parse date origin '${d.date}'.`),s(u,"execution-failed");return}let g=await h.executeWithOutcome(m);switch(g.status){case"success":o(u,g.file,g.effect);break;case"cancelled":g.cancelKind==="user"?a(u):s(u,"execution-aborted");break;case"error":s(u,"execution-failed");break}});async function n(c){if(!c.choice){S.logWarning("URI was executed without a `choice` parameter.");return}let d=t(c.choice);if(!d){Me(new Error(`URI could not find any choice named '${c.choice}'`),"URI handler error");return}e(c.choice);let u=new Sr(r.app,r);if(!i(u,c)){Me(new Error(`Could not parse date origin '${c.date}'`),"URI handler error");return}try{await u.execute(d)}catch(p){xd(p,`Could not run "${d.name}"`)}}function i(c,d){return Object.entries(d).filter(([u])=>u.startsWith("value-")).forEach(([u,p])=>{let m=u.slice(6);m&&typeof p=="string"&&!u_(m)&&c.variables.set(m,p)}),!!Ef(c,d.date)}function o(c,d,u){let p={status:"success",effect:u};d&&(p.path=d.path,p.url=hj(r.app.vault.getName(),d.path)),c.success&&l(c.success,p)}function s(c,d){c.error&&l(c.error,{status:"error",errorCode:d})}function a(c){c.cancel&&l(c.cancel,{status:"cancel"})}function l(c,d){LO(()=>{window.open(fj(c,d))},"QuickAdd URI: failed to open callback URL")}}var vj=require("obsidian");BT();Sx();function yj(r){r.addCommand({id:"runQuickAdd",name:aa.run,callback:()=>{N_(r)}}),r.addCommand({id:"resumePrompt",name:aa.resumePrompt,checkCallback:t=>tl.isPeeking()?(t||tl.getActive()?.resume(),!0):!1}),r.addCommand({id:"runTemplateFromFolder",name:aa.runTemplateFromFolder,callback:()=>{L_(r.app,r,{choiceExecutor:new Sr(r.app,r)})}}),r.addCommand({id:"applyTemplateToActiveFile",name:aa.applyTemplate,checkCallback:t=>{let e=r.app.workspace.getActiveFile(),n=e?.extension==="md";if(t)return n;n&&Iy(r.app,r,{file:e,choiceExecutor:new Sr(r.app,r)})}}),r.registerEvent(r.app.workspace.on("file-menu",(t,e)=>{e instanceof vj.TFile&&e.extension==="md"&&t.addItem(n=>n.setTitle(`QuickAdd: ${aa.applyTemplate}`).setIcon("file-plus").onClick(()=>{Iy(r.app,r,{file:e,choiceExecutor:new Sr(r.app,r)})}))})),r.addCommand({id:"reloadQuickAdd",name:aa.reloadDev,checkCallback:t=>{if(t)return r.settings.devMode;let e=r.manifest.id,n=r.app.plugins;n.disablePlugin(e).then(()=>n.enablePlugin(e))}})}function bj(r,t,e=5e3){let n=!1,i;r.register(()=>{n=!0,window.clearTimeout(i)}),r.app.workspace.onLayoutReady(()=>{n||(i=window.setTimeout(t,e))})}function wj(r){let t=()=>{let e=activeDocument.activeElement;e?.instanceOf(HTMLElement)&&e.closest(".quickAddModal")&&e.scrollIntoView({block:"nearest"})};window.addEventListener("keyboardDidShow",t),r.register(()=>window.removeEventListener("keyboardDidShow",t))}function Cj(r,t){r.registerEvent(r.app.workspace.on("quit",n=>{vC(r.app),n.addPromise(t())}));let e=()=>{O1(r.app),t()};r.registerDomEvent(document,"visibilitychange",()=>{document.visibilityState==="hidden"&&e()}),r.registerDomEvent(window,"blur",e)}var coe=1e3,K_=class extends xj.Plugin{constructor(){super(...arguments);this.lastPersistedSettings=null;this.suppressSettingsSave=!1;this.persistChain=Promise.resolve();this.pendingSave=null;this.requestSave=Object.assign(()=>{this.pendingSave??(this.pendingSave=window.setTimeout(()=>this.requestSave.run(),coe))},{run:()=>{this.pendingSave!==null&&(this.requestSave.cancel(),(async()=>await this.persistSettings())())},cancel:()=>{this.pendingSave!==null&&window.clearTimeout(this.pendingSave),this.pendingSave=null}})}get api(){return Mf.GetApi(this.app,this,new Sr(this.app,this))}ingestImagesIntoActivePrompt(e){return DB(e)}async onload(){S.logMessage("Loading QuickAdd"),LV(this),await this.loadSettings(),U.replaceState(this.settings),this.unsubscribeSettingsStore=U.subscribe(s=>{this.settings=s,this.suppressSettingsSave||this.requestSave()}),yj(this),Cj(this,()=>this.flushPendingSave());let e=cl.getInstance();e.startAutomaticCleanup(s=>this.registerInterval(s)),e.registerInvalidationListeners(this.app,s=>this.registerEvent(s)),this.addCommand({id:"openQuickAddSettings",name:aa.openSettings,callback:()=>{dc(this.app,this.manifest.id)}}),gj(this,s=>this.getChoice("name",s),s=>this.warnIfChoiceNameAmbiguous(s)),S.register(new iy).register(new rT(this)),hz(this),wj(this),this.settings.enableRibbonIcon&&this.addRibbonIcon("file-plus","QuickAdd",()=>{N_(this)});let n=new tT(this.app,this);this.addSettingTab(n),this.addCommand({id:"openAIAssistantSettings",name:aa.openAISettings,callback:()=>n.openAIAssistantPageFromCommand()}),this.addCommandsForChoices(this.settings.choices);try{await FG(this)}catch(s){Me(s,"QuickAdd could not run its settings migrations")}let i=()=>{try{uj(this)}catch(s){Me(s,"QuickAdd could not register its CLI handlers")}};this.app.workspace.layoutReady?i():this.app.workspace.onLayoutReady(i);let o=async()=>{try{await new __(this.app,this,this.settings.choices,new Sr(this.app,this)).run()}catch(s){Me(s,"QuickAdd could not run its startup macros")}};this.app.workspace.layoutReady?o():this.app.workspace.onLayoutReady(o),bj(this,()=>{tz(this.app)}),this.announceUpdate()}onunload(){S.logMessage("Unloading QuickAdd"),vC(this.app),this.flushPendingSave(),this.unsubscribeSettingsStore?.call(this),kh.loggers.forEach(n=>{n instanceof iy&&n.clearErrorLog()}),cl.getInstance().destroy(),gl.stop(),tl.getActive()?.cancel()}normalizeLoadedSettings(e){let n=Object.assign({},Gb,e??{});return typeof n.announceUpdates=="boolean"&&(n.announceUpdates=n.announceUpdates?"all":"none"),Array.isArray(n.choices)&&(n.choices=zO(n.choices)),r$(n,rw),n}async loadSettings(){let e=await this.loadData(),n=this.normalizeLoadedSettings(e);this.settings=n,this.lastPersistedSettings=ke(n)}flushPendingSave(){return this.requestSave.run(),this.persistChain}async saveSettings(){this.requestSave.cancel(),await this.persistSettings()}persistSettings(){let e=async()=>{let n=this.lastPersistedSettings,i=async()=>n?this.normalizeLoadedSettings(await this.loadData()):null,o=await i(),s=u=>{let p=ke(this.settings);return NU({base:n,disk:u,local:p,currentStore:this.settings})},a=u=>{u.shouldReplaceStore&&_r(this.settings,u.local)&&this.publishSettingsFromDisk(u.toWrite)},l=s(o);if(l.didMerge&&S.logMessage("[Settings] data.json changed on disk since the last QuickAdd write; merged in-memory changes with on-disk settings before saving."),a(l),n){let u=await i();u&&(!o||!_r(u,o))&&(S.logMessage("[Settings] data.json changed again before save; re-merging with the fresher on-disk snapshot."),o=u,l=s(o),a(l))}let c=ke(this.settings),d=l.toWrite;_r(c,l.local)||(d=ol(l.local,c,l.toWrite)),VU(d,this.settings,c)&&this.publishSettingsFromDisk(d),await this.saveData(d),this.lastPersistedSettings=ke(d)};return this.persistChain=this.persistChain.then(e,e),this.persistChain}async onExternalSettingsChange(){let e=async()=>{let n;try{n=await this.loadData()}catch(a){S.logWarning(`QuickAdd could not read its changed settings: ${String(a)}`);return}if(!n)return;let i=this.lastPersistedSettings,o=this.normalizeLoadedSettings(n);if(i&&_r(o,i))return;let s=i?ol(i,ke(this.settings),o):o;this.lastPersistedSettings=ke(o),_r(s,this.settings)||this.publishSettingsFromDisk(s),_r(s,o)?this.requestSave.cancel():this.requestSave(),S.logMessage("[Settings] Applied settings that changed outside this Obsidian instance.")};this.persistChain=this.persistChain.then(e,e),await this.persistChain}publishSettingsFromDisk(e){let n=this.settings.choices;this.suppressSettingsSave=!0;try{U.replaceState(e),this.settings=e}finally{this.suppressSettingsSave=!1}if(!_r(n,e.choices)){for(let i of pr(n))Ee(i)&&this.removeCommandForChoice(i,{recursive:!0});this.addCommandsForChoices(e.choices)}}addCommandsForChoices(e){for(let n of pr(e))if(Ee(n))try{this.addCommandForChoice(n)}catch(i){Me(i,"Could not add a command for a QuickAdd choice")}}addCommandForChoice(e){if(e.type==="Multi"&&this.addCommandsForChoices(Le(e)),e.command){let n=e.id;this.addCommand({id:dC(n),name:e.name,icon:Ed(e),callback:()=>this.runRegisteredChoice(n,e.name)}),b1({origin:e.dateOrigin,enabled:e.pickDayCommand})&&this.addCommand({id:VA(n),name:BA(e.name),icon:Ed(e),callback:()=>this.runRegisteredChoice(n,e.name,!0)})}}async runRegisteredChoice(e,n,i=!1){let o;try{o=this.getChoiceById(e);let s=new Sr(this.app,this);s.pickDate=i,await s.execute(o)}catch(s){xd(s,`Could not run "${o?.name??n}"`)}}getChoiceById(e){let n=this.getChoice("id",e);if(!n)throw new Error(`Choice ${e} not found`);return n}getChoiceByName(e){let n=this.getChoice("name",e);if(!n)throw new Error(`Choice ${e} not found`);return n}getChoice(e,n,i=this.settings.choices){for(let o of pr(i))if(Ee(o)){if(o[e]===n)return o;if(o.type==="Multi"){let s=this.getChoice(e,n,Le(o));if(s)return s}}return null}countChoicesByName(e,n=this.settings.choices){let i=0;for(let o of pr(n))Ee(o)&&(o.name===e&&i++,o.type==="Multi"&&(i+=this.countChoicesByName(e,Le(o))));return i}warnIfChoiceNameAmbiguous(e){let n=this.countChoicesByName(e);n>1&&S.logWarning(`QuickAdd URI: ${n} choices are named '${e}'. Ran the first match \u2014 rename choices to keep names unique so URIs target the right one.`)}removeCommandForChoice(e,n){if(n?.recursive&&e.type==="Multi")for(let i of Le(e))Ee(i)&&this.removeCommandForChoice(i,n);this.removeCommand(dC(e.id)),this.removeCommand(VA(e.id))}getTemplateFiles(){let e=ei(this.settings.templateFolderPaths);return this.app.vault.getFiles().filter(n=>Ss(n.path)).filter(n=>RO(n.path,e))}announceUpdate(){let e=(l,c)=>{let d=Bf(l),u=Bf(c);return!d||!u?!0:d.major!==u.major?d.major>u.major:d.minor>u.minor},n=this.manifest.version,i=this.settings.version;if(n===i)return;let o=this.settings.announceUpdates,s=!0;if((o==="none"||o==="major"&&!e(n,i))&&(s=!1),this.settings.version=n,this.saveSettings(),!s)return;new q_(this.app,i).open()}};
- /* nosourcemap */
|