Files
thpeetz-notes/.obsidian/plugins/quickadd/main.js
T
2026-09-07 17:42:54 +02:00

424 lines
1.1 MiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var $6=Object.create;var kh=Object.defineProperty;var M6=Object.getOwnPropertyDescriptor;var O6=Object.getOwnPropertyNames;var R6=Object.getPrototypeOf,L6=Object.prototype.hasOwnProperty;var YP=r=>{throw TypeError(r)};var N6=(r,e,t)=>e in r?kh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var k=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var B6=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Nb=(r,e)=>{for(var t in e)kh(r,t,{get:e[t],enumerable:!0})},KP=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of O6(e))!L6.call(r,i)&&i!==t&&kh(r,i,{get:()=>e[i],enumerable:!(n=M6(e,i))||n.enumerable});return r};var QP=(r,e,t)=>(t=r!=null?$6(R6(r)):{},KP(e||!r||!r.__esModule?kh(t,"default",{value:r,enumerable:!0}):t,r)),V6=r=>KP(kh({},"__esModule",{value:!0}),r);var pe=(r,e,t)=>N6(r,typeof e!="symbol"?e+"":e,t),d_=(r,e,t)=>e.has(r)||YP("Cannot "+t);var z=(r,e,t)=>(d_(r,e,"read from private field"),t?t.call(r):e.get(r)),Ye=(r,e,t)=>e.has(r)?YP("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),He=(r,e,t,n)=>(d_(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),ct=(r,e,t)=>(d_(r,e,"access private method"),t);var BM,VM,qM=k(()=>{BM=r=>{let e,t=new Set,n=(c,u)=>{let d=typeof c=="function"?c(e):c;if(!Object.is(d,e)){let f=e;e=u??(typeof d!="object"||d===null)?d:Object.assign({},e,d),t.forEach(p=>p(e,f))}},i=()=>e,a={setState:n,getState:i,getInitialState:()=>l,subscribe:c=>(t.add(c),()=>t.delete(c))},l=e=r(n,i,a);return a},VM=(r=>r?BM(r):BM)});function sg(r){if(r.kind)return r.kind;let e=(r.name??"").toLowerCase(),t=oj(r.endpoint),n=i=>t===i||t.endsWith(`.${i}`);return e==="anthropic"||n("api.anthropic.com")?"anthropic":e==="gemini"||n("generativelanguage.googleapis.com")?"gemini":"openai"}function oj(r){let e=(r??"").trim();if(!e)return"";for(let t of[e,`https://${e}`])try{return new URL(t).hostname.toLowerCase()}catch{}return""}function sj(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Aw(r,e){let t=sj(r),n=new Set(e.map(o=>o.id).filter(o=>!!o)),i=t;for(let o=2;n.has(i);o++)i=`${t}-${o}`;return i}function Dw(r){let e=!1,t=new Set;for(let n of r){if(n.id&&!t.has(n.id)){t.add(n.id);continue}n.id=Aw(n.id??n.name,r),t.add(n.id),e=!0}return e}function gc(r,e){return e&&e.name===r?e:void 0}function Iw(r){return ag[r].map(e=>({...e}))}var ag,UM,aj,lj,Fw,fo=k(()=>{ag={openai:[{name:"gpt-5.5",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.4",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.4-mini",maxTokens:4e5,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.4-nano",maxTokens:4e5,maxOutputTokens:128e3,supportsTemperature:!1},{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.5-flash",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-pro-preview",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-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}]},UM={openai:["gpt-4-32k","gpt-4-1106-preview"],google:["gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"]};aj={id:"openai",name:"OpenAI",endpoint:"https://api.openai.com/v1",kind:"openai",apiKey:"",models:Iw("openai"),autoSyncModels:!0,modelSource:"modelsDev"},lj={id:"gemini",name:"Gemini",endpoint:"https://generativelanguage.googleapis.com",kind:"gemini",apiKey:"",models:Iw("google"),autoSyncModels:!0,modelSource:"modelsDev"},Fw=[aj,lj]});function zM(r,e){return Object.prototype.hasOwnProperty.call(r,e)?r[e]:void 0}function lg(r,e=$p){let t=r.trim();if(!t)return r;let n=zM(e,t.toLowerCase());if(n)return n;let[i,...o]=t.split(/\s+/),s=zM(e,i.toLowerCase());return s?[s,...o].join(" "):r}function HM(r){let e={},t=r.split(/\r?\n/);for(let n of t){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(e,s,{value:a,enumerable:!0,writable:!0,configurable:!0})}return e}function gk(r){return Object.entries(r).filter(([e,t])=>e&&t).map(([e,t])=>`${e} = ${t}`).join(`
`)}function cg(r){let e=Object.entries(r);if(e.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=e.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 Pw(r){return cg(r).map(([e,t])=>`${e}=${t}`).join(", ")}var $p,Ku=k(()=>{$p={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 $w,vk=k(()=>{fo();Ku();$w={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:$p,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:Fw,confirmToolCalls:"destructive"},migrations:{migrateToMacroIDFromEmbeddedMacro:!0,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,consolidateFileExistsBehavior:!1,repairTemplateFileExistsBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1,migrateToMultipleTemplateFolders:!1,refreshStaleDefaultModelSeeds:!1,pinAiModelRefs:!1}}});function Ze(r){if(typeof structuredClone=="function")try{return structuredClone(r)}catch{}return vc(r,new Map)}function vc(r,e){if(r===null||typeof r!="object")return r;if(e.has(r))return e.get(r);if(r instanceof Date){let i=new Date(r.getTime());return e.set(r,i),i}if(Array.isArray(r)){let i=[];e.set(r,i);for(let o of r)i.push(vc(o,e));return i}if(r instanceof Map){let i=new Map;e.set(r,i);for(let[o,s]of r.entries())i.set(vc(o,e),vc(s,e));return i}if(r instanceof Set){let i=new Set;e.set(r,i);for(let o of r.values())i.add(vc(o,e));return i}if(r instanceof RegExp){let i=new RegExp(r.source,r.flags);return i.lastIndex=r.lastIndex,e.set(r,i),i}if(r instanceof ArrayBuffer){let i=r.slice(0);return e.set(r,i),i}if(ArrayBuffer.isView(r)){if(r instanceof DataView){let a=new DataView(vc(r.buffer,e),r.byteOffset,r.byteLength);return e.set(r,a),a}let i=r,o=vc(i.buffer,e),s=new i.constructor(o,i.byteOffset,i.length);return e.set(r,s),s}let t=Object.getPrototypeOf(r),n=Object.create(t);e.set(r,n);for(let[i,o]of Object.entries(r))Object.defineProperty(n,i,{value:vc(o,e),writable:!0,enumerable:!0,configurable:!0});return n}var qn=k(()=>{});var ne,ht=k(()=>{qM();vk();qn();ne=(()=>{let r=VM((i,o)=>({...Ze($w)})),{getState:e,setState:t,subscribe:n}=r;return{getState:e,replaceState:i=>t(i,!0),setState:t,subscribe:n}})()});var Qu,ug,P,De=k(()=>{Qu=class Qu{register(e){return Qu.loggers.push(e),this}logError(e){let t=e instanceof Error?e.message:e,n=e instanceof Error?e.stack:void 0,i=e instanceof Error?e:void 0;Qu.loggers.forEach(o=>o.logError(t,n,i))}logWarning(e){let t=e instanceof Error?e.message:e,n=e instanceof Error?e.stack:void 0,i=e instanceof Error?e:void 0;Qu.loggers.forEach(o=>o.logWarning(t,n,i))}logMessage(e){let t=e instanceof Error?e.message:e,n=e instanceof Error?e.stack:void 0,i=e instanceof Error?e:void 0;Qu.loggers.forEach(o=>o.logMessage(t,n,i))}};Qu.loggers=[];ug=Qu,P=new ug});var zo,WM,yk,$i,ul,dl,Ds,Mw,Mp,Op,Rp,pl,Xu,GCe,Zu,Ow,Rw,yc,bk,wk,YCe,KCe,QCe,Ht,Cr,li,Ck,bc,Ho,ba,fl,Lw,Wo,Ek,xk,Tk,jM,GM,YM,KM,QM,XM,ZM,JM,eO,tO,rO,Sk,nO,iO,oO,sO,aO,lO,cO,uO,dO,pO,fO,mO,hO,Nw,dg,ml,gO,Je=k(()=>{zo="{{value}}",WM="{{name}}",yk=new RegExp(/^-?[0-9]*$/),$i="top",ul="bottom",dl="cursor",Ds="ordered",Mw=new RegExp(/{{DATE(\+-?[0-9]+)?(?:\|((?:startof|endof):[a-z]+))?(?:\|case:([a-z-]+))?}}/i),Mp=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),Op=new RegExp(/{{TIME(?:\|case:([a-z-]+))?}}/i),Rp=new RegExp(/{{TIME:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|\[]|\|(?!(?:case):[a-z-]+}}))*)(?:\|case:([a-z-]+))?}}/i),pl=new RegExp(/{{(?:NAME|VALUE)(?!:)(?:\|[^\n\r}]*)?}}/i),Xu=new RegExp(/{{VALUE:([^\n\r}]*)}}/i),GCe=new RegExp(/{{FIELD:([^\n\r}]*)}}/i),Zu="FIELD:",Ow=new RegExp(/{{FIELD:([^\n\r}|{]*)(\|[^\n\r}{]*)?}}/i),Rw=new RegExp(/{{FILE:([^\n\r{}]*)}}/i),yc=new RegExp(/{{VDATE:([^\n\r},|{]*)(?:,([^\n\r}|{]*))?(?:\|([^\n\r}{]*))?}}/i),bk=new RegExp(/{{LINKCURRENT}}/i),wk=new RegExp(/{{LINKSECTION}}/i),YCe=new RegExp(/{{FILENAMECURRENT}}/i),KCe=new RegExp(/{{FOLDERCURRENT(\|name)?}}/i),QCe=new RegExp(/{{FOLDER(\|name)?}}/i),Ht=new RegExp(/\.md$/i),Cr=new RegExp(/\.canvas$/i),li=new RegExp(/\.base$/i),Ck=new RegExp(/\.js$/),bc=new RegExp(/{{MACRO:([^\n\r}]*)}}/i),Ho=new RegExp(/{{TEMPLATE:([^\n\r}]*\.(?:md|canvas|base))}}/i),ba=new RegExp(/{{GLOBAL_VAR:([^\n\r}]*)}}/i),fl=new RegExp(/`{3,}js quickadd([\s\S]*?)`{3,}/),Lw=new RegExp(/{{MVALUE}}/i),Wo=new RegExp(/{{TITLE}}/i),Ek=new RegExp(/{{SELECTED}}/i),xk=new RegExp(/{{CLIPBOARD}}/i),Tk=new RegExp(/{{RANDOM:(\d+)}}/i),jM=new RegExp(/\[\[([^\]]*)$/),GM=new RegExp(/#([^ ]*)$/),YM=new RegExp(/{{[D]?[A]?[T]?[E]?[}]?[}]?$/i),KM=new RegExp(/{{[D]?[A]?[T]?[E]?[:]?$|{{DATE:[^\n\r}]*}}$/i),QM=new RegExp(/{{[N]?[A]?[M]?[E]?[}]?[}]?$/i),XM=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[}]?[}]?$/i),ZM=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[:]?$|{{VALUE:[^\n\r}]*}}$/i),JM=new RegExp(/{{[V]?[D]?[A]?[T]?[E]?[:]?$|{{VDATE:[^\n\r}]*}}$/i),eO=new RegExp(/{{[L]?[I]?[N]?[K]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),tO=new RegExp(/^\{\{(?:l(?:i(?:n(?:k(?:s(?:e(?:c(?:t(?:i(?:o(?:n(?:\}\}?)?)?)?)?)?)?)?)?)?)?)?)?$/i),rO=new RegExp(/{{[F]?[I]?[L]?[E]?[N]?[A]?[M]?[E]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),Sk=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),nO=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[}]?[}]?$/i),iO=new RegExp(/{{[F]?[I]?[L]?[E]?[:]?$/i),oO=new RegExp(/{{[F]?[I]?[E]?[L]?[D]?[:]?$/i),sO=new RegExp(/{{[T]?[E]?[M]?[P]?[L]?[A]?[T]?[E]?[:]?$|{{TEMPLATE:[^\n\r}]*[}]?[}]?$/i),aO=new RegExp(/{{[M]?[A]?[C]?[R]?[O]?[:]?$|{{MACRO:[^\n\r}]*}}$/i),lO=new RegExp(/{{[M]?[V]?[A]?[L]?[U]?[E]?[}]?[}]?/i),cO=new RegExp(/{{[T]?[I]?[T]?[L]?[E]?[}]?[}]?/i),uO=new RegExp(/{{[S]?[E]?[L]?[E]?[C]?[T]?[E]?[D]?[}]?[}]?/i),dO=new RegExp(/{{[C]?[L]?[I]?[P]?[B]?[O]?[A]?[R]?[D]?[}]?[}]?$/i),pO=new RegExp(/{{[R]?[A]?[N]?[D]?[O]?[M]?[:]?$|{{RANDOM:[^\n\r}]*}}$/i),fO=new RegExp(/{{[G]?[L]?[O]?[B]?[A]?[L]?[_]?[V]?[A]?[R]?[:]?$|{{GLOBAL_VAR:[^\n\r}]*}}$/i),mO=new RegExp(/{{[T]?[I]?[M]?[E]?[}]?[}]?/i),hO=new RegExp(/{{[T]?[I]?[M]?[E]?[:]?$|{{TIME:[^\n\r}]*}}$/i),Nw="__qa.",dg=`${Nw}captureTargetFilePath`,ml=`${Nw}dateOrigin`,gO=new RegExp(/\[\[([^\]]*)\]\]/)});var Bw=k(()=>{});var Tt,jo=k(()=>{Tt=class extends Error{constructor(e){super(e||"Macro execution aborted"),this.name="MacroAbortError"}}});function Ir(){return new dt(wc)}var dt,wc,Er=k(()=>{jo();dt=class extends Tt{},wc="Input cancelled by user"});function Ju(r,e){if(r instanceof Error){if(!e)return r;let n=new Error(`${e}: ${r.message}`);return n.name=r.name,n.stack=r.stack,n}if(typeof r=="string")return new Error(e?`${e}: ${r}`:r);let t=e?`${e}: ${String(r)}`:String(r);return new Error(t)}function pt(r){return r instanceof dt?!0:typeof r=="string"&&cj.has(r)}function bO(r){return typeof r=="object"&&r!==null||typeof r=="function"}function pj(r,e){let t=r;for(let n=0;n<dj&&bO(t);n++){let i=yO.get(t);if(i!==void 0&&e-i<uj)return!0;t=t.cause}return!1}function We(r,e,t="ERROR"){let n=Date.now();if(pj(r,n))return!1;bO(r)&&yO.set(r,n);let i=Ju(r,e);switch(t){case"ERROR":P.logError(i);break;case"WARNING":P.logWarning(i);break;case"LOG":P.logMessage(i);break;default:P.logError(i)}return!0}function Lp(r,e,t="ERROR"){return pt(r)?!1:We(r,e,t)}function wO(r,e,t="ERROR"){try{return r()}catch(n){We(n,e,t);return}}function Np(r,e){let t=n=>{Lp(n,r)};return(...n)=>{try{let i=e(...n);typeof i?.then=="function"&&Promise.resolve(i).catch(t)}catch(i){t(i)}}}var _k,cj,yO,uj,dj,rr=k(()=>{De();Bw();Er();_k=100;cj=new Set(["no input given.","No input given.","cancelled"]),yO=new WeakMap,uj=1e4,dj=8});function Ik(r,e){try{let t=r.workspace.getActiveViewOfType(kO.MarkdownView);if(!t||t.file?.path!==e.path)return{cursor:null,value:null};let n=t.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 xj(r,e){return r!==null&&e!==null&&(r.line!==e.line||r.ch!==e.ch)}function SO(r){return typeof r!="string"?null:[...r.matchAll(Ej)].length}function Tj(r,e){let t=SO(r),n=SO(e);return t!==null&&n!==null&&t>n}function _O(r,e){return xj(r.cursor,e.cursor)||Tj(r.value,e.value)}async function qw(r,e,t=500){try{let n=r.vault.adapter;if(!("stat"in n)||typeof n.stat!="function")return;let i=await n.stat(e.path);if(!i)return;let o=i.mtime,s=Date.now(),a=30;for(;Date.now()-s<t;){await mg(a);let l=await n.stat(e.path);if(!l||l.mtime===o)return;o=l.mtime,a=Math.min(a*2,200)}}catch(n){P.logWarning(`waitForFileSettle: fallback due to adapter/stat failure \u2013 ${n.message}`)}}function Uw(r){return r.plugins.plugins["templater-obsidian"]}function ed(r){let e=Uw(r);return e||null}function hg(r){return!!ed(r)?.settings?.trigger_on_file_creation}function mg(r){return new Promise(e=>window.setTimeout(e,r))}async function $k(r,e,t={}){if(e.extension!=="md"||!hg(r))return;let i=ed(r)?.templater?.files_with_pending_templates;if(!(i instanceof Set)){await AO(r,e,{timeoutMs:t.timeoutMs??5e3,gracePeriodMs:t.appearTimeoutMs??2500,quietPeriodMs:200});return}let{timeoutMs:o=5e3,appearTimeoutMs:s=2500}=t,a=Date.now();for(;Date.now()-a<s&&!i.has(e.path);)await mg(50);for(;Date.now()-a<o&&i.has(e.path);)await mg(50);await qw(r,e,800)}async function _j(r,e,t){if(!(Pk>0)&&t.size===0){if(fg){await fg;return}fg=(async()=>{try{r.workspace.trigger("templater:all-templates-executed"),await e.templater?.functions_generator?.teardown?.()}catch(n){P.logWarning(`withTemplaterFileCreationSuppressed: teardown failed \u2013 ${n.message}`)}})();try{await fg}finally{fg=null}}}async function Mk(r,e,t){let n=ed(r),i=n?.templater?.files_with_pending_templates;if(!n||!hg(r)||!(i instanceof Set))return await t();Pk++;let o=Fk.get(e);o||(o={count:0,hadPathInitially:i.has(e)},Fk.set(e,o),o.hadPathInitially||i.add(e)),o.count++;let s=!1;try{let a=await t();return s=!0,a}finally{o.count--,Pk--,o.count<=0&&(Fk.delete(e),o.hadPathInitially||(s&&await mg(Sj),i.delete(e),await _j(r,n,i)))}}async function AO(r,e,t={}){let{timeoutMs:n=2e3,quietPeriodMs:i=150,gracePeriodMs:o=800}=t;try{let s=r.vault.adapter;if(!("stat"in s)||typeof s.stat!="function")return;let a=await s.stat(e.path);if(!a)return;let l=a.mtime,c=Date.now(),u=!1,d=c,f=50;for(;Date.now()-d<n;){await mg(f);let p=await s.stat(e.path);if(!p)return;let m=Date.now();if(p.mtime!==l){u=!0,l=p.mtime,c=m,f=50;continue}if(u){if(m-c>=i)return}else if(m-d>=o)return;f=Math.min(Math.floor(f*1.5),200)}}catch(s){P.logWarning(`waitForFileToStopChanging: fallback due to adapter/stat failure \u2013 ${s.message}`)}}async function kj(r,e){let t=Vw.get(r)??Promise.resolve(),n,i=new Promise(s=>{n=()=>s()}),o=t.catch(()=>{}).then(()=>i);Vw.set(r,o),o.finally(()=>{Vw.get(r)===o&&Vw.delete(r)}).catch(()=>{}),await t.catch(()=>{});try{return await e()}finally{n()}}async function td(r,e,t={}){if(e.extension!=="md")return;let n=ed(r),i=n?.templater,o=i?.overwrite_file_commands;if(!n||!i||typeof o!="function")return;let{skipIfNoTags:s=!0,postWait:a=!0}=t;await kj(e.path,async()=>{await qw(r,e);let l;try{l=await r.vault.read(e)}catch(c){We(c,`overwriteTemplaterOnce: failed to read ${e.path} before render`);return}if(!(s&&!l.includes("<%")))try{await o.call(i,e),a&&await qw(r,e,800)}catch(c){try{await r.vault.modify(e,l)}catch(u){P.logWarning(`Failed to rollback ${e.path} after Templater error: ${u.message}`)}We(c,`Templater failed on ${e.path}. Rolled back to pre-render state.`)}})}async function hl(r,e,t){if(t.extension!=="md")return e;let n=ed(r),i=n?.templater,o=i?.parse_template;if(!n||!i||typeof o!="function")return e;let s=i.create_running_config,a=typeof s=="function"?s.call(i,void 0,t,4):{target_file:t,run_mode:4,frontmatter:{}};return await o.call(i,a,e)}async function Ec(r,e){if(e.extension!=="md"||r.workspace.getActiveFile()?.path!==e.path)return!1;let t=ed(r),n=!!t?.settings?.auto_jump_to_cursor,i=t?.editor_handler,o=i?.jump_to_next_cursor_location;if(!n)return!1;let s=Ik(r,e);if(typeof o=="function")try{return await o.call(i,e,!0),_O(s,Ik(r,e))}catch(a){P.logWarning(`jumpToNextTemplaterCursorIfPossible: API failed \u2013 ${a.message}`)}try{return!r.commands.executeCommandById?.("templater-obsidian:jump-to-next-cursor-location")?!1:_O(s,Ik(r,e))}catch{}return!1}var kO,Ej,Fk,Pk,fg,Sj,Vw,DO=k(()=>{kO=require("obsidian");De();rr();Ej=/<%\s*tp\.file\.cursor\([0-9]*\)\s*%>/g;Fk=new Map,Pk=0,fg=null,Sj=350;Vw=new Map});function ln(r){let e=r.workspace.getActiveViewOfType(IO.MarkdownView);return e?.editor?e:null}function rd(r){return ln(r)?.editor.getSelection()??""}var IO,wa=k(()=>{IO=require("obsidian")});function Vp(r){return Aj.has(r)}function id(r){return r==="inFrontmatter"}function zw(r){return Dj.has(r)}function Ij(r,e,t){return r==="embed"&&t.type==="activeFile"&&Vp(e)?"embed":"link"}function Fj(r,e,t,n){return r==="selection"&&t.type==="activeFile"&&zw(e)&&n==="link"?"selection":"none"}function Pj(r){return r?.type==="specifiedFile"?{type:"specifiedFile",path:typeof r.path=="string"?r.path.trim():""}:{type:"activeFile"}}function $j(r){return typeof r=="object"&&r!==null&&"enabled"in r&&"placement"in r}function xc(r){if($j(r)){let e=r.placement??"replaceSelection",t=Pj(r.destination),n=Ij(r.linkType,e,t);return{enabled:r.enabled,placement:e,requireActiveFile:r.requireActiveFile??!0,linkType:n,displayText:Fj(r.displayText,e,t,n),destination:t,frontmatterProperty:r.frontmatterProperty,frontmatterHandling:id(e)?r.frontmatterHandling??nd:r.frontmatterHandling}}return{enabled:r,placement:"replaceSelection",requireActiveFile:!!r,linkType:"link",displayText:"none",destination:{type:"activeFile"}}}var nd,Aj,Dj,od=k(()=>{nd="alwaysAppend",Aj=new Set(["replaceSelection","afterSelection","endOfLine","newLine"]);Dj=new Set(["replaceSelection","afterSelection"])});function Mj(r){return r.vault.getConfig?.("useMarkdownLinks")===!0}function Oj(r,e){let t=e.replace(/\s+/g,n=>/[\r\n]/.test(n)?" ":n).trim();if(t){if(Mj(r))return t.replace(/\\/g,"\\\\").replace(/\[/g,"\\[").replace(/\]/g,"\\]");if(!(t.includes("]]")||t.includes("[[")||t.endsWith("]")))return t}}function Rj(r){return`[[${r.path.replace(/\.md$/i,"")}]]`}function Hw(r,e,t={}){let n=t.sourcePath??"";if(t.linkType==="embed"&&(!t.placement||Vp(t.placement)))return`![[${r.metadataCache.fileToLinktext(e,n)}]]`;let o=t.alias===void 0?void 0:Oj(r,t.alias);return o===void 0?r.fileManager.generateMarkdownLink(e,n):r.fileManager.generateMarkdownLink(e,n,void 0,o)}function Ok(r){let e=r.trim().replace(/^\/+/,"");return e?/\.md$/i.test(e)?e:`${e}.md`:""}function vg(r,e){if(e.type!=="specifiedFile")return null;let t=Ok(e.path);if(!t)return null;let n=r.vault.getAbstractFileByPath(t);return!(n instanceof gg.TFile)||n.extension!=="md"?null:n}function Lj(r,e){return r.length===0?e:r.endsWith(`
`)?`${r}${e}`:`${r}
${e}`}async function Ww(r,e,t){let n=t.destination;if(n?.type!=="specifiedFile")return!1;let i=vg(r,n);if(!i)throw new Error(`Append link target file not found or is not a Markdown file: ${n.path}`);let o=Hw(r,e,{sourcePath:i.path,linkType:"link"});return await r.vault.process(i,s=>Lj(s,o)),!0}async function Nj(r){let e=window.navigator?.clipboard;if(!e?.writeText)return P.logMessage("QuickAdd: Clipboard API is unavailable."),!1;try{return await e.writeText(r),!0}catch(t){return P.logMessage(`QuickAdd: Could not copy link to clipboard: ${t instanceof Error?t.message:String(t)}`),!1}}async function jw(r){let e=Rj(r);return await Nj(e)?(new gg.Notice(`Copied link to '${r.basename}' to clipboard.`,FO),!0):(new gg.Notice(`Created '${r.basename}', but QuickAdd could not copy its link to the clipboard.`,FO),!1)}var gg,FO,yg=k(()=>{gg=require("obsidian");De();od();FO=4e3});function mo(r){if(r.nodeType===Node.DOCUMENT_NODE)return r;let e=r.ownerDocument;if(!e)throw new Error("Unable to resolve owner document for DOM node.");return e}function sd(r){let e=mo(r).defaultView;if(!e)throw new Error("Unable to resolve owner window for DOM node.");return e}function nr(r,e){return mo(r).createElement(e)}function bg(r,e){return mo(r).createTextNode(e)}var Is=k(()=>{});function Gw(r){for(let e of r.workspace.getLeavesOfType("markdown")){let t=e.view;if(!(!t.containerEl||!t.file||t.file.extension!=="md"))try{let n=mo(t.containerEl).activeElement;if(!n||!t.containerEl.contains(n)||!n.closest(".metadata-property-value")||n.matches(Bj))continue;let o=n.closest(".metadata-property")?.getAttribute("data-property-key");if(!o)continue;return{file:t.file,key:o}}catch{continue}}return null}function Vj(r,e,t){let n=e.trim();if(!n)throw new Error("Cannot append link to an empty frontmatter property key.");let i=OO(r,n),o=r[i];if(Array.isArray(o)){o.push(t);return}if(o==null||o===""){r[i]=t;return}if(typeof o=="string"){r[i]=`${o} ${t}`;return}throw new Error(`Cannot append link to frontmatter property '${i}' because it contains a ${typeof o} value.`)}function MO(r,e,t,n=nd){let i=e.trim();if(!i)throw new Error("Cannot append link to an empty frontmatter property key.");let o=OO(r,i),s=r[o];if(Array.isArray(s)){s.push(t);return}if(s===null||s===""){r[o]=[t];return}if(s===void 0){if(n==="error")throw new Error(`Cannot append link to frontmatter property '${o}' because it does not exist.`);r[o]=[t];return}if(typeof s=="object")throw new Error(`Cannot append link to frontmatter property '${o}' because it contains an object value.`);if(n!=="alwaysAppend")throw new Error(`Cannot append link to frontmatter property '${o}' because it is not a list and the link-handling mode is '${PO[n]}'. Choose '${PO.alwaysAppend}' to convert it into a list and append.`);r[o]=[s,t]}function OO(r,e){let t=$O(e),n=Object.keys(r).filter(i=>$O(i)===t);if(n.length>1)throw new Error(`Cannot append link to frontmatter property '${e}' because the note has multiple properties that normalize to that key.`);return n[0]??e}function $O(r){return r.trim().toLowerCase()}async function Yw(r,e,t){let n=r.fileManager.generateMarkdownLink(t,e.file.path);try{return await r.fileManager.processFrontMatter(e.file,i=>{Vj(i,e.key,n)}),!0}catch(i){return P.logError(`QuickAdd: created the file but could not append the link to frontmatter property '${e.key}' in '${e.file.path}': ${i instanceof Error?i.message:String(i)}`),!1}}var PO,Bj,qp=k(()=>{De();od();Is();PO={alwaysAppend:"Create or convert",createProperty:"Create if missing",error:"Require list"},Bj=['input[type="number"]','input[type="date"]','input[type="datetime-local"]','input[type="time"]','input[type="month"]','input[type="checkbox"]'].join(", ")});function wg(r,e){let t=ln(r);return t?.file?.path===e.path?t:null}function Rk(r,e){try{let t=ln(e);return t?(t.editor.replaceSelection(r),!0):(P.logError(`unable to append '${r}' to current line.`),!1)}catch{return P.logError(`unable to append '${r}' to current line.`),!1}}function Lk(r,e,t){try{let n=ln(t);if(!n)return P.logError(`unable to insert '${r}' on new line ${e}.`),!1;let i=n.editor,s=i.getCursor().line,a=r.split(`
`),l=a.length,c=a[l-1]?.length??0;if(e==="above")i.replaceRange(r+`
`,{line:s,ch:0}),i.setCursor({line:s+l-1,ch:c});else{let u=i.getLine(s);i.replaceRange(`
`+r,{line:s,ch:u.length}),i.setCursor({line:s+l,ch:c})}return!0}catch{return P.logError(`unable to insert '${r}' on new line ${e}.`),!1}}function Nk(r,e){return Lk(r,"above",e)}function Bk(r,e){return Lk(r,"below",e)}function qj(r,e,t,n){let i=l=>r.posToOffset(l),o=e.map(l=>{let[c,u]=i(l.anchor)<=i(l.head)?[l.anchor,l.head]:[l.head,l.anchor];return{from:c,to:u,text:n(r.getRange(c,u))}}).sort((l,c)=>i(l.from)-i(c.from)),s=o.map(({from:l,to:c,text:u})=>t==="replaceSelection"?{from:l,to:c,text:u}:{from:c,text:u}),a=[];if(t==="replaceSelection"){let l=0;for(let{from:c,to:u,text:d}of o)a.push(i(c)+l+d.length),l+=d.length-(i(u)-i(c))}r.transaction({changes:s}),t==="replaceSelection"&&r.setSelections(a.map(l=>({anchor:r.offsetToPos(l)})))}async function RO(r,e,t="replaceSelection",n={}){let{requireActiveView:i=!0,frontmatterProperty:o,frontmatterHandling:s=nd,textForSelection:a}=n,l=r.workspace.getActiveViewOfType(Kw.MarkdownView);if(!l){let p="Cannot append link because no active Markdown view is available.";if(i)throw new Error(p);P.logMessage(p);return}if(t==="inFrontmatter"){let p=l.file;if(!p)throw new Error("Cannot append link because the active Markdown view has no file.");await r.fileManager.processFrontMatter(p,m=>{MO(m,o??"",e,s)});return}let c=l.editor;if(!c){let p="Cannot append link because the active Markdown view has no editor.";if(i)throw new Error(p);P.logMessage(p);return}let u=c.listSelections().map(p=>({anchor:{...p.anchor},head:{...p.head}}));if(a&&u.length>0&&(t==="replaceSelection"||t==="afterSelection")){qj(c,u,t,a);return}if(t==="replaceSelection"){c.replaceSelection(e);return}let d=({line:p,ch:m})=>c.posToOffset({line:p,ch:m}),f=u.sort((p,m)=>d(m.head)-d(p.head));for(let p of f){let m=d(p.anchor)>d(p.head)?p.anchor:p.head;switch(t){case"afterSelection":{c.replaceRange(e,m);break}case"endOfLine":{let v=c.getLine(m.line),g={line:m.line,ch:v.length};c.replaceRange(e,g);break}case"newLine":{let v=c.getLine(m.line),g={line:m.line,ch:v.length},w=v.length===0?"":`
`;c.replaceRange(w+e,g);break}}}}async function ad(r,e,t){if(!t?.enabled)return!1;let n=xc(t),i=r.workspace.getActiveViewOfType(Kw.MarkdownView),o=n.placement!=="inFrontmatter";if(!i||!i.file||o&&!i.editor){if(t.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}let s=i.file.path,a=Hw(r,e,{sourcePath:s,linkType:n.linkType,placement:n.placement}),l=n.displayText==="selection"?c=>Hw(r,e,{sourcePath:s,linkType:n.linkType,placement:n.placement,alias:c}):void 0;return await RO(r,a,n.placement,{requireActiveView:!1,frontmatterProperty:n.frontmatterProperty,frontmatterHandling:n.frontmatterHandling,textForSelection:l}),!0}function Vk(r,e,t,n){try{if(e.extension!=="md"||!Number.isSafeInteger(t)||t<0||t>n.length)return!1;let i=r.workspace.getActiveViewOfType(Kw.MarkdownView);if(!i||i.file?.path!==e.path||i.getMode()==="preview")return!1;let o=i.editor;return!o||o.getValue()!==n?!1:(o.setCursor(o.offsetToPos(t)),!0)}catch{return P.logMessage(`Unable to place cursor after capture in '${e.path}'.`),!1}}var Kw,LO=k(()=>{Kw=require("obsidian");wa();De();od();yg();qp()});function Qw(r){return Ht.test(r)||Cr.test(r)||li.test(r)}function Mi(r,e){let t=e.trim().replace(/^\/+/,"");if(!t)return null;let n=Qw(t)?t:`${t}.md`,i=r.vault.getAbstractFileByPath(n);return i instanceof NO.TFile?i:null}function ui(r){if(!Array.isArray(r))return[];let e=new Set,t=[];for(let n of r){if(typeof n!="string")continue;let i=n.trim().replace(/^\/+/,"").replace(/\/+$/,"");!i||e.has(i)||(e.add(i),t.push(i))}return t}function qk(r,e){return e.length===0?!0:e.some(t=>r===t||r.startsWith(`${t}/`))}var NO,Xw=k(()=>{NO=require("obsidian");Je()});function VO(r){if(!r)return!1;let e=r,t=e.getViewState?.();return!!e.pinned||!!t?.pinned||!!t?.state?.pinned}function Cg(r){let e=r.workspace;return(e.rootSplit?e.getMostRecentLeaf?.(e.rootSplit):null)??e.getMostRecentLeaf?.()??null}function Uj(r){let e=[];return r.workspace.iterateRootLeaves(t=>{e.includes(t)||e.push(t)}),e}function BO(r){return r.parent?.id??r.parent??null}function zj(r,e){let t=BO(e),n=r.filter(s=>s===e||VO(s)?!1:t===null||BO(s)!==t);if(n.length===0)return null;let i=r.indexOf(e);return(i===-1?r:[...r.slice(i+1),...r.slice(0,i)]).find(s=>n.includes(s))??n[0]}function Hj(r){return r instanceof Up.TFile?!0:typeof r=="object"&&r!==null&&"path"in r&&typeof r.path=="string"&&"extension"in r&&typeof r.extension=="string"}function Wj(r,e,t,n){if(n&&(e==="tab"||e==="reuse")&&VO(n))return zj(Uj(r),n)??r.workspace.getLeaf("tab");switch(e){case"reuse":return r.workspace.getLeaf(!1);case"tab":return r.workspace.getLeaf("tab");case"split":return r.workspace.getLeaf("split",t);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 gl(r,e,t={}){let{location:n="tab",direction:i="vertical",mode:o,focus:s=!0,eState:a,originLeaf:l}=t,c=typeof e=="string"?r.vault.getAbstractFileByPath(e):e;if(!Hj(c)){let f=typeof e=="string"?e:e.path;throw new Error(`File not found: ${f}`)}let u=l??Cg(r),d=Wj(r,n,i,u);if(!d)throw new Error("Could not obtain a workspace leaf.");if(await d.openFile(c),o&&o!=="default"&&!(typeof o=="object"&&o.mode==="default")){let f=d.getViewState(),p={...f.state??{}};o==="preview"||typeof o=="object"&&o.mode==="preview"?(p.mode="preview",delete p.source):o==="source"?(p.mode="source",p.source=!0):o==="live"||o==="live-preview"?(p.mode="source",p.source=!1):typeof o=="object"&&o.mode==="source"&&(p.mode="source",p.source=o.source),await d.setViewState({...f,state:{...p,...a}})}return s&&r.workspace.setActiveLeaf(d,{focus:!0}),d}function Uk(r){return(0,Up.normalizePath)(r).replace(/\/{2,}/g,"/").replace(/^\/+/,"")}function qO(r,e){return Uk(r)===Uk(e)}function ld(r,e,t=!0){let n;return r.workspace.iterateRootLeaves(i=>{let o=i.view;if(o instanceof Up.FileView&&o.file&&(o.file===e||qO(e.path,o.file.path))){n=i;return}}),n!==void 0?(t&&r.workspace.setActiveLeaf(n,{focus:!0}),n):null}var Up,UO=k(()=>{Up=require("obsidian")});function vl(r){let e=0,t=0,n=!1,i=0,o=0,s=0;for(;e<=r.length;){let a=r.indexOf(`
`,e),l=a===-1?r.length:a,c=r.slice(e,l).replace(/\r$/,""),u=a===-1?r.length+1:a+1,d=jj.exec(c);if(n){if(d&&d[1].length>=i&&d[2].trim().length===0)return zO(r.slice(o,e),s)}else if(d){let f=d[2].trim().split(/\s+/)[0]?.toLowerCase();(f==="js"||f==="javascript")&&(n=!0,i=d[1].length,o=u,s=t+1)}if(e=u,t++,a===-1)break}return n?zO(r.slice(o),s):{code:null,error:Gj}}function zO(r,e){return r.trim().length===0?{code:"",error:Yj}:{code:`
`.repeat(e)+r}}var jj,Gj,Yj,Eg=k(()=>{jj=/^ {0,3}(`{3,})(.*)$/,Gj="No ```js (or ```javascript) code block found in the note.",Yj="The ```js code block is empty."});function HO(r){return r instanceof Zw}function Qj(r){return r.charCodeAt(0)===65279?r.slice(1):r}function Xj(r){return Qj(r).trimStart().slice(0,Kj).toLowerCase()}function Zj(r){return/^<(?:!doctype\s+html|html\b|head\b|body\b|script\b|meta\b|title\b|div\b)/.test(Xj(r))}function zk(r,e){let t=new Zw(r);throw e.reportLoadErrors!==!1&&We(t),t}function Jj(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 eG(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 tG(r,e){let t=e?`the required module "${e}"`:"a required module";return`QuickAdd could not load ${r} because it could not find ${t}. Check that the required file or package exists, and that the capitalization in require(...) matches the file name exactly.`}function rG(r){return WO(r)?(r instanceof Error?r.message:String(r)).match(/Cannot find module ['"]([^'"]+)['"]/)?.[1]:void 0}function WO(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 nG(r){return r!==null&&typeof r=="object"}function iG(r){return typeof r.entry=="function"?!0:Object.entries(r).some(([e,t])=>e!=="settings"&&e!=="quickadd"&&typeof t=="function")}function oG(r){return typeof r=="function"?!0:nG(r)?iG(r):!1}function cd(r){let e=r.split("::").map(t=>t.trim()).filter(Boolean);return{basename:e[0],memberAccess:e.slice(1)}}function eC(r){let e=r.path??r.id;if(e===void 0)return;let{memberAccess:t}=cd(r.name??"");return t&&t.length>0?`${e}::${t.join("::")}`:e}async function Fs(r,e,t={}){let n=e.vault.getAbstractFileByPath(r.path);if(!n){P.logError(`failed to load file ${r.path}.`);return}if(n instanceof Jw.TFile){let i=m=>window.require&&window.require(m),o={},s={exports:o},a=await e.vault.read(n),l=a;if(Ht.test(n.path)){let{code:m,error:v}=vl(a);if(m===null||m.length===0){t.reportLoadErrors!==!1&&new Jw.Notice(`QuickAdd: ${v} (${r.path})`);return}l=m}Zj(l)&&zk(Jj(r.path),t);try{new Function("require","module","exports",l)(i,s,o)}catch(m){throw WO(m)&&zk(tG(r.path,rG(m)),t),m}let c=o.default||s.exports;if(!c)return;let u=c,d=!!o.default,{memberAccess:f}=cd(r.name),p=!!(f&&f.length>0);if(f&&f.length>0){let m;for(;m=f.shift();)u=u[m]}return d&&!p&&!oG(u)&&zk(eG(r.path),t),u}}var Jw,Kj,Zw,tC=k(()=>{Jw=require("obsidian");Je();De();Eg();rr();Kj=1024,Zw=class extends Error{constructor(e){super(e),this.name="UserScriptLoadError"}}});function yl(r){if(r==null||typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")return"";let e=String(r).trim();return e.startsWith("#")?e.substring(1).trim():e}function Tc(r){return r==null?[]:(Array.isArray(r)?r:typeof r=="string"?r.split(/,|\s+/):[r]).map(yl).filter(Boolean)}var rC=k(()=>{});var di,ud=k(()=>{rC();di=class{static filterFiles(e,t,n){let i=e;return i=this.applyInclusionFilters(i,t,n),i=this.applyExclusionFilters(i,t,n),i}static applyInclusionFilters(e,t,n){let i=!1,o=e,s=this.getIncludeFolders(t);return s.length>0&&(i=!0,o=o.filter(a=>s.some(l=>this.matchesFolder(a,l)))),t.tags&&t.tags.length>0&&(i=!0,o=o.filter(a=>this.matchesAllTags(a,t.tags??[],n))),i?o:e}static applyExclusionFilters(e,t,n){return e.filter(i=>!(t.excludeFolders&&t.excludeFolders.length>0&&t.excludeFolders.some(o=>this.matchesFolder(i,o))||t.excludeTags&&t.excludeTags.length>0&&this.matchesAnyTag(i,t.excludeTags,n)||t.excludeFiles&&t.excludeFiles.length>0&&t.excludeFiles.some(o=>this.matchesFile(i,o))))}static getIncludeFolders(e){let t=e.folders?.length?e.folders:e.folder?[e.folder]:[];return[...new Set(t.map(n=>this.normalizePath(n)).filter(Boolean))]}static matchesFolder(e,t){let n=this.normalizePath(t),i=this.normalizePath(e.path);return i.startsWith(n+"/")||i.substring(0,i.lastIndexOf("/"))===n}static matchesAllTags(e,t,n){return this.matchesTags(e,t,n,"all")}static matchesAnyTag(e,t,n){return this.matchesTags(e,t,n,"any")}static matchesTags(e,t,n,i){let o=n(e);if(!o)return!1;let s=this.getAllTags(o),a=t.map(c=>this.normalizeTag(c)).filter(Boolean),l=c=>s.some(u=>u===c||u.startsWith(c+"/"));return i==="all"?a.every(l):a.some(l)}static matchesFile(e,t){return e.name===t||e.path===t}static getAllTags(e){let t=[];return e.frontmatter?.tags&&t.push(...Tc(e.frontmatter.tags)),e.frontmatter?.tag&&t.push(...Tc(e.frontmatter.tag)),e.tags&&t.push(...e.tags.map(n=>yl(n.tag))),t.filter(Boolean)}static normalizeTag(e){return yl(e)}static normalizePath(e){return e.replace(/^\/+|\/+$/g,"")}}});function Go(r){return r.vault.getAllLoadedFiles().filter(e=>e instanceof Hk.TFolder).map(e=>e.path)}function zp(r,e){let t=r.vault.getAbstractFileByPath(e);return!!t&&t instanceof Hk.TFolder}function ho(r,e){let t=e.replace(/\/+$/,"");if(t==="")return r.vault.getMarkdownFiles();let n=`${t}/`;return r.vault.getMarkdownFiles().filter(i=>i.path===t||i.path.startsWith(n))}function sG(r){let e=r.frontmatter;if(!e)return[];let t=Object.entries(e);if(!t.length)return[];let n=t.filter(([o,s])=>{let a=o.toLowerCase();return a==="tags"||a==="tag"});return n?n.flatMap(([,o])=>Tc(o)).filter(o=>!!o):[]}function aG(r,e){let t=r.metadataCache.getFileCache(e);if(!t)return[];let n=[];return t.frontmatter&&n.push(...sG(t)),t.tags&&Array.isArray(t.tags)&&n.push(...t.tags.map(i=>yl(i.tag))),n}function xg(r,e){let t=e.replace(/^#/,"");return r.vault.getMarkdownFiles().filter(n=>aG(r,n).includes(t))}function Hp(r,e){return di.filterFiles(r.vault.getMarkdownFiles(),e,t=>r.metadataCache.getFileCache(t))}function lG(r,e){let t=e.trim().toLowerCase();return r==null?!1:Array.isArray(r)?r.some(n=>n!=null&&typeof n!="object"&&String(n).trim().toLowerCase()===t):typeof r=="object"?!1:String(r).trim().toLowerCase()===t}function Wp(r,e,t,n){let i=e.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(([u])=>u.toLowerCase()===i);return c?t===void 0?!0:lG(c[1],t):!1});return n&&(n.folder||n.tags?.length||n.excludeFolders?.length||n.excludeTags?.length||n.excludeFiles?.length)&&(o=di.filterFiles(o,n,a=>r.metadataCache.getFileCache(a))),o}var Hk,jO=k(()=>{Hk=require("obsidian");ud();rC()});function GO(r,e){return r.commands.findCommand(e)}function nC(r,e){GO(r,e)&&(delete r.commands.commands[e],delete r.commands.editorCommands[e])}var YO=k(()=>{});function Yo(r){return r.split("|")}function KO(r){return r.startsWith("|")?r.slice(1):r}function Oi(r){let e=r.indexOf(":");if(e===-1)return null;let t=r.slice(0,e).trim().toLowerCase();if(!t)return null;let n=r.slice(e+1).trim();return{key:t,value:n}}function Sc(r){if(!r)return!0;let e=r.trim().toLowerCase();return!["false","no","0","off"].includes(e)}function Ps(r,e){let t=!1;return{remaining:r.filter(i=>i.trim().toLowerCase()===e?(t=!0,!1):!0),found:t}}var dd=k(()=>{});function iC(r){let e=r.trim().toLowerCase(),t=cG[e];if(!t)throw new Error(`Unknown date unit "${r.trim()}". Valid units: ${uG}.`);return t}function Wk(r){let e=Oi(r);return e?e.key==="startof"?{boundary:"start",unit:iC(e.value)}:e.key==="endof"?{boundary:"end",unit:iC(e.value)}:null:null}function jp(r,e){return e?e.boundary==="start"?r.startOf(e.unit):r.endOf(e.unit):r}var cG,uG,Tg=k(()=>{dd();cG={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"},uG="year, quarter, month, week, isoweek, day"});function dG(r){return r===void 0?window.moment():window.moment(r)}function pG(r){let e=dG(r?.now);return r?.origin?window.moment(r.origin).hour(e.hour()).minute(e.minute()).second(e.second()).millisecond(e.millisecond()):e}function Ko(r){let e;return r?.offset!==null&&r?.offset!==void 0&&typeof r.offset=="number"&&(e=window.moment.duration(r.offset,"days")),jp(pG(r).add(e),r?.snap).format(r?.format??"YYYY-MM-DD")}var QO=k(()=>{Tg()});var Dt=k(()=>{DO();LO();Xw();UO();tC();jO();YO();QO()});var xr,cn,Ur,Fr,oC,kc,bl,pd,XO,sC,Gp,ZO,jk,aC,fG,mG,hG,gG,vG,yG,bG,wG,CG,JO,go=k(()=>{xr="top",cn="bottom",Ur="right",Fr="left",oC="auto",kc=[xr,cn,Ur,Fr],bl="start",pd="end",XO="clippingParents",sC="viewport",Gp="popper",ZO="reference",jk=kc.reduce(function(r,e){return r.concat([e+"-"+bl,e+"-"+pd])},[]),aC=[].concat(kc,[oC]).reduce(function(r,e){return r.concat([e,e+"-"+bl,e+"-"+pd])},[]),fG="beforeRead",mG="read",hG="afterRead",gG="beforeMain",vG="main",yG="afterMain",bG="beforeWrite",wG="write",CG="afterWrite",JO=[fG,mG,hG,gG,vG,yG,bG,wG,CG]});function Sn(r){return r?(r.nodeName||"").toLowerCase():null}var Ac=k(()=>{});function pr(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var e=r.ownerDocument;return e&&e.defaultView||window}return r}var $s=k(()=>{});function Qo(r){var e=pr(r).Element;return r instanceof e||r instanceof Element}function un(r){var e=pr(r).HTMLElement;return r instanceof e||r instanceof HTMLElement}function Yp(r){if(typeof ShadowRoot>"u")return!1;var e=pr(r).ShadowRoot;return r instanceof e||r instanceof ShadowRoot}var vo=k(()=>{$s()});function EG(r){var e=r.state;Object.keys(e.elements).forEach(function(t){var n=e.styles[t]||{},i=e.attributes[t]||{},o=e.elements[t];!un(o)||!Sn(o)||(Object.assign(o.style,n),Object.keys(i).forEach(function(s){var a=i[s];a===!1?o.removeAttribute(s):o.setAttribute(s,a===!0?"":a)}))})}function xG(r){var e=r.state,t={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,t.popper),e.styles=t,e.elements.arrow&&Object.assign(e.elements.arrow.style,t.arrow),function(){Object.keys(e.elements).forEach(function(n){var i=e.elements[n],o=e.attributes[n]||{},s=Object.keys(e.styles.hasOwnProperty(n)?e.styles[n]:t[n]),a=s.reduce(function(l,c){return l[c]="",l},{});!un(i)||!Sn(i)||(Object.assign(i.style,a),Object.keys(o).forEach(function(l){i.removeAttribute(l)}))})}}var eR,tR=k(()=>{Ac();vo();eR={name:"applyStyles",enabled:!0,phase:"write",fn:EG,effect:xG,requires:["computeStyles"]}});function _n(r){return r.split("-")[0]}var Dc=k(()=>{});var Ms,fd,wl,Ic=k(()=>{Ms=Math.max,fd=Math.min,wl=Math.round});function Kp(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}var Gk=k(()=>{});function Sg(){return!/^((?!chrome|android).)*safari/i.test(Kp())}var Yk=k(()=>{Gk()});function Xo(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var n=r.getBoundingClientRect(),i=1,o=1;e&&un(r)&&(i=r.offsetWidth>0&&wl(n.width)/r.offsetWidth||1,o=r.offsetHeight>0&&wl(n.height)/r.offsetHeight||1);var s=Qo(r)?pr(r):window,a=s.visualViewport,l=!Sg()&&t,c=(n.left+(l&&a?a.offsetLeft:0))/i,u=(n.top+(l&&a?a.offsetTop:0))/o,d=n.width/i,f=n.height/o;return{width:d,height:f,top:u,right:c+d,bottom:u+f,left:c,x:c,y:u}}var Qp=k(()=>{vo();Ic();$s();Yk()});function md(r){var e=Xo(r),t=r.offsetWidth,n=r.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:r.offsetLeft,y:r.offsetTop,width:t,height:n}}var lC=k(()=>{Qp()});function _g(r,e){var t=e.getRootNode&&e.getRootNode();if(r.contains(e))return!0;if(t&&Yp(t)){var n=e;do{if(n&&r.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}var Kk=k(()=>{vo()});function Ri(r){return pr(r).getComputedStyle(r)}var Xp=k(()=>{$s()});function Qk(r){return["table","td","th"].indexOf(Sn(r))>=0}var rR=k(()=>{Ac()});function Un(r){return((Qo(r)?r.ownerDocument:r.document)||window.document).documentElement}var Cl=k(()=>{vo()});function El(r){return Sn(r)==="html"?r:r.assignedSlot||r.parentNode||(Yp(r)?r.host:null)||Un(r)}var kg=k(()=>{Ac();Cl();vo()});function nR(r){return!un(r)||Ri(r).position==="fixed"?null:r.offsetParent}function TG(r){var e=/firefox/i.test(Kp()),t=/Trident/i.test(Kp());if(t&&un(r)){var n=Ri(r);if(n.position==="fixed")return null}var i=El(r);for(Yp(i)&&(i=i.host);un(i)&&["html","body"].indexOf(Sn(i))<0;){var o=Ri(i);if(o.transform!=="none"||o.perspective!=="none"||o.contain==="paint"||["transform","perspective"].indexOf(o.willChange)!==-1||e&&o.willChange==="filter"||e&&o.filter&&o.filter!=="none")return i;i=i.parentNode}return null}function Os(r){for(var e=pr(r),t=nR(r);t&&Qk(t)&&Ri(t).position==="static";)t=nR(t);return t&&(Sn(t)==="html"||Sn(t)==="body"&&Ri(t).position==="static")?e:t||TG(r)||e}var Zp=k(()=>{$s();Ac();Xp();vo();rR();kg();Gk()});function hd(r){return["top","bottom"].indexOf(r)>=0?"x":"y"}var cC=k(()=>{});function gd(r,e,t){return Ms(r,fd(e,t))}function iR(r,e,t){var n=gd(r,e,t);return n>t?t:n}var Xk=k(()=>{Ic()});function Ag(){return{top:0,right:0,bottom:0,left:0}}var Zk=k(()=>{});function Dg(r){return Object.assign({},Ag(),r)}var Jk=k(()=>{Zk()});function Ig(r,e){return e.reduce(function(t,n){return t[n]=r,t},{})}var eA=k(()=>{});function _G(r){var e,t=r.state,n=r.name,i=r.options,o=t.elements.arrow,s=t.modifiersData.popperOffsets,a=_n(t.placement),l=hd(a),c=[Fr,Ur].indexOf(a)>=0,u=c?"height":"width";if(!(!o||!s)){var d=SG(i.padding,t),f=md(o),p=l==="y"?xr:Fr,m=l==="y"?cn:Ur,v=t.rects.reference[u]+t.rects.reference[l]-s[l]-t.rects.popper[u],g=s[l]-t.rects.reference[l],y=Os(o),w=y?l==="y"?y.clientHeight||0:y.clientWidth||0:0,T=v/2-g/2,b=d[p],E=w-f[u]-d[m],C=w/2-f[u]/2+T,_=gd(b,C,E),I=l;t.modifiersData[n]=(e={},e[I]=_,e.centerOffset=_-C,e)}}function kG(r){var e=r.state,t=r.options,n=t.element,i=n===void 0?"[data-popper-arrow]":n;i!=null&&(typeof i=="string"&&(i=e.elements.popper.querySelector(i),!i)||_g(e.elements.popper,i)&&(e.elements.arrow=i))}var SG,oR,sR=k(()=>{Dc();lC();Kk();Zp();cC();Xk();Jk();eA();go();SG=function(e,t){return e=typeof e=="function"?e(Object.assign({},t.rects,{placement:t.placement})):e,Dg(typeof e!="number"?e:Ig(e,kc))};oR={name:"arrow",enabled:!0,phase:"main",fn:_G,effect:kG,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]}});function Zo(r){return r.split("-")[1]}var Jp=k(()=>{});function DG(r,e){var t=r.x,n=r.y,i=e.devicePixelRatio||1;return{x:wl(t*i)/i||0,y:wl(n*i)/i||0}}function aR(r){var e,t=r.popper,n=r.popperRect,i=r.placement,o=r.variation,s=r.offsets,a=r.position,l=r.gpuAcceleration,c=r.adaptive,u=r.roundOffsets,d=r.isFixed,f=s.x,p=f===void 0?0:f,m=s.y,v=m===void 0?0:m,g=typeof u=="function"?u({x:p,y:v}):{x:p,y:v};p=g.x,v=g.y;var y=s.hasOwnProperty("x"),w=s.hasOwnProperty("y"),T=Fr,b=xr,E=window;if(c){var C=Os(t),_="clientHeight",I="clientWidth";if(C===pr(t)&&(C=Un(t),Ri(C).position!=="static"&&a==="absolute"&&(_="scrollHeight",I="scrollWidth")),C=C,i===xr||(i===Fr||i===Ur)&&o===pd){b=cn;var q=d&&C===E&&E.visualViewport?E.visualViewport.height:C[_];v-=q-n.height,v*=l?1:-1}if(i===Fr||(i===xr||i===cn)&&o===pd){T=Ur;var B=d&&C===E&&E.visualViewport?E.visualViewport.width:C[I];p-=B-n.width,p*=l?1:-1}}var J=Object.assign({position:a},c&&AG),re=u===!0?DG({x:p,y:v},pr(t)):{x:p,y:v};if(p=re.x,v=re.y,l){var L;return Object.assign({},J,(L={},L[b]=w?"0":"",L[T]=y?"0":"",L.transform=(E.devicePixelRatio||1)<=1?"translate("+p+"px, "+v+"px)":"translate3d("+p+"px, "+v+"px, 0)",L))}return Object.assign({},J,(e={},e[b]=w?v+"px":"",e[T]=y?p+"px":"",e.transform="",e))}function IG(r){var e=r.state,t=r.options,n=t.gpuAcceleration,i=n===void 0?!0:n,o=t.adaptive,s=o===void 0?!0:o,a=t.roundOffsets,l=a===void 0?!0:a,c={placement:_n(e.placement),variation:Zo(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:i,isFixed:e.options.strategy==="fixed"};e.modifiersData.popperOffsets!=null&&(e.styles.popper=Object.assign({},e.styles.popper,aR(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:s,roundOffsets:l})))),e.modifiersData.arrow!=null&&(e.styles.arrow=Object.assign({},e.styles.arrow,aR(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})}var AG,lR,cR=k(()=>{go();Zp();$s();Cl();Xp();Dc();Jp();Ic();AG={top:"auto",right:"auto",bottom:"auto",left:"auto"};lR={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:IG,data:{}}});function FG(r){var e=r.state,t=r.instance,n=r.options,i=n.scroll,o=i===void 0?!0:i,s=n.resize,a=s===void 0?!0:s,l=pr(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach(function(u){u.addEventListener("scroll",t.update,uC)}),a&&l.addEventListener("resize",t.update,uC),function(){o&&c.forEach(function(u){u.removeEventListener("scroll",t.update,uC)}),a&&l.removeEventListener("resize",t.update,uC)}}var uC,uR,dR=k(()=>{$s();uC={passive:!0};uR={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:FG,data:{}}});function ef(r){return r.replace(/left|right|bottom|top/g,function(e){return PG[e]})}var PG,pR=k(()=>{PG={left:"right",right:"left",bottom:"top",top:"bottom"}});function dC(r){return r.replace(/start|end/g,function(e){return $G[e]})}var $G,fR=k(()=>{$G={start:"end",end:"start"}});function vd(r){var e=pr(r),t=e.pageXOffset,n=e.pageYOffset;return{scrollLeft:t,scrollTop:n}}var pC=k(()=>{$s()});function yd(r){return Xo(Un(r)).left+vd(r).scrollLeft}var fC=k(()=>{Qp();Cl();pC()});function tA(r,e){var t=pr(r),n=Un(r),i=t.visualViewport,o=n.clientWidth,s=n.clientHeight,a=0,l=0;if(i){o=i.width,s=i.height;var c=Sg();(c||!c&&e==="fixed")&&(a=i.offsetLeft,l=i.offsetTop)}return{width:o,height:s,x:a+yd(r),y:l}}var mR=k(()=>{$s();Cl();fC();Yk()});function rA(r){var e,t=Un(r),n=vd(r),i=(e=r.ownerDocument)==null?void 0:e.body,o=Ms(t.scrollWidth,t.clientWidth,i?i.scrollWidth:0,i?i.clientWidth:0),s=Ms(t.scrollHeight,t.clientHeight,i?i.scrollHeight:0,i?i.clientHeight:0),a=-n.scrollLeft+yd(r),l=-n.scrollTop;return Ri(i||t).direction==="rtl"&&(a+=Ms(t.clientWidth,i?i.clientWidth:0)-o),{width:o,height:s,x:a,y:l}}var hR=k(()=>{Cl();Xp();fC();pC();Ic()});function bd(r){var e=Ri(r),t=e.overflow,n=e.overflowX,i=e.overflowY;return/auto|scroll|overlay|hidden/.test(t+i+n)}var mC=k(()=>{Xp()});function hC(r){return["html","body","#document"].indexOf(Sn(r))>=0?r.ownerDocument.body:un(r)&&bd(r)?r:hC(El(r))}var gR=k(()=>{kg();mC();Ac();vo()});function Fc(r,e){var t;e===void 0&&(e=[]);var n=hC(r),i=n===((t=r.ownerDocument)==null?void 0:t.body),o=pr(n),s=i?[o].concat(o.visualViewport||[],bd(n)?n:[]):n,a=e.concat(s);return i?a:a.concat(Fc(El(s)))}var nA=k(()=>{gR();kg();$s();mC()});function tf(r){return Object.assign({},r,{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height})}var iA=k(()=>{});function MG(r,e){var t=Xo(r,!1,e==="fixed");return t.top=t.top+r.clientTop,t.left=t.left+r.clientLeft,t.bottom=t.top+r.clientHeight,t.right=t.left+r.clientWidth,t.width=r.clientWidth,t.height=r.clientHeight,t.x=t.left,t.y=t.top,t}function vR(r,e,t){return e===sC?tf(tA(r,t)):Qo(e)?MG(e,t):tf(rA(Un(r)))}function OG(r){var e=Fc(El(r)),t=["absolute","fixed"].indexOf(Ri(r).position)>=0,n=t&&un(r)?Os(r):r;return Qo(n)?e.filter(function(i){return Qo(i)&&_g(i,n)&&Sn(i)!=="body"}):[]}function oA(r,e,t,n){var i=e==="clippingParents"?OG(r):[].concat(e),o=[].concat(i,[t]),s=o[0],a=o.reduce(function(l,c){var u=vR(r,c,n);return l.top=Ms(u.top,l.top),l.right=fd(u.right,l.right),l.bottom=fd(u.bottom,l.bottom),l.left=Ms(u.left,l.left),l},vR(r,s,n));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}var yR=k(()=>{go();mR();hR();nA();Zp();Cl();Xp();vo();Qp();kg();Kk();Ac();iA();Ic()});function Fg(r){var e=r.reference,t=r.element,n=r.placement,i=n?_n(n):null,o=n?Zo(n):null,s=e.x+e.width/2-t.width/2,a=e.y+e.height/2-t.height/2,l;switch(i){case xr:l={x:s,y:e.y-t.height};break;case cn:l={x:s,y:e.y+e.height};break;case Ur:l={x:e.x+e.width,y:a};break;case Fr:l={x:e.x-t.width,y:a};break;default:l={x:e.x,y:e.y}}var c=i?hd(i):null;if(c!=null){var u=c==="y"?"height":"width";switch(o){case bl:l[c]=l[c]-(e[u]/2-t[u]/2);break;case pd:l[c]=l[c]+(e[u]/2-t[u]/2);break;default:}}return l}var sA=k(()=>{Dc();Jp();cC();go()});function Rs(r,e){e===void 0&&(e={});var t=e,n=t.placement,i=n===void 0?r.placement:n,o=t.strategy,s=o===void 0?r.strategy:o,a=t.boundary,l=a===void 0?XO:a,c=t.rootBoundary,u=c===void 0?sC:c,d=t.elementContext,f=d===void 0?Gp:d,p=t.altBoundary,m=p===void 0?!1:p,v=t.padding,g=v===void 0?0:v,y=Dg(typeof g!="number"?g:Ig(g,kc)),w=f===Gp?ZO:Gp,T=r.rects.popper,b=r.elements[m?w:f],E=oA(Qo(b)?b:b.contextElement||Un(r.elements.popper),l,u,s),C=Xo(r.elements.reference),_=Fg({reference:C,element:T,strategy:"absolute",placement:i}),I=tf(Object.assign({},T,_)),q=f===Gp?I:C,B={top:E.top-q.top+y.top,bottom:q.bottom-E.bottom+y.bottom,left:E.left-q.left+y.left,right:q.right-E.right+y.right},J=r.modifiersData.offset;if(f===Gp&&J){var re=J[i];Object.keys(B).forEach(function(L){var W=[Ur,cn].indexOf(L)>=0?1:-1,j=[xr,cn].indexOf(L)>=0?"y":"x";B[L]+=re[j]*W})}return B}var Pg=k(()=>{yR();Cl();Qp();sA();iA();go();vo();Jk();eA()});function aA(r,e){e===void 0&&(e={});var t=e,n=t.placement,i=t.boundary,o=t.rootBoundary,s=t.padding,a=t.flipVariations,l=t.allowedAutoPlacements,c=l===void 0?aC:l,u=Zo(n),d=u?a?jk:jk.filter(function(m){return Zo(m)===u}):kc,f=d.filter(function(m){return c.indexOf(m)>=0});f.length===0&&(f=d);var p=f.reduce(function(m,v){return m[v]=Rs(r,{placement:v,boundary:i,rootBoundary:o,padding:s})[_n(v)],m},{});return Object.keys(p).sort(function(m,v){return p[m]-p[v]})}var bR=k(()=>{Jp();go();Pg();Dc()});function RG(r){if(_n(r)===oC)return[];var e=ef(r);return[dC(r),e,dC(e)]}function LG(r){var e=r.state,t=r.options,n=r.name;if(!e.modifiersData[n]._skip){for(var i=t.mainAxis,o=i===void 0?!0:i,s=t.altAxis,a=s===void 0?!0:s,l=t.fallbackPlacements,c=t.padding,u=t.boundary,d=t.rootBoundary,f=t.altBoundary,p=t.flipVariations,m=p===void 0?!0:p,v=t.allowedAutoPlacements,g=e.options.placement,y=_n(g),w=y===g,T=l||(w||!m?[ef(g)]:RG(g)),b=[g].concat(T).reduce(function(he,Ie){return he.concat(_n(Ie)===oC?aA(e,{placement:Ie,boundary:u,rootBoundary:d,padding:c,flipVariations:m,allowedAutoPlacements:v}):Ie)},[]),E=e.rects.reference,C=e.rects.popper,_=new Map,I=!0,q=b[0],B=0;B<b.length;B++){var J=b[B],re=_n(J),L=Zo(J)===bl,W=[xr,cn].indexOf(re)>=0,j=W?"width":"height",$=Rs(e,{placement:J,boundary:u,rootBoundary:d,altBoundary:f,padding:c}),G=W?L?Ur:Fr:L?cn:xr;E[j]>C[j]&&(G=ef(G));var U=ef(G),H=[];if(o&&H.push($[re]<=0),a&&H.push($[G]<=0,$[U]<=0),H.every(function(he){return he})){q=J,I=!1;break}_.set(J,H)}if(I)for(var Y=m?3:1,ie=function(Ie){var we=b.find(function(Ge){var Pe=_.get(Ge);if(Pe)return Pe.slice(0,Ie).every(function(Ve){return Ve})});if(we)return q=we,"break"},oe=Y;oe>0;oe--){var ce=ie(oe);if(ce==="break")break}e.placement!==q&&(e.modifiersData[n]._skip=!0,e.placement=q,e.reset=!0)}}var wR,CR=k(()=>{pR();Dc();fR();Pg();bR();go();Jp();wR={name:"flip",enabled:!0,phase:"main",fn:LG,requiresIfExists:["offset"],data:{_skip:!1}}});function ER(r,e,t){return t===void 0&&(t={x:0,y:0}),{top:r.top-e.height-t.y,right:r.right-e.width+t.x,bottom:r.bottom-e.height+t.y,left:r.left-e.width-t.x}}function xR(r){return[xr,Ur,cn,Fr].some(function(e){return r[e]>=0})}function NG(r){var e=r.state,t=r.name,n=e.rects.reference,i=e.rects.popper,o=e.modifiersData.preventOverflow,s=Rs(e,{elementContext:"reference"}),a=Rs(e,{altBoundary:!0}),l=ER(s,n),c=ER(a,i,o),u=xR(l),d=xR(c);e.modifiersData[t]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:u,hasPopperEscaped:d},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":d})}var TR,SR=k(()=>{go();Pg();TR={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:NG}});function BG(r,e,t){var n=_n(r),i=[Fr,xr].indexOf(n)>=0?-1:1,o=typeof t=="function"?t(Object.assign({},e,{placement:r})):t,s=o[0],a=o[1];return s=s||0,a=(a||0)*i,[Fr,Ur].indexOf(n)>=0?{x:a,y:s}:{x:s,y:a}}function VG(r){var e=r.state,t=r.options,n=r.name,i=t.offset,o=i===void 0?[0,0]:i,s=aC.reduce(function(u,d){return u[d]=BG(d,e.rects,o),u},{}),a=s[e.placement],l=a.x,c=a.y;e.modifiersData.popperOffsets!=null&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[n]=s}var _R,kR=k(()=>{Dc();go();_R={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:VG}});function qG(r){var e=r.state,t=r.name;e.modifiersData[t]=Fg({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})}var AR,DR=k(()=>{sA();AR={name:"popperOffsets",enabled:!0,phase:"read",fn:qG,data:{}}});function lA(r){return r==="x"?"y":"x"}var IR=k(()=>{});function UG(r){var e=r.state,t=r.options,n=r.name,i=t.mainAxis,o=i===void 0?!0:i,s=t.altAxis,a=s===void 0?!1:s,l=t.boundary,c=t.rootBoundary,u=t.altBoundary,d=t.padding,f=t.tether,p=f===void 0?!0:f,m=t.tetherOffset,v=m===void 0?0:m,g=Rs(e,{boundary:l,rootBoundary:c,padding:d,altBoundary:u}),y=_n(e.placement),w=Zo(e.placement),T=!w,b=hd(y),E=lA(b),C=e.modifiersData.popperOffsets,_=e.rects.reference,I=e.rects.popper,q=typeof v=="function"?v(Object.assign({},e.rects,{placement:e.placement})):v,B=typeof q=="number"?{mainAxis:q,altAxis:q}:Object.assign({mainAxis:0,altAxis:0},q),J=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,re={x:0,y:0};if(C){if(o){var L,W=b==="y"?xr:Fr,j=b==="y"?cn:Ur,$=b==="y"?"height":"width",G=C[b],U=G+g[W],H=G-g[j],Y=p?-I[$]/2:0,ie=w===bl?_[$]:I[$],oe=w===bl?-I[$]:-_[$],ce=e.elements.arrow,he=p&&ce?md(ce):{width:0,height:0},Ie=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:Ag(),we=Ie[W],Ge=Ie[j],Pe=gd(0,_[$],he[$]),Ve=T?_[$]/2-Y-Pe-we-B.mainAxis:ie-Pe-we-B.mainAxis,qe=T?-_[$]/2+Y+Pe+Ge+B.mainAxis:oe+Pe+Ge+B.mainAxis,et=e.elements.arrow&&Os(e.elements.arrow),_t=et?b==="y"?et.clientTop||0:et.clientLeft||0:0,ye=(L=J?.[b])!=null?L:0,$e=G+Ve-ye-_t,ge=G+qe-ye,xe=gd(p?fd(U,$e):U,G,p?Ms(H,ge):H);C[b]=xe,re[b]=xe-G}if(a){var tt,kt=b==="x"?xr:Fr,Pt=b==="x"?cn:Ur,gt=C[E],Lt=E==="y"?"height":"width",Lr=gt+g[kt],lt=gt-g[Pt],rt=[xr,Fr].indexOf(y)!==-1,cr=(tt=J?.[E])!=null?tt:0,ti=rt?Lr:gt-_[Lt]-I[Lt]-cr+B.altAxis,Fo=rt?gt+_[Lt]+I[Lt]-cr-B.altAxis:lt,vn=p&&rt?iR(ti,gt,Fo):gd(p?ti:Lr,gt,p?Fo:lt);C[E]=vn,re[E]=vn-gt}e.modifiersData[n]=re}}var FR,PR=k(()=>{go();Dc();cC();IR();Xk();lC();Zp();Pg();Jp();Zk();Ic();FR={name:"preventOverflow",enabled:!0,phase:"main",fn:UG,requiresIfExists:["offset"]}});var cA=k(()=>{});function uA(r){return{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}}var $R=k(()=>{});function dA(r){return r===pr(r)||!un(r)?vd(r):uA(r)}var MR=k(()=>{pC();$s();vo();$R()});function zG(r){var e=r.getBoundingClientRect(),t=wl(e.width)/r.offsetWidth||1,n=wl(e.height)/r.offsetHeight||1;return t!==1||n!==1}function pA(r,e,t){t===void 0&&(t=!1);var n=un(e),i=un(e)&&zG(e),o=Un(e),s=Xo(r,i,t),a={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(n||!n&&!t)&&((Sn(e)!=="body"||bd(o))&&(a=dA(e)),un(e)?(l=Xo(e,!0),l.x+=e.clientLeft,l.y+=e.clientTop):o&&(l.x=yd(o))),{x:s.left+a.scrollLeft-l.x,y:s.top+a.scrollTop-l.y,width:s.width,height:s.height}}var OR=k(()=>{Qp();MR();Ac();vo();fC();Cl();mC();Ic()});function HG(r){var e=new Map,t=new Set,n=[];r.forEach(function(o){e.set(o.name,o)});function i(o){t.add(o.name);var s=[].concat(o.requires||[],o.requiresIfExists||[]);s.forEach(function(a){if(!t.has(a)){var l=e.get(a);l&&i(l)}}),n.push(o)}return r.forEach(function(o){t.has(o.name)||i(o)}),n}function fA(r){var e=HG(r);return JO.reduce(function(t,n){return t.concat(e.filter(function(i){return i.phase===n}))},[])}var RR=k(()=>{go()});function mA(r){var e;return function(){return e||(e=new Promise(function(t){Promise.resolve().then(function(){e=void 0,t(r())})})),e}}var LR=k(()=>{});function hA(r){var e=r.reduce(function(t,n){var i=t[n.name];return t[n.name]=i?Object.assign({},i,n,{options:Object.assign({},i.options,n.options),data:Object.assign({},i.data,n.data)}):n,t},{});return Object.keys(e).map(function(t){return e[t]})}var NR=k(()=>{});function VR(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return!e.some(function(n){return!(n&&typeof n.getBoundingClientRect=="function")})}function qR(r){r===void 0&&(r={});var e=r,t=e.defaultModifiers,n=t===void 0?[]:t,i=e.defaultOptions,o=i===void 0?BR:i;return function(a,l,c){c===void 0&&(c=o);var u={placement:"bottom",orderedModifiers:[],options:Object.assign({},BR,o),modifiersData:{},elements:{reference:a,popper:l},attributes:{},styles:{}},d=[],f=!1,p={state:u,setOptions:function(y){var w=typeof y=="function"?y(u.options):y;v(),u.options=Object.assign({},o,u.options,w),u.scrollParents={reference:Qo(a)?Fc(a):a.contextElement?Fc(a.contextElement):[],popper:Fc(l)};var T=fA(hA([].concat(n,u.options.modifiers)));return u.orderedModifiers=T.filter(function(b){return b.enabled}),m(),p.update()},forceUpdate:function(){if(!f){var y=u.elements,w=y.reference,T=y.popper;if(VR(w,T)){u.rects={reference:pA(w,Os(T),u.options.strategy==="fixed"),popper:md(T)},u.reset=!1,u.placement=u.options.placement,u.orderedModifiers.forEach(function(B){return u.modifiersData[B.name]=Object.assign({},B.data)});for(var b=0;b<u.orderedModifiers.length;b++){if(u.reset===!0){u.reset=!1,b=-1;continue}var E=u.orderedModifiers[b],C=E.fn,_=E.options,I=_===void 0?{}:_,q=E.name;typeof C=="function"&&(u=C({state:u,options:I,name:q,instance:p})||u)}}}},update:mA(function(){return new Promise(function(g){p.forceUpdate(),g(u)})}),destroy:function(){v(),f=!0}};if(!VR(a,l))return p;p.setOptions(c).then(function(g){!f&&c.onFirstUpdate&&c.onFirstUpdate(g)});function m(){u.orderedModifiers.forEach(function(g){var y=g.name,w=g.options,T=w===void 0?{}:w,b=g.effect;if(typeof b=="function"){var E=b({state:u,name:y,instance:p,options:T}),C=function(){};d.push(E||C)}})}function v(){d.forEach(function(g){return g()}),d=[]}return p}}var BR,UR=k(()=>{OR();lC();nA();Zp();RR();LR();NR();vo();BR={placement:"bottom",modifiers:[],strategy:"absolute"}});var WG,gA,zR=k(()=>{UR();dR();DR();cR();tR();kR();CR();PR();sR();SR();cA();WG=[uR,AR,lR,eR,_R,wR,FR,oR,TR],gA=qR({defaultModifiers:WG})});var HR=k(()=>{go();cA();zR()});function WR(r,e){return jG.test(r[e])}function GG(r){if(!r.includes("![["))return r;let e="",t=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){e+=r.slice(t,n),n=i+2,t=n;continue}}n++}return e+r.slice(t)}function YG(r){if(!r.includes("[["))return r;let e="",t=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){e+=r.slice(t,n)+r.slice(n+2,i),n=i+2,t=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){e+=r.slice(t,n)+r.slice(i+1,o),n=o+2,t=n;continue}}}n++}return e+r.slice(t)}function KG(r){let e=0;if(r.charCodeAt(0)===35){for(;r.charCodeAt(e)===35;)e++;for(;e<r.length&&WR(r,e);)e++}let t=r.length;if(t>e&&r.charCodeAt(t-1)===35){for(;t>e&&r.charCodeAt(t-1)===35;)t--;for(;t>e&&WR(r,t-1);)t--}return r.slice(e,t)}function QG(r){if(!r.includes("[[")&&!r.includes("]]"))return r;let e="",t=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){e+=r.slice(t,n),n+=2,t=n;continue}n++}return e+r.slice(t)}function vA(r){return QG(KG(YG(GG(r)).replace(XG,""))).trim()}var jG,XG,jR=k(()=>{jG=/^\s$/;XG=/[*_`~]/g});function zr(r){return typeof r=="string"?r:r==null?"":String(r)}function gC(r,e){r.scope?.register(["Mod","Shift"],"Enter",()=>(e(),!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 t=r.modalEl;if(t&&typeof t.createDiv=="function"){let i=t.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(),e()})}}function wd(r){let e=!1;return t=>{e||(e=!0,P.logWarning(Ju(t,r)))}}function xl(r){return zr(r)}function fr(r){return r.normalize("NFC").toLowerCase()}function $g(r){return r.toLowerCase().endsWith(".md")?r.slice(0,-3):r}function vC(r,e,t,n,i={}){let o=r.value;r.value=o.slice(0,e)+n+o.slice(t),r.setSelectionRange(e+n.length,e+n.length);let s=new Event("input",{bubbles:!0});i.fromCompletion&&(s.fromCompletion=!0),r.dispatchEvent(s)}function GR(r,e,t){if(r.replaceChildren(),!t){r.textContent=e;return}let n="",i=[],o=[],s=0;for(let d of e){let f=d.toLowerCase(),p=s,m=s+d.length;for(let v=0;v<f.length;v++)i.push(p),o.push(m);n+=f,s=m}let a="";for(let d of t)a+=d.toLowerCase();let l=0,c=0,u=n.indexOf(a,c);for(;u!==-1;){let d=Math.max(l,i[u]),f=o[u+a.length-1];if(f>d){d>l&&r.append(bg(r,e.slice(l,d)));let p=nr(r,"mark");p.className="qa-highlight",p.textContent=e.slice(d,f),r.append(p),l=f}c=u+a.length,u=n.indexOf(a,c)}l<e.length&&r.append(bg(r,e.slice(l)))}var Qi=k(()=>{De();Is();rr();jR()});var yC,ZG,JG,yA,Mg,Hr,Ca=k(()=>{HR();yC=require("obsidian");De();Is();Qi();ZG=(r,e)=>(r%e+e)%e,JG=0,yA=class{constructor(e,t,n,i,o){this.isOpen=!1;this.owner=e,this.containerEl=t,this.optionIdPrefix=i,this.onActiveOptionChange=o,this.clickListener=s=>{let a=this.findSuggestionItem(s.target);a&&this.onSuggestionClick(s,a)},this.mousemoveListener=s=>{let a=this.findSuggestionItem(s.target);a&&this.onSuggestionMouseover(s,a)},t.addEventListener("click",this.clickListener),t.addEventListener("mousemove",this.mousemoveListener),n.register([],"ArrowUp",s=>{if(!s.isComposing&&this.isOpen)return this.setSelectedItem(this.selectedItem-1,!0),!1}),n.register([],"ArrowDown",s=>{if(!s.isComposing&&this.isOpen)return this.setSelectedItem(this.selectedItem+1,!0),!1}),n.register([],"Enter",s=>{if(!s.isComposing&&this.isOpen)return this.useSelectedItem(s),!1}),n.register([],"PageUp",s=>{if(!s.isComposing&&this.isOpen)return this.setSelectedItem(Math.max(0,this.selectedItem-5),!0),!1}),n.register([],"PageDown",s=>{if(!s.isComposing&&this.isOpen)return this.setSelectedItem(Math.min(this.suggestions.length-1,this.selectedItem+5),!0),!1})}findSuggestionItem(e){let t=this.containerEl.ownerDocument.defaultView;if(!t||!(e instanceof t.Element))return null;let n=e.closest(".suggestion-item");return n&&this.containerEl.contains(n)?n:null}onSuggestionClick(e,t){e.preventDefault();let n=this.suggestions.indexOf(t);this.setSelectedItem(n,!1),this.useSelectedItem(e)}onSuggestionMouseover(e,t){let n=this.suggestions.indexOf(t);this.setSelectedItem(n,!1)}setSuggestions(e){this.containerEl.replaceChildren();let t=[];if(e.forEach((n,i)=>{let o=this.containerEl.ownerDocument.createElement("div");o.classList.add("suggestion-item"),this.containerEl.appendChild(o),o.setAttribute("role","option"),o.setAttribute("aria-selected","false"),o.setAttribute("id",`${this.optionIdPrefix}-option-${i}`),this.owner.renderSuggestion(n,o),t.push(o)}),this.values=e,this.suggestions=t,e.length===0){this.isOpen=!1,this.onActiveOptionChange(null);return}this.setSelectedItem(0,!1),this.isOpen=!0}useSelectedItem(e){let t=this.values[this.selectedItem];t&&this.owner.selectSuggestion(t,e)}setSelectedItem(e,t){if(!this.suggestions?.length)return;let n=ZG(e,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,t&&o.scrollIntoView(!1)}close(){this.isOpen=!1,this.onActiveOptionChange(null)}getIsOpen(){return this.isOpen}},Mg=new WeakMap,Hr=class{constructor(e,t){this.popper=null;this.currentRequestId=0;this.isOpen=!1;this.destroyed=!1;this.noResultsTimeout=null;this.currentQuery="";this.renderMatch=GR;let n=this.constructor.name,i=Mg.get(t);i||(i=new Map,Mg.set(t,i));let o=i.get(n);o&&o.destroy(),Mg.set(t,i),i.set(n,this),this.app=e,this.inputEl=t,this.scope=new yC.Scope,this.suggestEl=this.inputEl.ownerDocument.createElement("div"),this.suggestEl.classList.add("suggestion-container");let s=this.inputEl.ownerDocument.createElement("div");s.classList.add("suggestion"),this.suggestEl.appendChild(s),this.listboxId=`qa-suggest-listbox-${++JG}`,s.id=this.listboxId,s.setAttribute("role","listbox"),s.setAttribute("aria-label","Suggestions"),this.suggest=new yA(this,s,this.scope,this.listboxId,a=>this.setActiveDescendant(a)),this.scope.register([],"Escape",this.close.bind(this)),this.debouncedOnInputChanged=(0,yC.debounce)(this.onInputChanged.bind(this),50),this.inputEventListener=a=>this.debouncedOnInputChanged(a),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",a=>{a.preventDefault()}),this.globalClickListener=this.onGlobalClick.bind(this),this.globalWheelListener=this.onGlobalWheel.bind(this),this.globalResizeListener=this.close.bind(this),this.globalBlurListener=this.close.bind(this)}onGlobalClick(e){if(!this.isOpen)return;let t=e.target;!this.suggestEl.contains(t)&&!this.inputEl.contains(t)&&this.close()}onGlobalWheel(e){if(!this.isOpen)return;let t=e.target;this.suggestEl.contains(t)||this.close()}async onInputChanged(e){if(this.destroyed)return;let t=e;if(t?.fromCompletion&&t.keepOpen){let o=this.inputEl.value,s=++this.currentRequestId;this.currentQuery=o;try{let a=await this.getSuggestions(o);s===this.currentRequestId&&(a?.length?(this.suggest.setSuggestions(a),this.isOpen||this.open(this.app.dom.appContainerEl,this.inputEl)):this.close())}catch(a){P.logError(a)}return}if(t?.fromCompletion)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||o.length===0){this.isOpen&&this.showNoResultsAndClose();return}this.suggest.setSuggestions(o),this.open(this.app.dom.appContainerEl,this.inputEl)}catch(o){P.logError(o),this.close()}}showNoResultsAndClose(){this.noResultsTimeout&&sd(this.inputEl).clearTimeout(this.noResultsTimeout),this.close()}open(e,t){if(this.destroyed)return;this.isOpen||this.app.keymap.pushScope(this.scope),this.isOpen=!0,this.inputEl.setAttribute("aria-expanded","true"),this.inputEl.setAttribute("aria-controls",this.listboxId);let n=mo(t);if((mo(e)===n?e:n.body).appendChild(this.suggestEl),this.popper){this.popper.update();return}this.popper=gA(t,this.suggestEl,{placement:"bottom-start",modifiers:[{name:"sameWidth",enabled:!0,fn:({state:l,instance:c})=>{let u=`${l.rects.reference.width}px`;l.styles.popper.width!==u&&(l.styles.popper.width=u,c.update())},phase:"beforeWrite",requires:["computeStyles"]},{name:"flip",enabled:!0},{name:"preventOverflow",enabled:!0},{name:"offset",enabled:!0,options:{offset:[0,4]}}]});let s=n,a=sd(t);s.addEventListener("pointerdown",this.globalClickListener,!0),s.addEventListener("wheel",this.globalWheelListener,!0),a.addEventListener("resize",this.globalResizeListener),a.addEventListener("blur",this.globalBlurListener)}close(){if(!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.popper&&(this.popper.destroy(),this.popper=null),this.suggestEl.remove(),this.noResultsTimeout&&(sd(this.inputEl).clearTimeout(this.noResultsTimeout),this.noResultsTimeout=null);let e=mo(this.inputEl),t=sd(this.inputEl);e.removeEventListener("pointerdown",this.globalClickListener,!0),e.removeEventListener("wheel",this.globalWheelListener,!0),t.removeEventListener("resize",this.globalResizeListener),t.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 e=this.constructor.name,t=Mg.get(this.inputEl);t&&(t.delete(e),t.size===0&&Mg.delete(this.inputEl))}setActiveDescendant(e){if(e){this.inputEl.setAttribute("aria-activedescendant",e);return}this.inputEl.removeAttribute("aria-activedescendant")}getCurrentQuery(){return this.currentQuery}}});function YR(r,e=0){return(zn[r[e+0]]+zn[r[e+1]]+zn[r[e+2]]+zn[r[e+3]]+"-"+zn[r[e+4]]+zn[r[e+5]]+"-"+zn[r[e+6]]+zn[r[e+7]]+"-"+zn[r[e+8]]+zn[r[e+9]]+"-"+zn[r[e+10]]+zn[r[e+11]]+zn[r[e+12]]+zn[r[e+13]]+zn[r[e+14]]+zn[r[e+15]]).toLowerCase()}var zn,KR=k(()=>{zn=[];for(let r=0;r<256;++r)zn.push((r+256).toString(16).slice(1))});function bA(){return crypto.getRandomValues(e4)}var e4,QR=k(()=>{e4=new Uint8Array(16)});function t4(r,e,t){return!e&&!r&&crypto.randomUUID?crypto.randomUUID():r4(r,e,t)}function r4(r,e,t){r=r||{};let n=r.random??r.rng?.()??bA();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[t+i]=n[i];return e}return YR(n)}var ir,XR=k(()=>{QR();KR();ir=t4});var Ea=k(()=>{XR()});function bC(r){return Ne(r)&&r.type==="Multi"}function Ne(r){return typeof r=="object"&&r!==null}function Qe(r){return bC(r)?Array.isArray(r.choices)?r.choices:[]:[]}function Tl(r){return bC(r)&&Array.isArray(r.choices)}function rf(r){if(!Array.isArray(r))return!0;let e=t=>t.some(n=>{if(Array.isArray(n))return!0;if(!Ne(n)||n.type!=="Multi")return!1;let i=n.choices;return Array.isArray(i)?e(i):wC(i)});return e(r)}function Wr(r){return Array.isArray(r)?r:[]}function wC(r){return Array.isArray(r)||r==null?!1:typeof r=="object"?Object.keys(r).length>0:!!r}function Jo(r){return bC(r)?wC(r.choices):!1}function nf(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 Cd(r){return(typeof r.icon=="string"?r.icon.trim():"")||nf(r.type)}function dn(r){let e=[],t=n=>{Ne(n)&&(e.push(n),Qe(n).forEach(t))};return Wr(r).forEach(t),e}function ZR(r){let e=new Map,t=n=>{let i=[];for(let o of n){if(!Ne(o)){i.push(o);continue}let s=o,a=e.get(s.id);if(a){if(JSON.stringify(s)===JSON.stringify(a))continue;s={...s,id:ir()}}e.set(s.id,s),bC(s)&&Array.isArray(s.choices)&&(s={...s,choices:t(s.choices)}),i.push(s)}return i};return t(r)}function JR(r){if(!Array.isArray(r))return{choices:[],changed:!1,repaired:[]};let e=new Set,t=[],n=o=>{let s=!1,a=[];for(let l of o){if(Array.isArray(l)){s=!0,a.push(...n(l));continue}if(!Ne(l)){s=!0;continue}let c=l;if(Tl(c)){let f=c.choices,p=n(f);p!==f&&(c={...c,choices:p},s=!0)}let u=c.id;if(typeof u=="string"&&u!==""&&!e.has(u)){e.add(u),a.push(c);continue}let d={...c,id:ir()};e.add(d.id),t.push({previousId:u,choice:d}),a.push(d),s=!0}return s?a:o},i=n(r);return{choices:i,changed:i!==r,repaired:t}}function Og(r,e=[],t=0,n=null){let i=[];for(let o of Wr(r)){if(!Ne(o))continue;let s=[...e,o.name];i.push({choice:o,id:o.id,path:s,depth:t,parentId:n}),i.push(...Og(Qe(o),s,t+1,o.id))}return i}var It=k(()=>{Ea()});function Pc(r){return Array.isArray?Array.isArray(r):dL(r)==="[object Array]"}function v4(r){if(typeof r=="string")return r;if(typeof r=="bigint")return r.toString();let e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function CA(r){return r==null?"":v4(r)}function fi(r){return typeof r=="string"}function EC(r){return typeof r=="number"}function y4(r){return r===!0||r===!1||b4(r)&&dL(r)=="[object Boolean]"}function uL(r){return typeof r=="object"}function b4(r){return uL(r)&&r!==null}function yo(r){return r!=null}function CC(r){return!r.trim().length}function dL(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}function pL(r){let e=null,t=null,n=null,i=1,o=null;if(fi(r)||Pc(r))n=r,e=iL(r),t=xC(r);else{if(!nL.call(r,"name"))throw new Error(x4("name"));let s=r.name;if(n=s,nL.call(r,"weight")&&r.weight!==void 0&&(i=r.weight,i<=0))throw new Error(T4(xC(s)));e=iL(s),t=xC(s),o=r.getFn??null}return{path:e,id:t,weight:i,src:n,getFn:o}}function iL(r){return Pc(r)?r:r.split(".")}function xC(r){return Pc(r)?r.join("."):r}function k4(r,e){let t=[],n=!1,i=(o,s,a,l)=>{if(yo(o))if(!s[a])t.push(l!==void 0?{v:o,i:l}:o);else{let c=o[s[a]];if(!yo(c))return;if(a===s.length-1&&(fi(c)||EC(c)||y4(c)||typeof c=="bigint"))t.push(l!==void 0?{v:CA(c),i:l}:CA(c));else if(Pc(c)){n=!0;for(let u=0,d=c.length;u<d;u+=1)i(c[u],s,a+1,u)}else s.length&&i(c,s,a+1,l)}};return i(r,fi(e)?e.split("."):e,0),n?t:t[0]}function P4(r){return r>=9&&r<=13||r===32||r===160}function $4(r=1,e=3){let t=new Map,n=Math.pow(10,e);return{get(i){let o=0,s=!1;for(let l=0;l<i.length;l++)P4(i.charCodeAt(l))?s=!1:s||(o++,s=!0);if(o===0&&(o=1),t.has(o))return t.get(o);let a=Math.round(n/Math.pow(o,.5*r))/n;return t.set(o,a),a},clear(){t.clear()}}}function fL(r,e,{getFn:t=je.getFn,fieldNormWeight:n=je.fieldNormWeight}={}){let i=new DA({getFn:t,fieldNormWeight:n});return i.setKeys(r.map(pL)),i.setSources(e),i.create(),i}function M4(r,{getFn:e=je.getFn,fieldNormWeight:t=je.fieldNormWeight}={}){let{keys:n,records:i}=r,o=new DA({getFn:e,fieldNormWeight:t});return o.setKeys(n),o.setIndexRecords(i),o}function O4(r=[],e=je.minMatchCharLength){let t=[],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>=e&&t.push([n,i]),n=-1)}return r[o-1]&&o-n>=e&&t.push([n,o-1]),t}function R4(r,e,t,{location:n=je.location,distance:i=je.distance,threshold:o=je.threshold,findAllMatches:s=je.findAllMatches,minMatchCharLength:a=je.minMatchCharLength,includeMatches:l=je.includeMatches,ignoreLocation:c=je.ignoreLocation}={}){if(e.length>32)throw new Error(E4(32));let u=e.length,d=r.length,f=Math.max(0,Math.min(n,d)),p=o,m=f,v=(q,B)=>{let J=q/u;if(c)return J;let re=Math.abs(f-B);return i?J+re/i:re?1:J},g=a>1||l,y=g?Array(d):[],w;for(;(w=r.indexOf(e,m))>-1;){let q=v(0,w);if(p=Math.min(q,p),m=w+u,g){let B=0;for(;B<u;)y[w+B]=1,B+=1}}m=-1;let T=[],b=1,E=0,C=u+d,_=1<<u-1;for(let q=0;q<u;q+=1){let B=0,J=C;for(;B<J;)v(q,f+J)<=p?B=J:C=J,J=Math.floor((C-B)/2+B);C=J;let re=Math.max(1,f-J+1),L=s?d:Math.min(f+J,d)+u,W=Array(L+2);W[L+1]=(1<<q)-1;for(let j=L;j>=re;j-=1){let $=j-1,G=t[r[$]];if(W[j]=(W[j+1]<<1|1)&G,q&&(W[j]|=(T[j+1]|T[j])<<1|1|T[j+1]),W[j]&_&&(b=v(q,$),b<=p)){if(p=b,m=$,E=q,m<=f)break;re=Math.max(1,2*f-m)}}if(v(q+1,f)>p)break;T=W}if(g&&m>=0){let q=Math.min(d-1,m+u-1+E);for(let B=m;B<=q;B+=1)t[r[B]]&&(y[B]=1)}let I={isMatch:m>=0,score:Math.max(.001,b)};if(g){let q=O4(y,a);q.length?l&&(I.indices=q):I.isMatch=!1}return I}function L4(r){let e={};for(let t=0,n=r.length;t<n;t+=1){let i=r.charAt(t);e[i]=(e[i]||0)|1<<n-t-1}return e}function IA(r){if(r.length<=1)return r;r.sort((t,n)=>t[0]-n[0]||t[1]-n[1]);let e=[r[0]];for(let t=1,n=r.length;t<n;t+=1){let i=e[e.length-1],o=r[t];o[0]<=i[1]+1?i[1]=Math.max(i[1],o[1]):e.push(o)}return e}function V4(r){return r.startsWith("inverse")}function z4(r){let e=[],t=r.length,n=0;for(;n<t;){for(;n<t&&r[n]===" ";)n++;if(n>=t)break;let i=n;for(;i<t&&r[i]!==" "&&r[i]!=='"';)i++;if(i<t&&r[i]==='"'){for(i++;i<t;){if(r[i]==='"'){let o=i+1;if(o>=t||r[o]===" "){i++;break}if(r[o]==="$"&&(o+1>=t||r[o+1]===" ")){i+=2;break}}i++}e.push(r.substring(n,i)),n=i}else{for(;i<t&&r[i]!==" ";)i++;e.push(r.substring(n,i)),n=i}}return e}function sL(r,e){let t=r.match(e);return t?t[1]:null}function H4(r,e={}){return r.replace(/\\\|/g,q4).split(U4).map(t=>{let n=z4(t.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<oL;){let u=xA[c],d=sL(a,u.multiRegex);d&&(i.push(u.create(d,e)),l=!0)}if(!l)for(c=-1;++c<oL;){let u=xA[c],d=sL(a,u.singleRegex);if(d){i.push(u.create(d,e));break}}}return i})}function PA(...r){TA.push(...r)}function TC(r,e){for(let t=0,n=TA.length;t<n;t+=1){let i=TA[t];if(i.condition(r,e))return new i(r,e)}return new FA(r,e)}function hL(r,e,{auto:t=!0}={}){let n=i=>{if(fi(i)){let l={keyId:null,pattern:i};return t&&(l.searcher=TC(i,e)),l}let o=Object.keys(i),s=j4(i);if(!s&&o.length>1&&!_A(i))return n(aL(i));if(G4(i)){let l=s?i[SA.PATH]:o[0],c=s?i[SA.PATTERN]:i[l];if(!fi(c))throw new Error(C4(l));let u={keyId:xC(l),pattern:c};return t&&(u.searcher=TC(c,e)),u}let a={children:[],operator:o[0]};return o.forEach(l=>{let c=i[l];Pc(c)&&c.forEach(u=>{a.children.push(n(u))})}),a};return _A(r)||(r=aL(r)),n(r)}function kA(r,{ignoreFieldNorm:e=je.ignoreFieldNorm}){let t=1;return r.forEach(({key:n,norm:i,score:o})=>{let s=n?n.weight:null;t*=Math.pow(o===0&&s?Number.EPSILON:o,(s||1)*(e?1:i))}),t}function Y4(r,{ignoreFieldNorm:e=je.ignoreFieldNorm}){r.forEach(t=>{t.score=kA(t.matches,{ignoreFieldNorm:e})})}function Q4(r){let e=[];return r.matches.forEach(t=>{if(!yo(t.indices)||!t.indices.length)return;let n={indices:t.indices,value:t.value};t.key&&(n.key=t.key.id),t.idx>-1&&(n.refIndex=t.idx),e.push(n)}),e}function X4(r,e,{includeMatches:t=je.includeMatches,includeScore:n=je.includeScore}={}){return r.map(i=>{let{idx:o}=i,s={item:e[o],refIndex:o};return t&&(s.matches=Q4(i)),n&&(s.score=i.score),s})}function J4(r){lL.has(r)||(lL.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 eY(r){if(typeof r=="function"){let e=!1;return t=>{let n=r(t);if(!e&&(e=!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||J4(r),e=>e.match(r)||[]):e=>e.match(Z4)||[]}function AA({isCaseSensitive:r=!1,ignoreDiacritics:e=!1,tokenize:t}={}){let n=eY(t);return{tokenize(i){return r||(i=i.toLowerCase()),e&&(i=Rg(i)),n(i)}}}function wA(r,e,t,n){let i=n.tokenize(e);if(!i.length)return;r.fieldCount++,r.docFieldCount.set(t,(r.docFieldCount.get(t)||0)+1);let o=new Set(i),s=r.docTermFieldHits.get(t);s||(s=new Map,r.docTermFieldHits.set(t,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 gL(r,e,t,n){let{i,v:o,$:s}=e;if(o!==void 0){wA(r,o,i,n);return}if(s)for(let a=0;a<t;a++){let l=s[a];if(l)if(Array.isArray(l))for(let c of l)wA(r,c.v,i,n);else wA(r,l.v,i,n)}}function rY(r,e,t){let n={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of r)gL(n,i,e,t);return n}function nY(r,e,t,n){gL(r,e,t,n)}function iY(r,e){let t=r.docFieldCount.get(e);if(t===void 0)return;r.fieldCount-=t,r.docFieldCount.delete(e);let n=r.docTermFieldHits.get(e);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(e)}}function cL(r,e){if(e.length===0)return;let t=Array.from(new Set(e)).sort((a,l)=>a-l);for(let a of t)iY(r,a);let n=a=>{let l=0,c=t.length;for(;l<c;){let u=l+c>>>1;t[u]<a?l=u+1:c=u}return a-l},i=t[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 w4,EA,C4,E4,x4,T4,S4,nL,_4,A4,D4,I4,F4,je,DA,mL,N4,Rg,FA,B4,xA,oL,q4,U4,W4,TA,SC,SA,_A,j4,G4,aL,K4,Z4,lL,tY,$c,Mc,_C=k(()=>{w4="Incorrect 'index' type",EA="Invalid doc index: must be a non-negative integer within the bounds of the docs array",C4=r=>`Invalid value for key ${r}`,E4=r=>`Pattern length exceeds max of ${r}.`,x4=r=>`Missing ${r} property in key`,T4=r=>`Property 'weight' in key '${r}' must be a positive integer`,S4="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.",nL=Object.prototype.hasOwnProperty,_4=class{constructor(r){this._keys=[],this._keyMap={};let e=0;r.forEach(t=>{let n=pL(t);this._keys.push(n),this._keyMap[n.id]=n,e+=n.weight}),this._keys.forEach(t=>{t.weight/=e})}get(r){return this._keyMap[r]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};A4={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},D4={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(r,e)=>r.score===e.score?r.idx<e.idx?-1:1:r.score<e.score?-1:1},I4={location:0,threshold:.6,distance:100},F4={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:k4,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},je=Object.freeze({...D4,...A4,...I4,...F4});DA=class{constructor({getFn:r=je.getFn,fieldNormWeight:e=je.fieldNormWeight}={}){this.norm=$4(e,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((e,t)=>{this._keysMap[e.id]=t})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let r=this.docs.length;this.records=new Array(r);let e=0;if(fi(this.docs[0]))for(let t=0;t<r;t++){let n=this._createStringRecord(this.docs[t],t);n&&(this.records[e++]=n)}else for(let t=0;t<r;t++)this.records[e++]=this._createObjectRecord(this.docs[t],t);this.records.length=e,this.norm.clear()}add(r,e){if(!Number.isInteger(e)||e<0)throw new Error(EA);if(fi(r)){let n=this._createStringRecord(r,e);return n&&this.records.push(n),n}let t=this._createObjectRecord(r,e);return this.records.push(t),t}removeAt(r){if(!Number.isInteger(r)||r<0)throw new Error(EA);for(let e=0,t=this.records.length;e<t;e+=1)if(this.records[e].i===r){this.records.splice(e,1);break}for(let e=0,t=this.records.length;e<t;e+=1)this.records[e].i>r&&(this.records[e].i-=1)}removeAll(r){let e=new Set;for(let n of r)Number.isInteger(n)&&n>=0&&e.add(n);if(e.size===0)return;this.records=this.records.filter(n=>!e.has(n.i));let t=Array.from(e).sort((n,i)=>n-i);for(let n of this.records){let i=0,o=t.length;for(;i<o;){let s=i+o>>>1;t[s]<n.i?i=s+1:o=s}n.i-=i}}getValueForItemAtKeyId(r,e){return r[this._keysMap[e]]}size(){return this.records.length}_createStringRecord(r,e){return!yo(r)||CC(r)?null:{v:r,i:e,n:this.norm.get(r)}}_createObjectRecord(r,e){let t={i:e,$:{}};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(yo(s)){if(Pc(s)){let a=[];for(let l=0,c=s.length;l<c;l+=1){let u=s[l];if(yo(u)){if(fi(u)){if(!CC(u)){let d={v:u,i:l,n:this.norm.get(u)};a.push(d)}}else if(yo(u.v)){let d=fi(u.v)?u.v:CA(u.v);if(!CC(d)){let f={v:d,i:u.i,n:this.norm.get(d)};a.push(f)}}}}t.$[n]=a}else if(fi(s)&&!CC(s)){let a={v:s,n:this.norm.get(s)};t.$[n]=a}}}return t}toJSON(){return{keys:this.keys.map(({getFn:r,...e})=>e),records:this.records}}};mL={\u0142:"l",\u0141:"L",\u0111:"d",\u0110:"D",\u00F8:"o",\u00D8:"O",\u0127:"h",\u0126:"H",\u0167:"t",\u0166:"T",\u0131:"i",\u00DF:"ss"},N4=new RegExp("["+Object.keys(mL).join("")+"]","g"),Rg=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(N4,e=>mL[e]):r=>r,FA=class{constructor(r,{location:e=je.location,threshold:t=je.threshold,distance:n=je.distance,includeMatches:i=je.includeMatches,findAllMatches:o=je.findAllMatches,minMatchCharLength:s=je.minMatchCharLength,isCaseSensitive:a=je.isCaseSensitive,ignoreDiacritics:l=je.ignoreDiacritics,ignoreLocation:c=je.ignoreLocation}={}){if(this.options={location:e,threshold:t,distance:n,includeMatches:i,findAllMatches:o,minMatchCharLength:s,isCaseSensitive:a,ignoreDiacritics:l,ignoreLocation:c},r=a?r:r.toLowerCase(),r=l?Rg(r):r,this.pattern=r,this.chunks=[],!this.pattern.length)return;let u=(f,p)=>{this.chunks.push({pattern:f,alphabet:L4(f),startIndex:p})},d=this.pattern.length;if(d>32){let f=0,p=d%32,m=d-p;for(;f<m;)u(this.pattern.substr(f,32),f),f+=32;if(p){let v=d-32;u(this.pattern.substr(v),v)}}else u(this.pattern,0)}searchIn(r){let{isCaseSensitive:e,ignoreDiacritics:t,includeMatches:n}=this.options;if(r=e?r:r.toLowerCase(),r=t?Rg(r):r,this.pattern===r){if(r.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let m={isMatch:!0,score:0};return n&&(m.indices=[[0,r.length-1]]),m}let{location:i,distance:o,threshold:s,findAllMatches:a,minMatchCharLength:l,ignoreLocation:c}=this.options,u=[],d=0,f=!1;this.chunks.forEach(({pattern:m,alphabet:v,startIndex:g})=>{let{isMatch:y,score:w,indices:T}=R4(r,m,v,{location:i+g,distance:o,threshold:s,findAllMatches:a,minMatchCharLength:l,includeMatches:n,ignoreLocation:c});y&&(f=!0),d+=w,y&&T&&u.push(...T)});let p={isMatch:f,score:f?d/this.chunks.length:1};return f&&n&&(p.indices=IA(u)),p}},B4=new Set(["fuzzy","include"]);xA=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:r=>({type:"exact",search(e){let t=e===r;return{isMatch:t,score:t?0:1,indices:[0,r.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:r=>({type:"include",search(e){let t=0,n,i=[],o=r.length;for(;(n=e.indexOf(r,t))>-1;)t=n+o,i.push([n,t-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(e){let t=e.startsWith(r);return{isMatch:t,score:t?0:1,indices:[0,r.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:r=>({type:"inverse-prefix-exact",search(e){let t=!e.startsWith(r);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:r=>({type:"inverse-suffix-exact",search(e){let t=!e.endsWith(r);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:r=>({type:"suffix-exact",search(e){let t=e.endsWith(r);return{isMatch:t,score:t?0:1,indices:[e.length-r.length,e.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:r=>({type:"inverse-exact",search(e){let t=e.indexOf(r)===-1;return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(r,e={})=>{let t=new FA(r,{location:e.location??je.location,threshold:e.threshold??je.threshold,distance:e.distance??je.distance,includeMatches:e.includeMatches??je.includeMatches,findAllMatches:e.findAllMatches??je.findAllMatches,minMatchCharLength:e.minMatchCharLength??je.minMatchCharLength,isCaseSensitive:e.isCaseSensitive??je.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics??je.ignoreDiacritics,ignoreLocation:e.ignoreLocation??je.ignoreLocation});return{type:"fuzzy",search(n){return t.searchIn(n)}}}}],oL=xA.length,q4="\0",U4="|";W4=class{constructor(r,{isCaseSensitive:e=je.isCaseSensitive,ignoreDiacritics:t=je.ignoreDiacritics,includeMatches:n=je.includeMatches,minMatchCharLength:i=je.minMatchCharLength,ignoreLocation:o=je.ignoreLocation,findAllMatches:s=je.findAllMatches,location:a=je.location,threshold:l=je.threshold,distance:c=je.distance}={}){this.query=null,this.options={isCaseSensitive:e,ignoreDiacritics:t,includeMatches:n,minMatchCharLength:i,findAllMatches:s,ignoreLocation:o,location:a,threshold:l,distance:c},r=e?r:r.toLowerCase(),r=t?Rg(r):r,this.pattern=r,this.query=H4(this.pattern,this.options)}static condition(r,e){return e.useExtendedSearch}searchIn(r){let e=this.query;if(!e)return{isMatch:!1,score:1};let{includeMatches:t,isCaseSensitive:n,ignoreDiacritics:i}=this.options;r=n?r:r.toLowerCase(),r=i?Rg(r):r;let o=0,s=[],a=0,l=!1;for(let c=0,u=e.length;c<u;c+=1){let d=e[c];s.length=0,o=0,l=!1;for(let f=0,p=d.length;f<p;f+=1){let m=d[f],{isMatch:v,indices:g,score:y}=m.search(r);if(v)o+=1,a+=y,V4(m.type)&&(l=!0),t&&(B4.has(m.type)?s.push(...g):s.push(g));else{a=0,o=0,s.length=0,l=!1;break}}if(o){let f={isMatch:!0,score:a/o};return l&&(f.hasInverse=!0),t&&(f.indices=IA(s)),f}}return{isMatch:!1,score:1}}},TA=[];SC={AND:"$and",OR:"$or"},SA={PATH:"$path",PATTERN:"$val"},_A=r=>!!(r[SC.AND]||r[SC.OR]),j4=r=>!!r[SA.PATH],G4=r=>!Pc(r)&&uL(r)&&!_A(r),aL=r=>({[SC.AND]:Object.keys(r).map(e=>({[e]:r[e]}))});K4=class{constructor(r,e){this.limit=r,this.heap=[],this.comparator=e}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 e=this.heap;for(;r>0;){let t=r-1>>1;if(this.comparator(e[r],e[t])<=0)break;let n=e[r];e[r]=e[t],e[t]=n,r=t}}_sinkDown(r){let e=this.heap,t=e.length,n=r;do{r=n;let i=2*r+1,o=2*r+2;if(i<t&&this.comparator(e[i],e[n])>0&&(n=i),o<t&&this.comparator(e[o],e[n])>0&&(n=o),n!==r){let s=e[r];e[r]=e[n],e[n]=s}}while(n!==r)}};Z4=/[\p{L}\p{M}\p{N}_]+/gu,lL=new WeakSet;tY=class{static condition(r,e){return e.useTokenSearch}constructor(r,e){this.options=e,this.analyzer=AA({isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,tokenize:e.tokenize});let t=this.analyzer.tokenize(r),{df:n,fieldCount:i}=e._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let o of t){this.termSearchers.push(new FA(o,{location:e.location,threshold:e.threshold,distance:e.distance,includeMatches:e.includeMatches,findAllMatches:e.findAllMatches,minMatchCharLength:e.minMatchCharLength,isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,ignoreLocation:!0}));let s=n.get(o)||0,a=Math.log(1+(i-s+.5)/(s+.5));this.idfWeights.push(a)}this.combineAll=e.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(r){if(!this.termSearchers.length)return{isMatch:!1,score:1};let e=[],t=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 u=this.termSearchers[c].searchIn(r),d=this.idfWeights[c];n+=d,u.isMatch&&(i++,t+=d*(1-u.score),u.indices&&e.push(...u.indices),this.combineAll&&(this.useMask?o|=1<<c:s.add(c)))}if(i===0)return{isMatch:!1,score:1};let a=n>0?1-t/n:0,l={isMatch:!0,score:Math.max(.001,a)};return this.options.includeMatches&&e.length&&(l.indices=IA(e)),this.combineAll&&(this.useMask?l.matchedMask=o:l.matchedTerms=s,l.termCount=this.numTerms),l}};$c=class{constructor(r,e,t){this.options={...je,...e},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new _4(this.options.keys),this._docs=r,this._myIndex=null,this._invertedIndex=null,this.setCollection(r,t),this._lastQuery=null,this._lastSearcher=null}_getSearcher(r){if(this._lastQuery===r)return this._lastSearcher;let e=TC(r,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=r,this._lastSearcher=e,e}setCollection(r,e){if(this._docs=r,e&&!(e instanceof DA))throw new Error(w4);if(this._myIndex=e||fL(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let t=AA({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=rY(this._myIndex.records,this._myIndex.keys.length,t)}this._invalidateSearcherCache()}add(r){if(!yo(r))return;this._docs.push(r);let e=this._myIndex.add(r,this._docs.length-1);if(this._invertedIndex&&e){let t=AA({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});nY(this._invertedIndex,e,this._myIndex.keys.length,t)}this._invalidateSearcherCache()}remove(r=()=>!1){let e=[],t=[];for(let n=0,i=this._docs.length;n<i;n+=1)r(this._docs[n],n)&&(e.push(this._docs[n]),t.push(n));if(t.length){this._invertedIndex&&cL(this._invertedIndex,t);let n=new Set(t);this._docs=this._docs.filter((i,o)=>!n.has(o)),this._myIndex.removeAll(t),this._invalidateSearcherCache()}return e}removeAt(r){if(!Number.isInteger(r)||r<0||r>=this._docs.length)throw new Error(EA);this._invertedIndex&&cL(this._invertedIndex,[r]);let e=this._docs.splice(r,1)[0];return this._myIndex.removeAt(r),this._invalidateSearcherCache(),e}_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,e){let{limit:t=-1}=e||{},{includeMatches:n,includeScore:i,shouldSort:o,sortFn:s,ignoreFieldNorm:a}=this.options;if(fi(r)&&!r.trim()){let f=this._docs.map((p,m)=>({item:p,refIndex:m}));return EC(t)&&t>-1&&(f=f.slice(0,t)),f}let l=o&&EC(t)&&t>0&&fi(r),c=s,u=(f,p)=>c(f,p)||f.idx-p.idx,d;if(l){let f=new K4(t,u);fi(this._docs[0])?this._searchStringList(r,{heap:f,ignoreFieldNorm:a}):this._searchObjectList(r,{heap:f,ignoreFieldNorm:a}),d=f.extractSorted()}else d=fi(r)?fi(this._docs[0])?this._searchStringList(r):this._searchObjectList(r):this._searchLogical(r),Y4(d,{ignoreFieldNorm:a}),o&&d.sort(fi(r)?u:c),EC(t)&&t>-1&&(d=d.slice(0,t));return X4(d,this._docs,{includeMatches:n,includeScore:i})}_searchStringList(r,{heap:e,ignoreFieldNorm:t}={}){let n=this._getSearcher(r),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,s=e?null:[];return o.forEach(({v:a,i:l,n:c})=>{if(!yo(a))return;let u=n.searchIn(a);if(u.isMatch){let d={score:u.score,value:a,norm:c,indices:u.indices};i&&(d.matchedMask=u.matchedMask,d.matchedTerms=u.matchedTerms,d.termCount=u.termCount);let f=[d];if(!i||this._coversAllTokens(f)){let p={item:a,idx:l,matches:f};e?(p.score=kA(p.matches,{ignoreFieldNorm:t}),e.insert(p)):s.push(p)}}}),s}_searchLogical(r){let e=hL(r,this.options),t=this._normalizedKeys(),n=(a,l,c)=>{if(!("children"in a)){let{keyId:p,searcher:m}=a,v;return p===null?(v=[],t.forEach((g,y)=>{v.push(...this._findMatches({key:g,value:l[y],searcher:m}))})):v=this._findMatches({key:this._keyStore.get(p),value:this._myIndex.getValueForItemAtKeyId(l,p),searcher:m}),v&&v.length?[{idx:c,item:l,matches:v}]:[]}let{children:u,operator:d}=a,f=[];for(let p=0,m=u.length;p<m;p+=1){let v=u[p],g=n(v,l,c);if(g.length)f.push(...g);else if(d===SC.AND)return[]}return f},i=this._myIndex.records,o=new Map,s=[];return i.forEach(({$:a,i:l})=>{if(yo(a)){let c=n(e,a,l);c.length&&(o.has(l)||(o.set(l,{idx:l,item:a,matches:[]}),s.push(o.get(l))),c.forEach(({matches:u})=>{o.get(l).matches.push(...u)}))}}),s}_searchObjectList(r,{heap:e,ignoreFieldNorm:t}={}){let n=this._getSearcher(r),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,s=this._normalizedKeys(),a=e?null:[];return o.forEach(({$:l,i:c})=>{if(!yo(l))return;let u=[],d=!1,f=!1;if(s.forEach((p,m)=>{let v=this._findMatches({key:p,value:l[m],searcher:n});v.length?(u.push(...v),v[0].hasInverse&&(f=!0)):d=!0}),!(f&&d)&&u.length&&(!i||this._coversAllTokens(u))){let p={idx:c,item:l,matches:u};e?(p.score=kA(p.matches,{ignoreFieldNorm:t}),e.insert(p)):a.push(p)}}),a}_findMatches({key:r,value:e,searcher:t}){if(!yo(e))return[];let n=[];if(Pc(e))e.forEach(({v:i,i:o,n:s})=>{if(!yo(i))return;let a=t.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}=e,s=t.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 e=r.length?r[0].termCount:void 0;if(e===void 0)return!0;if(e<=31){let n=0;for(let i=0;i<r.length;i++)n|=r[i].matchedMask||0;return n===2**e-1}let t=new Set;for(let n=0;n<r.length;n++){let i=r[n].matchedTerms;if(i)for(let o of i)t.add(o)}return t.size===e}};$c.version="7.5.0";$c.createIndex=fL;$c.parseIndex=M4;$c.config=je;$c.match=function(r,e,t){if(t&&t.useTokenSearch)throw new Error(S4);return TC(r,{...je,...t}).searchIn(e)};$c.parseQuery=hL;PA(W4);PA(tY);$c.use=function(...r){r.forEach(e=>PA(e))};Mc=$c});var Lg,$A,oY,sY,vL,yL,of,MA=k(()=>{Lg=require("obsidian");_C();Qi();$A=class{constructor(e=100){this.cache=new Map;this.maxSize=e}peek(e){return this.cache.get(e)}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear()}},oY=20,sY=100,vL=/\w/,yL={base:{basenameExact:-1e3,aliasExact:-900,basenamePrefix:-500,aliasPrefix:-500,substringBasename:-300,fuzzyMatch:0,unresolvedLink:1e3},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}},of=class r{constructor(e,t){this.fileMap=new Map;this.recentFiles=new $A;this.unresolvedLinks=new Set;this.unresolvedLinksDirty=!0;this.isIndexing=!1;this.indexPromise=null;this.reindexTimeout=null;this.fuseUpdateTimeout=null;this.pendingFuseUpdates=new Map;this.reindexBuffer=null;this.effectiveWeights=yL;this.app=e,this.plugin=t;let n={keys:[{name:"basenameNormalized",weight:.8},{name:"aliasesNormalized",weight:.6},{name:"pathNormalized",weight:.2}],ignoreLocation:!0,findAllMatches:!0,shouldSort:!1,includeMatches:!0};this.fuseStrict=new Mc([],{...n,threshold:.2}),this.fuseRelaxed=new Mc([],{...n,threshold:.4}),this.setupEventListeners(),this.effectiveWeights=yL}static getInstance(e,t){return r.instance||(r.instance=new r(e,t)),r.instance}static getInstanceIfExists(){return r.instance??void 0}getLastOpenedAt(e){return this.recentFiles.peek(e)}setupEventListeners(){this.plugin.registerEvent(this.app.workspace.on("file-open",e=>{if(e){this.recentFiles.set(e.path,Date.now());let t=this.fileMap.get(e.path);t&&(t.openedAt=Date.now())}})),this.plugin.registerEvent(this.app.metadataCache.on("changed",e=>{e instanceof Lg.TFile&&e.extension==="md"&&this.updateFile(e)})),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",e=>{e instanceof Lg.TFile&&e.extension==="md"&&this.addFile(e)})),this.plugin.registerEvent(this.app.vault.on("delete",e=>{e instanceof Lg.TFile&&this.removeFile(e)})),this.plugin.registerEvent(this.app.vault.on("rename",(e,t)=>{e instanceof Lg.TFile&&e.extension==="md"&&(this.removeFileByPath(t),this.addFile(e))}))}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 e=new Map;this.reindexBuffer=e;try{let t=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 u=this.createIndexedFile(c);n.set(c.path,u)}await new Promise(c=>window.setTimeout(c,0))}})(t),this.fileMap=n;for(let[o,s]of e)s.op==="remove"?this.fileMap.delete(o):s.file&&this.fileMap.set(o,this.createIndexedFile(s.file));this.updateFuseIndex(),this.updateUnresolvedLinks()}catch(t){try{this.updateFuseIndex()}catch{}throw t}finally{this.reindexBuffer=null}}extractAliases(e){if(!e)return[];let t=[];for(let[n,i]of Object.entries(e)){let o=n.toLowerCase();if(!(o!=="alias"&&o!=="aliases"))if(typeof i=="string"){let s=i.split(",").map(a=>a.trim()).filter(a=>a.length>0);t.push(...s)}else Array.isArray(i)&&t.push(...i.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0))}return t}createIndexedFile(e){let t=this.app.metadataCache.getFileCache(e),n=t?.frontmatter,i=this.extractAliases(n),o=i.map(c=>fr(c)),s=(t?.headings??[]).map(c=>vA(c.heading)),a=[];if(t?.blocks)for(let c of Object.values(t.blocks))c.id&&a.push(c.id);let l=t?.tags?.map(c=>c.tag)??[];if(n?.tags){let c=Array.isArray(n.tags)?n.tags:[n.tags];l.push(...c.filter(u=>typeof u=="string"))}return{path:e.path,pathNormalized:fr(e.path),basename:e.basename,basenameNormalized:fr(e.basename),aliases:i,aliasesNormalized:o,headings:s,blockIds:a,tags:l,modified:e.stat.mtime,openedAt:this.recentFiles.peek(e.path),folder:e.parent?.path??""}}addFile(e){let t=this.createIndexedFile(e);this.fileMap.set(e.path,t),this.scheduleFuseUpdate(e.path,"add"),this.reindexBuffer?.set(e.path,{op:"upsert",file:e})}updateFile(e){let t=this.createIndexedFile(e);this.fileMap.set(e.path,t),this.scheduleFuseUpdate(e.path,"update"),this.unresolvedLinksDirty=!0,this.reindexBuffer?.set(e.path,{op:"upsert",file:e})}removeFile(e){this.removeFileByPath(e.path)}removeFileByPath(e){this.fileMap.delete(e),this.scheduleFuseUpdate(e,"remove"),this.reindexBuffer?.set(e,{op:"remove"})}updateFuseIndex(){let e=Array.from(this.fileMap.values());this.fuseStrict.setCollection(e),this.fuseRelaxed.setCollection(e)}scheduleFuseUpdate(e,t){if(this.isIndexing)return;let n=this.pendingFuseUpdates.get(e);if(n)if(n==="add"&&t==="remove"){this.pendingFuseUpdates.delete(e);return}else n==="remove"&&t==="add"?this.pendingFuseUpdates.set(e,"update"):this.pendingFuseUpdates.set(e,t);else this.pendingFuseUpdates.set(e,t);this.fuseUpdateTimeout!==null&&window.clearTimeout(this.fuseUpdateTimeout),this.fuseUpdateTimeout=window.setTimeout(()=>{this.processPendingFuseUpdates()},sY)}processPendingFuseUpdates(){if(this.pendingFuseUpdates.size!==0){if(this.isIndexing){this.pendingFuseUpdates.clear();return}if(this.pendingFuseUpdates.size>oY){this.updateFuseIndex(),this.pendingFuseUpdates.clear();return}for(let[e,t]of this.pendingFuseUpdates)switch(t){case"add":{this.fuseStrict.remove(i=>i.path===e),this.fuseRelaxed.remove(i=>i.path===e);let n=this.fileMap.get(e);n&&(this.fuseStrict.add(n),this.fuseRelaxed.add(n));break}case"update":{this.fuseStrict.remove(i=>i.path===e),this.fuseRelaxed.remove(i=>i.path===e);let n=this.fileMap.get(e);n&&(this.fuseStrict.add(n),this.fuseRelaxed.add(n));break}case"remove":{this.fuseStrict.remove(n=>n.path===e),this.fuseRelaxed.remove(n=>n.path===e);break}}this.pendingFuseUpdates.clear()}}updateUnresolvedLinks(){let e=this.app.metadataCache.unresolvedLinks;this.unresolvedLinks.clear();for(let t in e)for(let n in e[t])this.unresolvedLinks.add(n);this.unresolvedLinksDirty=!1}search(e,t={},n=50){this.unresolvedLinksDirty&&this.updateUnresolvedLinks();let i=[],o=fr(e);if(e.includes("#"))return this.searchWithHeadings(e,t,n);let s=new Set,a=Array.from(this.fileMap.values());for(let c of a)c.basenameNormalized===o&&(i.push({file:c,score:this.calculateScore(c,e,t,this.effectiveWeights.base.basenameExact,"exact"),matchType:"exact",displayText:c.basename}),s.add(c.path));for(let c of a){if(s.has(c.path))continue;let u=c.aliasesNormalized.indexOf(o);u!==-1&&(i.push({file:c,score:this.calculateScore(c,e,t,this.effectiveWeights.base.aliasExact,"alias"),matchType:"alias",displayText:c.aliases[u]}),s.add(c.path))}for(let c of a)c.basenameNormalized.startsWith(o)&&c.basenameNormalized!==o&&!s.has(c.path)&&(i.push({file:c,score:this.calculateScore(c,e,t,this.effectiveWeights.base.basenamePrefix,"fuzzy"),matchType:"fuzzy",displayText:c.basename}),s.add(c.path));for(let c of a)for(let[u,d]of c.aliasesNormalized.entries())d.startsWith(o)&&d!==o&&!s.has(c.path)&&(i.push({file:c,score:this.calculateScore(c,e,t,this.effectiveWeights.base.aliasPrefix,"alias"),matchType:"alias",displayText:c.aliases[u]}),s.add(c.path));for(let c of a){if(s.has(c.path))continue;let u=c.basenameNormalized.indexOf(o);if(u>0){let d=c.basenameNormalized[u-1];vL.test(d)||(i.push({file:c,score:this.calculateScore(c,e,t,this.effectiveWeights.base.substringBasename,"fuzzy"),matchType:"fuzzy",displayText:c.basename}),s.add(c.path))}}let l=this.fuseStrict.search(o,{limit:n*2});l.length<this.effectiveWeights.thresholds.fuzzyRelaxCount&&(l=this.fuseRelaxed.search(o,{limit:n*2}));for(let c of l){if(!c||!c.item||!c.item.path||s.has(c.item.path))continue;let u=(c.matches??[]).find(m=>m.key==="aliasesNormalized"),d=!!u,f=d?"alias":"fuzzy",p=c.item.basename;if(d){let m=typeof u?.value=="string"?u.value:void 0,v=m?c.item.aliasesNormalized.findIndex(g=>g===m):c.item.aliasesNormalized.findIndex(g=>g.includes(o));v>=0&&(p=c.item.aliases[v])}i.push({file:c.item,score:this.calculateScore(c.item,e,t,(c.score??.5)+this.effectiveWeights.base.fuzzyMatch,f),matchType:f,displayText:p}),s.add(c.item.path)}if(e.length>=2){let c=0,u=e.length<3?10:20;for(let d of this.unresolvedLinks){if(c>=u)break;fr(d).includes(o)&&(i.push({file:{path:d,pathNormalized:fr(d),basename:d,basenameNormalized:fr(d),aliases:[],aliasesNormalized:[],headings:[],blockIds:[],tags:[],modified:0,folder:""},score:this.effectiveWeights.base.unresolvedLink,matchType:"unresolved",displayText:d}),c++)}}return i.sort((c,u)=>c.score-u.score).slice(0,n)}calculateScore(e,t,n,i,o){let s=i;if(n.currentFolder&&e.folder===n.currentFolder&&(s+=this.effectiveWeights.boosts.sameFolder),e.openedAt&&(Date.now()-e.openedAt)/864e5<this.effectiveWeights.thresholds.recencyDays&&(s+=this.effectiveWeights.boosts.recency),n.currentFile){let d=this.fileMap.get(n.currentFile.path);if(d){let f=e.tags.filter(p=>d.tags.includes(p));f.length>0&&(s+=this.effectiveWeights.boosts.tagOverlap*Math.min(f.length,Math.abs(this.effectiveWeights.boosts.tagOverlapMax/this.effectiveWeights.boosts.tagOverlap)))}}let a=fr(t),l=e.basename.length;if(o==="alias"&&e.aliases.length>0){let d=e.aliasesNormalized.findIndex(f=>f.includes(a));d>=0&&(l=e.aliases[d].length)}if(o==="alias"){let d=Math.max(0,(l-this.effectiveWeights.penalties.titleLengthThreshold)*this.effectiveWeights.penalties.aliasLengthMultiplier),f=Math.min(this.effectiveWeights.penalties.aliasMaxPenalty,this.effectiveWeights.penalties.aliasMinPenalty+d);s+=f}l>this.effectiveWeights.penalties.titleLengthThreshold&&(s+=(l-this.effectiveWeights.penalties.titleLengthThreshold)*this.effectiveWeights.penalties.titleLengthMultiplier);let c=e.basenameNormalized;if(o==="alias"&&e.aliases.length>0){let d=e.aliasesNormalized.findIndex(f=>f.includes(a));d>=0&&(c=e.aliasesNormalized[d])}let u=c.indexOf(a);return u>=0&&(s+=u*this.effectiveWeights.penalties.positionMultiplier),s}searchWithHeadings(e,t,n){let[i,o]=e.split("#"),s=fr(o??""),a=[];if(i===""){let l=0,c=200,u=Array.from(this.fileMap.values());for(let d of u){if(l>=c)break;for(let f of d.headings){if(l>=c)break;fr(f).includes(s)&&(a.push({file:d,score:this.calculateScore(d,e,t,.1),matchType:"heading",displayText:`${d.basename}#${f}`}),l++)}}}else{let l=this.searchFiles(i,t,n);if(l.length===0)return[];for(let c of l)for(let u of c.file.headings)fr(u).includes(s)&&a.push({file:c.file,score:c.score+.05,matchType:"heading",displayText:`${c.file.basename}#${u}`})}return a.sort((l,c)=>l.score-c.score).slice(0,n)}searchFiles(e,t,n){let i=[],o=fr(e),s=new Set,a=Array.from(this.fileMap.values());for(let c of a)c.basenameNormalized===o&&(i.push({file:c,score:this.calculateScore(c,e,t,-1e3,"exact"),matchType:"exact",displayText:c.basename}),s.add(c.path));for(let c of a){if(s.has(c.path))continue;let u=c.aliasesNormalized.indexOf(o);u!==-1&&(i.push({file:c,score:this.calculateScore(c,e,t,this.effectiveWeights.base.aliasExact,"alias"),matchType:"alias",displayText:c.aliases[u]}),s.add(c.path))}for(let c of a)c.basenameNormalized.startsWith(o)&&c.basenameNormalized!==o&&!s.has(c.path)&&(i.push({file:c,score:this.calculateScore(c,e,t,-500,"fuzzy"),matchType:"fuzzy",displayText:c.basename}),s.add(c.path));for(let c of a)for(let[u,d]of c.aliasesNormalized.entries())d.startsWith(o)&&d!==o&&!s.has(c.path)&&(i.push({file:c,score:this.calculateScore(c,e,t,-500,"alias"),matchType:"alias",displayText:c.aliases[u]}),s.add(c.path));for(let c of a){if(s.has(c.path))continue;let u=c.basenameNormalized.indexOf(o);if(u>0){let d=c.basenameNormalized[u-1];vL.test(d)||(i.push({file:c,score:this.calculateScore(c,e,t,-300,"fuzzy"),matchType:"fuzzy",displayText:c.basename}),s.add(c.path))}}let l=this.fuseStrict.search(o,{limit:n*2});l.length<this.effectiveWeights.thresholds.fuzzyRelaxCount&&(l=this.fuseRelaxed.search(o,{limit:n*2}));for(let c of l){if(!c||!c.item||!c.item.path||s.has(c.item.path))continue;let u=(c.matches??[]).find(m=>m.key==="aliasesNormalized"),d=!!u,f=d?"alias":"fuzzy",p=c.item.basename;if(d){let m=typeof u?.value=="string"?u.value:void 0,v=m?c.item.aliasesNormalized.findIndex(g=>g===m):c.item.aliasesNormalized.findIndex(g=>g.includes(o));v>=0&&(p=c.item.aliases[v])}i.push({file:c.item,score:this.calculateScore(c.item,e,t,(c.score??.5)+this.effectiveWeights.base.fuzzyMatch,f),matchType:f,displayText:p}),s.add(c.item.path)}return i.sort((c,u)=>c.score-u.score).slice(0,n)}getFile(e){return this.fileMap.get(e)}getHeadings(e){return e.headings}getBlockIds(e){return e.blockIds}getIndexedFileCount(){return this.fileMap.size}}});function bL(r){OA=r}function kn(){if(!OA)throw new Error("QuickAdd plugin instance accessed before it was initialised.");return OA}var OA,xa=k(()=>{});function aY(r,e){let t=nr(r,"span");switch(t.classList.add("qa-suggestion-pill"),e){case"alias":return t.classList.add("qa-alias-pill"),t.textContent="alias",t;case"heading":return t.classList.add("qa-heading-pill"),t.textContent="H",t;case"block":return t.classList.add("qa-block-pill"),t.textContent="^",t;case"unresolved":return t.classList.add("qa-unresolved-pill"),t.textContent="unresolved",t;default:return null}}var kC,Oc,AC=k(()=>{Ca();kC=require("obsidian");Je();MA();Qi();xa();Is();Oc=class extends Hr{constructor(t,n,i){super(t,n);this.app=t;this.inputEl=n;this.lastInput="";this.sourcePathOverride=i?.sourcePath,this.fileIndex=of.getInstance(t,kn()),this.fileIndex.ensureIndexed()}normalizeFolderPath(t){return!t||t==="/"?"":t.replace(/\/+$/,"")}getSourcePath(){return this.sourcePathOverride??this.app.workspace.getActiveFile()?.path??""}getSourceFolder(){let t=this.getSourcePath();if(!t)return"";let n=this.app.fileManager.getNewFileParent(t);return this.normalizeFolderPath(n?.path)}resolveRelative(t,n){let i=this.normalizeFolderPath(t),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(t){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=t.slice(0,n),o=jM.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(),u=this.app.workspace.getActiveFile(),d={currentFile:this.sourcePathOverride?void 0:u??void 0,currentFolder:c};return this.fileIndex.search(s,d,50)}getHeadingSuggestions(t){let[n,i]=t.split("#"),o=n.trim()==="",s=fr(i??""),a=[];if(o){let c=this.app.workspace.getActiveFile();if(c){let u=this.fileIndex.getFile(c.path);u&&(a=[u])}}else a=this.fileIndex.search(n,{},1).map(c=>c.file);if(a.length===0)return[];let l=[];for(let c of a){let d=this.fileIndex.getHeadings(c).filter(f=>i===""||fr(f).includes(s)).slice(0,20);for(let f of d)l.push({file:c,score:0,matchType:"heading",displayText:o?`#${f}`:`${c.basename}#${f}`})}return l}getBlockSuggestions(t){let[n,i]=t.split("#^"),o=fr(i??""),s=this.fileIndex.search(n,{},1);if(s.length===0)return[];let a=s[0].file;return this.fileIndex.getBlockIds(a).filter(c=>i===""||fr(c).includes(o)).slice(0,20).map(c=>({file:a,score:0,matchType:"block",displayText:`${a.basename}#^${c}`}))}getRelativePathSuggestions(t){let n=this.getSourceFolder(),{folder:i,query:o}=this.resolveRelative(n,t);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(t){let n=this.app.vault.getFiles(),i=["png","jpg","jpeg","gif","svg","pdf","mp4","webm","mov","canvas"],o=fr(t);return n.filter(a=>i.includes(a.extension.toLowerCase())&&(t===""||fr(a.basename).includes(o))).slice(0,20).map(a=>({file:{path:a.path,pathNormalized:fr(a.path),basename:a.basename,basenameNormalized:fr(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(t,n){let{file:i,matchType:o,displayText:s}=t;n.classList.add("qaFileSuggestionItem"),n.classList.add(`qa-suggest-${o}`);let a=s,l="",c=!1,u="";switch(o){case"exact":a=i.basename,l=i.path;break;case"alias":a=s,l=i.path;break;case"fuzzy":a=i.basename,l=i.path;break;case"heading":{let[v,g]=s.split("#"),y=this.lastInput.includes("#")?this.lastInput.split("#")[1]:"",w=fr(y??"");y&&fr(g).includes(w)?(a=g,c=!0,u=y):a=g,l=v;break}case"block":{let[v,g]=s.split("#^");a=g,l=v;break}case"unresolved":a=s,l="Unresolved link";break}let d=nr(n,"div");d.className="qa-suggestion-content";let f=nr(n,"span");f.className="suggestion-main-text",c?this.renderMatch(f,a,u):f.textContent=a,d.appendChild(f);let p=aY(n,o);p&&d.appendChild(p);let m=nr(n,"span");m.className="suggestion-sub-text",m.textContent=l,n.replaceChildren(d,m),this.addHoverTooltip(n,i)}open(t,n){if(super.open(t,n),!this.scrollListener){let i=mo(this.inputEl),o=()=>this.hideTooltip();i.addEventListener("scroll",o,{passive:!0}),this.scrollListener=o,this.scrollListenerDocument=i}}hideTooltip(){let t=mo(this.inputEl);this.tooltipTimeout!==void 0&&(window.clearTimeout(this.tooltipTimeout),this.tooltipTimeout=void 0),t.querySelector(".qa-file-tooltip")?.remove()}addHoverTooltip(t,n){let i=mo(t);t.addEventListener("mouseenter",()=>{this.hideTooltip(),this.tooltipTimeout=window.setTimeout(()=>{let o=this.createTooltip(n);o&&(i.body.appendChild(o),this.positionTooltip(o,t))},200)}),t.addEventListener("mouseleave",()=>this.hideTooltip()),t.addEventListener("blur",()=>this.hideTooltip())}createTooltip(t){let n=this.app.vault.getAbstractFileByPath(t.path);if(!n||!(n instanceof kC.TFile))return null;let i=this.inputEl,o=nr(i,"div");o.className="qa-file-tooltip";let s=nr(i,"div");s.className="qa-tooltip-header",s.textContent=n.basename;let a=nr(i,"div");a.className="qa-tooltip-content";let l=nr(i,"div");l.textContent=`Path: ${n.path}`;let c=nr(i,"div");return c.textContent=`Modified: ${new Date(n.stat.mtime).toLocaleDateString()}`,a.append(l,c),o.append(s,a),o}positionTooltip(t,n){let i=n.getBoundingClientRect();t.style.left=`${i.right+10}px`,t.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(t){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.lastInput.length,o=this.inputEl.value,s=0,a=this.inputEl.value.slice(n-this.lastInput.length-3,n-this.lastInput.length)==="![[";if(t.matchType==="unresolved")s=this.makeLinkManually(o,t.displayText.replace(/.md$/,""),n,i);else if(t.matchType==="heading"||t.matchType==="block"){let l=t.displayText;s=this.makeLinkManually(o,l,n,i)}else if(a)s=this.makeLinkManually(o,t.displayText,n,i);else{let l=this.app.vault.getAbstractFileByPath(t.file.path);if(l instanceof kC.TFile){let c=t.matchType==="alias"?t.displayText:void 0;s=this.makeLinkObsidianMethod(l,o,n,i,c)}else s=this.makeLinkManually(o,t.displayText,n,i)}this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(s,s)}makeLinkObsidianMethod(t,n,i,o,s){let a=this.app.vault.getAbstractFileByPath(t.path);if(!(a instanceof kC.TFile))return this.makeLinkManually(n,t.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(t,n,i,o){return this.inputEl.value=this.getNewInputValueForFileName(t,n,i,o),i-o+n.length+2}getNewInputValueForFileLink(t,n,i,o){return`${t.slice(0,i-o-2)}${n}${t.slice(i)}`}getNewInputValueForFileName(t,n,i,o){return`${t.slice(0,i-o)}${n}]]${t.slice(i)}`}}});var wL,DC,CL=k(()=>{_C();wL={threshold:.4,includeScore:!0,keys:[""]},DC=class r{constructor(e,t){this.sortedTags=[];this.fuse=new Mc([],wL);this.app=e,this.refresh(),t.registerEvent(this.app.metadataCache.on("resolved",()=>this.refresh()))}static getInstance(e,t){return r.instance||(r.instance=new r(e,t)),r.instance}refresh(){let e=this.app.metadataCache.getTags(),t=Object.keys(e);this.sortedTags=t.sort((n,i)=>n.length!==i.length?n.length-i.length:n.localeCompare(i)),this.fuse=new Mc(this.sortedTags,wL)}getSortedTags(){return this.sortedTags}search(e){return this.fuse.search(e)}}});function lY(r,e){let t=r.slice(0,e),n=t.lastIndexOf("[[");return n===-1?!1:t.lastIndexOf("]]")<n}var Rc,IC=k(()=>{Je();Ca();Qi();xa();CL();Rc=class extends Hr{constructor(t,n,i){super(t,n);this.app=t;this.inputEl=n;this.lastInput="";this.lastInputStart=0;this.lastInputLength=0;this.tagIndex=DC.getInstance(t,kn()),i?.refreshIndex!==!1&&this.tagIndex.refresh()}getSuggestions(t){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=t.slice(0,n),o=GM.exec(i);if(!o)return[];if(o.index===void 0)return[];if(lY(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(p=>p.replace(/^#/,"").toLowerCase().startsWith(l)).slice(0,5),u=this.tagIndex.search(s).filter(p=>p.score!==void 0&&p.score<.8).map(p=>p.item).slice(0,10),d=new Set(c),f=[...c];for(let p of u)!d.has(p)&&f.length<15&&(f.push(p),d.add(p));return f}renderSuggestion(t,n){this.renderMatch(n,t,this.lastInput)}selectSuggestion(t){let n=this.inputEl;if(n.selectionStart===null)return;let i=this.lastInputStart,o=i+this.lastInputLength,s=t.startsWith("#")?t:`#${t}`;vC(n,i,o,s,{fromCompletion:!0}),this.close()}}});var mi,sf=k(()=>{mi=class r{constructor(){this.drafts=new Map;this.pendingSubmittedDraftKeys=new Set;this.executionScopeDepth=0;this.executionScopeFailed=!1;this.MAX_ENTRIES=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}makeKey(e){return JSON.stringify({v:1,kind:e.kind,header:e.header,placeholder:e.placeholder??"",linkSourcePath:e.linkSourcePath??"",scopeId:e.scopeId??""})}get(e){let t=this.drafts.get(e);if(t)return t.timestamp=Date.now(),t.value}set(e,t){this.drafts.size>=this.MAX_ENTRIES&&!this.drafts.has(e)&&this.evictOldest(1),this.drafts.set(e,{value:t,timestamp:Date.now()})}handleSubmittedDraft(e,t){if(!this.hasActiveExecutionScope()){this.clear(e);return}this.set(e,t),this.pendingSubmittedDraftKeys.add(e)}beginExecutionScope(){this.executionScopeDepth+=1}commitExecutionScope(){if(this.hasActiveExecutionScope()&&(this.executionScopeDepth-=1,!(this.executionScopeDepth>0))){if(!this.executionScopeFailed)for(let e of this.pendingSubmittedDraftKeys)this.clear(e);this.resetExecutionScope()}}rollbackExecutionScope(){this.hasActiveExecutionScope()&&(this.executionScopeFailed=!0,this.executionScopeDepth-=1,this.executionScopeDepth===0&&this.resetExecutionScope())}markExecutionScopeFailed(){this.hasActiveExecutionScope()&&(this.executionScopeFailed=!0)}hasActiveExecutionScope(){return this.executionScopeDepth>0}clear(e){this.drafts.delete(e),this.pendingSubmittedDraftKeys.delete(e)}clearAll(){this.drafts.clear(),this.resetExecutionScope()}evictOldest(e){let t=Array.from(this.drafts.entries()).sort(([,n],[,i])=>n.timestamp-i.timestamp).slice(0,e);for(let[n]of t)this.drafts.delete(n),this.pendingSubmittedDraftKeys.delete(n)}resetExecutionScope(){this.pendingSubmittedDraftKeys.clear(),this.executionScopeDepth=0,this.executionScopeFailed=!1}}});var af,RA=k(()=>{ht();sf();af=class{constructor(e,t){this.store=mi.getInstance();this.initialValue="";this.didChange=!1;this.draftKey=this.store.makeKey(e),this.shouldPersist=t??(()=>ne.getState().persistInputPromptDrafts)}hydrate(e){return this.initialValue=e,this.shouldPersist()?this.store.get(this.draftKey)??e:e}markChanged(){this.didChange=!0}persist(e,t){if(this.shouldPersist()){if(t){this.store.handleSubmittedDraft(this.draftKey,e);return}if(!(!this.didChange||e===this.initialValue)){if(!e.trim()){this.store.clear(this.draftKey);return}this.store.set(this.draftKey,e)}}}}});function FC(r,e){if(r.focus(),e?.cursorAtEnd){let t=r.value.length;r.setSelectionRange(t,t);return}r.select()}var LA=k(()=>{});function PC(r,e,t){let n=e?.trim();if(!n)return;let i=r.createDiv({text:n,cls:"qa-prompt-context"});return i.setAttr("title",t?.trim()||n),i}var NA=k(()=>{});var lf,Ng,$C=k(()=>{De();lf=r=>{P.logWarning(r)},Ng=()=>{}});function cY(r,e){let t=Math.min(r.length,e.length),n=0;for(;n<t&&r[n]===e[n];)n++;return n}function EL(r,e,t){if(r===e)return 0;if(Math.abs(r.length-e.length)>t||r.length>64||e.length>64)return t+1;let n=[],i=Array.from({length:e.length+1},(s,a)=>a),o=[];for(let s=1;s<=r.length;s++){o=new Array(e.length+1),o[0]=s;let a=o[0];for(let l=1;l<=e.length;l++){let c=r[s-1]===e[l-1]?0:1,u=Math.min(i[l]+1,o[l-1]+1,i[l-1]+c);s>1&&l>1&&r[s-1]===e[l-2]&&r[s-2]===e[l-1]&&(u=Math.min(u,n[l-2]+1)),o[l]=u,u<a&&(a=u)}if(a>t)return t+1;n=i,i=o}return i[e.length]}function xL(r,e,t=3){let n=r.trim().toLowerCase();if(!n)return[];let i=e.map((a,l)=>({candidate:a,index:l})).filter(a=>a.candidate!==n),o=i.map(a=>({...a,distance:EL(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,t).map(a=>a.candidate);if(n.length>=2){let a=i.map(l=>({...l,shared:cY(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,t).map(l=>l.candidate)}return i.map(a=>({...a,distance:EL(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,t).map(a=>a.candidate)}var TL=k(()=>{});function Bg(r){let t=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(r);return t?[0,t[0].length]:null}function Vg(r,e,t,n){let[i,o]=n??[Number.NaN,Number.NaN];if(!(n!==null&&e>=i&&e<=o))return{isInYaml:!1,isQuoted:!1,lineStart:0,lineEnd:0,baseIndent:"",isKeyValuePosition:!1,isListItemPosition:!1};let a=r.lastIndexOf(`
`,e-1)+1,l=r.indexOf(`
`,Math.max(e,t)),c=l===-1?r.length:l,u=r.slice(a,e),d=r.slice(t,c),f=(u.match(/^\s*/)||[""])[0],p=r[e-1]==='"'&&r[t]==='"'||r[e-1]==="'"&&r[t]==="'",m=u.replace(/["']$/,""),g=d.replace(/^["']/,"").replace(/\s+#.*$/,"").trim().length===0,y=/:\s*$/.test(m)&&g,w=/^\s*-\s*$/.test(m)&&g;return{isInYaml:!0,isQuoted:p,lineStart:a,lineEnd:c,baseIndent:f,isKeyValuePosition:y,isListItemPosition:w}}var BA=k(()=>{});function SL(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(uY,e=>`\\x${e.charCodeAt(0).toString(16).padStart(2,"0")}`)}function qg(r){return`"${SL(r)}"`}function VA(r,e,t){let n=Vg(r,e,t,Bg(r));return!n.isInYaml||!n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}function cf(r,e,t,n){return VA(r,e,t)?r[e-1]==='"'?SL(n):n.replace(/'/g,"''"):n}function qA(r,e,t){let n=Vg(r,e,t,Bg(r));return!n.isInYaml||n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}var uY,UA=k(()=>{BA();uY=new RegExp("[\0-\x7F]","g")});function MC(r,e,t){let n=r.trim().toLowerCase();if(dY.has(n))return n;t?.(`QuickAdd: Unsupported multi-select format "${r}" in "${e}". Supported formats: auto, inline, spaced, yaml, markdown.`)}function pY(r,e){let t=r.lastIndexOf(`
`,e-1)+1;return r.slice(t,e).match(/^\s*/)?.[0]??""}function fY(r){return`- ${r.replace(/\r\n?|\n/g,`
`)}`}function _L(r){let{input:e,matchStart:t,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(qg).join(", ")}]`;case"markdown":{if(o.length===0)return"";let s=pY(e,t);return o.map(fY).join(`
${s}`)}default:return i}}var dY,OC=k(()=>{UA();dY=new Set(["auto","inline","spaced","yaml","markdown"])});function LC(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function hY(r){let e=r.map(t=>`"${t}"`);return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function kL(r,e){let t=LC(r,32),n=`{{FIELD:${LC(e,48)}}}`,i=mY.get(r);if(i)return`Unknown FIELD filter "${t}" - ${i}. Ignored in ${n}.`;let o=xL(r,RC);return o.length>0?`Unknown FIELD filter "${t}" - did you mean ${hY(o)}? Ignored in ${n}.`:`Unknown FIELD filter "${t}" in ${n} was ignored. Supported filters: ${RC.join(", ")}.`}function gY(r,e){let t=LC(r,32);return`FIELD filter "${t}" needs a value - write "${t}:value". Ignored in {{FIELD:${LC(e,48)}}}.`}function vY(r,e,t){(t.warn??lf)(kL(r,e))}var RC,mY,hi,Lc=k(()=>{$C();dd();TL();OC();RC=["folder","tag","inline","inline-code-blocks","exclude-folder","exclude-tag","exclude-file","default","default-from","default-empty","default-always","case-sensitive","multi","format"],mY=new Map([["case-insensitive",'matching is already case-insensitive; use "case-sensitive:true" to match exactly']]);hi=class{static parse(e,t){let n=Yo(e).map(c=>c.trim()),i=n[0],o={},s=!1,a="auto",l=!1;for(let c=1;c<n.length;c++){let u=n[c];if(u.toLowerCase()==="multi"){s=!0;continue}let d=Oi(u);if(!d){let m=u.toLowerCase();t?.warnUnknown&&m&&(t.warn??lf)(RC.includes(m)?gY(m,e):kL(m,e));continue}let f=d.key,p=d.value;if(!RC.includes(f)){t?.warnUnknown&&vY(f,e,t);continue}switch(f){case"multi":s=Sc(p);break;case"format":l=!0,a=MC(p,`{{FIELD:${e}}}`,t?.warn)??"auto";break;case"folder":o.folders||(o.folders=[]),o.folders.push(p),o.folder||(o.folder=p);break;case"tag":{o.tags||(o.tags=[]);let m=p.startsWith("#")?p.substring(1):p;o.tags.push(m);break}case"inline":o.inline=p.toLowerCase()==="true";break;case"inline-code-blocks":o.inlineCodeBlocks||(o.inlineCodeBlocks=[]),o.inlineCodeBlocks.push(...p.split(",").map(m=>m.trim().toLowerCase()).filter(m=>m.length>0));break;case"default":o.defaultValue=p;break;case"default-from":o.defaultFrom=p.toLowerCase();break;case"default-empty":o.defaultEmpty=p.toLowerCase()==="true";break;case"default-always":o.defaultAlways=p.toLowerCase()==="true";break;case"case-sensitive":o.caseSensitive=p.toLowerCase()==="true";break;case"exclude-folder":o.excludeFolders||(o.excludeFolders=[]),o.excludeFolders.push(p);break;case"exclude-tag":{o.excludeTags||(o.excludeTags=[]);let m=p.startsWith("#")?p.substring(1):p;o.excludeTags.push(m);break}case"exclude-file":o.excludeFiles||(o.excludeFiles=[]),o.excludeFiles.push(p);break}}return!s&&l&&(t?.warn?.(`QuickAdd: |format: needs |multi in "{{FIELD:${e}}}"; ignoring.`),a="auto"),{fieldName:i,filters:o,...s?{multiSelect:s}:{},...a!=="auto"?{multiFormat:a}:{}}}}});function zA(r){return r.replace(/^\/+|\/+$/g,"")}function Ug(r,e=t=>t){return JSON.stringify([...r].map(e).sort())}function AL(r,e){let t=[`folder=${zA(r)}`];return e.folders?.length&&t.push(`folders=${Ug(e.folders,zA)}`),e.tags?.length&&t.push(`tags=${Ug(e.tags)}`),e.excludeFolders?.length&&t.push(`xfolder=${Ug(e.excludeFolders,zA)}`),e.excludeTags?.length&&t.push(`xtag=${Ug(e.excludeTags)}`),e.excludeFiles?.length&&t.push(`xfile=${Ug(e.excludeFiles)}`),t.join("|")}function bY(r){let{folderPath:e,mode:t,label:n,optional:i,allowCustomInput:o,multiSelect:s,filter:a}=r,l=[AL(e,a),`mode=${t}`];return n&&l.push(`label=${n}`),i&&l.push("optional"),o&&l.push("custom"),s&&l.push("multi"),l.join("|")}function NC(r,e){if(!r)return null;let t=Yo(r),n=(t.shift()??"").trim();if(!n)return null;let i=t,o=Ps(i,"optional");i=o.remaining;let s=o.found,a=Ps(i,"custom");i=a.remaining;let l=a.found,c=Ps(i,"multi");i=c.remaining;let u=c.found,d="name",f=[];for(let b of i){let E=b.trim().toLowerCase();if(yY.has(E)){d=E;continue}f.push(b)}let p,m;for(let b of f){let E=Oi(b);E&&(E.key==="label"&&E.value?p=E.value:E.key==="name"&&E.value&&(m=E.value))}let v=hi.parse(r,{warn:e?.warn}),g=u||(v.multiSelect??!1),y=v.multiFormat??"auto",w={folder:n,tags:v.filters.tags,excludeFolders:v.filters.excludeFolders,excludeTags:v.filters.excludeTags,excludeFiles:v.filters.excludeFiles},T=m?`${zg}name=${m}|${AL(n,w)}${g?"|multi":""}`:`${zg}${bY({folderPath:n,mode:d,label:p,optional:s,allowCustomInput:l,multiSelect:g,filter:w})}`;return{raw:r,folderPath:n,mode:d,label:p,aliasName:m,optional:s,allowCustomInput:l,filter:w,multiSelect:g,multiFormat:y,variableKey:T}}function DL(r,e){if(!r)return r;for(let t of e)if(r===t)return r;return`${bo}${r}`}function Ed(r){return typeof r!="string"||r===""?{kind:"empty"}:r.startsWith(bo)?{kind:"custom",text:r.slice(bo.length)}:r.startsWith(Ta)?{kind:"file",path:r.slice(Ta.length)}:{kind:"raw",value:r}}function Nc(r){return(r.split("/").pop()??r).replace(/\.(md|canvas|base)$/i,"")}function IL(r){return typeof r=="string"&&r.trim().length>0?r.trim():void 0}function wY(r){if(!r)return;let e=Object.entries(r).find(([t])=>t.toLowerCase()==="title");return e?IL(e[1]):void 0}function CY(r){let e=r?.headings?.find(t=>t.level===1);return IL(e?.heading)}function EY(r){let e=r.parent?.path;return e&&e!=="/"?e:r.path.includes("/")?r.path.slice(0,r.path.lastIndexOf("/")):"vault root"}function xY(r){return r.basename?r.basename:Nc(r.path)}function HA(r,e){let t=r.map(i=>{let o=e?.(i)??null,s=xY(i),a=wY(o?.frontmatter)??CY(o)??s,l=a===s?s:`${a} (${s})`;return{file:i,primary:a,label:l}}),n=new Map;for(let{label:i}of t)n.set(i,(n.get(i)??0)+1);return t.map(({file:i,primary:o,label:s})=>{let a=(n.get(s)??0)<=1?s:`${s} - ${EY(i)}`;return{primary:o,secondary:i.path,label:a}})}function Sl(r,e){return HA(r,e).map(t=>t.label)}var zg,Ta,bo,yY,wo=k(()=>{Lc();dd();zg="FILE:",Ta="@file:",bo="@filecustom:",yY=new Set(["name","link","path"])});function xd(r){return TY.has(r.toUpperCase())}function WA(r){if(r.length===0||r==="."||r===".."||r.startsWith(".")||Hg.test(r)||Wg.test(r)||jg.test(r))return!1;let e=r.split(".")[0]??"";return e.length===0||!xd(e)}var Hg,Wg,jg,TY,Gg=k(()=>{Hg=new RegExp("[\0-]","u"),Wg=/[\\/:*?"<>|]/u,jg=/[. ]$/u,TY=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 SY(r){return(r??"").trim().replace(/\\/g,"/")}function _Y(r){return r.startsWith("/")||/^[a-zA-Z]:/.test(r)}function kY(r){return r.split("/").some(e=>/^\.\.[. ]*$/u.test(e))}function Pr(r){let e=SY(r);return e?_Y(e)||kY(e):!1}var Sa=k(()=>{});function kl(r){return Object.hasOwn(_l,r)}function FL(r){let e=r.toLowerCase();return e==="jpeg"||Object.values(_l).includes(e)}function AY(r){let e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}-${e(r.getMonth()+1)}-${e(r.getDate())} ${e(r.getHours())}.${e(r.getMinutes())}.${e(r.getSeconds())}`}function IY(r){return r.replace(DY,"").replace(/\s+/g," ").replace(/[. ]+$/g,"").trim()}function BC(r){if(r.nameAfterNoteTitle){let e=IY(Nc(r.sourcePath));if(e.length>0&&WA(e))return`${e}.${r.extension}`}return`Clipboard image ${AY(r.now)}.${r.extension}`}function PL(r,e){if(!kl(r))throw new Error(`Unsupported clipboard image type: ${r}`);return BC({extension:_l[r],sourcePath:"",now:e,nameAfterNoteTitle:!1})}function $L(r){let e=r.split(/[\\/]/u).at(-1)??"",t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e;return WA(n)?n:null}async function jA(r,e,t,n,i){if(!kl(t))throw new Error(`Unsupported image type: ${t}`);let o=await r.fileManager.getAvailablePathForAttachment(i,n||void 0);if(Pr(o))throw new Error(`Refusing to save image outside the vault: '${o}'`);return r.vault.createBinary(o,e)}async function VC(r,e,t,n,i){if(!kl(t))throw new Error(`Unsupported clipboard image type: ${t}`);let o=i?.nameAfterNoteTitle??ne.getState().namePastedImagesAfterNoteTitle;return jA(r,e,t,n,BC({extension:_l[t],sourcePath:n,now:i?.now??new Date,nameAfterNoteTitle:o}))}function qC(r,e,t){let n=r.fileManager.generateMarkdownLink(e,t);return n.startsWith("!")?n:`!${n}`}var _l,DY,UC=k(()=>{ht();wo();Gg();Sa();_l=Object.assign(Object.create(null),{"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"});DY=/[/\\:*?"<>|#^[\]]/g});function FY(){let r=zC.filter(t=>t.inputEl.isConnected);return r.find(t=>document.activeElement!==null&&t.inputEl.contains(document.activeElement))??r.at(-1)??null}function uf(r,e,t={}){let n=t.sourcePath??"",i=null,o=!1,s=!1,a=()=>{s=!0},l=()=>{s=!1},c=(y,w,T,b)=>{switch(T.kind){case"stand-down":return;case"take":if(w.preventDefault(),i){new Yg.Notice(y==="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=m(T.images,b).then(()=>{}).finally(()=>{i=null});return;default:return HC(T)}},u=y=>{let w=y.clipboardData;if(!w||s)return;let T=new Date;c("paste",y,ML("paste",w,r),T)},d=y=>{if(s)return;let w=y.dataTransfer;!w||!RL(w)||(y.preventDefault(),w.dropEffect="copy",e.classList.add("qa-image-drop-target"))},f=()=>{e.classList.remove("qa-image-drop-target")},p=y=>{if(f(),s)return;let w=y.dataTransfer;if(!w||!RL(w))return;let T=new Date;c("drop",y,ML("drop",w,r),T)};async function m(y,w){let T=e.readOnly;e.readOnly=!0,e.setAttribute("aria-busy","true"),e.classList.add("qa-image-paste-busy");let b=[];try{for(let C of y){let _;switch(C.origin){case"vault":_=C.file;break;case"bytes":{let I=await C.file.arrayBuffer(),q=OY(C,w,n);_=await RY(()=>jA(r,I,C.mimeType,n,q));break}default:return HC(C)}b.push(qC(r,_,n))}}catch(C){P.logError(`Failed to save image: ${C instanceof Error?C.message:String(C)}`),new Yg.Notice("QuickAdd: failed to save image.")}finally{e.readOnly=T,e.removeAttribute("aria-busy"),e.classList.remove("qa-image-paste-busy")}if(b.length===0||o)return"";let E=b.join(e.tagName==="TEXTAREA"?`
`:" ");try{return LY(e,E),E}catch(C){return P.logError(`Failed to insert image link: ${C instanceof Error?C.message:String(C)}`),new Yg.Notice("QuickAdd: saved the image but could not insert its link."),""}}async function v(y){let w=new Date,T=MY(y);if(T.length===0)return P.logMessage("QuickAdd: image ingest skipped (no-images)."),"";if(i)return new Yg.Notice("QuickAdd: an image is still being saved \u2014 drop again in a moment."),P.logMessage("QuickAdd: image ingest skipped (busy)."),"";let b="";return i=(async()=>{b=await m(T,w)})().finally(()=>{i=null}),await i,b.length>0&&P.logMessage(`QuickAdd: ingested ${T.length} image(s) into the active prompt.`),b}e.addEventListener("paste",u),e.addEventListener("dragenter",d),e.addEventListener("dragover",d),e.addEventListener("dragleave",f),e.addEventListener("drop",p),e.addEventListener("compositionstart",a),e.addEventListener("compositionend",l);let g={isBusy:()=>i!==null,whenIdle:()=>i??Promise.resolve(),ingestFiles:v,detach:()=>{o=!0,f(),e.removeEventListener("paste",u),e.removeEventListener("dragenter",d),e.removeEventListener("dragover",d),e.removeEventListener("dragleave",f),e.removeEventListener("drop",p),e.removeEventListener("compositionstart",a),e.removeEventListener("compositionend",l);let y=zC.findIndex(w=>w.handle===g);y>=0&&zC.splice(y,1)}};return zC.push({handle:g,inputEl:e}),g}async function NL(r){let e=FY();if(!e)return P.logMessage("QuickAdd: image ingest skipped (no-active-prompt)."),{ok:!1,reason:"no-active-prompt"};if(e.handle.isBusy())return P.logMessage("QuickAdd: image ingest skipped (busy)."),{ok:!1,reason:"busy"};let t=await e.handle.ingestFiles(r);return t.length===0?{ok:!1,reason:"no-images"}:{ok:!0,inserted:t}}function ML(r,e,t){switch(r){case"paste":{if(e.getData("text/plain").length>0)return{kind:"stand-down"};let n=OL(e).map(i=>({origin:"bytes",...i,naming:{kind:"paste-name"}}));return n.length>0?{kind:"take",images:n}:{kind:"stand-down"}}case"drop":{let n=PY(e,t);if(n.length>0)return{kind:"take",images:n};let i=OL(e).map(o=>({origin:"bytes",...o,naming:BL(o)}));return i.length>0?{kind:"take",images:i}:{kind:"stand-down"}}default:return HC(r)}}function PY(r,e){let t=[];for(let n of r.getData("text/plain").split(/\r?\n/u)){let i=n.trim();if(i.length===0||i.toLowerCase().startsWith("file://")||Pr(i))continue;let o=e.vault.getAbstractFileByPath(i);$Y(o)&&t.push({origin:"vault",file:o})}return t}function $Y(r){return r!==null&&"extension"in r&&typeof r.extension=="string"&&FL(r.extension)}function OL(r){let e=[],t=0;for(let o of Array.from(r.items??[])){if(o.kind!=="file"||(t++,!kl(o.type)))continue;let s=o.getAsFile();s&&e.push({file:s,mimeType:o.type})}if(t>0&&e.length===t)return e;if(e.length===0){let o=[];for(let s of Array.from(r.files??[]))kl(s.type)&&o.push({file:s,mimeType:s.type});return o}let n=[...e],i=new Set(e.map(({file:o,mimeType:s})=>`${o.name}\0${o.size}\0${s}\0${o.lastModified}`));for(let o of Array.from(r.files??[])){if(!kl(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 MY(r){return r.flatMap(e=>{if(!kl(e.type))return[];let t={file:e,mimeType:e.type};return[{origin:"bytes",...t,naming:BL(t)}]})}function BL(r){let e=$L(r.file.name);return e===null?{kind:"clipboard-stamp"}:{kind:"original-stem",stem:e}}function OY(r,e,t){switch(r.naming.kind){case"clipboard-stamp":return PL(r.mimeType,e);case"paste-name":return BC({extension:_l[r.mimeType],sourcePath:t,now:e,nameAfterNoteTitle:ne.getState().namePastedImagesAfterNoteTitle});case"original-stem":return`${r.naming.stem}.${_l[r.mimeType]}`;default:return HC(r.naming)}}function RL(r){return Array.from(r.types??[]).some(e=>e==="Files"||kl(e))}function HC(r){throw new Error(`Unexpected image intake value: ${String(r)}`)}function RY(r){let e=LL.then(r,r);return LL=e.catch(()=>{}),e}function LY(r,e){r.focus();let t=!1;try{t=r.ownerDocument.execCommand("insertText",!1,e)}catch{t=!1}if(t)return;let n=r.selectionStart??r.value.length,i=r.selectionEnd??n;r.setRangeText(e,n,i,"end"),r.dispatchEvent(new Event("input",{bubbles:!0}))}var Yg,zC,LL,Kg=k(()=>{Yg=require("obsidian");De();UC();ht();Sa();zC=[];LL=Promise.resolve()});function VL(r,e){return!r.isComposing&&r.key.toLowerCase()===e.toLowerCase()&&r.shiftKey&&(r.ctrlKey||r.metaKey)}function WC(r){return VL(r,"Enter")}function jC(r){return VL(r,Qg)}function UL(r){return r?`Look at the note without losing this draft. ${qL}`:"Look at the note without losing this draft."}function zL(){return`${qL} returns to the prompt`}var Qg,qL,df=k(()=>{Qg="E",qL="Ctrl/Cmd+Shift+E"});function HL(r,e,t,n){let i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(t,r.length));return{text:r.slice(0,i)+n+r.slice(o),cursor:i+n.length}}function WL(r,e=42){let t=r.slice(0,e*4),n=t.replace(/\s+/g," ").trim();return n.length<=e?t.length<r.length?`${n}\u2026`:n:`${n.slice(0,Math.max(0,e-1))}\u2026`}var GA=k(()=>{});function KA(r){YA.add(r)}function QA(r){YA.delete(r)}function jL(){return YA.size>0}var YA,XA=k(()=>{YA=new Set});function NY(r,e){let t=new Set([e]);return r.workspace.iterateAllLeaves?.(i=>{let o=i.view?.containerEl?.ownerDocument;o&&t.add(o)}),[...t]}var Wn,Ls,Bc,ZA=k(()=>{Wn=require("obsidian");wa();Is();df();GA();XA();Ls=class Ls{constructor(e,t){this.app=e;this.handle=t;this.chipEl=null;this.insertButton=null;this.compactChrome=!1;this.returnScope=null;this.selectionDocuments=[];this.selectionListener=null;this.chipKeyListener=null;this.hasSelection=null;this.selectionPreview=""}static isPeeking(){return Ls.active!==null}static getActive(){return Ls.active}static activate(e,t){let n=Ls.active;if(n){let o=n.handle.title;n.cancel(),new Wn.Notice(`QuickAdd: cancelled the peeked prompt "${o}".`)}let i=new Ls(e,t);return Ls.active=i,i.mount(),i}static discard(){Ls.active?.destroy()}discard(){this.destroy()}resume(){if(!this.canReturnNow())return;let e=this.handle;this.destroy(),e.resume()}cancel(){let e=this.handle;this.destroy(),e.cancel()}insertSelectionAndResume(){if(!this.canReturnNow())return;let e=rd(this.app);if(!e){this.resume();return}let t=this.handle;this.destroy(),t.insertSelectionAndResume(e)}canReturnNow(){return jL()?(new Wn.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=Wn.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.createEl("span",{cls:"qa-peek-chip-icon"});s.setAttribute("aria-hidden","true"),(0,Wn.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 Wn.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 Wn.ButtonComponent(l).setButtonText("Return").setTooltip("Go back to the prompt without inserting").onClick(()=>this.resume());let c=new Wn.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 u=nr(c.buttonEl,"span");u.className="qa-peek-chip-cancel-icon",u.setAttribute("aria-hidden","true"),(0,Wn.setIcon)(u,"x"),c.buttonEl.replaceChildren(u)}else c.setButtonText("Cancel");Wn.Platform.isMobile||i.createEl("p",{cls:"qa-peek-chip-keys",text:zL()}),this.chipEl=i,this.refreshInsertButton(),this.listenForSelection(),this.listenForChipEscape(),this.pushReturnShortcut()}listenForSelection(){let e=(0,Wn.debounce)(()=>this.refreshInsertButton(),100,!0);this.selectionListener=e,this.selectionDocuments=NY(this.app,this.chipEl?.ownerDocument??document);for(let t of this.selectionDocuments)t.addEventListener("selectionchange",e)}refreshInsertButton(){let e=this.insertButton;if(!e)return;let t=rd(this.app),n=t.length>0,i=n&&!this.compactChrome?WL(t):"";n===this.hasSelection&&i===this.selectionPreview||(this.hasSelection=n,this.selectionPreview=i,e.setDisabled(!n),e.buttonEl.classList.toggle("qa-peek-insert-ready",n),this.compactChrome||e.setButtonText(n?`Insert \u201C${i}\u201D`:"Insert selection"))}listenForChipEscape(){let e=this.chipEl;e&&(this.chipKeyListener=t=>{if(t.isComposing||t.key!=="Escape")return;let n=t.target;!(n instanceof Node)||!e.contains(n)||(t.preventDefault(),this.resume())},e.addEventListener("keydown",this.chipKeyListener))}pushReturnShortcut(){this.returnScope=new Wn.Scope(this.app.scope),this.returnScope.register(["Mod","Shift"],Qg,()=>(this.resume(),!1)),this.app.keymap.pushScope(this.returnScope)}destroy(){if(Ls.active===this&&(Ls.active=null),this.returnScope&&(this.app.keymap.popScope(this.returnScope),this.returnScope=null),this.chipKeyListener&&this.chipEl&&(this.chipEl.removeEventListener("keydown",this.chipKeyListener),this.chipKeyListener=null),this.selectionListener){for(let e of this.selectionDocuments)e.removeEventListener("selectionchange",this.selectionListener);this.selectionListener.cancel?.(),this.selectionListener=null}this.selectionDocuments=[],this.chipEl?.remove(),this.chipEl=null,this.insertButton=null}};Ls.active=null;Bc=Ls});function BY(r){ln(r)?.editor?.focus?.()}var GL,Vc,GC=k(()=>{wa();ZA();GA();XA();GL="qa-prompt-peek-hidden",Vc=class{constructor(e){this.host=e;this.peeking=!1;this.session=null}peek(){if(this.peeking)return;let e=this.host.getField();e&&this.host.setValue(e.value),this.host.persistDraft(),this.peeking=!0,this.hideModal(),this.session=Bc.activate(this.host.app,{title:this.host.title,resume:()=>this.resume(),cancel:()=>this.cancel(),insertSelectionAndResume:t=>this.insertSelectionAndResume(t)})}onHostOpened(){KA(this.host)}onHostClosed(){QA(this.host),this.peeking&&(this.peeking=!1,this.session?.discard(),this.session=null)}hideModal(){QA(this.host),this.host.containerEl.addClass(GL),this.host.app.keymap.popScope(this.host.scope),BY(this.host.app)}showModal(){this.host.app.keymap.pushScope(this.host.scope),this.host.containerEl.removeClass(GL),KA(this.host),this.host.getField()?.focus()}resume(){this.peeking&&(this.peeking=!1,this.session=null,this.showModal())}insertSelectionAndResume(e){if(!this.peeking)return;let t=this.host.getField();if(t){let n=t.selectionStart??t.value.length,i=t.selectionEnd??n,o=HL(t.value,n,i,e);t.value=o.text,t.setSelectionRange(o.cursor,o.cursor),this.host.setValue(o.text)}else this.host.setValue(this.host.getValue()+e);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 YL(r){return Xg.Platform.isPhone||(r?.innerWidth??Number.POSITIVE_INFINITY)<=540}function pf(r){let e=YL(r.ownerDocument.defaultView);return r.classList.toggle("qa-prompt-compact",e),e}function ff(r){let e=YL(r.buttonEl.ownerDocument.defaultView);r.setButtonText(e?qY:VY),r.setTooltip(UL(!Xg.Platform.isMobile)),r.buttonEl.setAttribute("aria-label","Peek at the note. Your draft stays."),r.buttonEl.classList.add("qa-peek-button");let t=nr(r.buttonEl,"span");return t.className="qa-peek-button-icon",t.setAttribute("aria-hidden","true"),(0,Xg.setIcon)(t,"eye"),r.buttonEl.prepend(t),r}var Xg,VY,qY,YC=k(()=>{Xg=require("obsidian");Is();df();VY="Peek at note",qY="Peek"});var mf,sr,Ns=k(()=>{mf=require("obsidian");AC();IC();RA();LA();NA();Kg();Er();GC();df();YC();sr=class r extends mf.Modal{constructor(t,n,i,o,s,a,l){super(t);this.header=n;this.linkSourcePath=s;this.options=l;this.didSubmit=!1;this.didClose=!1;this.submitClickCallback=t=>this.submit();this.cancelClickCallback=t=>this.cancel();this.skipClickCallback=t=>this.skip();this.submitEnterCallback=t=>{if(this.supportsPeek()&&jC(t)){t.preventDefault(),this.peek.peek();return}if(this.isOptionalPrompt&&WC(t)){t.preventDefault(),this.skip();return}!t.isComposing&&t.key==="Enter"&&(t.preventDefault(),this.submit())};this.placeholder=i??"",this.description=a?.trim()||void 0,this.draftHandler=new af({kind:"single",header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath,scopeId:l?.draftScopeId}),this.input=this.draftHandler.hydrate(o??""),this.waitForClose=new Promise((c,u)=>{this.resolvePromise=c,this.rejectPromise=u}),this.peek=new Vc({app:t,title:this.header,containerEl:this.containerEl,scope:this.scope,getField:()=>this.inputComponent?.inputEl,getValue:()=>this.input,setValue:c=>{this.input=c},markDraftChanged:()=>this.draftHandler.markChanged(),persistDraft:()=>this.persistDraft(),close:()=>this.close()}),this.display(),this.open(),this.attachSuggesters()}static Prompt(t,n,i,o,s,a){return new r(t,n,i,o,void 0,s,a).waitForClose}static PromptWithContext(t,n,i,o,s,a,l){return new r(t,n,i,o,s,a,l).waitForClose}display(){this.containerEl.addClass("quickAddModal","qaInputPrompt"),pf(this.containerEl),this.contentEl.empty(),this.titleEl.textContent=this.header,PC(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 t=this.contentEl.createDiv();this.inputComponent=this.createInputField(t,this.placeholder,this.input),this.createButtonBar(t)}get isOptionalPrompt(){return this.options?.optional===!0}supportsPeek(){return this.options?.allowPeek===!0}createInputField(t,n,i){let o=new mf.TextComponent(t);return o.inputEl.setCssStyles({width:"100%"}),o.setPlaceholder(n??"").setValue(i??"").onChange(s=>this.onInputChanged(s)).inputEl.addEventListener("keydown",this.submitEnterCallback),this.options?.imagePaste&&(this.imagePasteHandle=uf(this.app,o.inputEl,this.options.imagePaste)),o}createButton(t,n,i){let o=new mf.ButtonComponent(t);return o.setButtonText(n).onClick(i),o}createButtonBar(t){let n=t.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"});ff(this.createButton(o,"Peek at note",()=>this.peek.peek()))}}transformInputOnSubmit(t){return t}submit(){if(this.didSubmit||this.didClose)return;if(this.imagePasteHandle?.isBusy()){this.imagePasteHandle.whenIdle().then(()=>this.submit());return}let t=this.inputComponent?.inputEl?.value??this.input;this.input=this.transformInputOnSubmit(t),this.didSubmit=!0,this.close()}skip(){this.input="",this.didSubmit=!0,this.close()}cancel(){this.close()}resolveInput(){this.didSubmit?this.resolvePromise(this.input):this.rejectPromise(Ir())}onInputChanged(t){this.draftHandler.markChanged(),this.input=t}syncInputFromEl(){this.inputComponent?.inputEl&&(this.input=this.inputComponent.inputEl.value)}persistDraft(){this.draftHandler.persist(this.input,this.didSubmit)}attachSuggesters(){this.fileSuggester=new Oc(this.app,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new Rc(this.app,this.inputComponent.inputEl)}removeInputListener(){this.inputComponent.inputEl.removeEventListener("keydown",this.submitEnterCallback),this.imagePasteHandle?.detach()}onOpen(){super.onOpen(),this.peek.onHostOpened(),FC(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()}}});function XL(r,e,t){return Array.isArray(r)?r.map(n=>QL(n,e,t)):QL(r,e,t)}function QL(r,e,t){if(e==="link")return t(r);let n=Ed(r);switch(n.kind){case"empty":return"";case"file":return e==="path"?n.path:Nc(n.path);case"custom":case"raw":return n.kind==="custom"?n.text:n.value}}var ZL=k(()=>{wo()});function t8(r){return ZY.test(r.trim())}function r8(r){let e=r.replace(JY,"");return e===r?!1:!e8.test(e)}function QC(r,e){return QY.has(r)?r8(e):t8(e)}function XC(r){return r==="noteTitle"||r==="captureTarget"||r==="folder"||r==="templatePath"||r==="lineTarget"||r==="filePath"}function JA(r){return r!=="templatePath"&&r!=="generic"}function ZC(r,e){if(r==="generic")return{};let t=XY[r];return e?{title:t.ask,placeholder:t.hint}:{placeholder:t.partOf}}function n8(r,e=44){if(r.length<=e)return r;let t=r.split("/");if(t.length===1)return r;let n=t[t.length-1];if(t.length===2){let s=`${JL}/${n}`;return s.length<r.length?s:r}let o=`${t[0]}/${JL}/${n}`;return o.length<r.length?o:r}function Jg(r,e,t){if(!r)return;let n=[],i=r.choiceName?.trim();i&&i!==e?.trim()&&n.push(i);let o=t?.showDestination===!1?void 0:r.destination?.trim();if(o){let s=t?.elide===!1?o:n8(o);n.push(`\u2192 ${r.destinationKind==="folder"?`${s}/`:s}`)}return n.length?n.join(" "):void 0}var QY,XY,ZY,JY,e8,JL,ev=k(()=>{Je();QY=new Set(["captureText"]),XY={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"},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"}},ZY=new RegExp(`^(?:${pl.source})$`,"i"),JY=new RegExp(pl.source,"gi"),e8=/\{\{[^}\n\r]*\}\}/;JL="\u2026"});function tv(r,e){if(!r||!e)return null;let t=r,n=t.metadataTypeManager??t.metadataCache?.app?.metadataTypeManager;if(!n||typeof n.getTypeInfo!="function")return null;let i=n.getTypeInfo(e),o=i?.expected?.type??i?.inferred?.type;return typeof o=="string"?o:null}function s8(r){return r!==null&&i8.has(r.toLowerCase())}function eN(r,e){return o8.has(e.toLowerCase())||s8(tv(r,e))}var i8,o8,JC=k(()=>{i8=new Set(["aliases","list","multitext","tags"]),o8=new Set(["aliases","cssclasses","tags"])});function a8(r,e=","){let t=[],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 u=a-1;u>=0&&r[u]==="\\";u--)c++;c%2===0&&(o=null)}continue}if(l==='"'){o=l,n+=l;continue}if(l in tN){i.push(tN[l]),n+=l;continue}if(i.length>0){let c=i[i.length-1];l===c&&i.pop(),n+=l;continue}if(l===e){let c=n.trim();c.length>0&&t.push(c),n="";continue}n+=l}let s=n.trim();return s.length>0&&t.push(s),t}function l8(r){return r.includes(`
`)?r.replace(/\r?\n/g,`
`):r.includes("\\n")?r.replace(/\\n/g,`
`):r}function c8(r){if(!r)return!1;let e=r.toLowerCase();return e==="list"||e==="tags"||e==="multitext"}function rN(r,e){let t=r.trim();if(!t)return;let n=l8(t),i=e?.propertyType??tv(e?.app,e?.propertyKey),o=c8(i),a=o||i===null,c=n.split(/\n/).map(u=>u.trim()).filter(u=>u.length>0);if(a&&c.length>0&&c.every(u=>/^-\s+/.test(u)))return c.map(u=>u.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 u=a8(n);if(u.length>1)return u}}var tN,nN=k(()=>{JC();tN={"[":"]","(":")","{":"}","<":">"}});function eE(r){if(typeof r=="string"&&r.startsWith("@date:")){let e=r.substring(6),t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return r}function eD(r){return typeof r!="string"&&(Array.isArray(r)||typeof r=="object"&&r!==null||typeof r=="number"||typeof r=="boolean"||r===null)}function iN(r){return Array.isArray(r)||typeof r=="object"&&r!==null}function oN(r){if(eD(r))return Array.isArray(r)?"[]":r===null?"null":typeof r=="object"?"{}":String(r)}var rv=k(()=>{});var sN,Bs,tE=k(()=>{BA();nN();rv();JC();sN="\0",Bs=class{constructor(e){this.app=e;this.map=new Map;this.propertyTypeCache=new Map}maybeCollect(e){let{input:t,matchStart:n,matchEnd:i,rawValue:o,fallbackKey:s,collectionActive:a,heuristicEnabled:l}=e;if(!a)return;let c=Bg(t),u=Vg(t,n,i,c);if(!u.isInYaml)return;let d=t.slice(u.lineStart,u.lineEnd),f=d.trim(),p=d.match(/^\s*([^:]+):/),m=p?p[1].trim():s,v=/^-\s*['"]?\{\{(?:VALUE|FIELD|FILE):[^}]+\}\}['"]?\s*$/i,g=null;if(u.isKeyValuePosition?g=[m]:v.test(f)&&(g=this.findListParentPath(t,u.lineStart,u.baseIndent??"")),!g||g.length===0)return;let y=g[g.length-1],w=o;if(l&&typeof o=="string"){let b=rN(o,this.buildParseOptions(y));b!==void 0&&(w=b)}if(!eD(w)||Array.isArray(w)&&w.length===0||!l&&!iN(w))return;let T=g.join(sN);return this.map.set(T,w),w}drain(){let e=new Map(this.map);return this.map.clear(),e}merge(e){for(let[t,n]of e)this.map.set(t,n)}buildParseOptions(e){return{propertyKey:e,propertyType:this.resolvePropertyType(e),app:this.app}}findListParentPath(e,t,n){let i=t-1,o=[],s=n.length;for(;i>=0;){let a=e.lastIndexOf(`
`,i),l=a===-1?0:a+1,c=e.slice(l,i+1),u=c.trim();if(u.length===0){i=l-2;continue}if(u==="---"||u==="...")break;if(u.startsWith("-")){i=l-2;continue}let d=c.match(/^(\s*)([^:\n]+):/);if(d){let p=(d[1]??"").length;if(p<s&&(o.unshift(d[2].trim()),s=p,s===0))break}i=l-2}return o.length>0?o:null}resolvePropertyType(e){if(!this.app)return null;if(this.propertyTypeCache.has(e))return this.propertyTypeCache.get(e)??null;let t=tv(this.app,e);return this.propertyTypeCache.set(e,t),t}};Bs.PATH_SEPARATOR=sN});function aN(r){if(!r)return null;let e=r.trim().toLowerCase();switch(e){case"kebab":case"snake":case"camel":case"pascal":case"title":case"lower":case"upper":case"slug":return e;default:return null}}function iv(r){return aN(r)!==null}function tD(r){if(!r)return r;let e=r.toLowerCase();return e.slice(0,1).toUpperCase()+e.slice(1)}function rD(r){return/\p{L}/u.test(r)?/\p{Lu}/u.test(r)&&!/\p{Ll}/u.test(r):!1}function rE(r){return/\p{Lu}/u.test(r)&&/\p{Ll}/u.test(r)}function u8(r){return/^\p{Ll}/u.test(r)&&rE(r)}function d8(r){if(!r)return[];{let t=r.match(/^([\p{Ll}][\p{Lu}]{2,})([\p{N}]+)?$/u);if(t){let n=[t[1]];return t[2]&&n.push(t[2]),n}}if(/^[\p{Ll}][\p{Lu}][\p{Ll}]+(?:[\p{Lu}][\p{Ll}]+)*$/u.test(r))return[r];let e=r;return e=e.replace(/([\p{Lu}])([\p{Lu}][\p{Ll}])/gu,"$1 $2"),e=e.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu,"$1 $2"),e=e.replace(/([\p{L}])([\p{N}])/gu,"$1 $2"),e=e.replace(/([\p{N}])([\p{L}])/gu,"$1 $2"),e.trim().split(/\s+/u).map(t=>t.trim()).filter(Boolean)}function p8(r){return r.split(/[^\p{L}\p{N}\p{M}]+/gu).filter(Boolean).flatMap(d8).filter(Boolean)}function ov(r,e){let t=aN(e);if(!t)return r;if(t==="lower")return r.toLowerCase();if(t==="upper")return r.toUpperCase();let n=p8(r);if(n.length===0)return"";switch(t){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?u8(i)?i:i.toLowerCase():"",a=o.map(l=>rD(l)||rE(l)?l:tD(l));return[s,...a].join("")}case"pascal":return n.map(i=>rD(i)||rE(i)?i:tD(i)).join("");case"title":return n.map(i=>rD(i)||rE(i)?i:tD(i)).join(" ");case"slug":{let i=n.map(o=>o.toLowerCase()).join("-");return xd(i)?`${i}-`:i}default:return r}}var nv,nE=k(()=>{Gg();nv=["kebab","snake","camel","pascal","title","lower","upper","slug"]});function iE(r){let e=r.trim();return e&&(/^\[\[.*\]\]$/.test(e)?e:`[[${e}]]`)}var nD=k(()=>{});function h8(r,e,t){return t&&e?`${r}${iD}${e}`:r}function av(r){let e=r.indexOf(iD);return e===-1?r:r.slice(0,e)}function g8(r,e){let t=e.toLowerCase(),n=null;for(let i of r.keys())if(i.toLowerCase()===t&&r.get(i)!==void 0){if(n)return null;n=i}return n}function qc(r,e){if(!e)return null;let t=[e],n=av(e);n!==e&&t.push(n);for(let i of t){if(r.has(i)&&r.get(i)!==void 0)return i;let o=g8(r,i);if(o)return o}return null}function v8(r){let{remaining:e,found:t}=Ps(r,"optional");return{remaining:e,optional:t}}function dN(r){let{remaining:e,optional:t}=v8(r),{remaining:n,found:i}=Ps(e,"trim");return{remaining:n,optional:t,trim:i}}function y8(r,e){let t=r.trim();if(!t)return!1;let n=Oi(t);return n?(e?oD:sE).has(n.key):!1}function b8(r,e){let t=e?oD:sE;return r.some(n=>{let i=Oi(n.trim());if(!i||i.key!=="type"||!t.has("type"))return!1;let o=i.value.trim().toLowerCase();return o==="number"||o==="slider"})}function pN(r,e,t,n,i){if(r.length===0)return{defaultValue:"",allowCustomInput:!1,usesOptions:!1};let o=t?oD:sE,s=b8(r,t),a=r.some(B=>y8(B,t)||s&&lN.has(Oi(B.trim())?.key??"")),l=e&&r.some(B=>B.trim().toLowerCase()==="custom"),c=e&&r.some(B=>B.trim().toLowerCase()==="multi");if(!(a||l||c))return{defaultValue:r.join("|").trim(),allowCustomInput:!1,usesOptions:!1};let d,f,p="",m=!1,v,g,y,w,T,b,E,C,_=!1,I,q;for(let B of r){let J=B.trim();if(!J)continue;if(e&&J.toLowerCase()==="custom"){m=!0;continue}if(e&&J.toLowerCase()==="multi"){_=!0;continue}let re=Oi(J);if(!re)continue;let{key:L,value:W}=re;if(!(!o.has(L)&&!(s&&lN.has(L))))switch(L){case"label":W&&(d=W);break;case"case":W&&(f=W);break;case"default":p=W;break;case"custom":m=Sc(W);break;case"type":W&&(v=W);break;case"min":g=W;break;case"max":y=W;break;case"step":w=W;break;case"text":T=W;break;case"optional":b=Sc(W);break;case"trim":E=Sc(W);break;case"multi":_=!0,I=W.trim().toLowerCase()==="linklist"?"linklist":"text";break;case"format":q=MC(W,n,i);break;case"name":W?C=W:i(`QuickAdd: empty |name: ignored in "${n}"; provide a variable name, e.g. {{VALUE:a,b|name:category}}.`);break;default:break}}return{label:d,caseStyle:f,defaultValue:p,allowCustomInput:m,name:C,usesOptions:!0,inputTypeOverride:v,minRaw:g,maxRaw:y,stepRaw:w,displayValuesRaw:T,optionalExplicit:b,trimExplicit:E,multiSelect:_,multiEmit:I,multiFormat:q}}function fN(r,{tokenDisplay:e,hasOptions:t,allowCustomInput:n},i){if(!r)return;let o=r.trim().toLowerCase(),s=o==="boolean"?"checkbox":o;if(!f8.has(s)){i(`QuickAdd: Unsupported VALUE type "${r}" in token "${e}". Supported types: multiline, number, slider, checkbox, text.`);return}if(t||n){i(`QuickAdd: Ignoring type:${s} for option-list VALUE token "${e}".`);return}return s}function gf(r){if(r===void 0)return;let e=r.trim();if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function w8(r){return r.minRaw!==void 0||r.maxRaw!==void 0||r.stepRaw!==void 0}function cN(r,e,t){let n=gf(r.minRaw),i=gf(r.maxRaw),o=gf(r.stepRaw),s={};return r.minRaw!==void 0&&(n===void 0?t(`QuickAdd: Ignoring invalid min in VALUE token "${e}".`):s.min=n),r.maxRaw!==void 0&&(i===void 0?t(`QuickAdd: Ignoring invalid max in VALUE token "${e}".`):s.max=i),s.min!==void 0&&s.max!==void 0&&s.max<s.min&&(t(`QuickAdd: Ignoring invalid numeric range in VALUE token "${e}"; max must be greater than or equal to min.`),delete s.min,delete s.max),r.stepRaw!==void 0&&(o===void 0||o<=0?t(`QuickAdd: Ignoring invalid step in VALUE token "${e}"; step must be greater than 0.`):s.step=o),Object.keys(s).length>0?s:void 0}function mN(r,e,t,n){if(t!=="number"&&t!=="slider")return w8(r)&&n(`QuickAdd: Ignoring numeric range options in "${e}" because type is not number or slider.`),{inputTypeOverride:t};if(t!=="slider"){let c=cN(r,e,n);return{inputTypeOverride:t,numericConfig:c}}let i=gf(r.minRaw),o=gf(r.maxRaw),s=r.stepRaw===void 0?1:gf(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 "${e}" (${a}); falling back to type:number.`),{inputTypeOverride:"number",numericConfig:cN(r,e,Ng)};let l={min:i,max:o,step:s};return{inputTypeOverride:t,numericConfig:l,sliderConfig:l}}function uN(r){let e=String(r),t=/e-(\d+)$/i.exec(e);if(t)return Number(t[1]);let n=e.indexOf(".");return n===-1?0:e.length-n-1}function C8(r,e){return String(Number(r.toFixed(e)))}function Vs(r,e){let t=r?.trim()??"";if(!t)return"";let n=Number(t);if(!Number.isFinite(n))return"";let i=e?.min,o=e?.max,s=n;if(i!==void 0&&(s=Math.max(i,s)),o!==void 0&&(s=Math.min(o,s)),e?.step!==void 0&&e.step>0){let a=i??0,l=Math.round((s-a)/e.step);s=a+l*e.step,i!==void 0&&(s=Math.max(i,s)),o!==void 0&&(s=Math.min(o,s));let c=Math.max(uN(a),uN(e.step));return C8(s,c)}return String(s)}function lv(r,e){return Vs(r,e)||String(e.min)}function oE(r){return r!==void 0&&E8.has(r)}function sv(r){let e=[],t="",n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(n){if(oE(o)){if(oE(r[i+1])){t+='"',i++;continue}let s=i+1;for(;s<r.length&&x8.test(r[s]);)s++;if(s>=r.length||r[s]===","){n=!1,i=s-1;continue}return r.split(",")}t+=o;continue}if(o===","){e.push(t),t="";continue}if(oE(o)&&t.trim()===""){n=!0,t="";continue}t+=o}return n?r.split(","):(e.push(t),e)}function sD(r){let e=r.trim();if(!oE(e[0]))return r;let t=sv(e);return t.length===1&&t[0]!==e?t[0].trim():r}function cv(r,e){if(!r)return null;let t=e?.warn??lf,n=Yo(r),i=(n.shift()??"").trim();if(!i)return null;let o=sv(i).map(B=>B.trim()).filter(Boolean),s=o.length>1,{remaining:a,optional:l,trim:c}=dN(n),u=`{{VALUE:${r}}}`,d=pN(a,s,!0,u,t),{label:f,caseStyle:p,defaultValue:m,allowCustomInput:v}=d,g=d.multiSelect??!1,y=d.multiEmit??"text",w=d.multiFormat??"auto",T=d.optionalExplicit??l,b=d.trimExplicit??c;if(!d.usesOptions){let B=m;v=s&&B.toLowerCase()==="custom",m=v?"":B}s&&m&&(m=sD(m));let E=fN(d.inputTypeOverride,{tokenDisplay:u,hasOptions:s,allowCustomInput:v},t),C=mN(d,u,E,t),_;if(d.displayValuesRaw!==void 0){if(!s)throw new Error(`QuickAdd: VALUE option "text" is only supported for option-list tokens in "${u}".`);if(_=sv(d.displayValuesRaw).map(B=>B.trim()).filter(Boolean),_.length!==o.length)throw new Error(`QuickAdd: VALUE token "${u}" 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 "${u}" has duplicate text entries. Text entries must be unique.`)}let I=d.name?.trim()||void 0;I&&I.includes(iD)&&(t(`QuickAdd: |name in "${u}" contains a reserved control character and was ignored.`),I=void 0),I&&m8.has(I.toLowerCase())&&(t(`QuickAdd: |name:${I} is reserved and was ignored in "${u}". Choose a different name.`),I=void 0),I&&!s&&t(`QuickAdd: |name on a single value in "${u}" is redundant \u2014 use {{VALUE:${I}}} directly.`),p&&!iv(p)&&(t(`QuickAdd: Unsupported |case style "${p}" in token "${u}". Supported styles: ${nv.join(", ")}.`),p=void 0),g&&!s&&(t(`QuickAdd: |multi needs an option list (2+ comma-separated values) in "${u}"; ignoring.`),g=!1),g&&p&&(t(`QuickAdd: |case is ignored with |multi in "${u}" \u2014 a list is not case-transformed.`),p=void 0),!g&&d.multiFormat!==void 0&&(t(`QuickAdd: |format: needs |multi in "${u}"; ignoring.`),w="auto"),!s&&!d.usesOptions&&a.some(B=>B.trim().toLowerCase()==="custom")&&(t(`QuickAdd: |custom needs an option list (2+ comma-separated values) in "${u}"; ignoring.`),m.toLowerCase()==="custom"&&(m=""));let q=I||h8(i,f,s);return{raw:r,variableName:i,aliasName:I,variableKey:q,label:f,caseStyle:p,defaultValue:m,allowCustomInput:v,suggestedValues:o,displayValues:_,hasOptions:s,inputTypeOverride:C.inputTypeOverride,numericConfig:C.numericConfig,sliderConfig:C.sliderConfig,optional:T,trim:b,multiSelect:g,multiEmit:y,multiFormat:w}}function aD(r,e){let t=e?.warn??lf,n=KO(r),i=Yo(n).map(v=>v.trim()).filter(Boolean),{remaining:o,optional:s,trim:a}=dN(i);if(o.length===0)return{defaultValue:"",optional:s,trim:a};let l=`{{VALUE${r}}}`,c=pN(o,!1,!1,l,t);if(c.displayValuesRaw!==void 0)throw new Error(`QuickAdd: VALUE option "text" is only supported for option-list tokens in "${l}".`);let{label:u,caseStyle:d,defaultValue:f}=c;c.usesOptions||(f=f.trim()),d&&!iv(d)&&(t(`QuickAdd: Unsupported |case style "${d}" in token "${l}". Supported styles: ${nv.join(", ")}.`),d=void 0);let p=fN(c.inputTypeOverride,{tokenDisplay:l,hasOptions:!1,allowCustomInput:c.allowCustomInput},t),m=mN(c,l,p,t);return{label:u,caseStyle:d,defaultValue:f,inputTypeOverride:m.inputTypeOverride,numericConfig:m.numericConfig,sliderConfig:m.sliderConfig,optional:c.optionalExplicit??s,trim:c.trimExplicit??a}}var iD,f8,lN,sE,oD,m8,E8,x8,es=k(()=>{dd();nE();OC();$C();iD="",f8=new Set(["multiline","number","slider","checkbox","text"]),lN=new Set(["min","max","step"]),sE=new Set(["label","default","custom","type","case","text","optional","trim","multi","format"]),oD=new Set([...sE,"name"]),m8=new Set(["value","title"]);E8=new Set(['"',"\u201C","\u201D"]);x8=/[^\S\r\n]/});function uv(r){if(!r)return{optional:!1,withTime:!1};let{remaining:e,found:t}=Ps(Yo(r),"optional"),{remaining:n,found:i}=Ps(e,"time"),{remaining:o,found:s}=Ps(n,"datetime"),a,l=!1,c,u,d=[];for(let p of o){let m=Oi(p.trim());if(m?.key==="optional"){a=Sc(m.value);continue}if(m?.key==="type"){m.value.trim().toLowerCase()==="datetime"&&(l=!0);continue}if(m?.key==="startof"||m?.key==="endof"){c||(c={boundary:m.key==="startof"?"start":"end",unit:iC(m.value)});continue}if(m?.key==="case"){u=m.value.trim()||void 0;continue}d.push(p)}return{defaultValue:d.join("|").trim()||void 0,optional:a??t,withTime:i||s||l,snap:c,...u?{caseStyle:u}:{}}}function aE(r){try{return{options:uv(r)}}catch(e){return{options:{optional:!1,withTime:!1},error:e instanceof Error?e.message:String(e)}}}var dv=k(()=>{dd();Tg()});function hN(r){if(!r)return null;let e=r.indexOf("|");if(e===-1){let o=r.trim();return o?{macroName:o}:null}let t=r.slice(0,e).trim();if(!t)return null;let n=r.slice(e+1).trim();if(!n)return{macroName:t};if(!n.toLowerCase().startsWith("label:"))return null;let i=n.slice(6).trim();return{macroName:t,label:i||void 0}}var gN=k(()=>{});function Uc(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 zc(r){return T8.includes(r)}function bN(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 wN(r){if(!zc(r.operator)||r.expectedValue===void 0||r.expectedValue===null)return;let e=r.expectedValue.trim();switch(r.valueType){case"number":{let t=Number(e);return Number.isNaN(t)?NaN:t}case"boolean":{let t=e.toLowerCase();return vN.has(t)?!0:yN.has(t)?!1:!!e}default:return e}}function lD(r,e){switch(e){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 t=r.trim().toLowerCase();if(vN.has(t))return!0;if(yN.has(t))return!1}return!!r;default:return r==null?"":Uc(r)}}function S8(r){if(!zc(r.operator))return"";let e=r.expectedValue??"";return e.length===0?"(empty)":r.valueType==="string"?`"${e}"`:e}function _8(r){let e=r.variableName?`$${r.variableName}`:"(missing variable)",t=A8(r.operator),n=zc(r.operator)?` ${S8(r)}`:"";return`${e} ${t}${n}`.trim()}function k8(r){let e=r.exportName?`::${r.exportName}`:"";return`script ${r.scriptPath}${e}`}function vf(r){return r.mode==="variable"?_8(r):k8(r)}function A8(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 T8,vN,yN,yf=k(()=>{T8=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],vN=new Set(["true","1","yes","on"]),yN=new Set(["false","0","no","off"])});function pv(r){let e=[],t=r.length,n=0;for(;n<t;){let i=r.indexOf("`",n);if(i===-1)break;let o=i;for(;o<t&&r[o]==="`";)o++;if(o-i<3||!r.startsWith(cD,o)){n=o;continue}let s=o+cD.length,a=-1;for(;s<t;){let l=r.indexOf("`",s);if(l===-1)break;let c=l;for(;c<t&&r[c]==="`";)c++;if(c-l>=3){a=c;break}s=c}if(a===-1)break;e.push({start:i,end:a}),n=a}return e}function EN(r){let e=pv(r),t=r.length,n=e.length>0?e[e.length-1].end:0;for(;n<t;){let i=r.indexOf("`",n);if(i===-1)return!1;let o=i;for(;o<t&&r[o]==="`";)o++;if(o-i>=3&&r.startsWith(cD,o))return!0;n=o}return!1}function fv(r){return r?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"}function mv(r,e,t,n){if(r===void 0)return null;let i=r,o;if(typeof i=="string"&&i&&!i.startsWith("@date:")){if(n){let s=ne.getState().dateAliases,a=n.parseDate(lg(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:jp(a,t).format(e),...o!==void 0?{normalized:o}:{}}}return{text:"",...o!==void 0?{normalized:o}:{}}}return typeof i=="string"&&i?{text:i}:i!=null?{text:Uc(i)}:{text:""}}var CN,D8,lE,cD,_a,bf=k(()=>{CN=require("obsidian");Je();wo();ZL();ev();Dt();De();tE();ht();Ku();nE();rv();UA();OC();nD();Lc();es();$C();dv();Tg();gN();yf();D8=new Set(["number","slider","checkbox"]),lE=10,cD="js quickadd";_a=class{constructor(e){this.app=e;this.variables=new Map;this.linkToCurrentFileBehavior="required";this.targetFolderPath=null;this.promptScope="generic";this.promptScopeSoleValue=!1;this.templatePropertyCollectionDepth=0;this.namedSuggesterOptionSigs=new Map;this.namedSuggesterConflictsWarned=new Set;this.warnSink=e=>this.warn(e);this.propertyCollector=new Bs(e)}runClocks(){return this.clocks}warn(e){P.logWarning(e)}reportProblem(e){P.logError(e)}setTemplateInclusionState(e){this.templateInclusion=e}setPromptRunContext(e){this.promptRunContext={...this.promptRunContext,...e}}getPromptRunContext(){return this.promptRunContext}async withPromptScope(e,t,n){let i=this.promptScope,o=this.promptScopeSoleValue;this.promptScope=e,this.promptScopeSoleValue=QC(e,t);try{return await n()}finally{this.promptScope=i,this.promptScopeSoleValue=o}}hasConcreteVariable(e){return this.variables.has(e)?this.variables.get(e)!==void 0:!1}setTitle(e){this.hasConcreteVariable("title")||this.variables.set("title",e)}getAnonymousValue(){return this.value}replacer(e,t,n){return e.replace(t,function(){return n})}applyCaseOption(e,t,n){return t?iv(t)?ov(e,t):(this.warn(`QuickAdd: Unsupported |case style "${t}" in token "${n}". Supported styles: ${nv.join(", ")}.`),e):e}replaceDateInString(e){let t=e;for(;Mw.test(t);){let n=Mw.exec(t),i;if(n&&n[1]){let l=n[1].replace("+","").trim();yk.test(l)&&(i=parseInt(l))}let o=n?.[2]?Wk(n[2])??void 0:void 0,s=this.runClocks(),a=Ko({offset:i,snap:o,origin:s?.date,now:s?.now});t=this.replacer(t,Mw,this.applyCaseOption(a,n?.[3],n?.[0]??"{{DATE}}"))}for(;Mp.test(t);){let n=Mp.exec(t);if(!n)throw new Error(`Unable to parse date format. Invalid syntax in: "${t.substring(Math.max(0,t.search(Mp)-10),Math.min(t.length,t.search(Mp)+30))}..."`);let i=n[1],o;if(n[2]){let c=n[2].replace("+","").trim();yk.test(c)&&(o=parseInt(c))}let s=n[3]?Wk(n[3])??void 0:void 0,a=this.runClocks(),l=Ko({format:i,offset:o,snap:s,origin:a?.date,now:a?.now});t=this.replacer(t,Mp,this.applyCaseOption(l,n[4],n[0]))}return t}replaceTimeInString(e){let t=e;for(;Op.test(t);){let n=Op.exec(t);if(!n)throw new Error(`Unable to parse time format. Invalid syntax in: "${t.substring(Math.max(0,t.search(Op)-10),Math.min(t.length,t.search(Op)+30))}..."`);let i=Ko({format:"HH:mm",now:this.runClocks()?.now});t=this.replacer(t,Op,this.applyCaseOption(i,n[1],n[0]))}for(;Rp.test(t);){let n=Rp.exec(t);if(!n)throw new Error(`Unable to parse formatted time. Invalid syntax in: "${t.substring(Math.max(0,t.search(Rp)-10),Math.min(t.length,t.search(Rp)+30))}..."`);let i=n[1],o=Ko({format:i,now:this.runClocks()?.now});t=this.replacer(t,Rp,this.applyCaseOption(o,n[2],n[0]))}return t}async replaceValueInString(e){let t=e;if(!pl.test(t))return t;if(this.valuePromptContext=this.getValuePromptContext(t),this.hasConcreteVariable("value")){let i=this.variables.get("value");this.value=Uc(i)}this.value===void 0&&(this.value=await this.promptForValue());let n=new RegExp(pl.source,"gi");return t=t.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 cf(a,s,s+o.length,this.value);let u=l.slice(c),d=aD(u,{warn:this.warnSink}),f=this.value===""&&d.defaultValue&&!d.optional?d.defaultValue:this.value,p=this.applyValueTextOptions(f,d);return d.inputTypeOverride==="text"&&p!==""&&qA(a,s,s+o.length)?qg(p):cf(a,s,s+o.length,p)}),t}applyValueTextOptions(e,t){let n=String(e??""),i=t.trim?n.trim():n;return ov(i,t.caseStyle)}applyValueTokenOptions(e,t){return Array.isArray(e)?t.trim?e.map(n=>typeof n=="string"?n.trim():n):e:typeof e=="string"?this.applyValueTextOptions(e,t):e}getValuePromptContext(e){let t=new RegExp(pl.source,"gi"),n,i;for(;(n=t.exec(e))!==null;){let s=n[0].slice(2,-2),a=s.indexOf("|");if(a===-1)continue;let l=s.slice(a),c=aD(l,{warn:Ng});i||(i={}),!i.description&&c.label&&(i.description=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}async replaceSelectedInString(e){if(!Ek.test(e))return e;let t=await this.getSelectedText(),n=new RegExp(Ek.source,"gi");return e.replace(n,()=>t)}async replaceClipboardInString(e){if(!xk.test(e))return e;let t=await this.getClipboardContent(),n=new RegExp(xk.source,"gi");return e.replace(n,()=>t)}async replaceLinkToCurrentFileInString(e){if(!bk.test(e))return e;let t=this.getCurrentFileLink();if(!t){if(this.linkToCurrentFileBehavior==="required")throw new Error("Unable to get current file path. Make sure you have a file open in the editor.");P.logMessage("Skipping {{LINKCURRENT}} replacement because no active file is available.")}let n=new RegExp(bk.source,"gi");return e.replace(n,()=>t??"")}replaceLinkToCurrentSectionInString(e){if(!wk.test(e))return e;let t=this.getCurrentFileLinkToSection();if(!t){if(this.linkToCurrentFileBehavior==="required")throw new Error("Unable to get current file path. Make sure you have a file open in the editor.");P.logMessage("Skipping {{LINKSECTION}} replacement because no active file is available.")}let n=new RegExp(wk.source,"gi");return e.replace(n,()=>t??"")}replaceCurrentFileLinksInString(e){return this.replaceCurrentFileTokensInString(e,{links:!0})}replaceCurrentFileTokensInString(e,t){let n=/{{(?:(LINKCURRENT|LINKSECTION|FILENAMECURRENT|TITLE)|(FOLDERCURRENT|FOLDER)(\|name)?)}}/gi,i,o,s,a,l,c,u,d,f=!1,p=!1,m=!1,v=e.replace(n,(y,w,T,b)=>{if(T!==void 0&&T.toUpperCase()==="FOLDERCURRENT"){if(!t.activeFolder)return y;if(c===void 0)if(c=this.getCurrentFolderPath(),c===null)u=null;else{let E=c.lastIndexOf("/");u=E===-1?c:c.slice(E+1)}return c===null&&(m=!0),(b?u:c)??""}if(T!==void 0){if(!t.folder)return y;if(a===void 0){a=this.targetFolderPath??"";let E=a.lastIndexOf("/");l=E===-1?a:a.slice(E+1)}return b?l:a}switch((w??"").toUpperCase()){case"LINKCURRENT":return t.links?(i===void 0&&(i=this.getCurrentFileLink()??null),i||(f=!0),i??""):y;case"LINKSECTION":return t.links?(o===void 0&&(o=this.getCurrentFileLinkToSection()??null),o||(f=!0),o??""):y;case"FILENAMECURRENT":return t.fileName?(s===void 0&&(s=this.getCurrentFileName()??null),s||(p=!0),s??""):y;case"TITLE":return t.title?(d===void 0&&(d=this.getVariableValue("title")),d):y}return y}),g="Unable to get the active file's folder. Make sure you have a file open in the editor.";if(m&&t.activeFolder==="path")throw new Error(g);if(f||p||m){if(this.linkToCurrentFileBehavior==="required")throw new Error(f?"Unable to get current file path. Make sure you have a file open in the editor.":p?"Unable to get current file name. Make sure you have a file open in the editor.":g);P.logMessage("Skipping current-file token replacement because no active file is available.")}return v}async replaceCurrentFileNameInString(e){return this.replaceCurrentFileTokensInString(e,{fileName:!0})}setLinkToCurrentFileBehavior(e){this.linkToCurrentFileBehavior=e}setTargetFolderPath(e){if(e==null){this.targetFolderPath=null;return}let t=e.trim();this.targetFolderPath=t==="/"?"":t.replace(/^\/+/,"").replace(/\/+$/,"")}replaceTargetFolderInString(e){return this.replaceCurrentFileTokensInString(e,{folder:!0})}getAndClearTemplatePropertyVars(){return this.propertyCollector.drain()}mergeTemplatePropertyVars(e){this.propertyCollector.merge(e)}renderCollectedOrArrayValue(e){if(Array.isArray(e.rawValue)&&e.multiFormat){let i=_L({input:e.input,matchStart:e.matchStart,values:e.rawValue,format:e.multiFormat});if(i!==void 0)return i}let t=this.propertyCollector.maybeCollect({...e,collectionActive:this.templatePropertyCollectionDepth>0}),n=oN(t);if(n!==void 0)return n;if(Array.isArray(e.rawValue))return cf(e.input,e.matchStart,e.matchEnd,e.rawValue.join(","))}async withTemplatePropertyCollection(e){this.templatePropertyCollectionDepth+=1;try{return await e()}finally{this.templatePropertyCollectionDepth-=1}}getCurrentFileLinkToSection(){return null}getCurrentFolderPath(){return null}warnOnNamedOptionConflict(e){if(!e.aliasName||!e.hasOptions)return;let t=e.variableKey.toLowerCase(),n=JSON.stringify([e.suggestedValues,e.allowCustomInput,e.displayValues??null,e.multiSelect,e.multiEmit]),i=this.namedSuggesterOptionSigs.get(t);if(i===void 0){this.namedSuggesterOptionSigs.set(t,n);return}i!==n&&!this.namedSuggesterConflictsWarned.has(t)&&(this.namedSuggesterConflictsWarned.add(t),this.warn(`QuickAdd: named value "${e.variableKey}" is defined with different option lists; the first definition's value is reused.`))}async ensureValueVariableResolved(e){let{variableName:t,variableKey:n,label:i,defaultValue:o,allowCustomInput:s,suggestedValues:a,displayValues:l,hasOptions:c}=e;this.warnOnNamedOptionConflict(e);let u=qc(this.variables,n);if(u)return u;let d=!c&&i?i:void 0,f=c&&i?i:void 0;if(c&&e.multiSelect){let m=await this.suggestForValueMulti(a,s,{placeholder:f,variableKey:n,displayValues:l,optional:e.optional});return this.variables.set(n,e.multiEmit==="linklist"?m.map(iE):m),n}let p="";return c?p=await this.suggestForValue(a,s,{placeholder:f,variableKey:n,displayValues:l,optional:e.optional}):p=await this.promptForVariable(t,{defaultValue:o,description:d,inputTypeOverride:e.inputTypeOverride,numericConfig:e.numericConfig,sliderConfig:e.sliderConfig,variableKey:n,optional:e.optional}),!p&&o&&!e.optional&&(p=o),this.variables.set(n,p),n}async resolveNamedSuggesterDefinitions(e){if(!/\|\s*name\s*:/i.test(e))return;let t=new RegExp(Xu.source,"gi"),n=[],i;for(;(i=t.exec(e))!==null;){if(!i[1])continue;let a;try{a=cv(i[1],{warn:Ng})}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(e){let t=e;await this.resolveNamedSuggesterDefinitions(t);let n=new RegExp(Xu.source,"gi"),i=this.isTemplatePropertyTypesEnabled(),o;for(;(o=n.exec(t))!==null;){if(!o[1])throw new Error(`Unable to parse variable. Invalid syntax in: "${t.substring(Math.max(0,o.index-10),Math.min(t.length,o.index+30))}..."`);let s=cv(o[1],{warn:this.warnSink});if(!s)throw new Error(`Unable to parse variable. Invalid syntax in: "${t.substring(Math.max(0,o.index-10),Math.min(t.length,o.index+30))}..."`);let{variableName:a}=s,l=await this.ensureValueVariableResolved(s),c=this.variables.get(l),u=this.applyValueTokenOptions(c,s),d=this.renderCollectedOrArrayValue({input:t,matchStart:o.index,matchEnd:o.index+o[0].length,rawValue:u,fallbackKey:a,heuristicEnabled:i&&this.templatePropertyCollectionDepth>0&&s.inputTypeOverride!=="text",multiFormat:s.multiFormat}),f,p=!1;if(d!==void 0)f=d;else{let g=String(this.applyValueTextOptions(this.getVariableValue(l),s)??"");s.inputTypeOverride==="text"&&g!==""&&qA(t,o.index,o.index+o[0].length)?f=qg(g):D8.has(s.inputTypeOverride??"")&&VA(t,o.index,o.index+o[0].length)?(p=!0,f=g):f=cf(t,o.index,o.index+o[0].length,g)}let m=p?o.index-1:o.index,v=o.index+o[0].length+(p?1:0);t=t.slice(0,m)+f+t.slice(v),n.lastIndex=m+f.length}return t}async replaceFieldVarInString(e){let t=new RegExp(Ow.source,"gi"),n="",i=0,o;for(;(o=t.exec(e))!==null;){n+=e.slice(i,o.index);let s=o[1]+(o[2]||"");if(s){let a=this.getFieldVariableKey(s),l=hi.parse(s,{warnUnknown:!0,warn:this.warnSink});this.hasConcreteVariable(a)||this.variables.set(a,await this.suggestForField(s,l));let c=this.hasConcreteVariable(a)?this.variables.get(a):this.getVariableValue(a),u;Array.isArray(c)?u=this.renderCollectedOrArrayValue({input:e,matchStart:o.index,matchEnd:o.index+o[0].length,rawValue:c,fallbackKey:l.fieldName,heuristicEnabled:!1,multiFormat:l.multiFormat??"auto"})??c.join(","):u=cf(e,o.index,o.index+o[0].length,String(c??"")),n+=u}else n+=o[0];i=t.lastIndex}return n+e.slice(i)}getFieldVariableKey(e){return`${Zu}${e}`}async replaceFileInString(e){let t=new RegExp(Rw.source,"gi"),n="",i=0,o;for(;(o=t.exec(e))!==null;){n+=e.slice(i,o.index);let s=NC(o[1]??"",{warn:this.warnSink});if(!s){n+=o[0],i=t.lastIndex;continue}let a=s.variableKey;this.hasConcreteVariable(a)||this.variables.set(a,await this.suggestForFile(s));let l=XL(this.variables.get(a),s.mode,c=>this.getFileLinkForStoredValue(c));if(Array.isArray(l)){let c=this.renderCollectedOrArrayValue({input:e,matchStart:o.index,matchEnd:o.index+o[0].length,rawValue:l,fallbackKey:s.aliasName??s.folderPath,heuristicEnabled:!1,multiFormat:s.multiFormat});n+=c??l.join(",")}else n+=l;i=t.lastIndex}return n+e.slice(i)}getFileLinkForStoredValue(e){let t=Ed(e);if(t.kind==="empty")return"";if(t.kind!=="file"){let o=t.kind==="custom"?t.text:t.value;return o?`[[${o}]]`:""}let n=t.path;if(!n)return"";let i=this.app?.vault.getAbstractFileByPath(n);return i instanceof CN.TFile?this.app?.fileManager.generateMarkdownLink(i,this.getLinkSourcePath()??"")??`[[${Nc(n)}]]`:`[[${Nc(n)}]]`}getLinkSourcePath(){return null}async replaceMathValueInString(e){let t=new RegExp(Lw.source,"gi"),n=this.variables.get("mvalue"),i=typeof n=="string"&&n.trim()?n:null,o="",s=0,a;for(;(a=t.exec(e))!==null;)o+=e.slice(s,a.index),o+=i??await this.promptForMathValue(),s=a.index+a[0].length;return o+=e.slice(s),o}async replaceMacrosInString(e){let t=e;for(;bc.test(t);){let n=bc.exec(t);if(!n)continue;if(!n[1]){t=this.replacer(t,bc,"");continue}let i=hN(n[1]);if(!i){t=this.replacer(t,bc,"");continue}let{macroName:o,label:s}=i,a=await this.getMacroValue(o,s?{label:s}:void 0);t=this.replacer(t,bc,a?a.toString():"")}return t}suggestForValueMulti(e,t,n){return[]}async replaceDateVariableInString(e){let t=new RegExp(yc.source,"gi"),n="",i=0,o;for(;(o=t.exec(e))!==null;){n+=e.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:u,caseStyle:d}=uv(o[3]),f=o[2]?.trim()||fv(c);if(this.variables.get(s)===void 0){let v=await this.promptForVariable(s,{type:"VDATE",dateFormat:f,defaultValue:a,optional:l,withTime:c});if(l&&!v?.trim())this.variables.set(s,"");else if(v?.startsWith("@date:"))this.variables.set(s,v);else{if(!this.dateParser)throw new Error("Date parser is not available");let g=ne.getState().dateAliases,y=lg(v,g),w=this.dateParser.parseDate(y);if(w)this.variables.set(s,`@date:${w.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 m=mv(this.variables.get(s),f,u,this.dateParser);m?.normalized!==void 0&&this.variables.set(s,m.normalized),n+=this.applyCaseOption(m?.text??"",d,o[0])}return n+e.slice(i)}async replaceTemplateInString(e){let t=e;for(;Ho.test(t);){let n=Ho.exec(t);if(!n||!n[1])continue;let i=n[1];if(this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0}),this.templateInclusion.visited.has(i)){let s=`[QuickAdd: template inclusion cycle detected at "${i}"]`;this.reportProblem(s),t=this.replacer(t,Ho,s);continue}if(this.templateInclusion.depth>=lE){let s=`[QuickAdd: max template inclusion depth (${lE}) exceeded at "${i}"]`;this.reportProblem(s),t=this.replacer(t,Ho,s);continue}this.templateInclusion.visited.add(i);let o;try{o=await this.getTemplateContent(i)}finally{this.templateInclusion.visited.delete(i)}t=this.replacer(t,Ho,o)}return t}replaceLinebreakInString(e){let t="";for(let n=0;n<e.length;n++){let i=e[n],o=e[n+1];i=="\\"?o=="n"?(t+=`
`,n++):o=="\\"?(t+="\\",n++):t+="\\":t+=i}return t}expandLinebreakEscapesOutsideTokens(e){let t=pv(e),n="",i=0,o=0;for(;i<e.length;){for(;o<t.length&&t[o].end<=i;)o++;let s=t[o];if(s&&s.start===i){n+=e.slice(s.start,s.end),i=s.end;continue}if(e[i]==="{"&&e[i+1]==="{"){let c=e.indexOf("}}",i+2),u=!1;if(c!==-1){let d=c+2;for(let f=o;f<t.length;f++){let p=t[f];if(p.start>=d)break;if(d<p.end&&d>p.start){u=!0;break}}}if(c!==-1&&!u){n+=e.slice(i,c+2),i=c+2;continue}}let a=e[i],l=e[i+1];a==="\\"?l==="n"?(n+=`
`,i+=2):l==="\\"?(n+="\\",i+=2):(n+="\\",i+=1):(n+=a,i+=1)}return n}replaceRandomInString(e){let t=e;for(;Tk.test(t);){let n=Tk.exec(t);if(!n||!n[1])continue;let i=parseInt(n[1]);if(i<=0||i>100)throw new Error(`Random string length must be between 1 and 100. Got: ${i}`);let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",s="";for(let a=0;a<i;a++)s+=o.charAt(Math.floor(Math.random()*o.length));t=t.replace(n[0],s)}return t}replaceTitleInString(e){return this.replaceCurrentFileTokensInString(e,{title:!0})}}});var vt,Zt,Eo,Al=k(()=>{(function(r){r[r.AM=0]="AM",r[r.PM=1]="PM"})(vt||(vt={}));(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"})(Zt||(Zt={}));(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"})(Eo||(Eo={}))});function qs(r,e){r.assign("day",e.getDate()),r.assign("month",e.getMonth()+1),r.assign("year",e.getFullYear())}function cE(r,e){r.assign("hour",e.getHours()),r.assign("minute",e.getMinutes()),r.assign("second",e.getSeconds()),r.assign("millisecond",e.getMilliseconds()),r.assign("meridiem",e.getHours()<12?vt.AM:vt.PM)}function Dl(r,e){r.imply("day",e.getDate()),r.imply("month",e.getMonth()+1),r.imply("year",e.getFullYear())}function hv(r,e){r.imply("hour",e.getHours()),r.imply("minute",e.getMinutes()),r.imply("second",e.getSeconds()),r.imply("millisecond",e.getMilliseconds()),r.imply("meridiem",e.getHours()<12?vt.AM:vt.PM)}var Sd=k(()=>{Al()});function Wc(r,e,t,n,i=0){let o=0,s=0;for(;s<n;)o++,new Date(r,e-1,o).getDay()===t&&s++;return new Date(r,e-1,o,i)}function TN(r,e,t,n=0){let i=t===0?7:t,o=new Date(r,e-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,e-1,o.getDate(),n)}function uE(r,e,t={}){if(r==null)return null;if(typeof r=="number")return r;let n=t[r]??P8[r];return n==null?null:typeof n=="number"?n:e==null?null:e>n.dstStart(e.getFullYear())&&!(e>n.dstEnd(e.getFullYear()))?n.timezoneOffsetDuringDst:n.timezoneOffsetNonDst}var P8,uD=k(()=>{Al();P8={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=>TN(r,Eo.MARCH,Zt.SUNDAY,2),dstEnd:r=>TN(r,Eo.OCTOBER,Zt.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-300,timezoneOffsetNonDst:-360,dstStart:r=>Wc(r,Eo.MARCH,Zt.SUNDAY,2,2),dstEnd:r=>Wc(r,Eo.NOVEMBER,Zt.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=>Wc(r,Eo.MARCH,Zt.SUNDAY,2,2),dstEnd:r=>Wc(r,Eo.NOVEMBER,Zt.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=>Wc(r,Eo.MARCH,Zt.SUNDAY,2,2),dstEnd:r=>Wc(r,Eo.NOVEMBER,Zt.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=>Wc(r,Eo.MARCH,Zt.SUNDAY,2,2),dstEnd:r=>Wc(r,Eo.NOVEMBER,Zt.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 Dn(r,e){let t=new Date(r);if(e.y&&(e.year=e.y,delete e.y),e.mo&&(e.month=e.mo,delete e.mo),e.M&&(e.month=e.M,delete e.M),e.w&&(e.week=e.w,delete e.w),e.d&&(e.day=e.d,delete e.d),e.h&&(e.hour=e.h,delete e.h),e.m&&(e.minute=e.m,delete e.m),e.s&&(e.second=e.s,delete e.s),e.ms&&(e.millisecond=e.ms,delete e.ms),"year"in e){let n=Math.floor(e.year);t.setFullYear(t.getFullYear()+n);let i=e.year-n;i>0&&(e.month=e?.month??0,e.month+=i*12)}if("quarter"in e){let n=Math.floor(e.quarter);t.setMonth(t.getMonth()+n*3)}if("month"in e){let n=Math.floor(e.month);t.setMonth(t.getMonth()+n);let i=e.month-n;i>0&&(e.week=e?.week??0,e.week+=i*4)}if("week"in e){let n=Math.floor(e.week);t.setDate(t.getDate()+n*7);let i=e.week-n;i>0&&(e.day=e?.day??0,e.day+=Math.round(i*7))}if("day"in e){let n=Math.floor(e.day);t.setDate(t.getDate()+n);let i=e.day-n;i>0&&(e.hour=e?.hour??0,e.hour+=Math.round(i*24))}if("hour"in e){let n=Math.floor(e.hour);t.setHours(t.getHours()+n);let i=e.hour-n;i>0&&(e.minute=e?.minute??0,e.minute+=Math.round(i*60))}if("minute"in e){let n=Math.floor(e.minute);t.setMinutes(t.getMinutes()+n);let i=e.minute-n;i>0&&(e.second=e?.second??0,e.second+=Math.round(i*60))}if("second"in e){let n=Math.floor(e.second);t.setSeconds(t.getSeconds()+n);let i=e.second-n;i>0&&(e.millisecond=e?.millisecond??0,e.millisecond+=Math.round(i*1e3))}if("millisecond"in e){let n=Math.floor(e.millisecond);t.setMilliseconds(t.getMilliseconds()+n)}return t}function jc(r){let e={};for(let t in r)e[t]=-r[t];return e}var SN,Il=k(()=>{SN={day:0,second:0,millisecond:0}});var Gc,Ct,Fl,Us=k(()=>{Sd();uD();Il();Gc=class r{constructor(e,t){pe(this,"instant");pe(this,"timezoneOffset");this.instant=e??new Date,this.timezoneOffset=t??null}static fromDate(e){return new r(e)}static fromInput(e,t){if(e instanceof Date)return r.fromDate(e);let n=e?.instant??new Date,i=uE(e?.timezone,n,t);return new r(n,i)}getDateWithAdjustedTimezone(){let e=new Date(this.instant);return this.timezoneOffset!==null&&e.setMinutes(e.getMinutes()-this.getSystemTimezoneAdjustmentMinute(this.instant)),e}getSystemTimezoneAdjustmentMinute(e,t){e||(e=new Date);let n=-e.getTimezoneOffset(),i=t??this.timezoneOffset??n;return n-i}getTimezoneOffset(){return this.timezoneOffset??-this.instant.getTimezoneOffset()}},Ct=class r{constructor(e,t){pe(this,"knownValues");pe(this,"impliedValues");pe(this,"reference");pe(this,"_tags",new Set);if(this.reference=e,this.knownValues={},this.impliedValues={},t)for(let i in t)this.knownValues[i]=t[i];let n=e.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(e,t=SN){let n=Dn(e.getDateWithAdjustedTimezone(),t),i=new r(e);return i.addTag("result/relativeDate"),"hour"in t||"minute"in t||"second"in t||"millisecond"in t?(i.addTag("result/relativeDateAndTime"),cE(i,n),qs(i,n),i.assign("timezoneOffset",e.getTimezoneOffset())):(hv(i,n),i.imply("timezoneOffset",e.getTimezoneOffset()),"day"in t?(i.assign("day",n.getDate()),i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear()),i.assign("weekday",n.getDay())):"week"in t?(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 t?(i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear())):(i.imply("month",n.getMonth()+1),"year"in t?i.assign("year",n.getFullYear()):i.imply("year",n.getFullYear())))),i}get(e){return e in this.knownValues?this.knownValues[e]:e in this.impliedValues?this.impliedValues[e]:null}isCertain(e){return e in this.knownValues}getCertainComponents(){return Object.keys(this.knownValues)}imply(e,t){return e in this.knownValues?this:(this.impliedValues[e]=t,this)}assign(e,t){return this.knownValues[e]=t,delete this.impliedValues[e],this}addDurationAsImplied(e){let t=this.dateWithoutTimezoneAdjustment(),n=Dn(t,e);return("day"in e||"week"in e||"month"in e||"year"in e)&&(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 e||"minute"in e||"hour"in e)&&(this.delete(["second","minute","hour"]),this.imply("second",n.getSeconds()),this.imply("minute",n.getMinutes()),this.imply("hour",n.getHours())),this}delete(e){typeof e=="string"&&(e=[e]);for(let t of e)delete this.knownValues[t],delete this.impliedValues[t]}clone(){let e=new r(this.reference);e.knownValues={},e.impliedValues={};for(let t in this.knownValues)e.knownValues[t]=this.knownValues[t];for(let t in this.impliedValues)e.impliedValues[t]=this.impliedValues[t];return e}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 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")),!(e.getUTCFullYear()!==this.get("year")||e.getUTCMonth()!==this.get("month")-1||e.getUTCDate()!==this.get("day")||this.get("hour")!=null&&e.getUTCHours()!=this.get("hour")||this.get("minute")!=null&&e.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 e=this.get("timezoneOffset")??this.reference.timezoneOffset;if(e==null)return this.dateWithoutTimezoneAdjustment();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")),new Date(t.getTime()-e*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let t of e)this._tags.add(t);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=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 e.setFullYear(this.get("year")),e}},Fl=class r{constructor(e,t,n,i,o){pe(this,"refDate");pe(this,"index");pe(this,"text");pe(this,"reference");pe(this,"start");pe(this,"end");this.reference=e,this.refDate=e.instant,this.index=t,this.text=n,this.start=i||new Ct(e),this.end=o}clone(){let e=new r(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}addTag(e){return this.start.addTag(e),this.end&&this.end.addTag(e),this}addTags(e){return this.start.addTags(e),this.end&&this.end.addTags(e),this}tags(){let e=new Set(this.start.tags());if(this.end)for(let t of this.end.tags())e.add(t);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}}});function dD(r,e,t="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${r}${n}(?:${t}${n}){0,10}`}function $8(r){let e;return r instanceof Array?e=[...r]:r instanceof Map?e=Array.from(r.keys()):e=Object.keys(r),e}function pn(r){return`(?:${$8(r).sort((t,n)=>n.length-t.length).join("|").replace(/\./g,"\\.")})`}var Pl=k(()=>{});function dE(r){return r<100&&(r>50?r=r+1900:r=r+2e3),r}function Yc(r,e,t){let n=new Date(r);n.setMonth(t-1),n.setDate(e);let i=Dn(n,{year:1}),o=Dn(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 Cf=k(()=>{Il()});function M8(r){let e=r.toLowerCase();return pD[e]!==void 0?pD[e]:e==="a"||e==="an"||e=="the"?1:e.match(/few/)?3:e.match(/half/)?.5:e.match(/couple/)?2:e.match(/several/)?7:parseFloat(e)}function xf(r){let e=r.toLowerCase();return fD[e]!==void 0?fD[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}function ka(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 e=parseInt(r);return dE(e)}function ts(r){let e={},t=r,n=_N.exec(t);for(;n;)R8(e,n),t=t.substring(n[0].length).trim(),n=_N.exec(t);return Object.keys(e).length==0?null:e}function R8(r,e){if(e[0].match(/^[a-zA-Z]+$/))return;let t=M8(e[1]),n=gv[e[2].toLowerCase()];r[n]=t}var pE,mD,Li,pD,fD,kN,gv,AN,Ef,Kc,DN,_N,O8,IN,$l,Qc,$r=k(()=>{Pl();Cf();pE={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},mD={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},Li={...mD,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},pD={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},fD={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},kN={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"},gv={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",...kN},AN=`(?:${pn(pD)}|[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)?)`;Ef=`(?:${pn(fD)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;Kc="(?:[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)))";DN=`(${AN})\\s{0,3}(${pn(gv)})`,_N=new RegExp(DN,"i"),O8=`(${AN})\\s{0,3}(${pn(kN)})`,IN="\\s{0,5},?(?:\\s*and)?\\s{0,5}",$l=dD("(?:(?:about|around)\\s{0,3})?",DN,IN),Qc=dD("(?:(?:about|around)\\s{0,3})?",O8,IN)});var Ft,gi=k(()=>{Ft=class{constructor(){pe(this,"cachedInnerPattern",null);pe(this,"cachedPattern",null)}innerPatternHasChange(e,t){return this.innerPattern(e)!==t}patternLeftBoundary(){return"(\\W|^)"}pattern(e){return this.cachedInnerPattern&&!this.innerPatternHasChange(e,this.cachedInnerPattern)?this.cachedPattern:(this.cachedInnerPattern=this.innerPattern(e),this.cachedPattern=new RegExp(`${this.patternLeftBoundary()}${this.cachedInnerPattern.source}`,this.cachedInnerPattern.flags),this.cachedPattern)}extract(e,t){let n=t[1]??"";t.index=t.index+n.length,t[0]=t[0].substring(n.length);for(let i=2;i<t.length;i++)t[i-1]=t[i];return this.innerExtract(e,t)}}});var L8,N8,B8,vv,FN=k(()=>{$r();Us();gi();L8=new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${$l})(?=\\W|$)`,"i"),N8=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${$l})(?=\\W|$)`,"i"),B8=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Qc})(?=\\W|$)`,"i"),vv=class extends Ft{constructor(t){super();pe(this,"strictMode");this.strictMode=t}innerPattern(t){return this.strictMode?B8:t.option.forwardDate?L8:N8}innerExtract(t,n){if(n[0].match(/^for\s*the\s*\w+/))return null;let i=ts(n[1]);return i?Ct.createRelativeFromReference(t.reference,i):null}}});var V8,PN,$N,q8,MN,yv,ON=k(()=>{Cf();$r();$r();$r();Pl();gi();V8=new RegExp(`(?:on\\s{0,3})?(${Ef})(?:\\s{0,3}(?:to|\\-|\\\u2013|until|through|till)\\s{0,3}(${Ef}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${pn(Li)})(?:(?:-|/|,?\\s{0,3})(${Kc}(?!\\w)))?(?=\\W|$)`,"i"),PN=1,$N=2,q8=3,MN=4,yv=class extends Ft{innerPattern(){return V8}innerExtract(e,t){let n=e.createParsingResult(t.index,t[0]),i=Li[t[q8].toLowerCase()],o=xf(t[PN]);if(o>31)return t.index=t.index+t[PN].length,null;if(n.start.assign("month",i),n.start.assign("day",o),t[MN]){let s=ka(t[MN]);n.start.assign("year",s)}else{let s=Yc(e.refDate,o,i);n.start.imply("year",s)}if(t[$N]){let s=xf(t[$N]);n.end=n.start.clone(),n.end.assign("day",s)}return n}}});var U8,z8,RN,hD,gD,bv,LN=k(()=>{Cf();$r();$r();$r();Pl();gi();U8=new RegExp(`(${pn(Li)})(?:-|/|\\s*,?\\s*)(${Ef})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${Ef})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${Kc}))?(?=\\W|$)(?!\\:\\d)`,"i"),z8=1,RN=2,hD=3,gD=4,bv=class extends Ft{constructor(t){super();pe(this,"shouldSkipYearLikeDate");this.shouldSkipYearLikeDate=t}innerPattern(){return U8}innerExtract(t,n){let i=Li[n[z8].toLowerCase()],o=xf(n[RN]);if(o>31||this.shouldSkipYearLikeDate&&!n[hD]&&!n[gD]&&n[RN].match(/^\d{2}$/))return null;let s=t.createParsingComponents({day:o,month:i}).addTag("parser/ENMonthNameMiddleEndianParser");if(n[gD]){let c=ka(n[gD]);s.assign("year",c)}else{let c=Yc(t.refDate,o,i);s.imply("year",c)}if(!n[hD])return s;let a=xf(n[hD]),l=t.createParsingResult(n.index,n[0]);return l.start=s,l.end=s.clone(),l.end.assign("day",a),l}}});var H8,W8,j8,NN,wv,BN=k(()=>{$r();Cf();Pl();$r();gi();H8=new RegExp(`((?:in)\\s*)?(${pn(Li)})\\s*(?:(?:,|-|of)?\\s*(${Kc})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),W8=1,j8=2,NN=3,wv=class extends Ft{innerPattern(){return H8}innerExtract(e,t){let n=t[j8].toLowerCase();if(t[0].length<=3&&!mD[n])return null;let i=e.createParsingResult(t.index+(t[W8]||"").length,t.index+t[0].length);i.start.imply("day",1),i.start.addTag("parser/ENMonthNameParser");let o=Li[n];if(i.start.assign("month",o),t[NN]){let s=ka(t[NN]);i.start.assign("year",s)}else{let s=Yc(e.refDate,1,o);i.start.imply("year",s)}return i}}});var G8,Y8,K8,VN,Q8,Cv,qN=k(()=>{$r();Pl();gi();G8=new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${pn(Li)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),Y8=1,K8=2,VN=3,Q8=4,Cv=class extends Ft{constructor(t){super();pe(this,"strictMonthDateOrder");this.strictMonthDateOrder=t}innerPattern(){return G8}innerExtract(t,n){let i=parseInt(n[Y8]),o=parseInt(n[Q8]),s=n[VN]?parseInt(n[VN]):Li[n[K8].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 X8,Z8,J8,e5,Ev,UN=k(()=>{$r();Pl();$r();gi();X8="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-9][0-9]{3})",Z8=new RegExp(`(${X8})(?:\\s*[-.\\/,]?\\s*|\\s+of\\s+)(${pn(Li)})(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),J8=1,e5=2,Ev=class extends Ft{innerPattern(){return Z8}innerExtract(e,t){let n=ka(t[J8]),i=t[e5].toLowerCase(),o=Li[i],s=e.createParsingResult(t.index,t[0]);return s.start.imply("day",1),s.start.assign("month",o),s.start.assign("year",n),s.start.addTag("parser/ENYearMonthNameParser"),s}}});var t5,r5,n5,xv,zN=k(()=>{gi();t5=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),r5=1,n5=2,xv=class extends Ft{innerPattern(){return t5}innerExtract(e,t){let n=parseInt(t[n5]),i=parseInt(t[r5]);return e.createParsingComponents().imply("day",1).assign("month",i).assign("year",n)}}});function i5(r,e,t,n){return new RegExp(`${r}${e}(\\d{1,4})(?:(?:\\.|:|\uFF1A)(\\d{1,2})(?:(?::|\uFF1A)(\\d{2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${t}`,n)}function o5(r,e){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?))?${e}`,"i")}var vD,_d,fE,mE,Tf,hE,HN=k(()=>{Al();vD=2,_d=3,fE=4,mE=5,Tf=6,hE=class{constructor(e=!1){pe(this,"strictMode");pe(this,"cachedPrimaryPrefix",null);pe(this,"cachedPrimarySuffix",null);pe(this,"cachedPrimaryTimePattern",null);pe(this,"cachedFollowingPhase",null);pe(this,"cachedFollowingSuffix",null);pe(this,"cachedFollowingTimePatten",null);this.strictMode=e}patternFlags(){return"i"}primaryPatternLeftBoundary(){return"(^|\\s|T|\\b)"}primarySuffix(){return"(?!/)(?=\\W|$)"}followingSuffix(){return"(?!/)(?=\\W|$)"}pattern(e){return this.getPrimaryTimePatternThroughCache()}extract(e,t){let n=this.extractPrimaryTimeComponents(e,t);if(!n)return t[0].match(/^\d{4}/)?(t.index+=4,null):(t.index+=t[0].length,null);let i=t.index+t[1].length,o=t[0].substring(t[1].length),s=e.createParsingResult(i,o,n);t.index+=t[0].length;let a=e.text.substring(t.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(e,c,s),s.end&&(s.text+=c[0]),this.checkAndReturnWithFollowingPattern(s))}extractPrimaryTimeComponents(e,t,n=!1){let i=e.createParsingComponents(),o=0,s=null,a=parseInt(t[vD]);if(a>100){if(t[vD].length==4&&t[_d]==null&&!t[Tf]||this.strictMode||t[_d]!=null)return null;o=a%100,a=Math.floor(a/100)}if(a>24)return null;if(t[_d]!=null){if(t[_d].length==1&&!t[Tf])return null;o=parseInt(t[_d])}if(o>=60)return null;if(a>12&&(s=vt.PM),t[Tf]!=null){if(a>12)return null;let l=t[Tf][0].toLowerCase();l=="a"&&(s=vt.AM,a==12&&(a=0)),l=="p"&&(s=vt.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",vt.AM):i.imply("meridiem",vt.PM),t[mE]!=null){let l=parseInt(t[mE].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(t[fE]!=null){let l=parseInt(t[fE]);if(l>=60)return null;i.assign("second",l)}return i}extractFollowingTimeComponents(e,t,n){let i=e.createParsingComponents();if(t[mE]!=null){let l=parseInt(t[mE].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(t[fE]!=null){let l=parseInt(t[fE]);if(l>=60)return null;i.assign("second",l)}let o=parseInt(t[vD]),s=0,a=-1;if(t[_d]!=null?s=parseInt(t[_d]):o>100&&(s=o%100,o=Math.floor(o/100)),s>=60||o>24)return null;if(o>=12&&(a=vt.PM),t[Tf]!=null){if(o>12)return null;let l=t[Tf][0].toLowerCase();l=="a"&&(a=vt.AM,o==12&&(o=0,i.isCertain("day")||i.imply("day",i.get("day")+1))),l=="p"&&(a=vt.PM,o!=12&&(o+=12)),n.start.isCertain("meridiem")||(a==vt.AM?(n.start.imply("meridiem",vt.AM),n.start.get("hour")==12&&n.start.assign("hour",0)):(n.start.imply("meridiem",vt.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",vt.AM):o<=12&&(i.assign("hour",o+12),i.assign("meridiem",vt.PM)):o>12?i.imply("meridiem",vt.PM):o<=12&&i.imply("meridiem",vt.AM),i.date().getTime()<n.start.date().getTime()&&i.imply("day",i.get("day")+1),i}checkAndReturnWithoutFollowingPattern(e){if(e.text.match(/^\d$/)||e.text.match(/^\d\d\d+$/)||e.text.match(/\d[apAP]$/))return null;let t=e.text.match(/[^\d:.](\d[\d.]+)$/);if(t){let n=t[1];if(this.strictMode||n.includes(".")&&!n.match(/\d(\.\d{2})+$/)||parseInt(n)>24)return null}return e}checkAndReturnWithFollowingPattern(e){if(e.text.match(/^\d+-\d+$/))return null;let t=e.text.match(/[^\d:.](\d[\d.]+)\s*-\s*(\d[\d.]+)$/);if(t){if(this.strictMode)return null;let n=t[1],i=t[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 e}getPrimaryTimePatternThroughCache(){let e=this.primaryPrefix(),t=this.primarySuffix();return this.cachedPrimaryPrefix===e&&this.cachedPrimarySuffix===t?this.cachedPrimaryTimePattern:(this.cachedPrimaryTimePattern=i5(this.primaryPatternLeftBoundary(),e,t,this.patternFlags()),this.cachedPrimaryPrefix=e,this.cachedPrimarySuffix=t,this.cachedPrimaryTimePattern)}getFollowingTimePatternThroughCache(){let e=this.followingPhase(),t=this.followingSuffix();return this.cachedFollowingPhase===e&&this.cachedFollowingSuffix===t?this.cachedFollowingTimePatten:(this.cachedFollowingTimePatten=o5(e,t),this.cachedFollowingPhase=e,this.cachedFollowingSuffix=t,this.cachedFollowingTimePatten)}}});var Tv,WN=k(()=>{Al();HN();Tv=class extends hE{constructor(e){super(e)}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(e,t){let n=super.extractPrimaryTimeComponents(e,t);if(!n)return n;if(t[0].endsWith("night")){let i=n.get("hour");i>=6&&i<12?(n.assign("hour",n.get("hour")+12),n.assign("meridiem",vt.PM)):i<6&&n.assign("meridiem",vt.AM)}if(t[0].endsWith("afternoon")){n.assign("meridiem",vt.PM);let i=n.get("hour");i>=0&&i<=6&&n.assign("hour",n.get("hour")+12)}return t[0].endsWith("morning")&&(n.assign("meridiem",vt.AM),n.get("hour")<12&&n.assign("hour",n.get("hour"))),n.addTag("parser/ENTimeExpressionParser")}extractFollowingTimeComponents(e,t,n){let i=super.extractFollowingTimeComponents(e,t,n);return i&&i.addTag("parser/ENTimeExpressionParser"),i}}});var s5,a5,Sv,jN=k(()=>{$r();Us();gi();Il();s5=new RegExp(`(${$l})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),a5=new RegExp(`(${Qc})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),Sv=class extends Ft{constructor(t){super();pe(this,"strictMode");this.strictMode=t}innerPattern(){return this.strictMode?a5:s5}innerExtract(t,n){let i=ts(n[1]);return i?Ct.createRelativeFromReference(t.reference,jc(i)):null}}});var l5,c5,u5,_v,GN=k(()=>{$r();Us();gi();l5=new RegExp(`(${$l})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`,"i"),c5=new RegExp(`(${Qc})\\s{0,5}(later|after|from now)(?=\\W|$)`,"i"),u5=1,_v=class extends Ft{constructor(t){super();pe(this,"strictMode");this.strictMode=t}innerPattern(){return this.strictMode?c5:l5}innerExtract(t,n){let i=ts(n[u5]);return i?Ct.createRelativeFromReference(t.reference,i):null}}});var Sf,rs,Xc=k(()=>{Sf=class{refine(e,t){return t.filter(n=>this.isValid(e,n))}},rs=class{refine(e,t){if(t.length<2)return t;let n=[],i=t[0],o=null;for(let s=1;s<t.length;s++){o=t[s];let a=e.text.substring(i.index+i.text.length,o.index);if(!this.shouldMergeResults(a,i,o,e))n.push(i),i=o;else{let l=i,c=o,u=this.mergeResults(a,l,c,e);e.debug(()=>{console.log(`${this.constructor.name} merged ${l} and ${c} into ${u}`)}),i=u}}return i!=null&&n.push(i),n}}});var kv,YN=k(()=>{Xc();Il();kv=class extends rs{shouldMergeResults(e,t,n){return!t.end&&!n.end&&e.match(this.patternBetween())!=null}mergeResults(e,t,n){if(!t.start.isOnlyWeekdayComponent()&&!n.start.isOnlyWeekdayComponent()&&(n.start.getCertainComponents().forEach(o=>{t.start.isCertain(o)||t.start.imply(o,n.start.get(o))}),t.start.getCertainComponents().forEach(o=>{n.start.isCertain(o)||n.start.imply(o,t.start.get(o))})),t.start.date()>n.start.date()){let o=t.start.date(),s=n.start.date();n.start.isOnlyWeekdayComponent()&&Dn(s,{day:7})>o?(s=Dn(s,{day:7}),n.start.imply("day",s.getDate()),n.start.imply("month",s.getMonth()+1),n.start.imply("year",s.getFullYear())):t.start.isOnlyWeekdayComponent()&&Dn(o,{day:-7})<s?(o=Dn(o,{day:-7}),t.start.imply("day",o.getDate()),t.start.imply("month",o.getMonth()+1),t.start.imply("year",o.getFullYear())):n.start.isDateWithUnknownYear()&&Dn(s,{year:1})>o?(s=Dn(s,{year:1}),n.start.imply("year",s.getFullYear())):t.start.isDateWithUnknownYear()&&Dn(o,{year:-1})<s?(o=Dn(o,{year:-1}),t.start.imply("year",o.getFullYear())):[n,t]=[t,n]}let i=t.clone();return i.start=t.start,i.end=n.start,i.index=Math.min(t.index,n.index),t.index<n.index?i.text=t.text+e+n.text:i.text=n.text+e+t.text,i}}});var Av,KN=k(()=>{YN();Av=class extends kv{patternBetween(){return/^\s*(to|-|–|until|through|till)\s*$/i}}});function yD(r,e){let t=r.clone(),n=r.start,i=e.start;if(t.start=QN(n,i),r.end!=null||e.end!=null){let o=r.end==null?r.start:r.end,s=e.end==null?e.start:e.end,a=QN(o,s);if(r.end==null&&a.date().getTime()<t.start.date().getTime()){let l=new Date(a.date().getTime());l.setDate(l.getDate()+1),a.isCertain("day")?qs(a,l):Dl(a,l)}t.end=a}return t}function QN(r,e){let t=r.clone();e.isCertain("hour")?(t.assign("hour",e.get("hour")),t.assign("minute",e.get("minute")),e.isCertain("second")?(t.assign("second",e.get("second")),e.isCertain("millisecond")?t.assign("millisecond",e.get("millisecond")):t.imply("millisecond",e.get("millisecond"))):(t.imply("second",e.get("second")),t.imply("millisecond",e.get("millisecond")))):(t.imply("hour",e.get("hour")),t.imply("minute",e.get("minute")),t.imply("second",e.get("second")),t.imply("millisecond",e.get("millisecond"))),e.isCertain("timezoneOffset")&&t.assign("timezoneOffset",e.get("timezoneOffset"));let n=r.get("meridiem")!=null&&(r.isCertain("meridiem")||Array.from(r.tags()).some(i=>i.startsWith("casualReference/")));return e.isCertain("meridiem")?t.assign("meridiem",e.get("meridiem")):e.get("meridiem")!=null&&!n&&t.imply("meridiem",e.get("meridiem")),t.get("meridiem")==vt.PM&&t.get("hour")<12&&(e.isCertain("hour")?t.assign("hour",t.get("hour")+12):t.imply("hour",t.get("hour")+12)),t.addTags(r.tags()),t.addTags(e.tags()),t}var XN=k(()=>{Al();Sd()});var Dv,ZN=k(()=>{Xc();XN();Dv=class extends rs{shouldMergeResults(e,t,n){return(t.start.isOnlyDate()&&n.start.isOnlyTime()||n.start.isOnlyDate()&&t.start.isOnlyTime())&&e.match(this.patternBetween())!=null}mergeResults(e,t,n){let i=t.start.isOnlyDate()?yD(t,n):yD(n,t);return i.index=t.index,i.text=t.text+e+n.text,i}}});var _f,JN=k(()=>{ZN();_f=class extends Dv{patternBetween(){return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|\u2219|:)?\\s*$")}}});var d5,Iv,e1=k(()=>{uD();d5=new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)","i"),Iv=class{constructor(e){pe(this,"timezoneOverrides");this.timezoneOverrides=e}refine(e,t){let n=e.option.timezones??{};return t.forEach(i=>{let o=e.text.substring(i.index+i.text.length),s=d5.exec(o);if(!s)return;let a=s[1].toUpperCase(),l=i.start.date()??i.refDate??new Date,c={...this.timezoneOverrides,...n},u=uE(a,l,c);if(u==null)return;e.debug(()=>{console.log(`Extracting timezone: '${a}' into: ${u} for: ${i.start}`)});let d=i.start.get("timezoneOffset");d!==null&&u!=d&&(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",u),i.end!=null&&!i.end.isCertain("timezoneOffset")&&i.end.assign("timezoneOffset",u))}),t}}});var p5,f5,m5,h5,Fv,t1=k(()=>{p5=new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?","i"),f5=1,m5=2,h5=3,Fv=class{refine(e,t){return t.forEach(function(n){if(n.start.isCertain("timezoneOffset"))return;let i=e.text.substring(n.index+n.text.length),o=p5.exec(i);if(!o)return;e.debug(()=>{console.log(`Extracting timezone: '${o[0]}' into : ${n}`)});let s=parseInt(o[m5]),a=parseInt(o[h5]||"0"),l=s*60+a;l>840||(o[f5]==="-"&&(l=-l),n.end!=null&&n.end.assign("timezoneOffset",l),n.start.assign("timezoneOffset",l),n.text+=o[0])}),t}}});var Zc,bD=k(()=>{Zc=class{refine(e,t){if(t.length<2)return t;let n=[],i=t[0];for(let o=1;o<t.length;o++){let s=t[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),e.debug(()=>{console.log(`${this.constructor.name} remove ${l} by ${a}`)}),i=a}return i!=null&&n.push(i),n}}});function r1(r,e,t){let n=r.getDateWithAdjustedTimezone(),i=g5(n,e,t),o=new Ct(r);return o=o.addDurationAsImplied({day:i}),o.assign("weekday",e),o}function g5(r,e,t){let n=r.getDay();switch(t){case"this":return kd(r,e);case"last":return n1(r,e);case"next":return n==Zt.SUNDAY?e==Zt.SUNDAY?7:e:n==Zt.SATURDAY?e==Zt.SATURDAY?7:e==Zt.SUNDAY?8:1+e:e<n&&e!=Zt.SUNDAY?kd(r,e):kd(r,e)+7}return v5(r,e)}function v5(r,e){let t=n1(r,e),n=kd(r,e);return n<-t?n:t}function kd(r,e){let t=r.getDay(),n=e-t;return n<0&&(n+=7),n}function n1(r,e){let t=r.getDay(),n=e-t;return n>=0&&(n-=7),n}var wD=k(()=>{Al();Us()});var Pv,i1=k(()=>{Sd();Sd();Il();wD();Pv=class{refine(e,t){return e.option.forwardDate&&t.forEach(n=>{let i=e.reference.getDateWithAdjustedTimezone();if(n.start.isOnlyTime()&&e.reference.instant>n.start.date()){let o=e.reference.getDateWithAdjustedTimezone(),s=new Date(o);s.setDate(s.getDate()+1),Dl(n.start,s),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} time from the ref date (${o}) to the following day (${s})`)}),n.end&&n.end.isOnlyTime()&&(Dl(n.end,s),n.start.date()>n.end.date()&&(s.setDate(s.getDate()+1),Dl(n.end,s)))}if(n.start.isOnlyWeekdayComponent()&&i>n.start.date()){let o=kd(i,n.start.get("weekday"))||7,s=Dn(i,{day:o});if(Dl(n.start,s),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} weekday (${n.start})`)}),n.end&&n.start.date()>n.end.date()){let a=kd(i,n.start.get("weekday"))||7,l=Dn(i,{day:a});Dl(n.end,l),e.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),e.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),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} month (${n.start})`)}))}),t}}});var $v,o1=k(()=>{Xc();$v=class extends Sf{constructor(t){super();pe(this,"strictMode");this.strictMode=t}isValid(t,n){return n.text.replace(" ","").match(/^\d*(\.\d*)?$/)?(t.debug(()=>{console.log(`Removing unlikely result '${n.text}'`)}),!1):n.start.isValidDate()?n.end&&!n.end.isValidDate()?(t.debug(()=>{console.log(`Removing invalid result: ${n} (${n.end})`)}),!1):this.strictMode?this.isStrictModeValid(t,n):!0:(t.debug(()=>{console.log(`Removing invalid result: ${n} (${n.start})`)}),!1)}isStrictModeValid(t,n){return n.start.isOnlyWeekdayComponent()?(t.debug(()=>{console.log(`(Strict) Removing weekday only component: ${n} (${n.end})`)}),!1):!0}}});var y5,b5,w5,C5,s1,E5,a1,l1,x5,c1,u1,Mv,d1=k(()=>{gi();y5=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"),b5=1,w5=2,C5=3,s1=4,E5=5,a1=6,l1=7,x5=8,c1=9,u1=10,Mv=class extends Ft{innerPattern(){return y5}innerExtract(e,t){let n=e.createParsingComponents({year:parseInt(t[b5]),month:parseInt(t[w5]),day:parseInt(t[C5])});if(t[s1]!=null&&(n.assign("hour",parseInt(t[s1])),n.assign("minute",parseInt(t[E5])),t[a1]!=null&&n.assign("second",parseInt(t[a1])),t[l1]!=null&&n.assign("millisecond",parseInt(t[l1])),t[x5]!=null)){let i=0;if(t[c1]){let o=parseInt(t[c1]),s=0;t[u1]!=null&&(s=parseInt(t[u1])),i=o*60,i<0?i-=s:i+=s}n.assign("timezoneOffset",i)}return n.addTag("parser/ISOFormatParser")}}});var Ov,p1=k(()=>{Xc();Ov=class extends rs{mergeResults(e,t,n){let i=n.clone();return i.index=t.index,i.text=t.text+e+i.text,i.start.assign("weekday",t.start.get("weekday")),i.end&&i.end.assign("weekday",t.start.get("weekday")),i}shouldMergeResults(e,t,n){return t.start.isOnlyWeekdayComponent()&&!t.start.isCertain("hour")&&n.start.isCertain("day")&&e.match(/^,?\s*$/)!=null}}});function f1(r,e=!1){return r.parsers.unshift(new Mv),r.refiners.unshift(new Ov),r.refiners.unshift(new Fv),r.refiners.unshift(new Zc),r.refiners.push(new Iv),r.refiners.push(new Zc),r.refiners.push(new Pv),r.refiners.push(new $v(e)),r}var m1=k(()=>{e1();t1();bD();i1();o1();d1();p1()});function h1(r){let e=r.getDateWithAdjustedTimezone(),t=new Ct(r,{});return qs(t,e),cE(t,e),t.assign("timezoneOffset",r.getTimezoneOffset()),t.addTag("casualReference/now"),t}function g1(r){let e=r.getDateWithAdjustedTimezone(),t=new Ct(r,{});return qs(t,e),hv(t,e),t.delete("meridiem"),t.addTag("casualReference/today"),t}function v1(r){return T5(r,1).addTag("casualReference/yesterday")}function y1(r){return gE(r,1).addTag("casualReference/tomorrow")}function T5(r,e){return gE(r,-e)}function gE(r,e){let t=r.getDateWithAdjustedTimezone(),n=new Ct(r,{}),i=new Date(t.getTime());return i.setDate(i.getDate()+e),qs(n,i),hv(n,i),n.delete("meridiem"),n}function b1(r,e=22){let t=r.getDateWithAdjustedTimezone(),n=new Ct(r,{});return qs(n,t),n.imply("hour",e),n.imply("meridiem",vt.PM),n.addTag("casualReference/tonight"),n}function w1(r,e=20){let t=new Ct(r,{});return t.imply("meridiem",vt.PM),t.imply("hour",e),t.addTag("casualReference/evening"),t}function C1(r){let e=new Ct(r,{});return r.getDateWithAdjustedTimezone().getHours()>2&&e.addDurationAsImplied({day:1}),e.assign("hour",0),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/midnight"),e}function E1(r,e=6){let t=new Ct(r,{});return t.imply("meridiem",vt.AM),t.imply("hour",e),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/morning"),t}function x1(r,e=15){let t=new Ct(r,{});return t.imply("meridiem",vt.PM),t.imply("hour",e),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/afternoon"),t}function T1(r){let e=new Ct(r,{});return e.imply("meridiem",vt.AM),e.assign("hour",12),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/noon"),e}var CD=k(()=>{Us();Sd();Al()});var S5,Rv,_1=k(()=>{gi();Sd();CD();S5=/(now|today|tonight|tomorrow|overmorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i,Rv=class extends Ft{innerPattern(e){return S5}innerExtract(e,t){let n=e.refDate,i=t[0].toLowerCase(),o=e.createParsingComponents();switch(i){case"now":o=h1(e.reference);break;case"today":o=g1(e.reference);break;case"yesterday":o=v1(e.reference);break;case"tomorrow":case"tmr":case"tmrw":o=y1(e.reference);break;case"tonight":o=b1(e.reference);break;case"overmorrow":o=gE(e.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}qs(o,n),o.imply("hour",0)}break}return o.addTag("parser/ENCasualDateParser"),o}}});var _5,Lv,k1=k(()=>{gi();CD();_5=/(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i,Lv=class extends Ft{innerPattern(){return _5}innerExtract(e,t){let n=null;switch(t[1].toLowerCase()){case"afternoon":n=x1(e.reference);break;case"evening":case"night":n=w1(e.reference);break;case"midnight":n=C1(e.reference);break;case"morning":n=E1(e.reference);break;case"noon":case"midday":n=T1(e.reference);break}return n&&n.addTag("parser/ENCasualTimeParser"),n}}});var k5,A5,D5,I5,Nv,A1=k(()=>{$r();Pl();gi();wD();Al();k5=new RegExp(`(?:(?:\\,|\\(|\\\uFF08)\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${pn(pE)}|weekend|weekday)(?:\\s*(?:\\,|\\)|\\\uFF09))?(?:\\s*(?:of\\s*)?(this|last|past|next)\\s*week)?(?=\\W|$)`,"i"),A5=1,D5=2,I5=3,Nv=class extends Ft{innerPattern(){return k5}innerExtract(e,t){let n=t[A5],i=t[I5],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=t[D5].toLowerCase(),l;if(pE[a]!==void 0)l=pE[a];else if(a=="weekend")l=s=="last"?Zt.SUNDAY:Zt.SATURDAY;else if(a=="weekday"){let c=e.reference.getDateWithAdjustedTimezone().getDay();c==Zt.SUNDAY||c==Zt.SATURDAY?l=s=="last"?Zt.FRIDAY:Zt.MONDAY:(l=c-1,l=s=="last"?l-1:l+1,l=l%5+1)}else return null;return r1(e.reference,l,s)}}});var F5,P5,$5,Bv,D1=k(()=>{$r();Us();gi();Pl();F5=new RegExp(`(this|last|past|next|after\\s*this)\\s*(${pn(gv)})(?=\\s*)(?=\\W|$)`,"i"),P5=1,$5=2,Bv=class extends Ft{innerPattern(){return F5}innerExtract(e,t){let n=t[P5].toLowerCase(),i=t[$5].toLowerCase(),o=gv[i];if(n=="next"||n.startsWith("after")){let l={};return l[o]=1,Ct.createRelativeFromReference(e.reference,l)}if(n=="last"||n=="past"){let l={};return l[o]=-1,Ct.createRelativeFromReference(e.reference,l)}let s=e.createParsingComponents(),a=new Date(e.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 M5,O5,R5,I1,F1,ED,Vv,P1=k(()=>{Cf();M5=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"),O5=1,R5=5,I1=2,F1=3,ED=4,Vv=class{constructor(e){pe(this,"groupNumberMonth");pe(this,"groupNumberDay");this.groupNumberMonth=e?F1:I1,this.groupNumberDay=e?I1:F1}pattern(){return M5}extract(e,t){let n=t.index+t[O5].length,i=t.index+t[0].length-t[R5].length;if(n>0&&e.text.substring(0,n).match("\\d/?$")||i<e.text.length&&e.text.substring(i).match("^/?\\d"))return;let o=e.text.substring(n,i);if(o.match(/^\d\.\d$/)||o.match(/^\d\.\d{1,2}\.\d{1,2}\s*$/)||!t[ED]&&o.indexOf("/")<0)return;let s=e.createParsingResult(n,o),a=parseInt(t[this.groupNumberMonth]),l=parseInt(t[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),t[ED]){let c=parseInt(t[ED]),u=dE(c);s.start.assign("year",u)}else{let c=Yc(e.refDate,l,a);s.start.imply("year",c)}return s.addTag("parser/SlashDateFormatParser")}}});var L5,N5,qv,$1=k(()=>{$r();Us();gi();Il();L5=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${$l})(?=\\W|$)`,"i"),N5=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${Qc})(?=\\W|$)`,"i"),qv=class extends Ft{constructor(t=!0){super();pe(this,"allowAbbreviations");this.allowAbbreviations=t}innerPattern(){return this.allowAbbreviations?L5:N5}innerExtract(t,n){let i=n[1].toLowerCase(),o=ts(n[2]);if(!o)return null;switch(i){case"last":case"past":case"-":o=jc(o);break}return Ct.createRelativeFromReference(t.reference,o)}}});function B5(r){return r.text.match(/^[+-]/i)!=null}function M1(r){return r.text.match(/^-/i)!=null}var Uv,O1=k(()=>{Xc();Us();$r();Il();Uv=class extends rs{shouldMergeResults(e,t,n){return e.match(/^\s*$/i)?B5(n)||M1(n):!1}mergeResults(e,t,n,i){let o=ts(n.text);M1(n)&&(o=jc(o));let s=Ct.createRelativeFromReference(Gc.fromDate(t.start.date()),o);return new Fl(t.reference,t.index,`${t.text}${e}${n.text}`,s)}}});function R1(r){return r.text.match(/\s+(before|from)$/i)!=null}function V5(r){return r.text.match(/\s+(after|since)$/i)!=null}var zv,L1=k(()=>{Xc();Us();$r();Il();zv=class extends rs{patternBetween(){return/^\s*$/i}shouldMergeResults(e,t,n){return!e.match(this.patternBetween())||!R1(t)&&!V5(t)?!1:!!n.start.get("day")&&!!n.start.get("month")&&!!n.start.get("year")}mergeResults(e,t,n){let i=ts(t.text);R1(t)&&(i=jc(i));let o=Ct.createRelativeFromReference(Gc.fromDate(n.start.date()),i);return new Fl(n.reference,t.index,`${t.text}${e}${n.text}`,o)}}});var q5,U5,Hv,N1=k(()=>{$r();q5=new RegExp(`^\\s*(${Kc})`,"i"),U5=1,Hv=class{refine(e,t){return t.forEach(function(n){if(!n.start.isDateWithUnknownYear())return;let i=e.text.substring(n.index+n.text.length),o=q5.exec(i);if(!o||o[0].trim().length<=3)return;e.debug(()=>{console.log(`Extracting year: '${o[0]}' into : ${n}`)});let s=ka(o[U5]);n.end!=null&&n.end.assign("year",s),n.start.assign("year",s),n.text+=o[0]}),t}}});var Wv,B1=k(()=>{Xc();Wv=class extends Sf{constructor(){super()}isValid(e,t){let n=t.text.trim();return n===e.text.trim()?!0:n.toLowerCase()==="may"&&!e.text.substring(0,t.index).trim().match(/\b(in)$/i)?(e.debug(()=>{console.log(`Removing unlikely result: ${t}`)}),!1):n.toLowerCase().endsWith("the second")?(e.text.substring(t.index+t.text.length).trim().length>0&&e.debug(()=>{console.log(`Removing unlikely result: ${t}`)}),!1):!0}}});var Ad,xD=k(()=>{FN();ON();LN();BN();qN();UN();zN();WN();jN();GN();KN();JN();m1();_1();k1();A1();D1();P1();$1();O1();L1();bD();N1();B1();Ad=class{createCasualConfiguration(e=!1){let t=this.createConfiguration(!1,e);return t.parsers.push(new Rv),t.parsers.push(new Lv),t.parsers.push(new wv),t.parsers.push(new Bv),t.parsers.push(new qv),t.refiners.push(new Wv),t}createConfiguration(e=!0,t=!1){let n=f1({parsers:[new Vv(t),new vv(e),new yv,new bv(t),new Nv,new xv,new Tv(e),new Sv(e),new _v(e),new Ev],refiners:[new _f]},e);return n.parsers.unshift(new Cv(e)),n.refiners.unshift(new zv),n.refiners.unshift(new Uv),n.refiners.unshift(new Zc),n.refiners.push(new _f),n.refiners.push(new Hv),n.refiners.push(new Av),n}}});var kf,TD,V1=k(()=>{Us();xD();kf=class r{constructor(e){pe(this,"parsers");pe(this,"refiners");pe(this,"defaultConfig",new Ad);e=e||this.defaultConfig.createCasualConfiguration(),this.parsers=[...e.parsers],this.refiners=[...e.refiners]}clone(){return new r({parsers:[...this.parsers],refiners:[...this.refiners]})}parseDate(e,t,n){let i=this.parse(e,t,n);return i.length>0?i[0].start.date():null}parse(e,t,n){let i=new TD(e,t,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(e,t){let n=[],i=t.pattern(e),o=e.text,s=e.text,a=i.exec(s);for(;a;){let l=a.index+o.length-s.length;a.index=l;let c=t.extract(e,a);if(!c){s=o.substring(a.index+1),a=i.exec(s);continue}let u=null;c instanceof Fl?u=c:c instanceof Ct?(u=e.createParsingResult(a.index,a[0]),u.start=c):u=e.createParsingResult(a.index,a[0],c);let d=u.index,f=u.text;e.debug(()=>console.log(`${t.constructor.name} extracted (at index=${d}) '${f}'`)),n.push(u),s=o.substring(d+f.length),a=i.exec(s)}return n}},TD=class{constructor(e,t,n){pe(this,"text");pe(this,"option");pe(this,"reference");pe(this,"refDate");this.text=e,this.option=n??{},this.reference=Gc.fromInput(t,this.option.timezones),this.refDate=this.reference.instant}createParsingComponents(e){return e instanceof Ct?e:new Ct(this.reference,e)}createParsingResult(e,t,n,i){let o=typeof t=="string"?t:this.text.substring(e,t),s=n?this.createParsingComponents(n):null,a=i?this.createParsingComponents(i):null;return new Fl(this.reference,e,o,s,a)}debug(e){this.option.debug&&(this.option.debug instanceof Function?this.option.debug(e):this.option.debug.debug(e))}}});var SD,q1,z5,u$e,U1=k(()=>{V1();xD();SD=new Ad,q1=new kf(SD.createCasualConfiguration(!1)),z5=new kf(SD.createConfiguration(!0,!1)),u$e=new kf(SD.createCasualConfiguration(!0))});function z1(r,e,t){return W5.parseDate(r,e,t)}var W5,H1=k(()=>{U1();W5=q1});function K5(r){return!G5.test(r)}var G5,Y5,_D,ns,Dd=k(()=>{H1();G5=/\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,Y5=/\bprevious\b/gi;_D=class{getParsedDate(e,t=new Date){let n=e.replace(Y5,"last");return z1(n,t,{forwardDate:K5(n)})}parseDate(e){if(!e||!e.trim())return null;try{let t=this.getParsedDate(e);return t?window.moment?{moment:window.moment(t)}:(console.warn("Moment.js is not available"),null):null}catch(t){return console.warn("Failed to parse date:",e,t),null}}},ns=new _D});function W1(r){return r<=31||r===127||r===8232||r===8233}function Z5(r){let e="",t=0;for(;t<r.length;){let n=t;for(;n<r.length&&r.charCodeAt(n)===32;)n++;if(n<r.length&&W1(r.charCodeAt(n))){for(;n<r.length&&W1(r.charCodeAt(n));)n++;for(;n<r.length&&r.charCodeAt(n)===32;)n++;e+=" ",t=n;continue}e+=r.slice(t,Math.min(n+1,r.length)),t=n+1}return e}function j1(r,e){let t=r.length;for(;t>0&&e.includes(r[t-1]);)t--;return r.slice(0,t)}function Id(r){return J5.filter(e=>r.includes(e))}function Y1(r){return`A file or folder name cannot contain ${X1(r)}, so this choice would fail at run time. ${Q1}`}function K1(r,e){return`Cannot create "${e}": a file or folder name cannot contain ${X1(r)}. ${Q1}`}function X1(r){return r.map(e=>`"${e}"`).join(", ")}function In(r,e="File path"){let{path:t,problems:n}=J1(r,e);if(n.length>0)throw new Error(n[0]);return t}function Z1(r,e="File path"){return J1(r,e)}function J1(r,e){let t=[],n=r.replace(/\\/g,"/").split("/");return{path:n.map((o,s)=>o.length===0&&s!==0&&s!==n.length-1?(t.push(`${e} contains an empty path segment after formatting.`),o):eK(o,e,t)).join("/"),problems:t}}function eK(r,e,t){if(r.length===0)return r;let n=Q5.test(r),i=X5.test(r),o=Z5(r);n&&(o=o.replace(/^ /u,"")),i&&(o=o.replace(/ $/u,""));let s=j1(o," ");return s==="."||s===".."?(t.push(`${e} cannot contain "." or ".." path segments.`),s):(o=j1(o,". "),o||t.push(`${e} contains an empty path segment after formatting.`),o)}var G1,Q5,X5,J5,Q1,Aa=k(()=>{G1="\0-\x7F\u2028\u2029",Q5=new RegExp(`^ *[${G1}]`,"u"),X5=new RegExp(`[${G1}] *$`,"u");J5=[":"];Q1="Check your own text and tokens like {{TIME}}, which is HH:mm."});function OE(r){return mK.has(r)}function Ol(r){if(!r||r.kind==="now")return"today";if(r.kind==="ask")return"ask";if(r.kind==="variable")return"variable";for(let e of AD)if(r.offset===e.offset&&r.unit===e.unit)return e.id;return"custom"}function RE(r){let{preset:e,previous:t}=r;if(e!=="today"){if(e==="ask")return t?.kind==="ask"?t:n2(Ol(t));if(e==="variable")return t?.kind==="variable"?t:{kind:"variable",name:""};if(e==="custom")return t?.kind==="relative"&&Ol(t)==="custom"?t:{kind:"relative",offset:-2,unit:"days"};for(let n of AD)if(n.id===e)return{kind:"relative",offset:n.offset,unit:n.unit}}}function n2(r){for(let e of ME)if(e.id===r&&e.defaultValue)return{kind:"ask",defaultValue:e.defaultValue};return{kind:"ask"}}function ty(r){let e=(r??"").trim().toLowerCase();for(let t of ME)if(t.aliases.some(n=>n===e))return t.id;return"kept"}function LE(r){let e=ME.map(t=>({value:t.id,label:t.label}));if(ty(r)==="kept"){let t=r?.trim();t&&e.push({value:"kept",label:t})}return e}function NE(r,e){if(r==="kept"){let t=e?.trim();return t||void 0}for(let t of ME)if(t.id===r)return t.defaultValue}function i2(r){return typeof r=="string"&&r.trim().toLowerCase()==="ask"}function $f(r){return r?.kind==="ask"?r:n2(Ol(r))}var fK,kE,AE,DE,IE,Jv,FE,ey,PE,AD,$E,ME,mK,Jc=k(()=>{fK=["today","ask","yesterday","last-week","next-week","last-month","custom","variable"],kE="Which day",AE="The day {{DATE}} writes. The clock stays now. Hold Shift in the QuickAdd menu to pick a different day.",DE="Picker starts on",IE="The date the picker suggests first. You can still pick a different day.",Jv="How far from today",FE="How many days, weeks, months, or years from today. Negative is the past.",ey="Variable name",PE="A VDATE or script value that already has the day.",AD=[{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"}],$E=[{value:"today",label:"Today"},{value:"ask",label:"Ask each time"},...AD.map(r=>({value:r.id,label:r.label})),{value:"custom",label:"Custom\u2026"},{value:"variable",label:"A variable\u2026"}],ME=[{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"]}],mK=new Set(fK)});function $2(r){let e=t=>{t.preventDefault(),t.stopPropagation()};r.addEventListener("pointerdown",e),r.addEventListener("mousedown",e)}function aQ(r){r.forEach(e=>{e.addEventListener("keydown",t=>{if(t.key==="ArrowRight"||t.key==="ArrowLeft"){let i=(r.indexOf(e)+(t.key==="ArrowRight"?1:-1)+r.length)%r.length;r[i].focus(),t.preventDefault()}})})}var dy,vi,Pd=k(()=>{dy=require("obsidian"),vi=class r extends dy.Modal{constructor(t,n,i){super(t);this.header=n;this.text=i;this.input=null;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Ask(t,n,i){return new r(t,n,i).waitForClose}static async Prompt(t,n,i){return await r.Ask(t,n,i)===!0}display(){this.containerEl.addClass("quickAddModal","qaYesNoPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.header,this.contentEl.createEl("p",{text:this.text});let t=this.contentEl.createDiv({cls:"yesNoPromptButtonContainer"}),n=new dy.ButtonComponent(t).setButtonText("No").onClick(()=>this.submit(!1));$2(n.buttonEl);let i=new dy.ButtonComponent(t).setButtonText("Yes").onClick(()=>this.submit(!0)).setDestructive();$2(i.buttonEl),i.buttonEl.focus(),aQ([n.buttonEl,i.buttonEl])}submit(t){this.input=t,this.close()}onClose(){super.onClose(),this.resolvePromise(this.input)}}});var vr,Tr=k(()=>{vr=(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))(vr||{})});function mn(r){return typeof r=="object"&&r!==null}function ou(r){return mn(r)&&!Array.isArray(r)}function M7(r){return ou(r)?!1:Array.isArray(r)?r.length>0:Kn(r)}function hn(r){return ou(r)?r.commands:M7(r)?r:void 0}function ar(r){return Array.isArray(r)?r:[]}function Xf(r){return Array.isArray(r)?r:[]}function xy(r){return Array.isArray(r)}function Kn(r){return Array.isArray(r)||r==null?!1:typeof r=="object"?Object.keys(r).length>0:!!r}function pI(r){let e=ar(r),t=new Set,n=!1,i=[];for(let o of e){if(Array.isArray(o)){let l=pI(o);for(let c of l.commands){let u=c.id;if(typeof u=="string"&&u!==""&&!t.has(u)){t.add(u),i.push(c);continue}let d={...c,id:ir()};t.add(d.id),i.push(d)}n=!0;continue}if(!mn(o)){n=!0;continue}let s=o.id;if(typeof s=="string"&&s!==""&&!t.has(s)){t.add(s),i.push(o);continue}let a={...o,id:ir()};t.add(a.id),i.push(a),n=!0}return n?{commands:i,changed:n}:{commands:e,changed:!1}}function vB(r){yB(r,new Set)}function yB(r,e){mn(r)&&(e.has(r)||(e.add(r),ou(r)&&(r.id=ir()),mx(hn(r),e)))}function mx(r,e){if(xy(r))for(let t of r){if(Array.isArray(t)){mx(t,e);continue}if(!mn(t)||e.has(t))continue;e.add(t),t.id=ir();let n=t;mx(n.thenCommands,e),mx(n.elseCommands,e),bB(n.choice,e)}}function bB(r,e){if(!mn(r)||e.has(r))return;e.add(r);let t=r;if(t.id=ir(),t.type==="Macro"&&yB(t.macro,e),t.type==="Multi"&&Array.isArray(t.choices))for(let n of t.choices)bB(n,e)}var Qn=k(()=>{Ea()});function su(r){return r!==null&&typeof r=="object"}function wx(r){return r?.secretStorage}function gx(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"setting"}function L7(r){let e=5381;for(let t=0;t<r.length;t+=1)e=e*33^r.charCodeAt(t);return(e>>>0).toString(36).slice(0,R7)}function CB(r,e){return r.length<=e?r:r.slice(0,e).replace(/-+$/g,"")||"setting"}function TB(r,e){let t=e?.id;return typeof t=="string"&&t.trim().length>0?t:r}function fI(r,e,t){let i=(t?[hx,r,e,t]:[hx,r,e]).join("-");if(i.length<=wB)return i;let o=L7([r,e,t].filter(Boolean).join(":")),s=t?4:3,a=wB-hx.length-o.length-(t?.length??0)-s,l=Math.max(8,Math.floor(a*.6)),c=Math.max(8,a-l);return[hx,CB(r,l),CB(e,c),...t?[t]:[],o].join("-")}function mI(r){return r?.message??String(r)}function Hs(r,e){let t=e;for(;t<r.length;){let n=r[t],i=r[t+1];if(/\s/.test(n)){t+=1;continue}if(n==="/"&&i==="/"){let o=r.indexOf(`
`,t+2);t=o===-1?r.length:o+1;continue}if(n==="/"&&i==="*"){let o=r.indexOf("*/",t+2);t=o===-1?r.length:o+2;continue}return t}return t}function Sy(r,e){let t=r[e];if(t!=='"'&&t!=="'"&&t!=="`")return null;let n="";for(let i=e+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===t)return{value:n,end:i+1};n+=o}return null}function EB(r,e){let t=/^[A-Za-z_$][\w$]*/.exec(r.slice(e));return t?{value:t[0],end:e+t[0].length}:null}function Ty(r,e,t,n){let i=0;for(let o=e;o<r.length;o++){let s=r[o],a=r[o+1];if(s==='"'||s==="'"||s==="`"){let l=Sy(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===t){i+=1;continue}if(s===n&&(i-=1,i===0))return o}return-1}function SB(r){let e=new Map,t=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(["'`])/g,n;for(;(n=t.exec(r))!==null;){let i=Sy(r,t.lastIndex-1);i&&(e.set(n[1],i.value),t.lastIndex=i.end)}return e}function N7(r){let e=[],t=SB(r),n=0;for(;n<r.length;){n=Hs(r,n);let i=r[n],o=r[n+1];if(i==='"'||i==="'"||i==="`"){let l=Sy(r,n);n=l?l.end:n+1;continue}if(i==="/"&&o==="/"){let l=r.indexOf(`
`,n+2);n=l===-1?r.length:l+1;continue}if(i==="/"&&o==="*"){let l=r.indexOf("*/",n+2);n=l===-1?r.length:l+2;continue}let s=hI(r,n,t);if(!s){n+=1;continue}if(n=Hs(r,s.end),r[n]!==":"){n=s.end;continue}if(n=Hs(r,n+1),s.name!=="options"||r[n]!=="{")continue;let a=Ty(r,n,"{","}");if(a===-1)break;e.push({start:n+1,end:a}),n=a+1}return e}function hI(r,e,t){if(r[e]==='"'||r[e]==="'"||r[e]==="`"){let i=Sy(r,e);return i?{name:i.value,end:i.end}:null}if(r[e]==="["){let i=Hs(r,e+1),o=EB(r,i),s=Ty(r,e,"[","]");if(s===-1)return null;let a=o?Hs(r,o.end):i;return{name:o&&a===s?t.get(o.value)??null:null,end:s+1}}let n=EB(r,e);return n?{name:n.value,end:n.end}:null}function B7(r){let e=new Map,t=0;for(;t<r.length;){if(t=Hs(r,t),r[t]===","){t+=1;continue}if(t>=r.length)break;let n=hI(r,t,new Map);if(!n?.name){t+=1;continue}if(t=Hs(r,n.end),r[t]!==":"){t+=1;continue}if(t=Hs(r,t+1),r[t]==='"'||r[t]==="'"||r[t]==="`"){let i=Sy(r,t);if(!i)break;e.set(n.name,i.value),t=i.end;continue}if(r.slice(t,t+4)==="true"){e.set(n.name,!0),t+=4;continue}if(r.slice(t,t+5)==="false"){e.set(n.name,!1),t+=5;continue}if(r[t]==="{"){let i=Ty(r,t,"{","}");if(i===-1)break;t=i+1;continue}if(r[t]==="["){let i=Ty(r,t,"[","]");if(i===-1)break;t=i+1;continue}for(;t<r.length&&r[t]!==",";)t+=1}return e}function V7(r){let e=B7(r),t=e.get("type"),n=e.get("secret");return t==="secret"||(t==="text"||t==="input")&&n===!0}function Jf(r,e){let t=e&&O7.test(e)?vl(r).code??"":r,n=new Set,i=!1,o=SB(t);for(let{start:s,end:a}of N7(t)){let l=s;for(;l<a;){if(l=Hs(t,l),t[l]===","){l+=1;continue}if(l>=a)break;let c=hI(t,l,o);if(!c){l+=1;continue}if(l=Hs(t,c.end),t[l]!==":"){l+=1;continue}if(l=Hs(t,l+1),t[l]!=="{"){l+=1;continue}let u=Ty(t,l,"{","}");if(u===-1||u>a)break;let d=t.slice(l+1,u);V7(d)&&(i=!0,c.name&&n.add(c.name)),l=u+1}}return{names:n,foundSecretOptions:i}}function em(r){return su(r)?r.type==="secret"||(r.type==="text"||r.type==="input")&&r.secret===!0:!1}function Zf(r){return su(r)&&r[xB]===!0&&typeof r.secretRef=="string"&&r.secretRef.trim().length>0}function vx(r){return{[xB]:!0,secretRef:r}}function q7(r,e,t){let n=r.id?.trim()||r.path||r.name||"script";return fI(gx(n),gx(TB(e,t)))}function U7(r){let e=r?.options;return e?Object.entries(e).filter(([,t])=>em(t)).map(([t])=>t):[]}function z7(r){let e=r?.options;return e?Object.entries(e).filter(([,t])=>em(t)):[]}function H7(r){return typeof r.id=="string"&&r.id.trim().length>0}async function gI(r,e){let t=wx(r);if(!t?.getSecret)return null;try{return await Promise.resolve(t.getSecret(e))}catch(n){return P.logWarning(`Failed to read user script SecretStorage entry "${e}": ${mI(n)}`),null}}async function W7(r,e,t){let n=wx(r);if(!n?.setSecret)return!1;try{return await Promise.resolve(n.setSecret(e,t)),!0}catch(i){return P.logWarning(`Failed to write user script SecretStorage entry "${e}": ${mI(i)}`),!1}}async function j7(r,e,t,n,i){let o=e.id?.trim()||e.path||e.name||"script",s=gx(o),a=gx(TB(t,i)),l=fI(s,a),c=1;for(;;){let u=await gI(r,l);if(!u||u===n)return l;c+=1,l=fI(s,a,String(c))}}async function vI(r,e,t,n,i,o){if(n.length===0)return null;let s=i?.trim()||await j7(r,e,t,n,o);return await W7(r,s,n)?s:null}async function yI(r,e){let t=e?.trim();if(!t)return!0;let n=wx(r);if(!n)return!0;let i=n.deleteSecret??n.removeSecret??n.delete;try{if(i)return await Promise.resolve(i.call(n,t)),!0;if(n.setSecret)return await Promise.resolve(n.setSecret(t,"")),!0}catch(o){P.logWarning(`Failed to clear user script SecretStorage entry "${t}": ${mI(o)}`)}return!1}async function Cx(r,e,t){let n=e.settings??{},i={...n},o=new Set(U7(t));for(let[s,a]of Object.entries(n)){if(Zf(a)){let l=await gI(r,a.secretRef);if(l){i[s]=l;continue}throw new Error(`Secret setting "${s}" for user script "${e.name}" is unavailable. Re-enter it on this device.`)}o.has(s)&&(i[s]=typeof a=="string"?a:"")}return i}async function tm(r,e,t){let n=z7(t);if(n.length===0)return!1;let i=wx(r);if(!i?.getSecret||!i?.setSecret)return n.some(([a])=>{let l=e.settings?.[a];return typeof l=="string"&&l.length>0})&&P.logWarning(`SecretStorage unavailable; leaving plaintext user script secret settings for "${e.name}" unchanged.`),!1;let o=!1;for(let[s,a]of n){let l=e.settings?.[s];if(Zf(l))continue;if(typeof l!="string"||l.length===0){if(!H7(a))continue;let u=q7(e,s,a);if(!await gI(r,u))continue;e.settings[s]=vx(u);for(let[f,p]of Object.entries(e.settings))f!==s&&Zf(p)&&p.secretRef===u&&delete e.settings[f];o=!0;continue}let c=await vI(r,e,s,l,void 0,a);c&&(e.settings[s]=vx(c),o=!0)}return o}function Ex(r,e){let t=r.settings?.[e];return Zf(t)?t.secretRef:void 0}async function G7(r,e){if(!su(e))return!0;let t=Object.values(e).filter(Zf).map(i=>i.secretRef);return(await Promise.all(t.map(i=>yI(r,i)))).every(Boolean)}async function _B(r,e){if(!su(e))return!0;let t=!0;if(e.type==="Macro"&&(t=await yx(r,hn(e.macro))&&t),e.type==="Multi"&&Array.isArray(e.choices))for(let n of e.choices)t=await _B(r,n)&&t;return t}async function _y(r,e){if(!su(e))return!0;let t=!0;return e.type==="UserScript"&&(t=await G7(r,e.settings)&&t),Array.isArray(e.thenCommands)&&(t=await yx(r,e.thenCommands)&&t),Array.isArray(e.elseCommands)&&(t=await yx(r,e.elseCommands)&&t),t=await _B(r,e.choice)&&t,t}async function yx(r,e){if(!Array.isArray(e))return!0;let t=!0;for(let n of e){if(Array.isArray(n)){t=await yx(r,n)&&t;continue}t=await _y(r,n)&&t}return t}function Y7(r,e){let t=r.path;if(typeof t=="string")return e?.secretOptionNamesByPath?.get(t)}function K7(r,e,t){if(su(r))for(let[n,i]of Object.entries(r)){if(Zf(i)){delete r[n];continue}typeof i=="string"&&(e===null||e?.has(n)||e===void 0&&t?.stripUnknownStringSettings===!0)&&delete r[n]}}function bI(r,e){su(r)&&(r.type==="UserScript"&&K7(r.settings,Y7(r,e),e),Array.isArray(r.thenCommands)&&bx(r.thenCommands,e),Array.isArray(r.elseCommands)&&bx(r.elseCommands,e),rm(r.choice,e))}function bx(r,e){if(Array.isArray(r))for(let t of r){if(Array.isArray(t)){bx(t,e);continue}bI(t,e)}}function rm(r,e){if(su(r)&&(r.type==="Macro"&&bx(hn(r.macro),e),r.type==="Multi"&&Array.isArray(r.choices)))for(let t of r.choices)rm(t,e)}var hx,xB,O7,wB,R7,Bl=k(()=>{De();Eg();Qn();hx="quickadd-user-script",xB="__quickaddSecret",O7=/\.md$/i,wB=64,R7=8});function nm(r,e){if(e.options)for(let t in e.options){let n=r[t]===void 0,i="defaultValue"in e.options[t]&&e.options[t].defaultValue!==void 0;n&&i&&!em(e.options[t])&&(r[t]=e.options[t].defaultValue)}}var xx=k(()=>{Bl()});function Ji(r){if(r.length===0)return 0;let e=new TextEncoder().encode(r).length,t=!1;for(let i=0;i<r.length;i++)if(r.charCodeAt(i)>127){t=!0;break}return Math.max(1,Math.ceil(e/(t?3:4)))}function AB(r){return!Number.isFinite(r)||r<=0?1:Math.max(1,Math.floor(r*.45))}var ky=k(()=>{});function PB(){return ne.getState().ai.providers.flatMap(e=>e.models).map(e=>e.name)}function EI(){return ne.getState().ai.providers}function DB(r,e){for(let t of r){let n=t.models.find(i=>i.name===e);if(n)return{provider:t,model:n}}}function CI(r){let e=EI();return e.filter(t=>t.models.some(n=>n.name===r)).map(t=>{let n=`${t.id??t.name}/${r}`;return e.some(o=>o.models.some(s=>s.name===n))?`{ name: "${r}", provider: "${t.id??t.name}" } (the string "${n}" is itself a model id on another provider)`:n})}function FB(r,e){IB.has(r)||(IB.add(r),P.logWarning(e))}function Ld(r,e){let t=EI(),n=e?.silent===!0;if(r==null)return;if(typeof r!="string"){let s=t.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=DB(t,r.name);return l?(n||FB(`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=DB(t,r);if(i){let s=CI(r);return s.length>1&&!n&&FB(`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 $B(r.slice(0,o),r.slice(o+1))}function $B(r,e){let t=EI(),n=r.trim().toLowerCase(),i=t.find(s=>s.id?.toLowerCase()===n)??t.find(s=>s.name.trim().toLowerCase()===n),o=i?.models.find(s=>s.name===e);if(i&&o)return{provider:i,model:o}}function im(r){let e=typeof r=="string"?r:r?.name;if(!e)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 t=typeof r!="string"&&r.provider?$B(r.provider,e):Ld(e);if(!t){let n=e.includes("/")?e.slice(e.indexOf("/")+1):e,i=[...CI(e),...n!==e?CI(n):[]],o=i.length?` Did you mean ${i.join(" or ")}?`:" Add it under Edit providers in QuickAdd's AI Assistant settings (the sparkles button below the choice list), or enable auto-sync for that provider.";throw new Error(`Model '${typeof r=="string"?r:`${r.provider??""}/${e}`}' not found in configured providers.${o}`)}return t}var IB,om=k(()=>{De();ht();IB=new Set});var Dx=k(()=>{});var Mn,Vl=k(()=>{Ea();Mn=class{constructor(e,t){this.name=e,this.type=t,this.id=ir()}}});var Rx,Or,lu=k(()=>{Rx=require("obsidian");De();Qi();Er();Or=class r extends Rx.FuzzySuggestModal{constructor(t,n,i,o={}){super(t);this.warnedOnEmptyDisplay=!1;this.warnRenderItemFailure=wd("Custom renderItem threw an error; falling back to default rendering");this.warnCustomValueFailure=wd("Custom create-row rendering threw an error; falling back to default rendering");this.allowCustomValue=!0;this.items=i,this.displayItems=n.map(s=>zr(s)),this.searchItems=o.searchItems?.map(s=>zr(s))??[],this.promise=new Promise((s,a)=>{this.resolvePromise=s,this.rejectPromise=a}),this.renderItem=o.renderItem,this.allowCustomValue=o.allowCustomValue??!0,this.customValueLabel=o.customValueLabel,this.valueExists=o.valueExists,this.inputEl.addEventListener("keydown",s=>{if(s.code!=="Tab"||!("chooser"in this))return;let{values:a,selectedItem:l}=this.chooser,{value:c}=this.inputEl;this.inputEl.value=a[l]?.item??c}),o.placeholder&&this.setPlaceholder(o.placeholder),typeof o.limit=="number"&&(this.limit=o.limit),o.emptyStateText&&(this.emptyStateText=o.emptyStateText),this.displayItems.length!==this.items.length&&(this.displayItems=this.items.map((s,a)=>{let l=this.displayItems[a];return zr(l??s)})),this.searchItems.length!==this.items.length&&(this.searchItems=this.items.map((s,a)=>zr(this.searchItems[a]??this.displayItems[a]??s))),o.skippable&&gC(this,()=>this.skip()),this.warnIfEmptyDisplay(),this.open()}static Suggest(t,n,i,o={}){return new r(t,n,i,o).promise}getItemText(t){if(t===this.inputEl.value)return t;let n=this.items.indexOf(t),i=n>=0?this.searchItems[n]:void 0;return zr(i??t)}getItems(){return this.items}getSuggestions(t){let n=xl(t),i=super.getSuggestions(n);if(!this.allowCustomValue)return i;let o=xl(this.inputEl.value);if(!o||this.items.includes(o)||this.valueExists?.(o)||i.some(l=>l.item===o))return i;let a={item:o,match:{score:Number.NEGATIVE_INFINITY,matches:[]}};return this.customValueLabel?i.unshift(a):i.push(a),i}selectSuggestion(t,n){this.resolved=!0,super.selectSuggestion(t,n)}renderSuggestion(t,n){if(this.customValueLabel&&t.match.score===Number.NEGATIVE_INFINITY){this.renderCustomValue(t.item,n);return}if(!this.renderItem){super.renderSuggestion(t,n);return}try{n.empty(),this.renderItem(t.item,n)}catch(i){this.warnRenderItemFailure(i),n.empty(),super.renderSuggestion(t,n)}}renderCustomValue(t,n){try{n.empty(),n.addClass("mod-complex"),n.createDiv({cls:"suggestion-content"}).createDiv({cls:"suggestion-title",text:this.customValueLabel?.(t)??t});let o=n.createDiv({cls:"suggestion-aux"});(0,Rx.setIcon)(o.createSpan({cls:"suggestion-flair"}),"file-plus")}catch(i){this.warnCustomValueFailure(i),n.empty(),super.renderSuggestion({item:t,match:{score:0,matches:[]}},n)}}onChooseItem(t,n){this.resolved=!0,this.resolvePromise(t)}skip(){this.resolved=!0,this.resolvePromise(""),this.close()}onClose(){super.onClose(),this.resolved||this.rejectPromise(Ir())}warnIfEmptyDisplay(){if(this.warnedOnEmptyDisplay)return;this.displayItems.some(n=>n.length===0)&&(this.warnedOnEmptyDisplay=!0,P.logWarning("QuickAdd suggester received empty display values. Check your displayItems mapping."))}}});var So=k(()=>{});var St,Ws=k(()=>{Tr();Vl();wa();De();St=class extends Mn{constructor(e){super(e,"EditorCommand"),this.editorCommandType=e}static getSelectedText(e){return this.getActiveMarkdownView(e).editor.getSelection()}static getActiveMarkdownView(e){let t=ln(e);if(!t)throw P.logError("no active markdown editor."),new Error("no active markdown editor.");return t}}});var cm,kI=k(()=>{So();Ws();cm=class extends St{constructor(){super("Copy")}static async run(e){let t=St.getSelectedText(e);await navigator.clipboard.writeText(t)}}});var um,AI=k(()=>{So();Ws();De();um=class extends St{constructor(){super("Cut")}static async run(e){let t=St.getSelectedText(e),n=St.getActiveMarkdownView(e);if(!t){P.logError("nothing selected.");return}await navigator.clipboard.writeText(t),n.editor.replaceSelection("")}}});var dm,DI=k(()=>{So();De();Ws();dm=class extends St{constructor(){super("Paste")}static async run(e){let t=await navigator.clipboard.readText(),n=St.getActiveMarkdownView(e);if(!n){P.logError("no active markdown view.");return}n.editor.replaceSelection(t)}}});var UB,pm,II=k(()=>{UB=require("obsidian");De();Ws();So();pm=class extends St{constructor(){super("Paste with format")}static async run(e){let t=St.getActiveMarkdownView(e);if(!t){P.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,UB.htmlToMarkdown)(l),o=!0;break}o||(n=await navigator.clipboard.readText())}else n=await navigator.clipboard.readText();t.editor.replaceSelection(n)}catch(i){P.logWarning(`Formatted paste failed. Falling back to plain text: ${i}`);try{let o=await navigator.clipboard.readText();t.editor.replaceSelection(o)}catch(o){P.logError(`Failed to read clipboard text: ${o}`)}}}}});var fm,FI=k(()=>{So();Ws();fm=class extends St{constructor(){super("Select active line")}static run(e){let t=St.getActiveMarkdownView(e),{line:n}=t.editor.getCursor(),o=t.editor.getLine(n).length;t.editor.setSelection({line:n,ch:0},{line:n,ch:o})}}});var mm,PI=k(()=>{Ws();So();Je();De();mm=class extends St{constructor(){super("Select link on active line")}static run(e){let t=St.getActiveMarkdownView(e),{line:n}=t.editor.getCursor(),i=t.editor.getLine(n),o=gO.exec(i);if(!o){P.logError(`no internal link found on line ${n}.`);return}let s=o.index,a=o[0].length+s;t.editor.setSelection({line:n,ch:s},{line:n,ch:a})}}});var hm,$I=k(()=>{Ws();So();hm=class extends St{constructor(){super("Move cursor to file start")}static run(e){St.getActiveMarkdownView(e).editor.setCursor({line:0,ch:0})}}});var gm,MI=k(()=>{Ws();So();gm=class extends St{constructor(){super("Move cursor to file end")}static run(e){let t=St.getActiveMarkdownView(e),n=t.editor.lastLine(),i=t.editor.getLine(n).length;t.editor.setCursor({line:n,ch:i})}}});var vm,OI=k(()=>{Ws();So();vm=class extends St{constructor(){super("Move cursor to line start")}static run(e){let t=St.getActiveMarkdownView(e),{line:n}=t.editor.getCursor();t.editor.setCursor({line:n,ch:0})}}});var ym,RI=k(()=>{Ws();So();ym=class extends St{constructor(){super("Move cursor to line end")}static run(e){let t=St.getActiveMarkdownView(e),{line:n}=t.editor.getCursor(),i=t.editor.getLine(n).length;t.editor.setCursor({line:n,ch:i})}}});function sV(r,e=new Set){if(r==null||e.has(r))return[];if(e.add(r),typeof r=="string")return[r];if(typeof r!="object")return[String(r)];let t=r,n=[];for(let i of M9){let o=t[i];o!==void 0&&n.push(...sV(o,e))}return n}function Xx(r){return Number(r.replace(/,/g,""))}function O9(r){let e=r.match(/context (?:length|window)(?:\s+is)?(?:\s+of)?\s*(\d[\d,]*)/i);return e?Xx(e[1]):null}function R9(r){let e=r.match(/(\d[\d,]*)\s*(?:tokens?\s+)?in the completion\b/i);if(e){let n=Xx(e[1]),i=O9(r);return i===null?"input":n>=i?"output":"input"}let t=r.match(/input length and max_tokens exceed context limit:?\s*(\d[\d,]*)\s*\+\s*(\d[\d,]*)(?:\s*>\s*(\d[\d,]*))?/i);if(t){let n=Xx(t[2]),i=t[3]?Xx(t[3]):null;return i===null?"input":n>=i?"output":"input"}return null}function Oy(r){let e=sV(r).join(" "),t=R9(e);return t==="output"?"output_budget":t==="input"?"input_context":$9.some(n=>n.test(e))?"output_budget":P9.some(n=>n.test(e))?"input_context":"other"}function aV(r){return Oy(r)==="input_context"}function Zx(r,e){let t="",n="",i;try{i=e.json}catch{i=void 0}if(i&&typeof i=="object"){let s=i,a=s.error??s;t=String(a.message??s.message??""),n=String(a.code??a.type??a.status??"")}t||(t=typeof e.text=="string"&&e.text.length>0?e.text:`HTTP ${e.status}`);let o=new Error(`${r} request failed (HTTP ${e.status})${n?` [${n}]`:""}: ${t}`);return o.status=e.status,n&&(o.providerCode=n),o}var P9,$9,M9,Ry=k(()=>{P9=[/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],$9=[/max_tokens/i,/max_completion_tokens/i,/max(?:imum)? output tokens/i,/output token limit/i],M9=["message","code","type","status","statusText","providerCode","error","response","json","cause"]});function G9(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Y9(r){let e=r.name?.trim()||"provider";return`${j9}-${G9(e)}`}async function dV(r,e){if(!r?.secretStorage?.getSecret)return null;try{return await Promise.resolve(r.secretStorage.getSecret(e))}catch(t){return P.logWarning(`Failed to read SecretStorage entry "${e}": ${t.message??t}`),null}}async function Gs(r,e){let t=e.apiKeyRef?.trim();if(t){let n=await dV(r,t);if(n)return n}return e.apiKey??""}async function pV(r,e,t){let n=t?.trim();if(!n||!r?.secretStorage?.getSecret||!r.secretStorage?.setSecret)return null;let i=Y9(e),o=i,s=1;for(;;){let a=await dV(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 P.logWarning(`Failed to write SecretStorage entry "${o}": ${a.message??a}`),null}}var j9,Nd=k(()=>{De();j9="quickadd-ai"});function VV(r){try{let e=window.require;return e?e(r):null}catch{return null}}async function Im(r,e){let t=r.vault.adapter;if(typeof sF.FileSystemAdapter!="function"||!(t instanceof sF.FileSystemAdapter))return;let n=VV("fs"),i=VV("path");if(!n?.promises||!i)return;let o=await n.promises.realpath(t.getBasePath()),a=t.getFullPath(e);for(;!eZ(n,a);){let f=i.dirname(a);if(f===a)break;a=f}let l;try{l=await n.promises.realpath(a)}catch{throw new Ny(`Refusing to write to "${e}": it resolves through an unresolvable (dangling) symlink.`)}let c=i.relative(o,l);if(c===".."||c.startsWith(`..${i.sep}`)||i.isAbsolute(c))throw new Ny(`Refusing to write to "${e}": it resolves (via a symlink) outside the vault.`);if(c.split(i.sep).some(f=>f.startsWith(".")))throw new Ny(`Refusing to write to "${e}": it resolves (via a symlink) into a config/hidden directory.`)}function eZ(r,e){try{return r.lstatSync(e),!0}catch{return!1}}var sF,Ny,aF=k(()=>{sF=require("obsidian"),Ny=class extends Error{constructor(e){super(e),this.name="VaultWriteEscapeError"}}});var ve,Bi=k(()=>{jo();ve=class extends Tt{}});var Cq,hr,Ul=k(()=>{Cq=require("obsidian");De();Qi();Er();hr=class r extends Cq.FuzzySuggestModal{constructor(t,n,i,o,s){super(t);this.warnedOnEmptyDisplay=!1;this.warnRenderItemFailure=wd("Custom renderItem threw an error; falling back to default rendering");this.renderItem=o,this.items=i,this.displayItems=n.map(a=>zr(a)),this.promise=new Promise((a,l)=>{this.resolvePromise=a,this.rejectPromise=l}),s?.skippable&&gC(this,()=>this.skip()),this.inputEl.addEventListener("keydown",a=>{if(a.code!=="Tab"||!("chooser"in this))return;let{values:l,selectedItem:c}=this.chooser,{value:u}=this.inputEl;this.inputEl.value=l[c]?.item??u}),this.displayItems.length!==this.items.length&&(this.displayItems=this.items.map((a,l)=>{let c=this.displayItems[l];return zr(c??a)})),this.warnIfEmptyDisplay(),this.open()}static Suggest(t,n,i,o,s,a){let l=new r(t,n,i,s,a);return o&&l.setPlaceholder(o),l.promise}getItemText(t){let n=this.items.indexOf(t),i=n>=0?this.displayItems[n]:void 0;return zr(i??t)}getItems(){return this.items}getSuggestions(t){let n=xl(t);return super.getSuggestions(n)}selectSuggestion(t,n){this.resolved=!0,super.selectSuggestion(t,n)}renderSuggestion(t,n){if(!this.renderItem){super.renderSuggestion(t,n);return}try{n.empty(),this.renderItem(t.item,n)}catch(i){this.warnRenderItemFailure(i),n.empty(),super.renderSuggestion(t,n)}}onChooseItem(t,n){this.resolved=!0,this.resolvePromise(t)}skip(){this.resolved=!0,this.resolvePromise(""),this.close()}onClose(){super.onClose(),this.resolved||this.rejectPromise(Ir())}warnIfEmptyDisplay(){if(this.warnedOnEmptyDisplay)return;this.displayItems.some(n=>n.length===0)&&(this.warnedOnEmptyDisplay=!0,P.logWarning("QuickAdd suggester received empty display values. Check your displayItems mapping."))}}});function Jn(r,e){if(!r)throw new Error(typeof e=="function"?e():e)}var zy=k(()=>{});function $m(r){return _F.filter(e=>typeof r[e]=="number")}function PT(r){let e={...r};for(let t of _F)delete e[t];return e}function kF(r,e){return r.supportsTemperature===!1&&$m(e).length>0?PT(e):e}function AF(r,e){return e.length===0?!1:kJ.some(t=>t.test(r))}function $T(r){let e=r.map(t=>_J[t]);return e.length<=1?e.join(""):e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}var _F,_J,FT,kJ,Eq=k(()=>{_F=["temperature","top_p","frequency_penalty","presence_penalty"],_J={temperature:"Temperature",top_p:"Top P",frequency_penalty:"Frequency penalty",presence_penalty:"Presence penalty"};FT=_F.join("|"),kJ=[new RegExp(`unsupported (?:parameter|value)[^.]{0,40}['\`"]?(?:${FT})['\`"]?`,"i"),new RegExp(`['\`"]?(?:${FT})['\`"]?[^.]{0,40}(?:is deprecated|is not supported|not supported|does not support)`,"i"),new RegExp(`unrecognized request argument[^.]{0,40}(?:${FT})`,"i"),new RegExp(`(?:${FT})[^.]{0,40}extra inputs are not permitted`,"i")]});function MT(r){let e=r.workspace.activeEditor?.editor?.getCursor(),t=r.workspace.activeEditor?.editor?.listSelections();return()=>{e&&r.workspace.activeEditor?.editor?.setCursor(e),t&&r.workspace.activeEditor?.editor?.setSelections(t)}}var DF=k(()=>{});function Hy(r){let e=Array.isArray(r)?r:{...r},t=e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")||e.properties!==void 0;if(e.properties){let n={};for(let[i,o]of Object.entries(e.properties))n[i]=Hy(o);e.properties=n}return e.items&&!Array.isArray(e.items)&&(e.items=Hy(e.items)),t&&(e.additionalProperties=!1,e.required=e.properties?Object.keys(e.properties):[]),e}function AJ(r){let e=[];for(let t of r)if(t.role==="system")e.push({role:"system",content:t.content});else if(t.role==="user")e.push({role:"user",content:t.content});else if(t.role==="assistant"){let n={role:"assistant",content:t.content??""};t.toolCalls&&t.toolCalls.length>0&&(n.tool_calls=t.toolCalls.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:i.rawArgs??JSON.stringify(i.args??{})}}))),e.push(n)}else for(let n of t.results)e.push({role:"tool",tool_call_id:n.toolCallId,content:n.isError?`ERROR: ${n.content}`:n.content});return e}function DJ(r){return r.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.strict?Hy(e.parameters):e.parameters,...e.strict?{strict:!0}:{}}}))}function IJ(r){return typeof r=="string"?r:{type:"function",function:{name:r.name}}}function PJ(r,e){let t={model:r,...e.modelParams??{},messages:AJ(e.messages)};return e.tools&&e.tools.length>0&&(t.tools=DJ(e.tools),e.toolChoice&&(t.tool_choice=IJ(e.toolChoice)),e.disableParallel&&(t.parallel_tool_calls=!1)),e.maxOutputTokens!==void 0&&(FJ.test(r)?t.max_completion_tokens=e.maxOutputTokens:t.max_tokens=e.maxOutputTokens),e.responseFormat&&(t.response_format=e.responseFormat.schema?{type:"json_schema",json_schema:{name:e.responseFormat.name??"response",strict:e.responseFormat.strict??!0,schema:e.responseFormat.strict??!0?Hy(e.responseFormat.schema):e.responseFormat.schema}}:{type:"json_object"}),t}function $J(r){let e=r.choices?.[0]??{},t=e.message??{},i=(t.tool_calls??[]).map(a=>MJ(a)),o=String(e.finish_reason??""),s=r.usage??{};return{content:t.content??"",toolCalls:i,normalizedStopReason:i.length>0||o==="tool_calls"?"tool_calls":o==="length"?"length":o==="stop"?"stop":"other",rawStopReason:o,usage:{promptTokens:s.prompt_tokens??0,completionTokens:s.completion_tokens??0,totalTokens:s.total_tokens??0}}}function xq(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function MJ(r){let e=r.function.arguments;if(typeof e=="string")try{let n=xq(JSON.parse(e||"{}"));if(!n)throw new Error("tool arguments are not a JSON object");return{id:r.id,name:r.function.name,args:n,rawArgs:e}}catch{return{id:r.id,name:r.function.name,args:null,rawArgs:e,parseError:!0}}let t=xq(e);return t?{id:r.id,name:r.function.name,args:t}:{id:r.id,name:r.function.name,args:null,rawArgs:typeof e=="string"?e:JSON.stringify(e??{}),parseError:!0}}function OJ(r,e,t){let n=[],i=[];for(let a of e.messages)if(a.role==="system")a.content&&n.push(a.content);else if(a.role==="user")i.push({role:"user",content:a.content});else if(a.role==="assistant"){let l=[];a.content&&l.push({type:"text",text:a.content});for(let c of a.toolCalls??[])l.push({type:"tool_use",id:c.id,name:c.name,input:c.args??{}});i.push({role:"assistant",content:l})}else i.push({role:"user",content:a.results.map(l=>({type:"tool_result",tool_use_id:l.toolCallId,content:l.content,...l.isError?{is_error:!0}:{}}))});let o={model:r,max_tokens:e.maxOutputTokens??t,messages:i};n.length>0&&(o.system=n.join(`
`));let s=e.modelParams??{};return typeof s.temperature=="number"&&(o.temperature=s.temperature),typeof s.top_p=="number"&&(o.top_p=s.top_p),e.tools&&e.tools.length>0&&(o.tools=e.tools.map(a=>({name:a.name,description:a.description,input_schema:a.parameters})),e.toolChoice?o.tool_choice=RJ(e.toolChoice,e.disableParallel):e.disableParallel&&(o.tool_choice={type:"auto",disable_parallel_tool_use:!0})),e.responseFormat?.schema&&(o.output_config={format:{type:"json_schema",schema:Hy(e.responseFormat.schema)}}),o}function RJ(r,e){let t=e?{disable_parallel_tool_use:!0}:{};return typeof r=="string"?r==="required"?{type:"any",...t}:r==="none"?{type:"none"}:{type:"auto",...t}:{type:"tool",name:r.name,...t}}function LJ(r){let e=r.content??[],t=e.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:e.filter(a=>a.type==="text").map(a=>a.text??"").join(""),toolCalls:t,normalizedStopReason:n==="tool_use"||t.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 NJ(r,e){let t=[],n=[];for(let a of e.messages)if(a.role==="system")a.content&&t.push(a.content);else if(a.role==="user")n.push({role:"user",parts:[{text:a.content}]});else if(a.role==="assistant")if(Array.isArray(a.providerRaw))n.push({role:"model",parts:a.providerRaw});else{let l=[];a.content&&l.push({text:a.content});for(let c of a.toolCalls??[])l.push({functionCall:{name:c.name,args:c.args??{}}});n.push({role:"model",parts:l})}else n.push({role:"user",parts:a.results.map(l=>({functionResponse:{name:l.name,response:l.isError?{error:l.content}:{result:l.content}}}))});let i={contents:n};t.length>0&&(i.systemInstruction={role:"system",parts:[{text:t.join(`
`)}]}),e.tools&&e.tools.length>0&&(i.tools=[{functionDeclarations:e.tools.map(a=>({name:a.name,description:a.description,parameters:a.parameters}))}],e.toolChoice&&(i.toolConfig=BJ(e.toolChoice)));let o={},s=e.modelParams??{};return typeof s.temperature=="number"&&(o.temperature=s.temperature),typeof s.top_p=="number"&&(o.topP=s.top_p),e.maxOutputTokens!==void 0&&(o.maxOutputTokens=e.maxOutputTokens),e.responseFormat?.schema&&(o.responseMimeType="application/json",o.responseSchema=e.responseFormat.schema),Object.keys(o).length>0&&(i.generationConfig=o),i}function BJ(r){return typeof r=="string"?{functionCallingConfig:{mode:r==="required"?"ANY":r==="none"?"NONE":"AUTO"}}:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[r.name]}}}function VJ(r){let e=r.candidates?.[0]??{},n=(e.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(e.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 IF(r,e,t,n=8192){switch(r){case"anthropic":return OJ(e,t,n);case"gemini":return NJ(e,t);default:return PJ(e,t)}}function Tq(r,e){switch(r){case"anthropic":return LJ(e);case"gemini":return VJ(e);default:return $J(e)}}var FJ,Sq=k(()=>{FJ=/^(?:o[1-9]|gpt-(?:[5-9]|\d\d))/i});async function Mm(r,e,t){let n=(0,jy.requestUrl)({...r,throw:!1});t&&t();let i=await n;if(i.status>=400)throw Zx(e,i);return i.json}function qJ(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 UJ(r){return{id:r.id,model:r.model,content:r.content.filter(e=>e.type==="text").map(e=>e.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()}}async function zJ(r,e,t,n,i,o,s){return Mm({url:`${t.endpoint}/chat/completions`,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({model:e.name,...i,messages:[{role:"system",content:n},{role:"user",content:o}]})},t.name,s)}function FF(r){if(typeof r.maxOutputTokens=="number"&&Number.isFinite(r.maxOutputTokens)&&r.maxOutputTokens>0)return Math.floor(r.maxOutputTokens);let e=4096;return Number.isFinite(r.maxTokens)&&r.maxTokens>0?Math.min(e,r.maxTokens):e}async function HJ(r,e,t,n,i,o,s){let a={model:e.name,max_tokens:FF(e),messages:[{role:"user",content:o}]};return n&&n.trim().length>0&&(a.system=n),typeof i.temperature=="number"&&(a.temperature=i.temperature),typeof i.top_p=="number"&&(a.top_p=i.top_p),Mm({url:`${t.endpoint}/v1/messages`,method:"POST",headers:{"Content-Type":"application/json","x-api-key":r,"anthropic-version":"2023-06-01"},body:JSON.stringify(a)},t.name,s)}async function WJ(r,e,t,n,i,o,s){let a=`${t.endpoint}/v1beta/models/${encodeURIComponent(e.name)}:generateContent`,l={};typeof i.temperature=="number"&&(l.temperature=i.temperature),typeof i.top_p=="number"&&(l.topP=i.top_p);let c={contents:[{role:"user",parts:[{text:o}]}]};return n&&n.trim().length>0&&(c.systemInstruction={role:"system",parts:[{text:n}]}),Object.keys(l).length>0&&(c.generationConfig=l),Mm({url:a,method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":r},body:JSON.stringify(c)},t.name,s)}function jJ(r){let e=r.candidates?.[0],n=(e?.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:e?.finishReason??"",stopSequence:null,created:Date.now()}}function OT(r,e,t,n,i,o={}){return async function(a){if(ne.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let l=Ji(a)+Ji(i),c=Date.now(),u=MF({provider:n.name,endpoint:n.endpoint,model:t.name,systemPrompt:i,prompt:a,modelOptions:o});P.logMessage(`[AI Request ${u}] Started ${n.name}/${t.name}`),Number.isFinite(t.maxTokens)&&t.maxTokens>0&&l>t.maxTokens&&P.logMessage(`[AI Request ${u}] Estimated prompt size is ${l} tokens, above the configured ${t.maxTokens} token context. Sending anyway; the provider will enforce the exact limit.`);try{let d=MT(r),f=sg(n),p=async w=>f==="anthropic"?UJ(await HJ(e,t,n,i,w,a,d)):f==="gemini"?jJ(await WJ(e,t,n,i,w,a,d)):qJ(await zJ(e,t,n,i,w,a,d)),m=kF(t,o),v=$m(m);v.length===0&&$m(o).length>0&&P.logMessage(`[AI Request ${u}] ${t.name} uses fixed sampling; not sending ${$T($m(o))}.`);let g;try{g=await p(m)}catch(w){let T=w.message??String(w);if(!AF(T,v))throw w;let b=$T(v);P.logMessage(`[AI Request ${u}] ${n.name} rejected ${b}; retrying without sampling parameters.`),new jy.Notice(`${t.name} doesn't accept the ${b} setting${v.length>1?"s":""}, so QuickAdd retried without ${v.length>1?"them":"it"}. You can remove ${v.length>1?"them":"it"} from this command's advanced settings.`),g=await p(PT(m))}let y=Date.now()-c;return Wy(u,{status:"success",durationMs:y,usage:g.usage}),P.logMessage(`[AI Request ${u}] Success in ${y}ms`),g}catch(d){let f=d.message??String(d),p=Date.now()-c;Wy(u,{status:"error",durationMs:p,errorMessage:f}),P.logMessage(`[AI Request ${u}] Failed in ${p}ms: ${f}`);let m=Oy(d)==="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}: ${f}${m}`,{cause:d});throw We(v),v}}}async function _q(r,e,t,n,i,o){if(r==="anthropic")return Mm({url:`${t.endpoint}/v1/messages`,method:"POST",headers:{"Content-Type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"},body:JSON.stringify(i)},t.name,o);if(r==="gemini"){let s=`${t.endpoint}/v1beta/models/${encodeURIComponent(n.name)}:generateContent`;return Mm({url:s,method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":e},body:JSON.stringify(i)},t.name,o)}return Mm({url:`${t.endpoint}/chat/completions`,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(i)},t.name,o)}async function PF(r,e,t,n,i,o){if(ne.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let s=sg(n),a={...i,modelParams:kF(t,i.modelParams??{})},l=$m(a.modelParams??{}),c=IF(s,t.name,a,FF(t)),u=i.messages.find(m=>m.role==="system"),d=[...i.messages].reverse().find(m=>m.role==="user"),f=Date.now(),p=MF({provider:n.name,endpoint:n.endpoint,model:t.name,systemPrompt:u&&u.role==="system"?u.content:"",prompt:d&&d.role==="user"?d.content:"[tool-calling turn]",modelOptions:i.modelParams??{}});try{let m;try{m=await _q(s,e,n,t,c,o)}catch(y){let w=y.message??String(y);if(!AF(w,l))throw y;let T=$T(l);P.logMessage(`[AI Chat ${p}] ${n.name} rejected ${T}; retrying without sampling parameters.`),new jy.Notice(`${t.name} doesn't accept the ${T} setting${l.length>1?"s":""}, so QuickAdd retried without ${l.length>1?"them":"it"}.`);let b=IF(s,t.name,{...a,modelParams:PT(a.modelParams??{})},FF(t));m=await _q(s,e,n,t,b,o)}let v=Tq(s,m),g=Date.now()-f;return Wy(p,{status:"success",durationMs:g,usage:v.usage}),P.logMessage(`[AI Chat ${p}] Success in ${g}ms`),{id:m.id??`${Date.now()}`,model:t.name,content:v.content,usage:v.usage,stopReason:v.rawStopReason,stopSequence:null,created:Date.now(),toolCalls:v.toolCalls,normalizedStopReason:v.normalizedStopReason,providerRaw:v.providerRaw}}catch(m){let v=m.message??String(m),g=Date.now()-f;Wy(p,{status:"error",durationMs:g,errorMessage:v});let y=new Error(`Error while making request to ${n.name}: ${v}`,{cause:m});throw We(y),y}}var jy,$F=k(()=>{jy=require("obsidian");Eq();ht();RT();DF();rr();fo();Sq();De();ky();Ry()});function Om(r){if(r){let e=new Aq.Notice(kq("starting",""),1e6);return{setMessage:(t,n)=>{e.setMessage(kq(t,n))},hide:()=>e.hide()}}return{setMessage:()=>{},hide:()=>{}}}var Aq,kq,OF=k(()=>{Aq=require("obsidian"),kq=(r,e)=>`${r==="dead"?"AI request failed.":`Assistant is ${r}.`}${e?`
${e}`:""}`});function NF(r){return{...r,modelOptions:{...r.modelOptions},usage:r.usage?{...r.usage}:void 0}}function MF(r){let e=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,t=Date.now();return os.push({...r,modelOptions:{...r.modelOptions??{}},id:e,createdAt:t,status:"pending"}),Pq(),e}function Wy(r,e){let t=os.find(n=>n.id===r);t&&(t.status=e.status,t.durationMs=e.durationMs,t.usage=e.usage,t.errorMessage=e.errorMessage,Pq())}function Fq(r=10){Number.isFinite(r)||(r=10);let e=Math.floor(r);return e<=0?[]:os.slice(-e).map(NF).reverse()}function Pq(){if(os.length<=Dq)return;let r=os.length-Dq;for(;r>0;){let e=os.findIndex(t=>t.status!=="pending");if(e===-1)break;os.splice(e,1),r-=1}}function $q(r){let e=os.find(t=>t.id===r);return e?NF(e):null}function Mq(){let r=os[os.length-1];return r?NF(r):null}function Oq(){os.splice(0,os.length)}async function GJ(r,e,t){if(typeof r!="function")throw new TypeError("Callback must be a function.");if(!(e instanceof Promise))throw new TypeError("Promise must be an instance of Promise.");if(typeof t!="number"||t<=0)throw new TypeError("Interval must be a positive number.");let n=!1;for(e.then(()=>{n=!0},()=>{n=!0});!n;)r(),await sleep(t)}function YJ(r){return r instanceof Error?r:new Error(String(r))}async function KJ(r,e,t,n=!0,i){let o;if(e.enable)o=t.find(c=>c.path.endsWith(e.name));else{let c=t.map(u=>u.basename);if(i)o=await i.suggester(c,t,"Select a prompt template");else if(n)o=await hr.Suggest(r,c,t);else throw new ve("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.")}Jn(o,"Prompt template does not exist");let s=o.path,a=r.vault.getAbstractFileByPath(s);Jn(a instanceof Iq.TFile,`${s} is not a file`);let l=await r.vault.cachedRead(a);return[o.basename,l]}async function Rq(r,e,t){if(ne.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=Om(e.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,promptTemplate:l,systemPrompt:c,promptTemplateFolder:u}=e,d=ho(r,u),[f,p]=await KJ(r,l,d,e.interactive??!0,e.promptProvider);n.setMessage("waiting","QuickAdd is formatting the prompt template.");let m=await t(p),v=["prompting",`Using prompt template "${f}".`];n.setMessage(v[0],v[1]);let y=OT(r,i,o,s,c,e.modelOptions)(m),T=(await BF(y,100,C=>{n.setMessage(v[0],`${v[1]} (${(C/1e3).toFixed(2)}s)`)},C=>{n.setMessage("finished",`Took ${(C/1e3).toFixed(2)}s.`)})).content,b=("> "+T).replace(/\n/g,`
> `),E={[a]:T,[`${a}-quoted`]:b};return window.setTimeout(()=>n.hide(),5e3),E}catch(i){throw n.setMessage("dead",i.message),window.setTimeout(()=>n.hide(),5e3),pt(i)?new dt("Input cancelled by user"):i}}async function BF(r,e,t,n){let i=Date.now();return await GJ(()=>t(Date.now()-i),r,e),n(Date.now()-i),await r}async function Lq(r,e,t){if(ne.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=Om(e.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,systemPrompt:l,prompt:c,modelOptions:u}=e;n.setMessage("waiting","QuickAdd is formatting the prompt template.");let d=await t(c),f=["prompting","Using custom prompt."];n.setMessage(f[0],f[1]);let m=OT(r,i,o,s,l,u)(d),g=(await BF(m,100,T=>{n.setMessage(f[0],`${f[1]} (${(T/1e3).toFixed(2)}s)`)},T=>{n.setMessage("finished",`Took ${(T/1e3).toFixed(2)}s.`)})).content,y=("> "+g).replace(/\n/g,`
> `),w={[a]:g,[`${a}-quoted`]:y};return window.setTimeout(()=>n.hide(),5e3),w}catch(i){throw n.setMessage("dead",i.message),window.setTimeout(()=>n.hide(),5e3),i}}function XJ(){return Array.from(new Set([LF,...["kebab","snake","camel","pascal","title","lower","upper","slug"].map(r=>ov(LF,r))])).filter(Boolean)}function Bq(r){if(r.length<=1)return null;let e=Math.floor(r.length/2),t=[`
`,`
`,". "," "],n=-1,i=Number.POSITIVE_INFINITY;for(let a of t){let l=r.lastIndexOf(a,e),c=r.indexOf(a,e),u=[l,c].filter(d=>d>0);for(let d of u){let f=d+a.length;if(f<=0||f>=r.length)continue;let p=Math.abs(f-e);p<i&&(i=p,n=f)}}if(n>0&&n<r.length)return[r.slice(0,n),r.slice(n)];let o=e,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 ZJ(r){let e=new RegExp(Xu.source,"gi"),t;for(;(t=e.exec(r))!==null;)if(t[1].split("|")[0].trim().toLowerCase()==="chunk")return!0;return!1}function JJ(r){return Ho.test(r)||bc.test(r)||ba.test(r)||fl.test(r)}function eee(r){return Nq.some(e=>r.includes(e))}function tee(r){return Nq.slice().sort((e,t)=>t.length-e.length).reduce((e,t)=>e.split(t).join(" "),r)}function Vq(r){if(r>LT)throw new Error(`QuickAdd would split this chunked AI request into more than ${LT} prompts, which exceeds the safety limit. Increase the chunk size, use a larger chunk separator, or reduce the input text.`)}function ree(r,e,t){let n=Math.max(1,Math.floor(e)),i=[r],o=0;for(;i.length>0;){let s=i.pop(),l=Ji(s)<=n?null:Bq(s);if(!l){t.push(s),o+=1,Vq(o);continue}i.push(l[1],l[0])}}function nee(r){let e=r.flags.replace(/[gy]/g,"");return new RegExp(r.source+"|",e).exec("").length-1}function oee(r,e){if(typeof e=="string"){let s=r.split(e);return{chunks:s,separators:new Array(Math.max(0,s.length-1)).fill(e)}}if(nee(e)>0||iee.test(e.source))return{chunks:r.split(e),separators:null};let t=new RegExp(`(${e.source})`,e.flags),n=r.split(t),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 see(r,e,t,n){let i=[];if(r.forEach((l,c)=>{let u=[];ree(l,t,u),u.forEach((d,f)=>{i.push({text:d,joiner:f===0&&c>0?e?.[c-1]??"":""})})}),!n)return i.map(l=>l.text);let o=[],s="",a=0;for(let l of i){let c=Ji(l.text)+Math.max(1,Ji(l.joiner));s!==""&&a+c>=t&&(o.push(s),s="",a=0),s+=s===""?l.text:l.joiner+l.text,a+=c}return s!==""&&o.push(s),o}function aee(r,e){let t=Math.max(1,Math.floor(r));if(e!==void 0&&Number.isFinite(e)&&e>0){let n=Math.floor(e);return{budget:Math.min(t,n),clamped:n>t}}return{budget:t,clamped:!1}}async function qq(r,e,t){if(ne.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=Om(e.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,systemPrompt:l,promptTemplate:c,text:u,modelOptions:d}=e;n.setMessage("chunking","Creating prompt chunks with text and prompt template");let f=e.chunkSeparator||/\n/g,{chunks:p,separators:m}=oee(u,f),v=await t(c,{chunk:LF});if(!(ZJ(c)||JJ(c)&&eee(v)))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 y=o.maxTokens,w=AB(y),T=tee(v),b=Ji(l)+Ji(T);if(b>=y)throw new Error(`The estimated prompt overhead (${b} tokens) exceeds the model's entire context window (${y} tokens). Shorten the system prompt or prompt template, or use a model with a larger context window.`);let{budget:E,clamped:C}=aee(w-b,e.maxChunkTokens);C&&P.logMessage(`[ChunkedPrompt] Requested max chunk tokens (${e.maxChunkTokens}) exceeds this model's estimated input budget; using ${E} estimated tokens per chunk instead.`);let _=e.shouldMerge??!0,I=see(p,m,E,_);Vq(I.length);let q=OT(r,i,o,s,l,d),B=["prompting",`${I.length} prompts being sent.`];n.setMessage(B[0],B[1]);let J=new RF(5,1e3*30),re=!1,L=0,W=Promise.resolve(),j=ce=>{let he=W.then(()=>{if(re)throw new Error("Chunked prompt stopped after an earlier failure.");return t(c,{chunk:ce})});return W=he.then(()=>{},()=>{}),he},$=async(ce,he=0)=>{if(re)throw new Error("Chunked prompt stopped after an earlier failure.");let Ie;try{Ie=await j(ce)}catch(we){throw re=!0,we}try{return[(await J.add(()=>{if(re)throw new Error("Chunked prompt stopped after an earlier failure.");if(L+=1,L>LT)throw new Error(`Chunked AI request exceeded the safety limit of ${LT} provider requests.`);return q(Ie)})).content]}catch(we){let Ge=Bq(ce);if(he>=QJ||!Ge||!aV(we))throw re=!0,we;n.setMessage("prompting","Provider rejected a prompt for context length. Retrying with smaller chunks.");let[Pe,Ve]=Ge,qe=await $(Pe,he+1),et=await $(Ve,he+1);return[...qe,...et]}},G=Promise.all(I.map(ce=>$(ce))),Y=(await BF(G,100,ce=>{n.setMessage(B[0],`${B[1]} (${(ce/1e3).toFixed(2)}s)`)},ce=>{n.setMessage("finished",`Took ${(ce/1e3).toFixed(2)}s.`)})).flat().join(e.resultJoiner),ie=("> "+Y).replace(/\n/g,`
> `),oe={[a]:Y,[`${a}-quoted`]:ie};return window.setTimeout(()=>n.hide(),5e3),oe}catch(i){throw n.setMessage("dead",i.message),window.setTimeout(()=>n.hide(),5e3),i}}var Iq,Dq,os,RF,QJ,LT,LF,Nq,iee,RT=k(()=>{Iq=require("obsidian");Er();Bi();Ul();ht();Dt();zy();rr();$F();Ry();OF();ky();De();Je();nE();Dq=25,os=[];RF=class{constructor(e,t){this.maxRequests=e;this.intervalMs=t;this.queue=[];this.startTimes=[]}add(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{t(await e())}catch(i){n(YJ(i))}}),this.schedule()})}schedule(){if(this.queue.length===0)return;let e=Date.now();if(this.startTimes=this.startTimes.filter(i=>e-i<this.intervalMs),this.startTimes.length>=this.maxRequests){let i=this.startTimes[0],o=Math.max(0,this.intervalMs-(e-i));window.setTimeout(()=>this.schedule(),o+1);return}let t=this.queue.shift();if(!t)return;this.startTimes.push(e);let n=t();window.setTimeout(()=>this.schedule(),this.intervalMs),this.schedule()}},QJ=12,LT=500,LF="quickadd_chunk_probe_123456789";Nq=XJ();iee=/(?:^|[^\\])(?:\\\\)*\\[1-9]/});function Uq(r){return r.normalize("NFKD").toLowerCase()}var lee,Bd,VF=k(()=>{lee=0;Bd=class{constructor(e,t){this.options=t;this.instanceId=++lee;this.indexedItems=[];this.renderedRows=[];this.query="";this.rootEl=document.createElement("div"),this.rootEl.className="qa-searchable-multi-select";let n=document.createElement("div");n.className="search-input-container qa-searchable-multi-select__search-container",this.searchInputEl=document.createElement("input"),this.searchInputEl.className="qa-searchable-multi-select__search",this.searchInputEl.type="search",this.searchInputEl.name=`qa-multi-select-search-${this.instanceId}`,this.searchInputEl.placeholder=t.searchPlaceholder??"Search options...",this.searchInputEl.setAttribute("aria-label",this.searchInputEl.placeholder),this.searchInputEl.setAttribute("autocomplete","off"),this.searchInputEl.setAttribute("spellcheck","false"),n.appendChild(this.searchInputEl),this.summaryEl=document.createElement("div"),this.summaryEl.className="qa-searchable-multi-select__summary",this.summaryEl.setAttribute("aria-live","polite"),this.listEl=document.createElement("div"),this.listEl.className="qa-searchable-multi-select__list",this.listEl.setAttribute("role","group"),this.listEl.setAttribute("aria-label","Options"),this.rootEl.append(n,this.summaryEl,this.listEl),e.appendChild(this.rootEl),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}if(i.key==="ArrowUp"){i.preventDefault(),this.renderedRows.at(-1)?.input.focus();return}i.key==="Escape"&&this.query&&(i.preventDefault(),i.stopPropagation(),this.query="",this.searchInputEl.value="",this.renderList())}),this.setItems(t.items)}setItems(e){this.indexedItems=e.map((t,n)=>({item:t,index:n,searchableText:Uq(`${t.label} ${t.searchText??""}`)})),this.searchInputEl.disabled=e.length===0,this.renderList()}focusSearchOnOpen(){document.body.classList.contains("is-mobile")||this.searchInputEl.focus()}refreshSelection(){for(let{item:e,input:t}of this.renderedRows)t.checked=this.options.isSelected(e),t.closest("label")?.classList.toggle("is-selected",t.checked);this.updateSummary()}getMatchingItems(){let e=Uq(this.query.trim()).split(/\s+/).filter(Boolean);return e.length===0?this.indexedItems:this.indexedItems.filter(({searchableText:t})=>e.every(n=>t.includes(n)))}getVisibleItems(e){if(e.length<=200)return e;let t=[],n=[];for(let i of e)(this.options.isSelected(i.item)?t:n).push(i);return[...t,...n].slice(0,200)}renderList(){this.listEl.replaceChildren(),this.renderedRows=[];let e=this.getMatchingItems(),t=this.getVisibleItems(e);if(t.length===0){let n=document.createElement("div");n.className="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",this.listEl.appendChild(n)}for(let n of t)this.renderRow(n);if(e.length>t.length){let n=document.createElement("div");n.className="qa-searchable-multi-select__limit",n.setAttribute("role","status"),n.textContent=`Showing ${t.length} of ${e.length} options. Refine your search to see the rest.`,this.listEl.appendChild(n)}this.updateSummary(e.length)}renderRow(e){let{item:t,index:n}=e,i=document.createElement("label");i.className="qa-searchable-multi-select__option";let o=document.createElement("input");o.type="checkbox",o.name=`qa-multi-select-${this.instanceId}`,o.id=`qa-multi-select-${this.instanceId}-${n}`,o.checked=this.options.isSelected(t);let s=document.createElement("span");s.className="qa-searchable-multi-select__option-label",s.textContent=t.label,i.htmlFor=o.id,i.classList.toggle("is-selected",o.checked),i.append(s,o),o.addEventListener("change",()=>{this.options.onToggle(t,o.checked),this.refreshSelection()}),o.addEventListener("keydown",a=>{this.handleOptionKeydown(a,o)}),this.listEl.appendChild(i),this.renderedRows.push({item:t,input:o})}handleOptionKeydown(e,t){let n=this.renderedRows.findIndex(i=>i.input===t);if(e.key==="ArrowDown"){e.preventDefault(),this.renderedRows[n+1]?.input.focus();return}if(e.key==="ArrowUp"){e.preventDefault(),n===0?this.searchInputEl.focus():this.renderedRows[n-1]?.input.focus();return}if(e.key==="Home"){e.preventDefault(),this.renderedRows[0]?.input.focus();return}if(e.key==="End"){e.preventDefault(),this.renderedRows.at(-1)?.input.focus();return}if(e.key==="Enter"||e.key===" "){e.preventDefault(),t.checked=!t.checked,t.dispatchEvent(new Event("change",{bubbles:!0}));return}e.key==="/"&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&(e.preventDefault(),this.searchInputEl.focus())}updateSummary(e=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()){this.summaryEl.textContent=`${n} \xB7 ${this.indexedItems.length} options`;return}this.summaryEl.textContent=`${n} \xB7 ${e} matches`}}});var du,Vd,zq=k(()=>{du=require("obsidian");Qi();Er();VF();Vd=class r extends du.Modal{constructor(t,n,i,o={}){super(t);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(t,n,i,o={}){return new r(t,n,i,o).waitForClose}seedPreselection(t){if(t?.length)for(let n of t){let i=n?.trim();i&&(!this.items.includes(i)&&!this.customValues.includes(i)&&this.customValues.push(i),this.selected.add(i))}}render(){this.containerEl.addClass("quickAddModal","qaSearchableMultiSelectModal","qaMultiSuggester"),this.titleEl.setText(this.opts.placeholder??"Select one or more");let{contentEl:t}=this;t.empty();let n=t.createDiv({cls:"qa-multi-list"});this.picker=new Bd(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 du.Setting(t).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 du.Setting(t);i.settingEl.addClass("qa-multi-actions"),i.addButton(o=>o.setButtonText("Done").setCta().onClick(()=>this.submit())),i.addButton(o=>o.setButtonText("Cancel").onClick(()=>this.close())),this.opts.skippable&&i.addButton(o=>o.setButtonText("Skip").setTooltip("Leave empty").onClick(()=>{this.skipped=!0,this.didSubmit=!0,this.close()}))}getSearchableItems(){return[...this.items.map((t,n)=>({key:t,value:t,label:zr(this.displayItems[n]??t),searchText:t})),...this.customValues.map(t=>({key:t,value:t,label:t}))]}commitDraft(){let t=this.draft.trim();return t?(this.items.includes(t)||this.customValues.includes(t))&&this.selected.has(t)?(new du.Notice(`"${t}" is already added.`),!1):(!this.items.includes(t)&&!this.customValues.includes(t)&&this.customValues.push(t),this.selected.add(t),this.draft="",this.render(),this.focusCustomInput(),!0):(new du.Notice("Enter a value to add."),!1)}focusCustomInput(){this.contentEl.querySelector(".qa-multi-custom-input")?.focus()}submit(){if(this.opts.allowCustomValue&&this.draft.trim()){let t=this.draft.trim();!this.items.includes(t)&&!this.customValues.includes(t)&&this.customValues.push(t),this.selected.add(t),this.draft=""}this.didSubmit=!0,this.close()}collectResult(){let t=[];for(let n of this.items)this.selected.has(n)&&t.push(n);for(let n of this.customValues)this.selected.has(n)&&t.push(n);return t}onClose(){super.onClose(),this.didSubmit?this.resolvePromise(this.skipped?[]:this.collectResult()):this.rejectPromise(Ir())}}});var pu,cee,uee,dee,Wq,qF,Gy,UF,Hq,NT,zF=k(()=>{pu=r=>r.toString().padStart(2,"0"),cee=r=>{if(typeof r=="number"&&r>=0&&r<=6)return r;let t=window.moment?.localeData?.()?.firstDayOfWeek?.();return typeof t=="number"&&t>=0&&t<=6?t:0},uee=r=>{let e=new Intl.DateTimeFormat(void 0,{weekday:"short"}),t=new Date(2021,7,1),n=Array.from({length:7},(i,o)=>{let s=new Date(t.getFullYear(),t.getMonth(),t.getDate()+o);return e.format(s)});return n.slice(r).concat(n.slice(0,r))},dee=(r,e)=>new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(r,e,1)),Wq=(r,e,t)=>`${r}-${pu(e+1)}-${pu(t)}`,qF=r=>Wq(r.getFullYear(),r.getMonth(),r.getDate()),Gy=r=>{if(!r)return null;let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(e){let[,n,i,o]=e;return new Date(Number.parseInt(n,10),Number.parseInt(i,10)-1,Number.parseInt(o,10))}let t=new Date(r);return Number.isNaN(t.getTime())?null:t},UF=(r,e,t,n)=>{let i=Wq(r,e,t);return n?`${i}T${pu(n.hour)}:${pu(n.minute)}:00`:i},Hq=r=>{if(!r)return null;let e=/[T ](\d{2}):(\d{2})/.exec(r);if(!e)return null;let t=Number.parseInt(e[1],10),n=Number.parseInt(e[2],10);return Number.isNaN(t)||Number.isNaN(n)||t<0||t>23||n<0||n>59?null:{hour:t,minute:n}},NT=r=>{let e=cee(r.weekStartsOn),t=uee(e),n=Gy(r.initialIso)??new Date,i=n.getFullYear(),o=n.getMonth(),s=r.initialIso,a=r.withTime===!0,l=a?Hq(r.initialIso)??{hour:0,minute:0}:null,c=r.container.createDiv({cls:"qa-date-picker"}),u=c.createDiv({cls:"qa-date-picker__header"}),d=u.createEl("button",{cls:"qa-date-picker__nav",text:"\u2039"});d.type="button",d.setAttr("aria-label","Previous month");let f=u.createDiv({cls:"qa-date-picker__label"}),p=u.createEl("button",{cls:"qa-date-picker__nav",text:"\u203A"});p.type="button",p.setAttr("aria-label","Next month");let m=c.createDiv({cls:"qa-date-picker__weekdays"});t.forEach(I=>{let q=m.createDiv({cls:"qa-date-picker__weekday"});q.textContent=I});let v=c.createDiv({cls:"qa-date-picker__grid"}),g=c.createDiv({cls:"qa-date-picker__actions"}),y=g.createEl("button",{cls:"qa-date-picker__action",text:"Today"});y.type="button";let w=g.createEl("button",{cls:"qa-date-picker__action",text:"Clear"});w.type="button";let T;if(a){let I=c.createDiv({cls:"qa-date-picker__time"});I.createEl("label",{cls:"qa-date-picker__time-label",text:"Time"}),T=I.createEl("input",{cls:"qa-date-picker__time-input"}),T.type="time",l&&(T.value=`${pu(l.hour)}:${pu(l.minute)}`)}let b=I=>{o+=I,o>11?(o=0,i+=1):o<0&&(o=11,i-=1),_()},E=(I,q)=>{s=I,r.onSelect(I,q),_()},C=I=>{s=void 0,r.onSelect(null,I),_()};d.addEventListener("click",()=>b(-1)),p.addEventListener("click",()=>b(1)),y.addEventListener("click",()=>{let I=new Date,q=UF(I.getFullYear(),I.getMonth(),I.getDate(),l);i=I.getFullYear(),o=I.getMonth(),E(q,"action")}),w.addEventListener("click",()=>C("action")),T&&T.addEventListener("change",()=>{if(T.value.trim()==="")l={hour:0,minute:0};else{let[I,q]=T.value.split(":").map(B=>Number.parseInt(B,10));if(Number.isNaN(I)||Number.isNaN(q))return;l={hour:I,minute:q}}if(s){let I=Gy(s);I&&E(UF(I.getFullYear(),I.getMonth(),I.getDate(),l),"picker")}});let _=()=>{f.textContent=dee(i,o),v.empty();let q=(new Date(i,o,1).getDay()-e+7)%7,B=new Date(i,o,1-q),J=qF(new Date),re=s?Gy(s):null,L=re?qF(re):void 0,W=new Intl.DateTimeFormat(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"});for(let j=0;j<42;j+=1){let $=new Date(B);$.setDate(B.getDate()+j);let G=qF($),U=$.getMonth()!==o,H=G===J,Y=L&&G===L,ie=v.createEl("button",{cls:"qa-date-picker__day",text:String($.getDate())});ie.type="button",ie.setAttr("aria-label",W.format($)),U&&ie.addClass("is-outside"),H&&ie.addClass("is-today"),Y&&(ie.addClass("is-selected"),ie.setAttr("aria-pressed","true")),ie.addEventListener("click",()=>{let oe=UF($.getFullYear(),$.getMonth(),$.getDate(),l);E(oe,"picker")})}};return _(),{setSelectedIso:(I,{updateView:q}={})=>{if(s=I,I&&q!==!1){let B=Gy(I);B&&(i=B.getFullYear(),o=B.getMonth())}if(a&&I){let B=Hq(I);B&&(l=B,T&&(T.value=`${pu(B.hour)}:${pu(B.minute)}`))}_()},setViewFromIso:I=>{let q=Gy(I);q&&(i=q.getFullYear(),o=q.getMonth(),_())},destroy:()=>{c.remove()}}}});function zl(r,e,t=ns,n){if(!r||!r.trim())return{isValid:!1,error:"Empty input"};try{let i=n??ne.getState().dateAliases,o=lg(r,i),s=t.parseDate(o);if(s?.moment?.isValid()){let a=s.moment.toISOString(),l=e?s.moment.format(e):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 qa(r,e){if(!window.moment)return null;try{let t=window.moment(r);if(t.isValid())return t.format(e)}catch{}return null}var Rm=k(()=>{Dd();ht();Ku()});var Nm,Lm,Hl,BT=k(()=>{Nm=require("obsidian");Ns();zF();Rm();ht();Ku();Lm=class Lm extends sr{constructor(t,n,i,o,s,a,l){super(t,n,i,o??"",void 0,void 0,a);this.isOpen=!0;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.updatePreviewDebounced=(0,Nm.debounce)(this.updatePreview.bind(this),250,!0),this.updatePreview()}supportsPeek(){return!1}static Prompt(t,n,i,o,s,a,l){return new Lm(t,n,i,o,s,a,l).waitForClose}createInputField(t,n,i){t.addClass("qa-date-input");let o=new Nm.TextComponent(t);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=t.createDiv({cls:"qa-date-picker-container"}),this.createPreviewElement(t),o}mountDatePicker(){this.datePicker=NT({container:this.pickerHostEl,initialIso:this.selectedIso,withTime:this.withTime,onSelect:t=>{t?this.applyPickerSelection(t):this.clearPickerSelection()}})}createPreviewElement(t){let n=t.createDiv("vdate-preview-container");n.createEl("div",{text:"Preview:",cls:"vdate-preview-label"}),this.previewEl=n.createEl("div",{cls:"vdate-preview-text"}),this.previewEl.textContent=Lm.PREVIEW_PLACEHOLDER;let i=cg(ne.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.createEl("div",{cls:"vdate-alias-list"});a.textContent=Pw(ne.getState().dateAliases)}}updatePreview(){if(!this.isOpen)return;let t=this.currentInput.trim();if(!t&&this.defaultValue&&!this.isOptionalPrompt){this.renderPreviewFromInput(this.defaultValue);return}if(!t){this.selectedIso=void 0,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(),this.setPreviewText(this.isOptionalPrompt?"Will be left empty":Lm.PREVIEW_PLACEHOLDER,!1);return}if(t.startsWith("@date:")){let n=t.slice(6).trim();if(n){this.selectedIso=n,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(n),this.renderPreviewFromIso(n);return}}if(this.selectedIso&&this.lastPickerDisplayValue&&t===this.lastPickerDisplayValue){this.syncPickerSelection(this.selectedIso,!1),this.renderPreviewFromIso(this.selectedIso);return}this.renderPreviewFromInput(t)}formatIsoForInput(t){let n=qa(t,this.dateFormat);return n||(t.length>=10?t.slice(0,10):t)}syncPickerSelection(t,n=!0){this.datePicker?.setSelectedIso(t,{updateView:n})}applyPickerSelection(t){let n=this.formatIsoForInput(t);this.selectedIso=t,this.lastPickerDisplayValue=n,this.inputComponent?.inputEl&&(this.inputComponent.inputEl.value=n),this.onInputChanged(n),this.currentInput=n,this.syncPickerSelection(t),this.renderPreviewFromIso(t)}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(t){this.setPreviewText(this.formatIsoForInput(t),!1)}renderPreviewFromInput(t){let n=zl(t,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(t,n){this.previewEl.textContent=t,this.previewEl.toggleClass("is-error",n)}onOpen(){super.onOpen()}transformInputOnSubmit(t){let n=t.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=zl(this.defaultValue,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`}if(n){let i=zl(n,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`;new Nm.Notice(`QuickAdd: "${n}" could not be parsed as a date; using it as-is.`)}return t}onClose(){this.isOpen=!1,this.updatePreviewDebounced.cancel(),!this.input.trim()&&this.defaultValue&&!this.isOptionalPrompt&&(this.input=this.defaultValue),super.onClose()}};Lm.PREVIEW_PLACEHOLDER="Preview will appear here";Hl=Lm});function pee(r,e,t,n={}){let i=n.tab??" ";if(e===t){let d=e+i.length;return{regionStart:e,regionEnd:e,replacement:i,selectionStart:d,selectionEnd:d}}let o=e===0?0:r.lastIndexOf(`
`,e-1)+1,a=r.slice(o,t).split(`
`),l=a.length-1,c=0,u=a.map((d,f)=>f===l&&d===""?d:(c+=i.length,i+d));return{regionStart:o,regionEnd:t,replacement:u.join(`
`),selectionStart:e+i.length,selectionEnd:t+c}}function fee(r,e){r.setSelectionRange(e.regionStart,e.regionEnd);let t=r.ownerDocument,n=!1;try{n=typeof t.execCommand=="function"&&t.execCommand("insertText",!1,e.replacement)}catch{n=!1}if(!n){let i=r.value;r.value=i.slice(0,e.regionStart)+e.replacement+i.slice(e.regionEnd),r.setSelectionRange(e.selectionStart,e.selectionEnd),r.dispatchEvent(new Event("input",{bubbles:!0}));return}r.setSelectionRange(e.selectionStart,e.selectionEnd)}function jq(r,e={}){let t=i=>{if(i.key!=="Tab"||i.shiftKey||i.ctrlKey||i.metaKey||i.altKey||i.isComposing||i.defaultPrevented)return;i.preventDefault();let o=r.selectionStart??r.value.length,s=r.selectionEnd??o;fee(r,pee(r.value,o,s,e))};r.addEventListener("keydown",t);let n=!1;return()=>{n||(n=!0,r.removeEventListener("keydown",t))}}var Gq=k(()=>{});var Bm,fu,HF=k(()=>{Bm=require("obsidian");AC();IC();RA();LA();NA();Gq();Kg();Er();GC();df();YC();fu=class r extends Bm.Modal{constructor(t,n,i,o,s,a,l){super(t);this.header=n;this.linkSourcePath=s;this.options=l;this.didSubmit=!1;this.didClose=!1;this.submitClickCallback=t=>this.submit();this.cancelClickCallback=t=>this.cancel();this.skipClickCallback=t=>this.skip();this.submitEnterCallback=t=>{if(this.supportsPeek()&&jC(t)){t.preventDefault(),this.peek.peek();return}if(this.isOptionalPrompt&&WC(t)){t.preventDefault(),this.skip();return}(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.submit())};this.placeholder=i??"",this.description=a?.trim()||void 0,this.draftHandler=new af({kind:"multi",header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath,scopeId:l?.draftScopeId}),this.input=this.draftHandler.hydrate(o??""),this.waitForClose=new Promise((c,u)=>{this.resolvePromise=c,this.rejectPromise=u}),this.peek=new Vc({app:t,title:this.header,containerEl:this.containerEl,scope:this.scope,getField:()=>this.inputComponent?.inputEl,getValue:()=>this.input,setValue:c=>{this.input=c},markDraftChanged:()=>this.draftHandler.markChanged(),persistDraft:()=>this.persistDraft(),close:()=>this.close()}),this.display(),this.open(),this.attachSuggesters()}static Prompt(t,n,i,o,s,a){return new r(t,n,i,o,void 0,s,a).waitForClose}static PromptWithContext(t,n,i,o,s,a,l){return new r(t,n,i,o,s,a,l).waitForClose}display(){this.containerEl.addClass("quickAddModal","qaWideInputPrompt"),pf(this.containerEl),this.contentEl.empty(),this.titleEl.textContent=this.header,PC(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 t=this.contentEl.createDiv();this.inputComponent=this.createInputField(t,this.placeholder,this.input),this.createButtonBar(t)}createInputField(t,n,i){let o=new Bm.TextAreaComponent(t);return o.inputEl.classList.add("wideInputPromptInputEl"),o.inputEl.setAttribute("dir","auto"),o.setPlaceholder(n??"").setValue(i??"").onChange(s=>this.onInputChanged(s)).inputEl.addEventListener("keydown",this.submitEnterCallback),this.disposeIndent=jq(o.inputEl),this.options?.imagePaste&&(this.imagePasteHandle=uf(this.app,o.inputEl,this.options.imagePaste)),o}createButton(t,n,i){let o=new Bm.ButtonComponent(t);return o.setButtonText(n).onClick(i),o}get isOptionalPrompt(){return this.options?.optional===!0}supportsPeek(){return this.options?.allowPeek===!0}createButtonBar(t){let n=t.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"});ff(this.createButton(o,"Peek at note",()=>this.peek.peek()))}}submit(){if(!(this.didSubmit||this.didClose)){if(this.imagePasteHandle?.isBusy()){this.imagePasteHandle.whenIdle().then(()=>this.submit());return}this.input=this.inputComponent?.inputEl?.value??this.input,this.didSubmit=!0,this.close()}}skip(){this.didSubmit||(this.input="",this.didSubmit=!0,this.close())}cancel(){this.close()}resolveInput(){this.didSubmit?this.resolvePromise(this.input):this.rejectPromise(Ir())}onInputChanged(t){this.draftHandler.markChanged(),this.input=t}syncInputFromEl(){this.inputComponent?.inputEl&&(this.input=this.inputComponent.inputEl.value)}persistDraft(){this.draftHandler.persist(this.input,this.didSubmit)}attachSuggesters(){this.fileSuggester=new Oc(this.app,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new Rc(this.app,this.inputComponent.inputEl)}removeInputListener(){this.inputComponent.inputEl.removeEventListener("keydown",this.submitEnterCallback),this.disposeIndent?.(),this.imagePasteHandle?.detach()}onOpen(){super.onOpen(),this.peek.onHostOpened(),FC(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 Yy,Yq=k(()=>{Ns();es();Yy=class r extends sr{supportsPeek(){return!1}static Prompt(e,t,n,i,o,s){return new r(e,t,n,i,void 0,o,s).waitForClose}static PromptWithContext(e,t,n,i,o,s,a){return new r(e,t,n,i,o,s,a).waitForClose}createInputField(e,t,n){let i=super.createInputField(e,t,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(e){return this.options?.numeric?e===""&&this.isOptionalPrompt?"":Vs(e,this.options.numeric):e}}});var WF,Ky,Kq=k(()=>{Ns();es();WF={min:0,max:100,step:1},Ky=class r extends sr{supportsPeek(){return!1}static Prompt(e,t,n,i,o,s){return new r(e,t,n,i,void 0,o,s).waitForClose}static PromptWithContext(e,t,n,i,o,s,a){return new r(e,t,n,i,o,s,a).waitForClose}createInputField(e,t,n){let i=this.options?.slider??WF,o=this.isOptionalPrompt&&!n,s=lv(n,i);this.sliderEl=e.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(e,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 e=this.numberEl.value;if(e===""&&this.isOptionalPrompt){this.onInputChanged("");return}let t=Vs(e,this.options?.slider??WF);t!==""&&(this.sliderEl.value=t),this.onInputChanged(e)}transformInputOnSubmit(e){return e===""&&this.isOptionalPrompt?"":lv(e,this.options?.slider??WF)}}});var Vm,Qq=k(()=>{HF();Ns();Yq();Kq();xa();Vm=class{factory(e){return e==="multiline"?fu:e==="number"?Yy:e==="slider"?Ky:kn().settings.inputPrompt==="multi-line"?fu:sr}}});function gee(r){return`\\begin{${r}}
\u261A
\\end{${r}}\u261A`}var mee,hee,Xq,jF=k(()=>{mee=["\\!","\\,","\\:","\\>","\\;","\\#","\\$","\\%","\\&","\\","_","{ }","|","^{\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"],hee=["align","align*","alignat","alignat*","array","Bmatrix","bmatrix","cases","eqnarray","eqnarray*","equation","equation*","gather","gather*","matrix","pmatrix","smallmatrix","subarray","Vmatrix","vmatrix"];Xq=[...mee,...hee.map(gee)]});function yee(r){if(GF.has(r))return GF.get(r)??null;let e=null;try{e=(0,Zq.renderMath)(r,!0)}catch{e=null}return GF.set(r,e),e}function bee(r){return YF===null&&(YF=new Mc(r,{findAllMatches:!0,threshold:.8})),YF}var Zq,vee,GF,YF,VT,Jq=k(()=>{Ca();_C();Zq=require("obsidian");jF();xa();vee=new RegExp(/\\([a-z{}A-Z0-9]*)$/),GF=new Map,YF=null;VT=class extends Hr{constructor(t){super(kn().app,t);this.inputEl=t;this.lastInput="";this.symbols=Object.assign([],Xq)}getSuggestions(t){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=t.slice(0,n),o=i.lastIndexOf("\\"),s=i.slice(o),a=vee.exec(s),l=[];a&&(this.lastInput=a[1],l=this.symbols.filter(d=>d.toLowerCase().contains(this.lastInput)));let c=new Set(l);return bee(this.symbols).search(this.lastInput).map(d=>d.item).filter(d=>c.has(d))}renderSuggestion(t,n){if(t){n.setText(t);let i=yee(t);i&&n.append(i.cloneNode(!0))}}selectSuggestion(t){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.lastInput.length,o=this.inputEl.value,s=0,a=t.replace(/\\\\/g,"\\");if(this.inputEl.value=`${o.slice(0,n-i-1)}${a}${o.slice(n)}`,s=n-i+t.length-1,this.inputEl.trigger("input"),this.close(),t.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 eo,qT,eU=k(()=>{eo=require("obsidian");xa();jF();Jq();Er();qT=class r extends eo.Modal{constructor(){super(kn().app);this.didSubmit=!1;this.keybindListener=t=>{(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&this.submit(),t.key==="Tab"&&(t.preventDefault(),this.cursorToGoTo())};this.submitClickCallback=t=>this.submit();this.cancelClickCallback=t=>this.cancel();this.open(),this.display(),this.waitForClose=new Promise((t,n)=>{this.resolvePromise=t,this.rejectPromise=n}),new VT(this.inputEl),this.inputEl.focus(),this.inputEl.select()}static Prompt(){return new r().waitForClose}display(){this.containerEl.addClass("quickAddModal","qaMathModal"),this.contentEl.empty();let t=this.contentEl.createDiv();t.className="math math-block is-loaded";let n=new eo.TextAreaComponent(this.contentEl);n.inputEl.setCssStyles({width:"100%",height:"10rem"}),this.inputEl=n.inputEl,n.onChange((0,eo.debounce)(async o=>await this.mathjaxLoop(t,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,eo.loadMathJax)()}async mathjaxLoop(t,n){let i=(0,eo.renderMath)(n,!0);await(0,eo.finishRenderMath)(),t.empty(),t.append(i)}cursorToGoTo(){if(this.inputEl.value.contains("\u261A")){let t=this.inputEl.value.indexOf("\u261A");this.inputEl.value=this.inputEl.value.replace("\u261A",""),this.inputEl.setSelectionRange(t,t)}}createButton(t,n,i){let o=new eo.ButtonComponent(t);return o.setButtonText(n).onClick(i),o}createButtonBar(t){let n=t.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 t=this.inputEl.value.replace(/\\n/g,"\\\\n").replace(new RegExp("\u261A","g"),"");this.didSubmit?this.resolvePromise(t):this.rejectPromise(Ir())}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListeners()}}});var Pz=B6(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});require("obsidian");var jl=class extends Error{},n0=class extends jl{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},i0=class extends jl{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},o0=class extends jl{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},zd=class extends jl{},QT=class extends jl{constructor(e){super(`Invalid unit ${e}`)}},to=class extends jl{},Ua=class extends jl{constructor(){super("Zone is an abstract class")}},be="numeric",ea="short",Ao="long",XT={year:be,month:be,day:be},PU={year:be,month:ea,day:be},wee={year:be,month:ea,day:be,weekday:ea},$U={year:be,month:Ao,day:be},MU={year:be,month:Ao,day:be,weekday:Ao},OU={hour:be,minute:be},RU={hour:be,minute:be,second:be},LU={hour:be,minute:be,second:be,timeZoneName:ea},NU={hour:be,minute:be,second:be,timeZoneName:Ao},BU={hour:be,minute:be,hourCycle:"h23"},VU={hour:be,minute:be,second:be,hourCycle:"h23"},qU={hour:be,minute:be,second:be,hourCycle:"h23",timeZoneName:ea},UU={hour:be,minute:be,second:be,hourCycle:"h23",timeZoneName:Ao},zU={year:be,month:be,day:be,hour:be,minute:be},HU={year:be,month:be,day:be,hour:be,minute:be,second:be},WU={year:be,month:ea,day:be,hour:be,minute:be},jU={year:be,month:ea,day:be,hour:be,minute:be,second:be},Cee={year:be,month:ea,day:be,weekday:ea,hour:be,minute:be},GU={year:be,month:Ao,day:be,hour:be,minute:be,timeZoneName:ea},YU={year:be,month:Ao,day:be,hour:be,minute:be,second:be,timeZoneName:ea},KU={year:be,month:Ao,day:be,weekday:Ao,hour:be,minute:be,timeZoneName:Ao},QU={year:be,month:Ao,day:be,weekday:Ao,hour:be,minute:be,second:be,timeZoneName:Ao},jd=class{get type(){throw new Ua}get name(){throw new Ua}get ianaName(){return this.name}get isUniversal(){throw new Ua}offsetName(e,t){throw new Ua}formatOffset(e,t){throw new Ua}offset(e){throw new Ua}equals(e){throw new Ua}get isValid(){throw new Ua}},KF=null,ZT=class r extends jd{static get instance(){return KF===null&&(KF=new r),KF}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return ZU(e,t,n)}formatOffset(e,t){return tb(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},YT={};function Eee(r){return YT[r]||(YT[r]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),YT[r]}var xee={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Tee(r,e){let t=r.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,i,o,s,a,l,c,u]=n;return[s,i,o,a,l,c,u]}function See(r,e){let t=r.formatToParts(e),n=[];for(let i=0;i<t.length;i++){let{type:o,value:s}=t[i],a=xee[o];o==="era"?n[a]=s:yt(a)||(n[a]=parseInt(s,10))}return n}var UT={},yu=class r extends jd{static create(e){return UT[e]||(UT[e]=new r(e)),UT[e]}static resetCache(){UT={},YT={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=r.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return ZU(e,t,n,this.name)}formatOffset(e,t){return tb(this.offset(e),t)}offset(e){let t=new Date(e);if(isNaN(t))return NaN;let n=Eee(this.name),[i,o,s,a,l,c,u]=n.formatToParts?See(n,t):Tee(n,t);a==="BC"&&(i=-Math.abs(i)+1);let f=aS({year:i,month:o,day:s,hour:l===24?0:l,minute:c,second:u,millisecond:0}),p=+t,m=p%1e3;return p-=m>=0?m:1e3+m,(f-p)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},tU={};function _ee(r,e={}){let t=JSON.stringify([r,e]),n=tU[t];return n||(n=new Intl.ListFormat(r,e),tU[t]=n),n}var s0={};function a0(r,e={}){let t=JSON.stringify([r,e]),n=s0[t];return n||(n=new Intl.DateTimeFormat(r,e),s0[t]=n),n}var l0={};function kee(r,e={}){let t=JSON.stringify([r,e]),n=l0[t];return n||(n=new Intl.NumberFormat(r,e),l0[t]=n),n}var c0={};function Aee(r,e={}){let{base:t,...n}=e,i=JSON.stringify([r,n]),o=c0[i];return o||(o=new Intl.RelativeTimeFormat(r,e),c0[i]=o),o}var Jy=null;function Dee(){return Jy||(Jy=new Intl.DateTimeFormat().resolvedOptions().locale,Jy)}function Iee(r){let e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));let t=r.indexOf("-u-");if(t===-1)return[r];{let n,i;try{n=a0(r).resolvedOptions(),i=r}catch{let l=r.substring(0,t);n=a0(l).resolvedOptions(),i=l}let{numberingSystem:o,calendar:s}=n;return[i,o,s]}}function Fee(r,e,t){return(t||e)&&(r.includes("-u-")||(r+="-u"),t&&(r+=`-ca-${t}`),e&&(r+=`-nu-${e}`)),r}function Pee(r){let e=[];for(let t=1;t<=12;t++){let n=ft.utc(2009,t,1);e.push(r(n))}return e}function $ee(r){let e=[];for(let t=1;t<=7;t++){let n=ft.utc(2016,11,13+t);e.push(r(n))}return e}function zT(r,e,t,n){let i=r.listingMode();return i==="error"?null:i==="en"?t(e):n(e)}function Mee(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||new Intl.DateTimeFormat(r.intl).resolvedOptions().numberingSystem==="latn"}var u0=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:o,...s}=n;if(!t||Object.keys(s).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=kee(e,a)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{let t=this.floor?Math.floor(e):T0(e,3);return Yr(t,this.padTo)}}},d0=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let i;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&yu.create(a).valid?(i=a,this.dt=e):(i="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,i=e.zone.name):(i="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||i,this.dtf=a0(t,o)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:n}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},p0=class{constructor(e,t,n){this.opts={style:"long",...n},!t&&XU()&&(this.rtf=Aee(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):Qee(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},kr=class r{static fromOpts(e){return r.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,t,n,i=!1){let o=e||_r.defaultLocale,s=o||(i?"en-US":Dee()),a=t||_r.defaultNumberingSystem,l=n||_r.defaultOutputCalendar;return new r(s,a,l,o)}static resetCache(){Jy=null,s0={},l0={},c0={}}static fromObject({locale:e,numberingSystem:t,outputCalendar:n}={}){return r.create(e,t,n)}constructor(e,t,n,i){let[o,s,a]=Iee(e);this.locale=o,this.numberingSystem=t||s||null,this.outputCalendar=n||a||null,this.intl=Fee(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=Mee(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:r.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return zT(this,e,tz,()=>{let n=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";return this.monthsCache[i][e]||(this.monthsCache[i][e]=Pee(o=>this.extract(o,n,"month"))),this.monthsCache[i][e]})}weekdays(e,t=!1){return zT(this,e,iz,()=>{let n=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=t?"format":"standalone";return this.weekdaysCache[i][e]||(this.weekdaysCache[i][e]=$ee(o=>this.extract(o,n,"weekday"))),this.weekdaysCache[i][e]})}meridiems(){return zT(this,void 0,()=>oz,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ft.utc(2016,11,13,9),ft.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return zT(this,e,sz,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[ft.utc(-40,1,1),ft.utc(2017,1,1)].map(n=>this.extract(n,t,"era"))),this.eraCache[e]})}extract(e,t,n){let i=this.dtFormatter(e,t),o=i.formatToParts(),s=o.find(a=>a.type.toLowerCase()===n);return s?s.value:null}numberFormatter(e={}){return new u0(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new d0(e,this.intl,t)}relFormatter(e={}){return new p0(this.intl,this.isEnglish(),e)}listFormatter(e={}){return _ee(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}},QF=null,ls=class r extends jd{static get utcInstance(){return QF===null&&(QF=new r(0)),QF}static instance(e){return e===0?r.utcInstance:new r(e)}static parseSpecifier(e){if(e){let t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new r(lS(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${tb(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${tb(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return tb(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},f0=class extends jd{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function vu(r,e){if(yt(r)||r===null)return e;if(r instanceof jd)return r;if(Oee(r)){let t=r.toLowerCase();return t==="default"?e:t==="local"||t==="system"?ZT.instance:t==="utc"||t==="gmt"?ls.utcInstance:ls.parseSpecifier(t)||yu.create(r)}else return Wd(r)?ls.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new f0(r)}var rU=()=>Date.now(),nU="system",iU=null,oU=null,sU=null,aU=60,lU,_r=class{static get now(){return rU}static set now(e){rU=e}static set defaultZone(e){nU=e}static get defaultZone(){return vu(nU,ZT.instance)}static get defaultLocale(){return iU}static set defaultLocale(e){iU=e}static get defaultNumberingSystem(){return oU}static set defaultNumberingSystem(e){oU=e}static get defaultOutputCalendar(){return sU}static set defaultOutputCalendar(e){sU=e}static get twoDigitCutoffYear(){return aU}static set twoDigitCutoffYear(e){aU=e%100}static get throwOnInvalid(){return lU}static set throwOnInvalid(e){lU=e}static resetCaches(){kr.resetCache(),yu.resetCache()}};function yt(r){return typeof r>"u"}function Wd(r){return typeof r=="number"}function sS(r){return typeof r=="number"&&r%1===0}function Oee(r){return typeof r=="string"}function Ree(r){return Object.prototype.toString.call(r)==="[object Date]"}function XU(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Lee(r){return Array.isArray(r)?r:[r]}function cU(r,e,t){if(r.length!==0)return r.reduce((n,i)=>{let o=[e(i),i];return n&&t(n[0],o[0])===n[0]?n:o},null)[1]}function Nee(r,e){return e.reduce((t,n)=>(t[n]=r[n],t),{})}function jm(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Wl(r,e,t){return sS(r)&&r>=e&&r<=t}function Bee(r,e){return r-e*Math.floor(r/e)}function Yr(r,e=2){let t=r<0,n;return t?n="-"+(""+-r).padStart(e,"0"):n=(""+r).padStart(e,"0"),n}function gu(r){if(!(yt(r)||r===null||r===""))return parseInt(r,10)}function qd(r){if(!(yt(r)||r===null||r===""))return parseFloat(r)}function x0(r){if(!(yt(r)||r===null||r==="")){let e=parseFloat("0."+r)*1e3;return Math.floor(e)}}function T0(r,e,t=!1){let n=10**e;return(t?Math.trunc:Math.round)(r*n)/n}function ib(r){return r%4===0&&(r%100!==0||r%400===0)}function eb(r){return ib(r)?366:365}function JT(r,e){let t=Bee(e-1,12)+1,n=r+(e-t)/12;return t===2?ib(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function aS(r){let e=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return r.year<100&&r.year>=0&&(e=new Date(e),e.setUTCFullYear(r.year,r.month-1,r.day)),+e}function eS(r){let e=(r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400))%7,t=r-1,n=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7;return e===4||n===3?53:52}function m0(r){return r>99?r:r>_r.twoDigitCutoffYear?1900+r:2e3+r}function ZU(r,e,t,n=null){let i=new Date(r),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(o.timeZone=n);let s={timeZoneName:e,...o},a=new Intl.DateTimeFormat(t,s).formatToParts(i).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function lS(r,e){let t=parseInt(r,10);Number.isNaN(t)&&(t=0);let n=parseInt(e,10)||0,i=t<0||Object.is(t,-0)?-n:n;return t*60+i}function JU(r){let e=Number(r);if(typeof r=="boolean"||r===""||Number.isNaN(e))throw new to(`Invalid unit value ${r}`);return e}function tS(r,e){let t={};for(let n in r)if(jm(r,n)){let i=r[n];if(i==null)continue;t[e(n)]=JU(i)}return t}function tb(r,e){let t=Math.trunc(Math.abs(r/60)),n=Math.trunc(Math.abs(r%60)),i=r>=0?"+":"-";switch(e){case"short":return`${i}${Yr(t,2)}:${Yr(n,2)}`;case"narrow":return`${i}${t}${n>0?`:${n}`:""}`;case"techie":return`${i}${Yr(t,2)}${Yr(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function cS(r){return Nee(r,["hour","minute","second","millisecond"])}var Vee=["January","February","March","April","May","June","July","August","September","October","November","December"],ez=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],qee=["J","F","M","A","M","J","J","A","S","O","N","D"];function tz(r){switch(r){case"narrow":return[...qee];case"short":return[...ez];case"long":return[...Vee];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var rz=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],nz=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Uee=["M","T","W","T","F","S","S"];function iz(r){switch(r){case"narrow":return[...Uee];case"short":return[...nz];case"long":return[...rz];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var oz=["AM","PM"],zee=["Before Christ","Anno Domini"],Hee=["BC","AD"],Wee=["B","A"];function sz(r){switch(r){case"narrow":return[...Wee];case"short":return[...Hee];case"long":return[...zee];default:return null}}function jee(r){return oz[r.hour<12?0:1]}function Gee(r,e){return iz(e)[r.weekday-1]}function Yee(r,e){return tz(e)[r.month-1]}function Kee(r,e){return sz(e)[r.year<0?0:1]}function Qee(r,e,t="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},o=["hours","minutes","seconds"].indexOf(r)===-1;if(t==="auto"&&o){let d=r==="days";switch(e){case 1:return d?"tomorrow":`next ${i[r][0]}`;case-1:return d?"yesterday":`last ${i[r][0]}`;case 0:return d?"today":`this ${i[r][0]}`}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=i[r],u=n?l?c[1]:c[2]||c[1]:l?i[r][0]:r;return s?`${a} ${u} ago`:`in ${a} ${u}`}function uU(r,e){let t="";for(let n of r)n.literal?t+=n.val:t+=e(n.val);return t}var Xee={D:XT,DD:PU,DDD:$U,DDDD:MU,t:OU,tt:RU,ttt:LU,tttt:NU,T:BU,TT:VU,TTT:qU,TTTT:UU,f:zU,ff:WU,fff:GU,ffff:KU,F:HU,FF:jU,FFF:YU,FFFF:QU},_o=class r{static create(e,t={}){return new r(e,t)}static parseFormat(e){let t=null,n="",i=!1,o=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?(n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),t=null,n="",i=!i):i||a===t?n+=a:(n.length>0&&o.push({literal:/^\s+$/.test(n),val:n}),n=a,t=a)}return n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),o}static macroTokenToFormatOpts(e){return Xee[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0){if(this.opts.forceSimple)return Yr(e,t);let n={...this.opts};return t>0&&(n.padTo=t),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,t){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(p,m)=>this.loc.extract(e,p,m),s=p=>e.isOffsetFixed&&e.offset===0&&p.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,p.format):"",a=()=>n?jee(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(p,m)=>n?Yee(e,p):o(m?{month:p}:{month:p,day:"numeric"},"month"),c=(p,m)=>n?Gee(e,p):o(m?{weekday:p}:{weekday:p,month:"long",day:"numeric"},"weekday"),u=p=>{let m=r.macroTokenToFormatOpts(p);return m?this.formatWithSystemDefault(e,m):p},d=p=>n?Kee(e,p):o({era:p},"era"),f=p=>{switch(p){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return i?o({day:"numeric"},"day"):this.num(e.day);case"dd":return i?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return i?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return i?o({month:"numeric"},"month"):this.num(e.month);case"MM":return i?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return i?o({year:"numeric"},"year"):this.num(e.year);case"yy":return i?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(p)}};return uU(r.parseFormat(t),f)}formatDurationFromString(e,t){let n=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=l=>c=>{let u=n(c);return u?this.num(l.get(u),c.length):c},o=r.parseFormat(t),s=o.reduce((l,{literal:c,val:u})=>c?l:l.concat(u),[]),a=e.shiftTo(...s.map(n).filter(l=>l));return uU(o,i(a))}},ko=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},az=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Gm(...r){let e=r.reduce((t,n)=>t+n.source,"");return RegExp(`^${e}$`)}function Ym(...r){return e=>r.reduce(([t,n,i],o)=>{let[s,a,l]=o(e,i);return[{...t,...s},a||n,l]},[{},null,1]).slice(0,2)}function Km(r,...e){if(r==null)return[null,null];for(let[t,n]of e){let i=t.exec(r);if(i)return n(i)}return[null,null]}function lz(...r){return(e,t)=>{let n={},i;for(i=0;i<r.length;i++)n[r[i]]=gu(e[t+i]);return[n,null,t+i]}}var cz=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Zee=`(?:${cz.source}?(?:\\[(${az.source})\\])?)?`,S0=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,uz=RegExp(`${S0.source}${Zee}`),_0=RegExp(`(?:T${uz.source})?`),Jee=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,ete=/(\d{4})-?W(\d\d)(?:-?(\d))?/,tte=/(\d{4})-?(\d{3})/,rte=lz("weekYear","weekNumber","weekDay"),nte=lz("year","ordinal"),ite=/(\d{4})-(\d\d)-(\d\d)/,dz=RegExp(`${S0.source} ?(?:${cz.source}|(${az.source}))?`),ote=RegExp(`(?: ${dz.source})?`);function Hm(r,e,t){let n=r[e];return yt(n)?t:gu(n)}function ste(r,e){return[{year:Hm(r,e),month:Hm(r,e+1,1),day:Hm(r,e+2,1)},null,e+3]}function Qm(r,e){return[{hours:Hm(r,e,0),minutes:Hm(r,e+1,0),seconds:Hm(r,e+2,0),milliseconds:x0(r[e+3])},null,e+4]}function ob(r,e){let t=!r[e]&&!r[e+1],n=lS(r[e+1],r[e+2]),i=t?null:ls.instance(n);return[{},i,e+3]}function sb(r,e){let t=r[e]?yu.create(r[e]):null;return[{},t,e+1]}var ate=RegExp(`^T?${S0.source}$`),lte=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function cte(r){let[e,t,n,i,o,s,a,l,c]=r,u=e[0]==="-",d=l&&l[0]==="-",f=(p,m=!1)=>p!==void 0&&(m||p&&u)?-p:p;return[{years:f(qd(t)),months:f(qd(n)),weeks:f(qd(i)),days:f(qd(o)),hours:f(qd(s)),minutes:f(qd(a)),seconds:f(qd(l),l==="-0"),milliseconds:f(x0(c),d)}]}var ute={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function k0(r,e,t,n,i,o,s){let a={year:e.length===2?m0(gu(e)):gu(e),month:ez.indexOf(t)+1,day:gu(n),hour:gu(i),minute:gu(o)};return s&&(a.second=gu(s)),r&&(a.weekday=r.length>3?rz.indexOf(r)+1:nz.indexOf(r)+1),a}var dte=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function pte(r){let[,e,t,n,i,o,s,a,l,c,u,d]=r,f=k0(e,i,n,t,o,s,a),p;return l?p=ute[l]:c?p=0:p=lS(u,d),[f,new ls(p)]}function fte(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var mte=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,hte=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,gte=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function dU(r){let[,e,t,n,i,o,s,a]=r;return[k0(e,i,n,t,o,s,a),ls.utcInstance]}function vte(r){let[,e,t,n,i,o,s,a]=r;return[k0(e,a,t,n,i,o,s),ls.utcInstance]}var yte=Gm(Jee,_0),bte=Gm(ete,_0),wte=Gm(tte,_0),Cte=Gm(uz),pz=Ym(ste,Qm,ob,sb),Ete=Ym(rte,Qm,ob,sb),xte=Ym(nte,Qm,ob,sb),Tte=Ym(Qm,ob,sb);function Ste(r){return Km(r,[yte,pz],[bte,Ete],[wte,xte],[Cte,Tte])}function _te(r){return Km(fte(r),[dte,pte])}function kte(r){return Km(r,[mte,dU],[hte,dU],[gte,vte])}function Ate(r){return Km(r,[lte,cte])}var Dte=Ym(Qm);function Ite(r){return Km(r,[ate,Dte])}var Fte=Gm(ite,ote),Pte=Gm(dz),$te=Ym(Qm,ob,sb);function Mte(r){return Km(r,[Fte,pz],[Pte,$te])}var pU="Invalid Duration",fz={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Ote={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...fz},ss=146097/400,qm=146097/4800,Rte={years:{quarters:4,months:12,weeks:ss/7,days:ss,hours:ss*24,minutes:ss*24*60,seconds:ss*24*60*60,milliseconds:ss*24*60*60*1e3},quarters:{months:3,weeks:ss/28,days:ss/4,hours:ss*24/4,minutes:ss*24*60/4,seconds:ss*24*60*60/4,milliseconds:ss*24*60*60*1e3/4},months:{weeks:qm/7,days:qm,hours:qm*24,minutes:qm*24*60,seconds:qm*24*60*60,milliseconds:qm*24*60*60*1e3},...fz},Hd=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Lte=Hd.slice(0).reverse();function hu(r,e,t=!1){let n={values:t?e.values:{...r.values,...e.values||{}},loc:r.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||r.conversionAccuracy,matrix:e.matrix||r.matrix};return new Ue(n)}function mz(r,e){let t=e.milliseconds??0;for(let n of Lte.slice(1))e[n]&&(t+=e[n]*r[n].milliseconds);return t}function fU(r,e){let t=mz(r,e)<0?-1:1;Hd.reduceRight((n,i)=>{if(yt(e[i]))return n;if(n){let o=e[n]*t,s=r[i][n],a=Math.floor(o/s);e[i]+=a*t,e[n]-=a*s*t}return i},null),Hd.reduce((n,i)=>{if(yt(e[i]))return n;if(n){let o=e[n]%1;e[n]-=o,e[i]+=o*r[n][i]}return i},null)}function Nte(r){let e={};for(let[t,n]of Object.entries(r))n!==0&&(e[t]=n);return e}var Ue=class r{constructor(e){let t=e.conversionAccuracy==="longterm"||!1,n=t?Rte:Ote;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||kr.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,t){return r.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new to(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new r({values:tS(e,r.normalizeUnit),loc:kr.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(Wd(e))return r.fromMillis(e);if(r.isDuration(e))return e;if(typeof e=="object")return r.fromObject(e);throw new to(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){let[n]=Ate(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){let[n]=Ite(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new to("need to specify a reason the Duration is invalid");let n=e instanceof ko?e:new ko(e,t);if(_r.throwOnInvalid)throw new o0(n);return new r({invalid:n})}static normalizeUnit(e){let t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new QT(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?_o.create(this.loc,n).formatDurationFromString(this,e):pU}toHuman(e={}){if(!this.isValid)return pU;let t=Hd.map(n=>{let i=this.values[n];return yt(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(t)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=T0(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},ft.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.isValid?mz(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e),n={};for(let i of Hd)(jm(t.values,i)||jm(this.values,i))&&(n[i]=t.get(i)+this.get(i));return hu(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=JU(e(this.values[n],n));return hu(this,{values:t},!0)}get(e){return this[r.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let t={...this.values,...tS(e,r.normalizeUnit)};return hu(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:i}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:i,conversionAccuracy:n};return hu(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return fU(this.matrix,e),hu(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Nte(this.normalize().shiftToAll().toObject());return hu(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>r.normalizeUnit(s));let t={},n={},i=this.toObject(),o;for(let s of Hd)if(e.indexOf(s)>=0){o=s;let a=0;for(let c in n)a+=this.matrix[c][s]*n[c],n[c]=0;Wd(i[s])&&(a+=i[s]);let l=Math.trunc(a);t[s]=l,n[s]=(a*1e3-l*1e3)/1e3}else Wd(i[s])&&(n[s]=i[s]);for(let s in n)n[s]!==0&&(t[o]+=s===o?n[s]:n[s]/this.matrix[o][s]);return fU(this.matrix,t),hu(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return hu(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of Hd)if(!t(this.values[n],e.values[n]))return!1;return!0}},Um="Invalid Interval";function Bte(r,e){return!r||!r.isValid?Wm.invalid("missing or invalid start"):!e||!e.isValid?Wm.invalid("missing or invalid end"):e<r?Wm.invalid("end before start",`The end of an interval must be after its start, but you had start=${r.toISO()} and end=${e.toISO()}`):null}var Wm=class r{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new to("need to specify a reason the Interval is invalid");let n=e instanceof ko?e:new ko(e,t);if(_r.throwOnInvalid)throw new i0(n);return new r({invalid:n})}static fromDateTimes(e,t){let n=Xy(e),i=Xy(t),o=Bte(n,i);return o??new r({start:n,end:i})}static after(e,t){let n=Ue.fromDurationLike(t),i=Xy(e);return r.fromDateTimes(i,i.plus(n))}static before(e,t){let n=Ue.fromDurationLike(t),i=Xy(e);return r.fromDateTimes(i.minus(n),i)}static fromISO(e,t){let[n,i]=(e||"").split("/",2);if(n&&i){let o,s;try{o=ft.fromISO(n,t),s=o.isValid}catch{s=!1}let a,l;try{a=ft.fromISO(i,t),l=a.isValid}catch{l=!1}if(s&&l)return r.fromDateTimes(o,a);if(s){let c=Ue.fromISO(i,t);if(c.isValid)return r.after(o,c)}else if(l){let c=Ue.fromISO(n,t);if(c.isValid)return r.before(a,c)}}return r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;let t=this.start.startOf(e),n=this.end.startOf(e);return Math.floor(n.diff(t,e).get(e))+(n.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?r.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];let t=e.map(Xy).filter(s=>this.contains(s)).sort(),n=[],{s:i}=this,o=0;for(;i<this.e;){let s=t[o]||this.e,a=+s>+this.e?this.e:s;n.push(r.fromDateTimes(i,a)),i=a,o+=1}return n}splitBy(e){let t=Ue.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s:n}=this,i=1,o,s=[];for(;n<this.e;){let a=this.start.plus(t.mapUnits(l=>l*i));o=+a>+this.e?this.e:a,s.push(r.fromDateTimes(n,o)),n=o,i+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let t=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return t>=n?null:r.fromDateTimes(t,n)}union(e){if(!this.isValid)return this;let t=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return r.fromDateTimes(t,n)}static merge(e){let[t,n]=e.sort((i,o)=>i.s-o.s).reduce(([i,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[i,o.union(s)]:[i.concat([o]),s]:[i,s],[[],null]);return n&&t.push(n),t}static xor(e){let t=null,n=0,i=[],o=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),s=Array.prototype.concat(...o),a=s.sort((l,c)=>l.time-c.time);for(let l of a)n+=l.type==="s"?1:-1,n===1?t=l.time:(t&&+t!=+l.time&&i.push(r.fromDateTimes(t,l.time)),t=null);return r.merge(i)}difference(...e){return r.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Um}toLocaleString(e=XT,t={}){return this.isValid?_o.create(this.s.loc.clone(t),e).formatInterval(this):Um}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Um}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Um}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Um}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Um}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):Ue.invalid(this.invalidReason)}mapEndpoints(e){return r.fromDateTimes(e(this.s),e(this.e))}},zm=class{static hasDST(e=_r.defaultZone){let t=ft.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return yu.isValidZone(e)}static normalizeZone(e){return vu(e,_r.defaultZone)}static months(e="long",{locale:t=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||kr.create(t,n,o)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||kr.create(t,n,o)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:n=null,locObj:i=null}={}){return(i||kr.create(t,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:i=null}={}){return(i||kr.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return kr.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return kr.create(t,null,"gregory").eras(e)}static features(){return{relative:XU()}}};function mU(r,e){let t=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=t(e)-t(r);return Math.floor(Ue.fromMillis(n).as("days"))}function Vte(r,e,t){let n=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{let u=mU(l,c);return(u-u%7)/7}],["days",mU]],i={},o=r,s,a;for(let[l,c]of n)t.indexOf(l)>=0&&(s=l,i[l]=c(r,e),a=o.plus(i),a>e?(i[l]--,r=o.plus(i),r>e&&(a=r,i[l]--,r=o.plus(i))):r=a);return[r,i,a,s]}function qte(r,e,t,n){let[i,o,s,a]=Vte(r,e,t),l=e-i,c=t.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);c.length===0&&(s<e&&(s=i.plus({[a]:1})),s!==i&&(o[a]=(o[a]||0)+l/(s-i)));let u=Ue.fromObject(o,n);return c.length>0?Ue.fromMillis(l,n).shiftTo(...c).plus(u):u}var A0={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},hU={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Ute=A0.hanidec.replace(/[\[|\]]/g,"").split("");function zte(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(r[t].search(A0.hanidec)!==-1)e+=Ute.indexOf(r[t]);else for(let i in hU){let[o,s]=hU[i];n>=o&&n<=s&&(e+=n-o)}}return parseInt(e,10)}else return e}function Xs({numberingSystem:r},e=""){return new RegExp(`${A0[r||"latn"]}${e}`)}var Hte="missing Intl.DateTimeFormat.formatToParts support";function Rt(r,e=t=>t){return{regex:r,deser:([t])=>e(zte(t))}}var Wte="\xA0",hz=`[ ${Wte}]`,gz=new RegExp(hz,"g");function jte(r){return r.replace(/\./g,"\\.?").replace(gz,hz)}function gU(r){return r.replace(/\./g,"").replace(gz," ").toLowerCase()}function Zs(r,e){return r===null?null:{regex:RegExp(r.map(jte).join("|")),deser:([t])=>r.findIndex(n=>gU(t)===gU(n))+e}}function vU(r,e){return{regex:r,deser:([,t,n])=>lS(t,n),groups:e}}function HT(r){return{regex:r,deser:([e])=>e}}function Gte(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Yte(r,e){let t=Xs(e),n=Xs(e,"{2}"),i=Xs(e,"{3}"),o=Xs(e,"{4}"),s=Xs(e,"{6}"),a=Xs(e,"{1,2}"),l=Xs(e,"{1,3}"),c=Xs(e,"{1,6}"),u=Xs(e,"{1,9}"),d=Xs(e,"{2,4}"),f=Xs(e,"{4,6}"),p=g=>({regex:RegExp(Gte(g.val)),deser:([y])=>y,literal:!0}),v=(g=>{if(r.literal)return p(g);switch(g.val){case"G":return Zs(e.eras("short"),0);case"GG":return Zs(e.eras("long"),0);case"y":return Rt(c);case"yy":return Rt(d,m0);case"yyyy":return Rt(o);case"yyyyy":return Rt(f);case"yyyyyy":return Rt(s);case"M":return Rt(a);case"MM":return Rt(n);case"MMM":return Zs(e.months("short",!0),1);case"MMMM":return Zs(e.months("long",!0),1);case"L":return Rt(a);case"LL":return Rt(n);case"LLL":return Zs(e.months("short",!1),1);case"LLLL":return Zs(e.months("long",!1),1);case"d":return Rt(a);case"dd":return Rt(n);case"o":return Rt(l);case"ooo":return Rt(i);case"HH":return Rt(n);case"H":return Rt(a);case"hh":return Rt(n);case"h":return Rt(a);case"mm":return Rt(n);case"m":return Rt(a);case"q":return Rt(a);case"qq":return Rt(n);case"s":return Rt(a);case"ss":return Rt(n);case"S":return Rt(l);case"SSS":return Rt(i);case"u":return HT(u);case"uu":return HT(a);case"uuu":return Rt(t);case"a":return Zs(e.meridiems(),0);case"kkkk":return Rt(o);case"kk":return Rt(d,m0);case"W":return Rt(a);case"WW":return Rt(n);case"E":case"c":return Rt(t);case"EEE":return Zs(e.weekdays("short",!1),1);case"EEEE":return Zs(e.weekdays("long",!1),1);case"ccc":return Zs(e.weekdays("short",!0),1);case"cccc":return Zs(e.weekdays("long",!0),1);case"Z":case"ZZ":return vU(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return vU(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return HT(/[a-z_+-/]{1,256}?/i);case" ":return HT(/[^\S\n\r]/);default:return p(g)}})(r)||{invalidReason:Hte};return v.token=r,v}var Kte={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Qte(r,e,t){let{type:n,value:i}=r;if(n==="literal"){let l=/^\s+$/.test(i);return{literal:!l,val:l?" ":i}}let o=e[n],s=n;n==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=t.hour12?"hour12":"hour24");let a=Kte[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function Xte(r){return[`^${r.map(t=>t.regex).reduce((t,n)=>`${t}(${n.source})`,"")}$`,r]}function Zte(r,e,t){let n=r.match(e);if(n){let i={},o=1;for(let s in t)if(jm(t,s)){let a=t[s],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(o,o+l))),o+=l}return[n,i]}else return[n,{}]}function Jte(r){let e=o=>{switch(o){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},t=null,n;return yt(r.z)||(t=yu.create(r.z)),yt(r.Z)||(t||(t=new ls(r.Z)),n=r.Z),yt(r.q)||(r.M=(r.q-1)*3+1),yt(r.h)||(r.h<12&&r.a===1?r.h+=12:r.h===12&&r.a===0&&(r.h=0)),r.G===0&&r.y&&(r.y=-r.y),yt(r.u)||(r.S=x0(r.u)),[Object.keys(r).reduce((o,s)=>{let a=e(s);return a&&(o[a]=r[s]),o},{}),t,n]}var XF=null;function ere(){return XF||(XF=ft.fromMillis(1555555555555)),XF}function tre(r,e){if(r.literal)return r;let t=_o.macroTokenToFormatOpts(r.val),n=bz(t,e);return n==null||n.includes(void 0)?r:n}function vz(r,e){return Array.prototype.concat(...r.map(t=>tre(t,e)))}function yz(r,e,t){let n=vz(_o.parseFormat(t),r),i=n.map(s=>Yte(s,r)),o=i.find(s=>s.invalidReason);if(o)return{input:e,tokens:n,invalidReason:o.invalidReason};{let[s,a]=Xte(i),l=RegExp(s,"i"),[c,u]=Zte(e,l,a),[d,f,p]=u?Jte(u):[null,null,void 0];if(jm(u,"a")&&jm(u,"H"))throw new zd("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:l,rawMatches:c,matches:u,result:d,zone:f,specificOffset:p}}}function rre(r,e,t){let{result:n,zone:i,specificOffset:o,invalidReason:s}=yz(r,e,t);return[n,i,o,s]}function bz(r,e){if(!r)return null;let n=_o.create(e,r).dtFormatter(ere()),i=n.formatToParts(),o=n.resolvedOptions();return i.map(s=>Qte(s,r,o))}var wz=[0,31,59,90,120,151,181,212,243,273,304,334],Cz=[0,31,60,91,121,152,182,213,244,274,305,335];function as(r,e){return new ko("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}function Ez(r,e,t){let n=new Date(Date.UTC(r,e-1,t));r<100&&r>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function xz(r,e,t){return t+(ib(r)?Cz:wz)[e-1]}function Tz(r,e){let t=ib(r)?Cz:wz,n=t.findIndex(o=>o<e),i=e-t[n];return{month:n+1,day:i}}function h0(r){let{year:e,month:t,day:n}=r,i=xz(e,t,n),o=Ez(e,t,n),s=Math.floor((i-o+10)/7),a;return s<1?(a=e-1,s=eS(a)):s>eS(e)?(a=e+1,s=1):a=e,{weekYear:a,weekNumber:s,weekday:o,...cS(r)}}function yU(r){let{weekYear:e,weekNumber:t,weekday:n}=r,i=Ez(e,1,4),o=eb(e),s=t*7+n-i-3,a;s<1?(a=e-1,s+=eb(a)):s>o?(a=e+1,s-=eb(e)):a=e;let{month:l,day:c}=Tz(a,s);return{year:a,month:l,day:c,...cS(r)}}function ZF(r){let{year:e,month:t,day:n}=r,i=xz(e,t,n);return{year:e,ordinal:i,...cS(r)}}function bU(r){let{year:e,ordinal:t}=r,{month:n,day:i}=Tz(e,t);return{year:e,month:n,day:i,...cS(r)}}function nre(r){let e=sS(r.weekYear),t=Wl(r.weekNumber,1,eS(r.weekYear)),n=Wl(r.weekday,1,7);return e?t?n?!1:as("weekday",r.weekday):as("week",r.week):as("weekYear",r.weekYear)}function ire(r){let e=sS(r.year),t=Wl(r.ordinal,1,eb(r.year));return e?t?!1:as("ordinal",r.ordinal):as("year",r.year)}function Sz(r){let e=sS(r.year),t=Wl(r.month,1,12),n=Wl(r.day,1,JT(r.year,r.month));return e?t?n?!1:as("day",r.day):as("month",r.month):as("year",r.year)}function _z(r){let{hour:e,minute:t,second:n,millisecond:i}=r,o=Wl(e,0,23)||e===24&&t===0&&n===0&&i===0,s=Wl(t,0,59),a=Wl(n,0,59),l=Wl(i,0,999);return o?s?a?l?!1:as("millisecond",i):as("second",n):as("minute",t):as("hour",e)}var JF="Invalid DateTime",wU=864e13;function WT(r){return new ko("unsupported zone",`the zone "${r.name}" is not supported`)}function e0(r){return r.weekData===null&&(r.weekData=h0(r.c)),r.weekData}function Ud(r,e){let t={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new ft({...t,...e,old:t})}function kz(r,e,t){let n=r-e*60*1e3,i=t.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let o=t.offset(n);return i===o?[n,i]:[r-Math.min(i,o)*60*1e3,Math.max(i,o)]}function jT(r,e){r+=e*60*1e3;let t=new Date(r);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function KT(r,e,t){return kz(aS(r),e,t)}function CU(r,e){let t=r.o,n=r.c.year+Math.trunc(e.years),i=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...r.c,year:n,month:i,day:Math.min(r.c.day,JT(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=Ue.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=aS(o),[l,c]=kz(a,t,r.zone);return s!==0&&(l+=s,c=r.zone.offset(l)),{ts:l,o:c}}function Qy(r,e,t,n,i,o){let{setZone:s,zone:a}=t;if(r&&Object.keys(r).length!==0||e){let l=e||a,c=ft.fromObject(r,{...t,zone:l,specificOffset:o});return s?c:c.setZone(a)}else return ft.invalid(new ko("unparsable",`the input "${i}" can't be parsed as ${n}`))}function GT(r,e,t=!0){return r.isValid?_o.create(kr.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(r,e):null}function t0(r,e){let t=r.c.year>9999||r.c.year<0,n="";return t&&r.c.year>=0&&(n+="+"),n+=Yr(r.c.year,t?6:4),e?(n+="-",n+=Yr(r.c.month),n+="-",n+=Yr(r.c.day)):(n+=Yr(r.c.month),n+=Yr(r.c.day)),n}function EU(r,e,t,n,i,o){let s=Yr(r.c.hour);return e?(s+=":",s+=Yr(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(s+=":")):s+=Yr(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(s+=Yr(r.c.second),(r.c.millisecond!==0||!n)&&(s+=".",s+=Yr(r.c.millisecond,3))),i&&(r.isOffsetFixed&&r.offset===0&&!o?s+="Z":r.o<0?(s+="-",s+=Yr(Math.trunc(-r.o/60)),s+=":",s+=Yr(Math.trunc(-r.o%60))):(s+="+",s+=Yr(Math.trunc(r.o/60)),s+=":",s+=Yr(Math.trunc(r.o%60)))),o&&(s+="["+r.zone.ianaName+"]"),s}var Az={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},ore={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},sre={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Dz=["year","month","day","hour","minute","second","millisecond"],are=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],lre=["year","ordinal","hour","minute","second","millisecond"];function xU(r){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[r.toLowerCase()];if(!e)throw new QT(r);return e}function TU(r,e){let t=vu(e.zone,_r.defaultZone),n=kr.fromObject(e),i=_r.now(),o,s;if(yt(r.year))o=i;else{for(let c of Dz)yt(r[c])&&(r[c]=Az[c]);let a=Sz(r)||_z(r);if(a)return ft.invalid(a);let l=t.offset(i);[o,s]=KT(r,l,t)}return new ft({ts:o,zone:t,loc:n,o:s})}function SU(r,e,t){let n=yt(t.round)?!0:t.round,i=(s,a)=>(s=T0(s,n||t.calendary?0:2,!0),e.loc.clone(t).relFormatter(t).format(s,a)),o=s=>t.calendary?e.hasSame(r,s)?0:e.startOf(s).diff(r.startOf(s),s).get(s):e.diff(r,s).get(s);if(t.unit)return i(o(t.unit),t.unit);for(let s of t.units){let a=o(s);if(Math.abs(a)>=1)return i(a,s)}return i(r>e?-0:0,t.units[t.units.length-1])}function _U(r){let e={},t;return r.length>0&&typeof r[r.length-1]=="object"?(e=r[r.length-1],t=Array.from(r).slice(0,r.length-1)):t=Array.from(r),[e,t]}var ft=class r{constructor(e){let t=e.zone||_r.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new ko("invalid input"):null)||(t.isValid?null:WT(t));this.ts=yt(e.ts)?_r.now():e.ts;let i=null,o=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[i,o]=[e.old.c,e.old.o];else{let a=t.offset(this.ts);i=jT(this.ts,a),n=Number.isNaN(i.year)?new ko("invalid input"):null,i=n?null:i,o=n?null:a}this._zone=t,this.loc=e.loc||kr.create(),this.invalid=n,this.weekData=null,this.c=i,this.o=o,this.isLuxonDateTime=!0}static now(){return new r({})}static local(){let[e,t]=_U(arguments),[n,i,o,s,a,l,c]=t;return TU({year:n,month:i,day:o,hour:s,minute:a,second:l,millisecond:c},e)}static utc(){let[e,t]=_U(arguments),[n,i,o,s,a,l,c]=t;return e.zone=ls.utcInstance,TU({year:n,month:i,day:o,hour:s,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){let n=Ree(e)?e.valueOf():NaN;if(Number.isNaN(n))return r.invalid("invalid input");let i=vu(t.zone,_r.defaultZone);return i.isValid?new r({ts:n,zone:i,loc:kr.fromObject(t)}):r.invalid(WT(i))}static fromMillis(e,t={}){if(Wd(e))return e<-wU||e>wU?r.invalid("Timestamp out of range"):new r({ts:e,zone:vu(t.zone,_r.defaultZone),loc:kr.fromObject(t)});throw new to(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(Wd(e))return new r({ts:e*1e3,zone:vu(t.zone,_r.defaultZone),loc:kr.fromObject(t)});throw new to("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};let n=vu(t.zone,_r.defaultZone);if(!n.isValid)return r.invalid(WT(n));let i=_r.now(),o=yt(t.specificOffset)?n.offset(i):t.specificOffset,s=tS(e,xU),a=!yt(s.ordinal),l=!yt(s.year),c=!yt(s.month)||!yt(s.day),u=l||c,d=s.weekYear||s.weekNumber,f=kr.fromObject(t);if((u||a)&&d)throw new zd("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&a)throw new zd("Can't mix ordinal dates with month/day");let p=d||s.weekday&&!u,m,v,g=jT(i,o);p?(m=are,v=ore,g=h0(g)):a?(m=lre,v=sre,g=ZF(g)):(m=Dz,v=Az);let y=!1;for(let I of m){let q=s[I];yt(q)?y?s[I]=v[I]:s[I]=g[I]:y=!0}let w=p?nre(s):a?ire(s):Sz(s),T=w||_z(s);if(T)return r.invalid(T);let b=p?yU(s):a?bU(s):s,[E,C]=KT(b,o,n),_=new r({ts:E,zone:n,o:C,loc:f});return s.weekday&&u&&e.weekday!==_.weekday?r.invalid("mismatched weekday",`you can't specify both a weekday of ${s.weekday} and a date of ${_.toISO()}`):_}static fromISO(e,t={}){let[n,i]=Ste(e);return Qy(n,i,t,"ISO 8601",e)}static fromRFC2822(e,t={}){let[n,i]=_te(e);return Qy(n,i,t,"RFC 2822",e)}static fromHTTP(e,t={}){let[n,i]=kte(e);return Qy(n,i,t,"HTTP",t)}static fromFormat(e,t,n={}){if(yt(e)||yt(t))throw new to("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:o=null}=n,s=kr.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0}),[a,l,c,u]=rre(s,e,t);return u?r.invalid(u):Qy(a,l,n,`format ${t}`,e,c)}static fromString(e,t,n={}){return r.fromFormat(e,t,n)}static fromSQL(e,t={}){let[n,i]=Mte(e);return Qy(n,i,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new to("need to specify a reason the DateTime is invalid");let n=e instanceof ko?e:new ko(e,t);if(_r.throwOnInvalid)throw new n0(n);return new r({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=bz(e,kr.fromObject(t));return n?n.map(i=>i?i.val:null).join(""):null}static expandFormat(e,t={}){return vz(_o.parseFormat(e),kr.fromObject(t)).map(i=>i.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?e0(this).weekYear:NaN}get weekNumber(){return this.isValid?e0(this).weekNumber:NaN}get weekday(){return this.isValid?e0(this).weekday:NaN}get ordinal(){return this.isValid?ZF(this.c).ordinal:NaN}get monthShort(){return this.isValid?zm.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?zm.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?zm.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?zm.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,t=6e4,n=aS(this.c),i=this.zone.offset(n-e),o=this.zone.offset(n+e),s=this.zone.offset(n-i*t),a=this.zone.offset(n-o*t);if(s===a)return[this];let l=n-s*t,c=n-a*t,u=jT(l,s),d=jT(c,a);return u.hour===d.hour&&u.minute===d.minute&&u.second===d.second&&u.millisecond===d.millisecond?[Ud(this,{ts:l}),Ud(this,{ts:c})]:[this]}get isInLeapYear(){return ib(this.year)}get daysInMonth(){return JT(this.year,this.month)}get daysInYear(){return this.isValid?eb(this.year):NaN}get weeksInWeekYear(){return this.isValid?eS(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:i}=_o.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:i}}toUTC(e=0,t={}){return this.setZone(ls.instance(e),t)}toLocal(){return this.setZone(_r.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:n=!1}={}){if(e=vu(e,_r.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(t||n){let o=e.offset(this.ts),s=this.toObject();[i]=KT(s,o,e)}return Ud(this,{ts:i,zone:e})}else return r.invalid(WT(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return Ud(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=tS(e,xU),n=!yt(t.weekYear)||!yt(t.weekNumber)||!yt(t.weekday),i=!yt(t.ordinal),o=!yt(t.year),s=!yt(t.month)||!yt(t.day),a=o||s,l=t.weekYear||t.weekNumber;if((a||i)&&l)throw new zd("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(s&&i)throw new zd("Can't mix ordinal dates with month/day");let c;n?c=yU({...h0(this.c),...t}):yt(t.ordinal)?(c={...this.toObject(),...t},yt(t.day)&&(c.day=Math.min(JT(c.year,c.month),c.day))):c=bU({...ZF(this.c),...t});let[u,d]=KT(c,this.o,this.zone);return Ud(this,{ts:u,o:d})}plus(e){if(!this.isValid)return this;let t=Ue.fromDurationLike(e);return Ud(this,CU(this,t))}minus(e){if(!this.isValid)return this;let t=Ue.fromDurationLike(e).negate();return Ud(this,CU(this,t))}startOf(e){if(!this.isValid)return this;let t={},n=Ue.normalizeUnit(e);switch(n){case"years":t.month=1;case"quarters":case"months":t.day=1;case"weeks":case"days":t.hour=0;case"hours":t.minute=0;case"minutes":t.second=0;case"seconds":t.millisecond=0;break}if(n==="weeks"&&(t.weekday=1),n==="quarters"){let i=Math.ceil(this.month/3);t.month=(i-1)*3+1}return this.set(t)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,t={}){return this.isValid?_o.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):JF}toLocaleString(e=XT,t={}){return this.isValid?_o.create(this.loc.clone(t),e).formatDateTime(this):JF}toLocaleParts(e={}){return this.isValid?_o.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:o=!1}={}){if(!this.isValid)return null;let s=e==="extended",a=t0(this,s);return a+="T",a+=EU(this,s,t,n,i,o),a}toISODate({format:e="extended"}={}){return this.isValid?t0(this,e==="extended"):null}toISOWeekDate(){return GT(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:o=!1,format:s="extended"}={}){return this.isValid?(i?"T":"")+EU(this,s==="extended",t,e,n,o):null}toRFC2822(){return GT(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return GT(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?t0(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(t||e)&&(n&&(i+=" "),t?i+="z":e&&(i+="ZZ")),GT(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():JF}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",n={}){if(!this.isValid||!e.isValid)return Ue.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},o=Lee(t).map(Ue.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,l=s?e:this,c=qte(a,l,o,i);return s?c.negate():c}diffNow(e="milliseconds",t={}){return this.diff(r.now(),e,t)}until(e){return this.isValid?Wm.fromDateTimes(this,e):this}hasSame(e,t){if(!this.isValid)return!1;let n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t)<=n&&n<=i.endOf(t)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let t=e.base||r.fromObject({},{zone:this.zone}),n=e.padding?this<t?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(i=e.unit,o=void 0),SU(t,this.plus(n),{...e,numeric:"always",units:i,unit:o})}toRelativeCalendar(e={}){return this.isValid?SU(e.base||r.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(r.isDateTime))throw new to("min requires all arguments be DateTimes");return cU(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(r.isDateTime))throw new to("max requires all arguments be DateTimes");return cU(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:i=null,numberingSystem:o=null}=n,s=kr.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});return yz(s,e,t)}static fromStringExplain(e,t,n={}){return r.fromFormatExplain(e,t,n)}static get DATE_SHORT(){return XT}static get DATE_MED(){return PU}static get DATE_MED_WITH_WEEKDAY(){return wee}static get DATE_FULL(){return $U}static get DATE_HUGE(){return MU}static get TIME_SIMPLE(){return OU}static get TIME_WITH_SECONDS(){return RU}static get TIME_WITH_SHORT_OFFSET(){return LU}static get TIME_WITH_LONG_OFFSET(){return NU}static get TIME_24_SIMPLE(){return BU}static get TIME_24_WITH_SECONDS(){return VU}static get TIME_24_WITH_SHORT_OFFSET(){return qU}static get TIME_24_WITH_LONG_OFFSET(){return UU}static get DATETIME_SHORT(){return zU}static get DATETIME_SHORT_WITH_SECONDS(){return HU}static get DATETIME_MED(){return WU}static get DATETIME_MED_WITH_SECONDS(){return jU}static get DATETIME_MED_WITH_WEEKDAY(){return Cee}static get DATETIME_FULL(){return GU}static get DATETIME_FULL_WITH_SECONDS(){return YU}static get DATETIME_HUGE(){return KU}static get DATETIME_HUGE_WITH_SECONDS(){return QU}};function Xy(r){if(ft.isDateTime(r))return r;if(r&&r.valueOf&&Wd(r.valueOf()))return ft.fromJSDate(r);if(r&&typeof r=="object")return ft.fromObject(r);throw new to(`Unknown datetime argument: ${r}, of type ${typeof r}`)}var D0={renderNullAs:"\\-",taskCompletionTracking:!1,taskCompletionUseEmojiShorthand:!1,taskCompletionText:"completion",taskCompletionDateFormat:"yyyy-MM-dd",recursiveSubTaskCompletion:!1,warnOnEmptyResult:!0,refreshEnabled:!0,refreshInterval:2500,defaultDateFormat:"MMMM dd, yyyy",defaultDateTimeFormat:"h:mm a - MMMM dd, yyyy",maxRecursiveRenderDepth:4,tableIdColumnName:"File",tableGroupColumnName:"Group",showResultCount:!0},cre={allowHtml:!0};({...D0,...cre});var g0=class r{constructor(e){pe(this,"value");pe(this,"successful");this.value=e,this.successful=!0}map(e){return new r(e(this.value))}flatMap(e){return e(this.value)}mapErr(e){return this}bimap(e,t){return this.map(e)}orElse(e){return this.value}cast(){return this}orElseThrow(e){return this.value}},v0=class r{constructor(e){pe(this,"error");pe(this,"successful");this.error=e,this.successful=!1}map(e){return this}flatMap(e){return this}mapErr(e){return new r(e(this.error))}bimap(e,t){return this.mapErr(t)}orElse(e){return e}cast(){return this}orElseThrow(e){throw e?new Error(e(this.error)):new Error(""+this.error)}},rS;(function(r){function e(o){return new g0(o)}r.success=e;function t(o){return new v0(o)}r.failure=t;function n(o,s,a){return o.successful?s.successful?a(o.value,s.value):t(s.error):t(o.error)}r.flatMap2=n;function i(o,s,a){return n(o,s,(l,c)=>e(a(l,c)))}r.map2=i})(rS||(rS={}));var ure=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},nS={exports:{}};nS.exports;(function(r,e){(function(t,n){r.exports=n()})(typeof self<"u"?self:ure,function(){return(function(t){var n={};function i(o){if(n[o])return n[o].exports;var s=n[o]={i:o,l:!1,exports:{}};return t[o].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=t,i.c=n,i.d=function(o,s,a){i.o(o,s)||Object.defineProperty(o,s,{configurable:!1,enumerable:!0,get:a})},i.r=function(o){Object.defineProperty(o,"__esModule",{value:!0})},i.n=function(o){var s=o&&o.__esModule?function(){return o.default}:function(){return o};return i.d(s,"a",s),s},i.o=function(o,s){return Object.prototype.hasOwnProperty.call(o,s)},i.p="",i(i.s=0)})([function(t,n,i){function o(x){if(!(this instanceof o))return new o(x);this._=x}var s=o.prototype;function a(x,A){for(var N=0;N<x;N++)A(N)}function l(x,A,N){return(function(K,Z){a(Z.length,function(se){K(Z[se],se,Z)})})(function(K,Z,se){A=x(A,K,Z,se)},N),A}function c(x,A){return l(function(N,K,Z,se){return N.concat([x(K,Z,se)])},[],A)}function u(x,A){var N={v:0,buf:A};return a(x,function(){var K;N={v:N.v<<1|(K=N.buf,K[0]>>7),buf:(function(Z){var se=l(function(de,Me,it,ur){return de.concat(it===ur.length-1?Buffer.from([Me,0]).readUInt16BE(0):ur.readUInt16BE(it))},[],Z);return Buffer.from(c(function(de){return(de<<1&65535)>>8},se))})(N.buf)}}),N}function d(){return typeof Buffer<"u"}function f(){if(!d())throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser.")}function p(x){f();var A=l(function(se,de){return se+de},0,x);if(A%8!=0)throw new Error("The bits ["+x.join(", ")+"] add up to "+A+" which is not an even number of bytes; the total should be divisible by 8");var N,K=A/8,Z=(N=function(se){return se>48},l(function(se,de){return se||(N(de)?de:se)},null,x));if(Z)throw new Error(Z+" bit range requested exceeds 48 bit (6 byte) Number max.");return new o(function(se,de){var Me=K+de;return Me>se.length?I(de,K.toString()+" bytes"):_(Me,l(function(it,ur){var $t=u(ur,it.buf);return{coll:it.coll.concat($t.v),buf:$t.buf}},{coll:[],buf:se.slice(de,Me)},x).coll)})}function m(x,A){return new o(function(N,K){return f(),K+A>N.length?I(K,A+" bytes for "+x):_(K+A,N.slice(K,K+A))})}function v(x,A){if(typeof(N=A)!="number"||Math.floor(N)!==N||A<0||A>6)throw new Error(x+" requires integer length in range [0, 6].");var N}function g(x){return v("uintBE",x),m("uintBE("+x+")",x).map(function(A){return A.readUIntBE(0,x)})}function y(x){return v("uintLE",x),m("uintLE("+x+")",x).map(function(A){return A.readUIntLE(0,x)})}function w(x){return v("intBE",x),m("intBE("+x+")",x).map(function(A){return A.readIntBE(0,x)})}function T(x){return v("intLE",x),m("intLE("+x+")",x).map(function(A){return A.readIntLE(0,x)})}function b(x){return x instanceof o}function E(x){return{}.toString.call(x)==="[object Array]"}function C(x){return d()&&Buffer.isBuffer(x)}function _(x,A){return{status:!0,index:x,value:A,furthest:-1,expected:[]}}function I(x,A){return E(A)||(A=[A]),{status:!1,index:-1,value:null,furthest:x,expected:A}}function q(x,A){if(!A||x.furthest>A.furthest)return x;var N=x.furthest===A.furthest?(function(K,Z){if((function(){if(o._supportsSet!==void 0)return o._supportsSet;var Yt=typeof Set<"u";return o._supportsSet=Yt,Yt})()&&Array.from){for(var se=new Set(K),de=0;de<Z.length;de++)se.add(Z[de]);var Me=Array.from(se);return Me.sort(),Me}for(var it={},ur=0;ur<K.length;ur++)it[K[ur]]=!0;for(var $t=0;$t<Z.length;$t++)it[Z[$t]]=!0;var ri=[];for(var ot in it)({}).hasOwnProperty.call(it,ot)&&ri.push(ot);return ri.sort(),ri})(x.expected,A.expected):A.expected;return{status:x.status,index:x.index,value:x.value,furthest:A.furthest,expected:N}}var B={};function J(x,A){if(C(x))return{offset:A,line:-1,column:-1};x in B||(B[x]={});for(var N=B[x],K=0,Z=0,se=0,de=A;de>=0;){if(de in N){K=N[de].line,se===0&&(se=N[de].lineStart);break}(x.charAt(de)===`
`||x.charAt(de)==="\r"&&x.charAt(de+1)!==`
`)&&(Z++,se===0&&(se=de+1)),de--}var Me=K+Z,it=A-se;return N[A]={line:Me,lineStart:se},{offset:A,line:Me+1,column:it+1}}function re(x){if(!b(x))throw new Error("not a parser: "+x)}function L(x,A){return typeof x=="string"?x.charAt(A):x[A]}function W(x){if(typeof x!="number")throw new Error("not a number: "+x)}function j(x){if(typeof x!="function")throw new Error("not a function: "+x)}function $(x){if(typeof x!="string")throw new Error("not a string: "+x)}var G=2,U=3,H=8,Y=5*H,ie=4*H,oe=" ";function ce(x,A){return new Array(A+1).join(x)}function he(x,A,N){var K=A-x.length;return K<=0?x:ce(N,K)+x}function Ie(x,A,N,K){return{from:x-A>0?x-A:0,to:x+N>K?K:x+N}}function we(x,A){var N,K,Z,se,de,Me=A.index,it=Me.offset,ur=1;if(it===x.length)return"Got the end of the input";if(C(x)){var $t=it-it%H,ri=it-$t,ot=Ie($t,Y,ie+H,x.length),Yt=c(function(mt){return c(function(qi){return he(qi.toString(16),2,"0")},mt)},(function(mt,qi){var hs=mt.length,Po=[],Nr=0;if(hs<=qi)return[mt.slice()];for(var Qr=0;Qr<hs;Qr++)Po[Nr]||Po.push([]),Po[Nr].push(mt[Qr]),(Qr+1)%qi==0&&Nr++;return Po})(x.slice(ot.from,ot.to).toJSON().data,H));se=(function(mt){return mt.from===0&&mt.to===1?{from:mt.from,to:mt.to}:{from:mt.from/H,to:Math.floor(mt.to/H)}})(ot),K=$t/H,N=3*ri,ri>=4&&(N+=1),ur=2,Z=c(function(mt){return mt.length<=4?mt.join(" "):mt.slice(0,4).join(" ")+" "+mt.slice(4).join(" ")},Yt),(de=(8*(se.to>0?se.to-1:se.to)).toString(16).length)<2&&(de=2)}else{var or=x.split(/\r\n|[\n\r\u2028\u2029]/);N=Me.column-1,K=Me.line-1,se=Ie(K,G,U,or.length),Z=or.slice(se.from,se.to),de=se.to.toString().length}var yn=K-se.from;return C(x)&&(de=(8*(se.to>0?se.to-1:se.to)).toString(16).length)<2&&(de=2),l(function(mt,qi,hs){var Po,Nr=hs===yn,Qr=Nr?"> ":oe;return Po=C(x)?he((8*(se.from+hs)).toString(16),de,"0"):he((se.from+hs+1).toString(),de," "),[].concat(mt,[Qr+Po+" | "+qi],Nr?[oe+ce(" ",de)+" | "+he("",N," ")+ce("^",ur)]:[])},[],Z).join(`
`)}function Ge(x,A){return[`
`,"-- PARSING FAILED "+ce("-",50),`
`,we(x,A),`
`,(N=A.expected,N.length===1?`Expected:
`+N[0]:`Expected one of the following:
`+N.join(", ")),`
`].join("");var N}function Pe(x){return x.flags!==void 0?x.flags:[x.global?"g":"",x.ignoreCase?"i":"",x.multiline?"m":"",x.unicode?"u":"",x.sticky?"y":""].join("")}function Ve(){for(var x=[].slice.call(arguments),A=x.length,N=0;N<A;N+=1)re(x[N]);return o(function(K,Z){for(var se,de=new Array(A),Me=0;Me<A;Me+=1){if(!(se=q(x[Me]._(K,Z),se)).status)return se;de[Me]=se.value,Z=se.index}return q(_(Z,de),se)})}function qe(){var x=[].slice.call(arguments);if(x.length===0)throw new Error("seqMap needs at least one argument");var A=x.pop();return j(A),Ve.apply(null,x).map(function(N){return A.apply(null,N)})}function et(){var x=[].slice.call(arguments),A=x.length;if(A===0)return tt("zero alternates");for(var N=0;N<A;N+=1)re(x[N]);return o(function(K,Z){for(var se,de=0;de<x.length;de+=1)if((se=q(x[de]._(K,Z),se)).status)return se;return se})}function _t(x,A){return ye(x,A).or(xe([]))}function ye(x,A){return re(x),re(A),qe(x,A.then(x).many(),function(N,K){return[N].concat(K)})}function $e(x){$(x);var A="'"+x+"'";return o(function(N,K){var Z=K+x.length,se=N.slice(K,Z);return se===x?_(Z,se):I(K,A)})}function ge(x,A){(function(Z){if(!(Z instanceof RegExp))throw new Error("not a regexp: "+Z);for(var se=Pe(Z),de=0;de<se.length;de++){var Me=se.charAt(de);if(Me!=="i"&&Me!=="m"&&Me!=="u"&&Me!=="s")throw new Error('unsupported regexp flag "'+Me+'": '+Z)}})(x),arguments.length>=2?W(A):A=0;var N=(function(Z){return RegExp("^(?:"+Z.source+")",Pe(Z))})(x),K=""+x;return o(function(Z,se){var de=N.exec(Z.slice(se));if(de){if(0<=A&&A<=de.length){var Me=de[0],it=de[A];return _(se+Me.length,it)}return I(se,"valid match group (0 to "+de.length+") in "+K)}return I(se,K)})}function xe(x){return o(function(A,N){return _(N,x)})}function tt(x){return o(function(A,N){return I(N,x)})}function kt(x){if(b(x))return o(function(A,N){var K=x._(A,N);return K.index=N,K.value="",K});if(typeof x=="string")return kt($e(x));if(x instanceof RegExp)return kt(ge(x));throw new Error("not a string, regexp, or parser: "+x)}function Pt(x){return re(x),o(function(A,N){var K=x._(A,N),Z=A.slice(N,K.index);return K.status?I(N,'not "'+Z+'"'):_(N,null)})}function gt(x){return j(x),o(function(A,N){var K=L(A,N);return N<A.length&&x(K)?_(N+1,K):I(N,"a character/byte matching "+x)})}function Lt(x,A){arguments.length<2&&(A=x,x=void 0);var N=o(function(K,Z){return N._=A()._,N._(K,Z)});return x?N.desc(x):N}function Lr(){return tt("fantasy-land/empty")}s.parse=function(x){if(typeof x!="string"&&!C(x))throw new Error(".parse must be called with a string or Buffer as its argument");var A,N=this.skip(ti)._(x,0);return A=N.status?{status:!0,value:N.value}:{status:!1,index:J(x,N.furthest),expected:N.expected},delete B[x],A},s.tryParse=function(x){var A=this.parse(x);if(A.status)return A.value;var N=Ge(x,A),K=new Error(N);throw K.type="ParsimmonError",K.result=A,K},s.assert=function(x,A){return this.chain(function(N){return x(N)?xe(N):tt(A)})},s.or=function(x){return et(this,x)},s.trim=function(x){return this.wrap(x,x)},s.wrap=function(x,A){return qe(x,this,A,function(N,K){return K})},s.thru=function(x){return x(this)},s.then=function(x){return re(x),Ve(this,x).map(function(A){return A[1]})},s.many=function(){var x=this;return o(function(A,N){for(var K=[],Z=void 0;;){if(!(Z=q(x._(A,N),Z)).status)return q(_(N,K),Z);if(N===Z.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");N=Z.index,K.push(Z.value)}})},s.tieWith=function(x){return $(x),this.map(function(A){if((function(Z){if(!E(Z))throw new Error("not an array: "+Z)})(A),A.length){$(A[0]);for(var N=A[0],K=1;K<A.length;K++)$(A[K]),N+=x+A[K];return N}return""})},s.tie=function(){return this.tieWith("")},s.times=function(x,A){var N=this;return arguments.length<2&&(A=x),W(x),W(A),o(function(K,Z){for(var se=[],de=void 0,Me=void 0,it=0;it<x;it+=1){if(Me=q(de=N._(K,Z),Me),!de.status)return Me;Z=de.index,se.push(de.value)}for(;it<A&&(Me=q(de=N._(K,Z),Me),de.status);it+=1)Z=de.index,se.push(de.value);return q(_(Z,se),Me)})},s.result=function(x){return this.map(function(){return x})},s.atMost=function(x){return this.times(0,x)},s.atLeast=function(x){return qe(this.times(x),this.many(),function(A,N){return A.concat(N)})},s.map=function(x){j(x);var A=this;return o(function(N,K){var Z=A._(N,K);return Z.status?q(_(Z.index,x(Z.value)),Z):Z})},s.contramap=function(x){j(x);var A=this;return o(function(N,K){var Z=A.parse(x(N.slice(K)));return Z.status?_(K+N.length,Z.value):Z})},s.promap=function(x,A){return j(x),j(A),this.contramap(x).map(A)},s.skip=function(x){return Ve(this,x).map(function(A){return A[0]})},s.mark=function(){return qe(lt,this,lt,function(x,A,N){return{start:x,value:A,end:N}})},s.node=function(x){return qe(lt,this,lt,function(A,N,K){return{name:x,value:N,start:A,end:K}})},s.sepBy=function(x){return _t(this,x)},s.sepBy1=function(x){return ye(this,x)},s.lookahead=function(x){return this.skip(kt(x))},s.notFollowedBy=function(x){return this.skip(Pt(x))},s.desc=function(x){E(x)||(x=[x]);var A=this;return o(function(N,K){var Z=A._(N,K);return Z.status||(Z.expected=x),Z})},s.fallback=function(x){return this.or(xe(x))},s.ap=function(x){return qe(x,this,function(A,N){return A(N)})},s.chain=function(x){var A=this;return o(function(N,K){var Z=A._(N,K);return Z.status?q(x(Z.value)._(N,Z.index),Z):Z})},s.concat=s.or,s.empty=Lr,s.of=xe,s["fantasy-land/ap"]=s.ap,s["fantasy-land/chain"]=s.chain,s["fantasy-land/concat"]=s.concat,s["fantasy-land/empty"]=s.empty,s["fantasy-land/of"]=s.of,s["fantasy-land/map"]=s.map;var lt=o(function(x,A){return _(A,J(x,A))}),rt=o(function(x,A){return A>=x.length?I(A,"any character/byte"):_(A+1,L(x,A))}),cr=o(function(x,A){return _(x.length,x.slice(A))}),ti=o(function(x,A){return A<x.length?I(A,"EOF"):_(A,null)}),Fo=ge(/[0-9]/).desc("a digit"),vn=ge(/[0-9]*/).desc("optional digits"),te=ge(/[a-z]/i).desc("a letter"),Ae=ge(/[a-z]*/i).desc("optional letters"),Gt=ge(/\s*/).desc("optional whitespace"),er=ge(/\s+/).desc("whitespace"),Kr=$e("\r"),no=$e(`
`),ra=$e(`\r
`),na=et(ra,no,Kr).desc("newline"),tc=et(na,ti);o.all=cr,o.alt=et,o.any=rt,o.cr=Kr,o.createLanguage=function(x){var A={};for(var N in x)({}).hasOwnProperty.call(x,N)&&(function(K){A[K]=Lt(function(){return x[K](A)})})(N);return A},o.crlf=ra,o.custom=function(x){return o(x(_,I))},o.digit=Fo,o.digits=vn,o.empty=Lr,o.end=tc,o.eof=ti,o.fail=tt,o.formatError=Ge,o.index=lt,o.isParser=b,o.lazy=Lt,o.letter=te,o.letters=Ae,o.lf=no,o.lookahead=kt,o.makeFailure=I,o.makeSuccess=_,o.newline=na,o.noneOf=function(x){return gt(function(A){return x.indexOf(A)<0}).desc("none of '"+x+"'")},o.notFollowedBy=Pt,o.of=xe,o.oneOf=function(x){for(var A=x.split(""),N=0;N<A.length;N++)A[N]="'"+A[N]+"'";return gt(function(K){return x.indexOf(K)>=0}).desc(A)},o.optWhitespace=Gt,o.Parser=o,o.range=function(x,A){return gt(function(N){return x<=N&&N<=A}).desc(x+"-"+A)},o.regex=ge,o.regexp=ge,o.sepBy=_t,o.sepBy1=ye,o.seq=Ve,o.seqMap=qe,o.seqObj=function(){for(var x,A={},N=0,K=(x=arguments,Array.prototype.slice.call(x)),Z=K.length,se=0;se<Z;se+=1){var de=K[se];if(!b(de)){if(E(de)&&de.length===2&&typeof de[0]=="string"&&b(de[1])){var Me=de[0];if(Object.prototype.hasOwnProperty.call(A,Me))throw new Error("seqObj: duplicate key "+Me);A[Me]=!0,N++;continue}throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(N===0)throw new Error("seqObj expects at least one named parser, found zero");return o(function(it,ur){for(var $t,ri={},ot=0;ot<Z;ot+=1){var Yt,or;if(E(K[ot])?(Yt=K[ot][0],or=K[ot][1]):(Yt=null,or=K[ot]),!($t=q(or._(it,ur),$t)).status)return $t;Yt&&(ri[Yt]=$t.value),ur=$t.index}return q(_(ur,ri),$t)})},o.string=$e,o.succeed=xe,o.takeWhile=function(x){return j(x),o(function(A,N){for(var K=N;K<A.length&&x(L(A,K));)K++;return _(K,A.slice(N,K))})},o.test=gt,o.whitespace=er,o["fantasy-land/empty"]=Lr,o["fantasy-land/of"]=xe,o.Binary={bitSeq:p,bitSeqObj:function(x){f();var A={},N=0,K=c(function(se){if(E(se)){var de=se;if(de.length!==2)throw new Error("["+de.join(", ")+"] should be length 2, got length "+de.length);if($(de[0]),W(de[1]),Object.prototype.hasOwnProperty.call(A,de[0]))throw new Error("duplicate key in bitSeqObj: "+de[0]);return A[de[0]]=!0,N++,de}return W(se),[null,se]},x);if(N<1)throw new Error("bitSeqObj expects at least one named pair, got ["+x.join(", ")+"]");var Z=c(function(se){return se[0]},K);return p(c(function(se){return se[1]},K)).map(function(se){return l(function(de,Me){return Me[0]!==null&&(de[Me[0]]=Me[1]),de},{},c(function(de,Me){return[de,se[Me]]},Z))})},byte:function(x){if(f(),W(x),x>255)throw new Error("Value specified to byte constructor ("+x+"=0x"+x.toString(16)+") is larger in value than a single byte.");var A=(x>15?"0x":"0x0")+x.toString(16);return o(function(N,K){var Z=L(N,K);return Z===x?_(K+1,Z):I(K,A)})},buffer:function(x){return m("buffer",x).map(function(A){return Buffer.from(A)})},encodedString:function(x,A){return m("string",A).map(function(N){return N.toString(x)})},uintBE:g,uint8BE:g(1),uint16BE:g(2),uint32BE:g(4),uintLE:y,uint8LE:y(1),uint16LE:y(2),uint32LE:y(4),intBE:w,int8BE:w(1),int16BE:w(2),int32BE:w(4),intLE:T,int8LE:T(1),int16LE:T(2),int32LE:T(4),floatBE:m("floatBE",4).map(function(x){return x.readFloatBE(0)}),floatLE:m("floatLE",4).map(function(x){return x.readFloatLE(0)}),doubleBE:m("doubleBE",8).map(function(x){return x.readDoubleBE(0)}),doubleLE:m("doubleLE",8).map(function(x){return x.readDoubleLE(0)})},t.exports=o}])})})(nS,nS.exports);var R=nS.exports,I0=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26F9(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC3\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC08\uDC26](?:\u200D\u2B1B)?|[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;function Iz(r){return r==null?r:r.shiftToAll().normalize()}function kU(r){return r.includes("/")&&(r=r.substring(r.lastIndexOf("/")+1)),r.endsWith(".md")&&(r=r.substring(0,r.length-3)),r}R.alt(R.regex(new RegExp(I0(),"")),R.regex(/[0-9\p{Letter}_-]+/u).map(r=>r.toLocaleLowerCase()),R.whitespace.map(r=>"-"),R.any.map(r=>"")).many().map(r=>r.join(""));var dre=R.alt(R.regex(new RegExp(I0(),"")),R.regex(/[0-9\p{Letter}_-]+/u),R.whitespace.map(r=>" "),R.any.map(r=>" ")).many().map(r=>r.join("").split(/\s+/).join(" ").trim());function pre(r){return dre.tryParse(r)}function fre(r){return r=Iz(r),r=Ue.fromObject(Object.fromEntries(Object.entries(r.toObject()).filter(([,e])=>e!=0))),r.toHuman()}var rb;(function(r){function e(b,E=D0,C=!1){let _=t(b);if(!_)return E.renderNullAs;switch(_.type){case"null":return E.renderNullAs;case"string":return _.value;case"number":case"boolean":return""+_.value;case"html":return _.value.outerHTML;case"widget":return _.value.markdown();case"link":return _.value.markdown();case"function":return"<function>";case"array":let I="";return C&&(I+="["),I+=_.value.map(q=>e(q,E,!0)).join(", "),C&&(I+="]"),I;case"object":return"{ "+Object.entries(_.value).map(q=>q[0]+": "+e(q[1],E,!0)).join(", ")+" }";case"date":return _.value.second==0&&_.value.hour==0&&_.value.minute==0?_.value.toFormat(E.defaultDateFormat):_.value.toFormat(E.defaultDateTimeFormat);case"duration":return fre(_.value)}}r.toString=e;function t(b){return f(b)?{type:"null",value:b}:c(b)?{type:"number",value:b}:l(b)?{type:"string",value:b}:m(b)?{type:"boolean",value:b}:d(b)?{type:"duration",value:b}:u(b)?{type:"date",value:b}:g(b)?{type:"widget",value:b}:p(b)?{type:"array",value:b}:v(b)?{type:"link",value:b}:T(b)?{type:"function",value:b}:y(b)?{type:"html",value:b}:w(b)?{type:"object",value:b}:void 0}r.wrapValue=t;function n(b,E){if(w(b)){let C={};for(let[_,I]of Object.entries(b))C[_]=n(I,E);return C}else if(p(b)){let C=[];for(let _ of b)C.push(n(_,E));return C}else return E(b)}r.mapLeaves=n;function i(b,E,C){if(b===void 0&&(b=null),E===void 0&&(E=null),b===null&&E===null)return 0;if(b===null)return-1;if(E===null)return 1;let _=t(b),I=t(E);if(_===void 0&&I===void 0)return 0;if(_===void 0)return-1;if(I===void 0)return 1;if(_.type!=I.type)return _.type.localeCompare(I.type);if(_.value===I.value)return 0;switch(_.type){case"string":return _.value.localeCompare(I.value);case"number":return _.value<I.value?-1:_.value==I.value?0:1;case"null":return 0;case"boolean":return _.value==I.value?0:_.value?1:-1;case"link":let q=_.value,B=I.value,J=C??(ie=>ie),re=J(q.path).localeCompare(J(B.path));if(re!=0)return re;let L=q.type.localeCompare(B.type);return L!=0?L:q.subpath&&!B.subpath?1:!q.subpath&&B.subpath?-1:!q.subpath&&!B.subpath?0:(q.subpath??"").localeCompare(B.subpath??"");case"date":return _.value<I.value?-1:_.value.equals(I.value)?0:1;case"duration":return _.value<I.value?-1:_.value.equals(I.value)?0:1;case"array":let W=_.value,j=I.value;for(let ie=0;ie<Math.min(W.length,j.length);ie++){let oe=i(W[ie],j[ie]);if(oe!=0)return oe}return W.length-j.length;case"object":let $=_.value,G=I.value,U=Array.from(Object.keys($)),H=Array.from(Object.keys(G));U.sort(),H.sort();let Y=i(U,H);if(Y!=0)return Y;for(let ie of U){let oe=i($[ie],G[ie]);if(oe!=0)return oe}return 0;case"widget":case"html":case"function":return 0}}r.compareValue=i;function o(b){return t(b)?.type}r.typeOf=o;function s(b){let E=t(b);if(!E)return!1;switch(E.type){case"number":return E.value!=0;case"string":return E.value.length>0;case"boolean":return E.value;case"link":return!!E.value.path;case"date":return E.value.toMillis()!=0;case"duration":return E.value.as("seconds")!=0;case"object":return Object.keys(E.value).length>0;case"array":return E.value.length>0;case"null":return!1;case"html":case"widget":case"function":return!0}}r.isTruthy=s;function a(b){if(b==null)return b;if(r.isArray(b))return[].concat(b.map(E=>a(E)));if(r.isObject(b)){let E={};for(let[C,_]of Object.entries(b))E[C]=a(_);return E}else return b}r.deepCopy=a;function l(b){return typeof b=="string"}r.isString=l;function c(b){return typeof b=="number"}r.isNumber=c;function u(b){return b instanceof ft}r.isDate=u;function d(b){return b instanceof Ue}r.isDuration=d;function f(b){return b==null}r.isNull=f;function p(b){return Array.isArray(b)}r.isArray=p;function m(b){return typeof b=="boolean"}r.isBoolean=m;function v(b){return b instanceof iS}r.isLink=v;function g(b){return b instanceof nb}r.isWidget=g;function y(b){return typeof HTMLElement<"u"?b instanceof HTMLElement:!1}r.isHtml=y;function w(b){return typeof b=="object"&&!y(b)&&!g(b)&&!p(b)&&!d(b)&&!u(b)&&!v(b)&&b!==void 0&&!f(b)}r.isObject=w;function T(b){return typeof b=="function"}r.isFunction=T})(rb||(rb={}));var AU;(function(r){function e(i){return rb.isObject(i)&&Object.keys(i).length==2&&"key"in i&&"rows"in i}r.isElementGroup=e;function t(i){for(let o of i)if(!e(o))return!1;return!0}r.isGrouping=t;function n(i){if(t(i)){let o=0;for(let s of i)o+=n(s.rows);return o}else return i.length}r.count=n})(AU||(AU={}));var iS=class r{constructor(e){pe(this,"path");pe(this,"display");pe(this,"subpath");pe(this,"embed");pe(this,"type");Object.assign(this,e)}static file(e,t=!1,n){return new r({path:e,embed:t,display:n,subpath:void 0,type:"file"})}static infer(e,t=!1,n){if(e.includes("#^")){let i=e.split("#^");return r.block(i[0],i[1],t,n)}else if(e.includes("#")){let i=e.split("#");return r.header(i[0],i[1],t,n)}else return r.file(e,t,n)}static header(e,t,n,i){return new r({path:e,embed:n,display:i,subpath:pre(t),type:"header"})}static block(e,t,n,i){return new r({path:e,embed:n,display:i,subpath:t,type:"block"})}static fromObject(e){return new r(e)}equals(e){return e==null||e==null?!1:this.path==e.path&&this.type==e.type&&this.subpath==e.subpath}toString(){return this.markdown()}toObject(){return{path:this.path,type:this.type,subpath:this.subpath,display:this.display,embed:this.embed}}withPath(e){return new r(Object.assign({},this,{path:e}))}withDisplay(e){return new r(Object.assign({},this,{display:e}))}withHeader(e){return r.header(this.path,e,this.embed,this.display)}toFile(){return r.file(this.path,this.embed,this.display)}toEmbed(){if(this.embed)return this;{let e=new r(this);return e.embed=!0,e}}fromEmbed(){if(this.embed){let e=new r(this);return e.embed=!1,e}else return this}markdown(){let e=(this.embed?"!":"")+"[["+this.obsidianLink();return this.display?e+="|"+this.display:(e+="|"+kU(this.path),(this.type=="header"||this.type=="block")&&(e+=" > "+this.subpath)),e+="]]",e}obsidianLink(){let e=this.path.replaceAll("|","\\|");return this.type=="header"?e+"#"+this.subpath?.replaceAll("|","\\|"):this.type=="block"?e+"#^"+this.subpath?.replaceAll("|","\\|"):e}fileName(){return kU(this.path).replace(".md","")}},nb=class{constructor(e){pe(this,"$widget");this.$widget=e}},y0=class extends nb{constructor(t,n){super("dataview:list-pair");pe(this,"key");pe(this,"value");this.key=t,this.value=n}markdown(){return`${rb.toString(this.key)}: ${rb.toString(this.value)}`}},b0=class extends nb{constructor(t,n){super("dataview:external-link");pe(this,"url");pe(this,"display");this.url=t,this.display=n}markdown(){return`[${this.display??this.url}](${this.url})`}},DU;(function(r){function e(s,a){return new y0(s,a)}r.listPair=e;function t(s,a){return new b0(s,a)}r.externalLink=t;function n(s){return s.$widget==="dataview:list-pair"}r.isListPair=n;function i(s){return s.$widget==="dataview:external-link"}r.isExternalLink=i;function o(s){return n(s)||i(s)}r.isBuiltin=o})(DU||(DU={}));var Sr;(function(r){function e(f){return{type:"variable",name:f}}r.variable=e;function t(f){return{type:"literal",value:f}}r.literal=t;function n(f,p,m){return{type:"binaryop",left:f,op:p,right:m}}r.binaryOp=n;function i(f,p){return{type:"index",object:f,index:p}}r.index=i;function o(f){let p=f.split("."),m=r.variable(p[0]);for(let v=1;v<p.length;v++)m=r.index(m,r.literal(p[v]));return m}r.indexVariable=o;function s(f,p){return{type:"lambda",arguments:f,value:p}}r.lambda=s;function a(f,p){return{type:"function",func:f,arguments:p}}r.func=a;function l(f){return{type:"list",values:f}}r.list=l;function c(f){return{type:"object",values:f}}r.object=c;function u(f){return{type:"negated",child:f}}r.negate=u;function d(f){return f=="<="||f=="<"||f==">"||f==">="||f=="!="||f=="="}r.isCompareOp=d,r.NULL=r.literal(null)})(Sr||(Sr={}));var za;(function(r){function e(u){return{type:"tag",tag:u}}r.tag=e;function t(u){return{type:"csv",path:u}}r.csv=t;function n(u){return{type:"folder",folder:u}}r.folder=n;function i(u,d){return{type:"link",file:u,direction:d?"incoming":"outgoing"}}r.link=i;function o(u,d,f){return{type:"binaryop",left:u,op:d,right:f}}r.binaryOp=o;function s(u,d){return{type:"binaryop",left:u,op:"&",right:d}}r.and=s;function a(u,d){return{type:"binaryop",left:u,op:"|",right:d}}r.or=a;function l(u){return{type:"negate",child:u}}r.negate=l;function c(){return{type:"empty"}}r.empty=c})(za||(za={}));var IU=new RegExp(I0(),""),w0={year:Ue.fromObject({years:1}),years:Ue.fromObject({years:1}),yr:Ue.fromObject({years:1}),yrs:Ue.fromObject({years:1}),month:Ue.fromObject({months:1}),months:Ue.fromObject({months:1}),mo:Ue.fromObject({months:1}),mos:Ue.fromObject({months:1}),week:Ue.fromObject({weeks:1}),weeks:Ue.fromObject({weeks:1}),wk:Ue.fromObject({weeks:1}),wks:Ue.fromObject({weeks:1}),w:Ue.fromObject({weeks:1}),day:Ue.fromObject({days:1}),days:Ue.fromObject({days:1}),d:Ue.fromObject({days:1}),hour:Ue.fromObject({hours:1}),hours:Ue.fromObject({hours:1}),hr:Ue.fromObject({hours:1}),hrs:Ue.fromObject({hours:1}),h:Ue.fromObject({hours:1}),minute:Ue.fromObject({minutes:1}),minutes:Ue.fromObject({minutes:1}),min:Ue.fromObject({minutes:1}),mins:Ue.fromObject({minutes:1}),m:Ue.fromObject({minutes:1}),second:Ue.fromObject({seconds:1}),seconds:Ue.fromObject({seconds:1}),sec:Ue.fromObject({seconds:1}),secs:Ue.fromObject({seconds:1}),s:Ue.fromObject({seconds:1})},C0={now:()=>ft.local(),today:()=>ft.local().startOf("day"),yesterday:()=>ft.local().startOf("day").minus(Ue.fromObject({days:1})),tomorrow:()=>ft.local().startOf("day").plus(Ue.fromObject({days:1})),sow:()=>ft.local().startOf("week"),"start-of-week":()=>ft.local().startOf("week"),eow:()=>ft.local().endOf("week"),"end-of-week":()=>ft.local().endOf("week"),soy:()=>ft.local().startOf("year"),"start-of-year":()=>ft.local().startOf("year"),eoy:()=>ft.local().endOf("year"),"end-of-year":()=>ft.local().endOf("year"),som:()=>ft.local().startOf("month"),"start-of-month":()=>ft.local().startOf("month"),eom:()=>ft.local().endOf("month"),"end-of-month":()=>ft.local().endOf("month")},E0=["FROM","WHERE","LIMIT","GROUP","FLATTEN"];function mre(r){let e=-1;for(;(e=r.indexOf("|",e+1))>=0;)if(!(e>0&&r[e-1]=="\\"))return[r.substring(0,e).replace(/\\\|/g,"|"),r.substring(e+1)];return[r.replace(/\\\|/g,"|"),void 0]}function hre(r){let[e,t]=mre(r);return iS.infer(e,!1,t)}function Zy(r,e,t){return R.seqMap(r,R.seq(R.optWhitespace,e,R.optWhitespace,r).many(),(n,i)=>{if(i.length==0)return n;let o=t(n,i[0][1],i[0][3]);for(let s=1;s<i.length;s++)o=t(o,i[s][1],i[s][3]);return o})}function gre(r,...e){return R.custom((t,n)=>(i,o)=>{let s=r._(i,o);if(!s.status)return s;for(let a of e){let l=a(s.value)._(i,s.index);if(!l.status)return s;s=l}return s})}var Js=R.createLanguage({number:r=>R.regexp(/-?[0-9]+(\.[0-9]+)?/).map(e=>Number.parseFloat(e)).desc("number"),string:r=>R.string('"').then(R.alt(r.escapeCharacter,R.noneOf('"\\')).atLeast(0).map(e=>e.join(""))).skip(R.string('"')).desc("string"),escapeCharacter:r=>R.string("\\").then(R.any).map(e=>e==='"'?'"':e==="\\"?"\\":"\\"+e),bool:r=>R.regexp(/true|false|True|False/).map(e=>e.toLowerCase()=="true").desc("boolean ('true' or 'false')"),tag:r=>R.seqMap(R.string("#"),R.alt(R.regexp(/[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s]/).desc("text")).many(),(e,t)=>e+t.join("")).desc("tag ('#hello/stuff')"),identifier:r=>R.seqMap(R.alt(R.regexp(/\p{Letter}/u),R.regexp(IU).desc("text")),R.alt(R.regexp(/[0-9\p{Letter}_-]/u),R.regexp(IU).desc("text")).many(),(e,t)=>e+t.join("")).desc("variable identifier"),link:r=>R.regexp(/\[\[([^\[\]]*?)\]\]/u,1).map(e=>hre(e)).desc("file link"),embedLink:r=>R.seqMap(R.string("!").atMost(1),r.link,(e,t)=>(e.length>0&&(t.embed=!0),t)).desc("file link"),binaryPlusMinus:r=>R.regexp(/\+|-/).map(e=>e).desc("'+' or '-'"),binaryMulDiv:r=>R.regexp(/\*|\/|%/).map(e=>e).desc("'*' or '/' or '%'"),binaryCompareOp:r=>R.regexp(/>=|<=|!=|>|<|=/).map(e=>e).desc("'>=' or '<=' or '!=' or '=' or '>' or '<'"),binaryBooleanOp:r=>R.regexp(/and|or|&|\|/i).map(e=>e.toLowerCase()=="and"?"&":e.toLowerCase()=="or"?"|":e).desc("'and' or 'or'"),rootDate:r=>R.seqMap(R.regexp(/\d{4}/),R.string("-"),R.regexp(/\d{2}/),(e,t,n)=>ft.fromObject({year:Number.parseInt(e),month:Number.parseInt(n)})).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),dateShorthand:r=>R.alt(...Object.keys(C0).sort((e,t)=>t.length-e.length).map(R.string)),date:r=>gre(r.rootDate,e=>R.seqMap(R.string("-"),R.regexp(/\d{2}/),(t,n)=>e.set({day:Number.parseInt(n)})),e=>R.seqMap(R.string("T"),R.regexp(/\d{2}/),(t,n)=>e.set({hour:Number.parseInt(n)})),e=>R.seqMap(R.string(":"),R.regexp(/\d{2}/),(t,n)=>e.set({minute:Number.parseInt(n)})),e=>R.seqMap(R.string(":"),R.regexp(/\d{2}/),(t,n)=>e.set({second:Number.parseInt(n)})),e=>R.alt(R.seqMap(R.string("."),R.regexp(/\d{3}/),(t,n)=>e.set({millisecond:Number.parseInt(n)})),R.succeed(e)),e=>R.alt(R.seqMap(R.string("+").or(R.string("-")),R.regexp(/\d{1,2}(:\d{2})?/),(t,n)=>e.setZone("UTC"+t+n,{keepLocalTime:!0})),R.seqMap(R.string("Z"),()=>e.setZone("utc",{keepLocalTime:!0})),R.seqMap(R.string("["),R.regexp(/[0-9A-Za-z+-\/]+/u),R.string("]"),(t,n,i)=>e.setZone(n,{keepLocalTime:!0})))).assert(e=>e.isValid,"valid date").desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),datePlus:r=>R.alt(r.dateShorthand.map(e=>C0[e]()),r.date).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"),durationType:r=>R.alt(...Object.keys(w0).sort((e,t)=>t.length-e.length).map(R.string)),duration:r=>R.seqMap(r.number,R.optWhitespace,r.durationType,(e,t,n)=>w0[n].mapUnits(i=>i*e)).sepBy1(R.string(",").trim(R.optWhitespace).or(R.optWhitespace)).map(e=>e.reduce((t,n)=>t.plus(n))).desc("duration like 4hr2min"),rawNull:r=>R.string("null"),tagSource:r=>r.tag.map(e=>za.tag(e)),csvSource:r=>R.seqMap(R.string("csv(").skip(R.optWhitespace),r.string,R.string(")"),(e,t,n)=>za.csv(t)),linkIncomingSource:r=>r.link.map(e=>za.link(e.path,!0)),linkOutgoingSource:r=>R.seqMap(R.string("outgoing(").skip(R.optWhitespace),r.link,R.string(")"),(e,t,n)=>za.link(t.path,!1)),folderSource:r=>r.string.map(e=>za.folder(e)),parensSource:r=>R.seqMap(R.string("("),R.optWhitespace,r.source,R.optWhitespace,R.string(")"),(e,t,n,i,o)=>n),negateSource:r=>R.seqMap(R.alt(R.string("-"),R.string("!")),r.atomSource,(e,t)=>za.negate(t)),atomSource:r=>R.alt(r.parensSource,r.negateSource,r.linkOutgoingSource,r.linkIncomingSource,r.folderSource,r.tagSource,r.csvSource),binaryOpSource:r=>Zy(r.atomSource,r.binaryBooleanOp.map(e=>e),za.binaryOp),source:r=>r.binaryOpSource,variableField:r=>r.identifier.chain(e=>E0.includes(e.toUpperCase())?R.fail("Variable fields cannot be a keyword ("+E0.join(" or ")+")"):R.succeed(Sr.variable(e))).desc("variable"),numberField:r=>r.number.map(e=>Sr.literal(e)).desc("number"),stringField:r=>r.string.map(e=>Sr.literal(e)).desc("string"),boolField:r=>r.bool.map(e=>Sr.literal(e)).desc("boolean"),dateField:r=>R.seqMap(R.string("date("),R.optWhitespace,r.datePlus,R.optWhitespace,R.string(")"),(e,t,n,i,o)=>Sr.literal(n)).desc("date"),durationField:r=>R.seqMap(R.string("dur("),R.optWhitespace,r.duration,R.optWhitespace,R.string(")"),(e,t,n,i,o)=>Sr.literal(n)).desc("duration"),nullField:r=>r.rawNull.map(e=>Sr.NULL),linkField:r=>r.link.map(e=>Sr.literal(e)),listField:r=>r.field.sepBy(R.string(",").trim(R.optWhitespace)).wrap(R.string("[").skip(R.optWhitespace),R.optWhitespace.then(R.string("]"))).map(e=>Sr.list(e)).desc("list ('[1, 2, 3]')"),objectField:r=>R.seqMap(r.identifier.or(r.string),R.string(":").trim(R.optWhitespace),r.field,(e,t,n)=>({name:e,value:n})).sepBy(R.string(",").trim(R.optWhitespace)).wrap(R.string("{").skip(R.optWhitespace),R.optWhitespace.then(R.string("}"))).map(e=>{let t={};for(let n of e)t[n.name]=n.value;return Sr.object(t)}).desc("object ('{ a: 1, b: 2 }')"),atomInlineField:r=>R.alt(r.date,r.duration.map(e=>Iz(e)),r.string,r.tag,r.embedLink,r.bool,r.number,r.rawNull),inlineFieldList:r=>r.atomInlineField.sepBy(R.string(",").trim(R.optWhitespace).lookahead(r.atomInlineField)),inlineField:r=>R.alt(R.seqMap(r.atomInlineField,R.string(",").trim(R.optWhitespace),r.inlineFieldList,(e,t,n)=>[e].concat(n)),r.atomInlineField),atomField:r=>R.alt(r.embedLink.map(e=>Sr.literal(e)),r.negatedField,r.linkField,r.listField,r.objectField,r.lambdaField,r.parensField,r.boolField,r.numberField,r.stringField,r.dateField,r.durationField,r.nullField,r.variableField),indexField:r=>R.seqMap(r.atomField,R.alt(r.dotPostfix,r.indexPostfix,r.functionPostfix).many(),(e,t)=>{let n=e;for(let i of t)switch(i.type){case"dot":n=Sr.index(n,Sr.literal(i.field));break;case"index":n=Sr.index(n,i.field);break;case"function":n=Sr.func(n,i.fields);break}return n}),negatedField:r=>R.seqMap(R.string("!"),r.indexField,(e,t)=>Sr.negate(t)).desc("negated field"),parensField:r=>R.seqMap(R.string("("),R.optWhitespace,r.field,R.optWhitespace,R.string(")"),(e,t,n,i,o)=>n),lambdaField:r=>R.seqMap(r.identifier.sepBy(R.string(",").trim(R.optWhitespace)).wrap(R.string("(").trim(R.optWhitespace),R.string(")").trim(R.optWhitespace)),R.string("=>").trim(R.optWhitespace),r.field,(e,t,n)=>({type:"lambda",arguments:e,value:n})),dotPostfix:r=>R.seqMap(R.string("."),r.identifier,(e,t)=>({type:"dot",field:t})),indexPostfix:r=>R.seqMap(R.string("["),R.optWhitespace,r.field,R.optWhitespace,R.string("]"),(e,t,n,i,o)=>({type:"index",field:n})),functionPostfix:r=>R.seqMap(R.string("("),R.optWhitespace,r.field.sepBy(R.string(",").trim(R.optWhitespace)),R.optWhitespace,R.string(")"),(e,t,n,i,o)=>({type:"function",fields:n})),binaryMulDivField:r=>Zy(r.indexField,r.binaryMulDiv,Sr.binaryOp),binaryPlusMinusField:r=>Zy(r.binaryMulDivField,r.binaryPlusMinus,Sr.binaryOp),binaryCompareField:r=>Zy(r.binaryPlusMinusField,r.binaryCompareOp,Sr.binaryOp),binaryBooleanField:r=>Zy(r.binaryCompareField,r.binaryBooleanOp,Sr.binaryOp),binaryOpField:r=>r.binaryBooleanField,field:r=>r.binaryOpField});function vre(r){try{return rS.success(Js.field.tryParse(r))}catch(e){return rS.failure(""+e)}}var oS;(function(r){function e(n,i){return{name:n,field:i}}r.named=e;function t(n,i){return{field:n,direction:i}}r.sortBy=t})(oS||(oS={}));function yre(r){return R.custom((e,t)=>(n,i)=>{let o=r._(n,i);return o.status?Object.assign({},o,{value:[o.value,n.substring(i,o.index)]}):o})}function bre(r){return r.split(/[\r\n]+/).map(e=>e.trim()).join("")}function FU(r,e){return R.eof.map(r).or(R.whitespace.then(e))}var Fz=R.createLanguage({queryType:r=>R.alt(R.regexp(/TABLE|LIST|TASK|CALENDAR/i)).map(e=>e.toLowerCase()).desc("query type ('TABLE', 'LIST', 'TASK', or 'CALENDAR')"),explicitNamedField:r=>R.seqMap(Js.field.skip(R.whitespace),R.regexp(/AS/i).skip(R.whitespace),Js.identifier.or(Js.string),(e,t,n)=>oS.named(n,e)),comment:()=>R.Parser((r,e)=>{let t=r.substring(e);if(!t.startsWith("//"))return R.makeFailure(e,"Not a comment");t=t.split(`
`)[0];let n=t.substring(2).trim();return R.makeSuccess(e+t.length,n)}),namedField:r=>R.alt(r.explicitNamedField,yre(Js.field).map(([e,t])=>oS.named(bre(t),e))),sortField:r=>R.seqMap(Js.field.skip(R.optWhitespace),R.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1),(e,t)=>{let n=t.length==0?"ascending":t[0].toLowerCase();return n=="desc"&&(n="descending"),n=="asc"&&(n="ascending"),{field:e,direction:n}}),headerClause:r=>r.queryType.chain(e=>{switch(e){case"table":return FU(()=>({type:e,fields:[],showId:!0}),R.seqMap(R.regexp(/WITHOUT\s+ID/i).skip(R.optWhitespace).atMost(1),R.sepBy(r.namedField,R.string(",").trim(R.optWhitespace)),(t,n)=>({type:e,fields:n,showId:t.length==0})));case"list":return FU(()=>({type:e,format:void 0,showId:!0}),R.seqMap(R.regexp(/WITHOUT\s+ID/i).skip(R.optWhitespace).atMost(1),Js.field.atMost(1),(t,n)=>({type:e,format:n.length==1?n[0]:void 0,showId:t.length==0})));case"task":return R.succeed({type:e});case"calendar":return R.whitespace.then(R.seqMap(r.namedField,t=>({type:e,showId:!0,field:t})));default:return R.fail(`Unrecognized query type '${e}'`)}}).desc("TABLE or LIST or TASK or CALENDAR"),fromClause:r=>R.seqMap(R.regexp(/FROM/i),R.whitespace,Js.source,(e,t,n)=>n),whereClause:r=>R.seqMap(R.regexp(/WHERE/i),R.whitespace,Js.field,(e,t,n)=>({type:"where",clause:n})).desc("WHERE <expression>"),sortByClause:r=>R.seqMap(R.regexp(/SORT/i),R.whitespace,r.sortField.sepBy1(R.string(",").trim(R.optWhitespace)),(e,t,n)=>({type:"sort",fields:n})).desc("SORT field [ASC/DESC]"),limitClause:r=>R.seqMap(R.regexp(/LIMIT/i),R.whitespace,Js.field,(e,t,n)=>({type:"limit",amount:n})).desc("LIMIT <value>"),flattenClause:r=>R.seqMap(R.regexp(/FLATTEN/i).skip(R.whitespace),r.namedField,(e,t)=>({type:"flatten",field:t})).desc("FLATTEN <value> [AS <name>]"),groupByClause:r=>R.seqMap(R.regexp(/GROUP BY/i).skip(R.whitespace),r.namedField,(e,t)=>({type:"group",field:t})).desc("GROUP BY <value> [AS <name>]"),clause:r=>R.alt(r.fromClause,r.whereClause,r.sortByClause,r.limitClause,r.groupByClause,r.flattenClause),query:r=>R.seqMap(r.headerClause.trim(r0),r.fromClause.trim(r0).atMost(1),r.clause.trim(r0).many(),(e,t,n)=>({header:e,source:t.length==0?za.folder(""):t[0],operations:n,settings:D0}))}),r0=R.alt(R.whitespace,Fz.comment).many().map(r=>r.join("")),wre=r=>r?r.plugins.plugins.dataview?.api:window.DataviewAPI,Cre=r=>r.plugins.enabledPlugins.has("dataview");Ha.DATE_SHORTHANDS=C0;Ha.DURATION_TYPES=w0;Ha.EXPRESSION=Js;Ha.KEYWORDS=E0;Ha.QUERY_LANGUAGE=Fz;Ha.getAPI=wre;Ha.isPluginEnabled=Cre;Ha.parseField=vre});function ab(r){if(!r.includes(",")){let o=r.trim();return o?[o]:[]}let e=[],t="",n=!1;for(let o=0;o<r.length;o++){let s=r[o],a=r[o+1];if(s==="["&&a==="["){n=!0,t+=s;continue}if(s==="]"&&a==="]"){n=!1,t+=s;continue}if(s===","&&!n){let l=t.trim();l&&e.push(l),t="";continue}t+=s}let i=t.trim();return i&&e.push(i),e}var F0=k(()=>{});function lb(r){return r.replace(/[\\"]/g,"\\$&")}function Ere(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $z(r){return lb(Ere(r))}function uS(r){return typeof r=="object"&&r!==null&&"path"in r&&typeof r.path=="string"}var P0,cb,Mz=k(()=>{P0=QP(Pz());De();F0();cb=class{static getDataviewAPI(e){let t=(0,P0.getAPI)(e);return t||(P.logMessage("Dataview plugin is not installed or enabled"),null)}static async getFieldValues(e,t){let n=new Set,i=this.getDataviewAPI(e);if(!i)return n;try{let s=`field("${lb(t)}")`,a=`TABLE ${s} WHERE ${s}`,l=await i.query(a);if(l.successful&&l.value.values)for(let c of l.value.values){let u=c[1];Array.isArray(u)?u.forEach(d=>{d&&typeof d=="string"?n.add(d.trim()):uS(d)?n.add(d.path):d&&typeof d!="object"&&n.add(String(d).trim())}):uS(u)?n.add(u.path):u&&typeof u=="string"?ab(u).forEach(d=>n.add(d)):u&&typeof u!="object"&&n.add(String(u).trim())}}catch(o){P.logError(new Error(`Failed to query Dataview for field ${t}: ${o}`))}return n}static async getFieldValuesWithFilter(e,t,n={}){let i=new Set,o=this.getDataviewAPI(e);if(!o)return i;try{let a=`field("${lb(t)}")`,l=[a],c=(n.folders?.length?n.folders:n.folder?[n.folder]:[]).map(v=>v.replace(/^\/+|\/+$/g,"")).filter(Boolean);if(c.length>0){let v=c.map(g=>`regexmatch("^${$z(g)}/", file.path)`);l.push(`(${v.join(" OR ")})`)}n.tags&&n.tags.length>0&&n.tags.forEach(v=>{let g=v.startsWith("#")?v:`#${v}`;l.push(`contains(file.tags, "${lb(g)}")`)}),n.excludeFolders&&n.excludeFolders.length>0&&n.excludeFolders.forEach(v=>{let g=v.replace(/^\/+|\/+$/g,"");l.push(`!regexmatch("^${$z(g)}/", file.path)`)}),n.excludeTags&&n.excludeTags.length>0&&n.excludeTags.forEach(v=>{let g=v.startsWith("#")?v:`#${v}`;l.push(`!contains(file.tags, "${lb(g)}")`)});let u=l.join(" AND "),d=`TABLE ${a} WHERE ${u}`,f=await o.query(d),p=n.excludeFiles??[],m=v=>{if(p.length===0)return!1;let g=v[0],y=g&&typeof g.path=="string"?g.path:null;if(!y)return!1;let w=y.split("/").pop()??y;return p.some(T=>T===y||T===w)};if(f.successful&&f.value.values)for(let v of f.value.values){if(m(v))continue;let g=v[1];Array.isArray(g)?g.forEach(y=>{y&&typeof y=="string"?i.add(y.trim()):uS(y)?i.add(y.path):y&&typeof y!="object"&&i.add(String(y).trim())}):uS(g)?i.add(g.path):g&&typeof g=="string"?ab(g).forEach(y=>i.add(y)):g&&typeof g!="object"&&i.add(String(g).trim())}}catch(s){P.logError(new Error(`Failed to query Dataview for field ${t} with filters: ${s}`))}return i}static isAvailable(e){return(0,P0.getAPI)(e)!==null}}});var Gl,dS=k(()=>{Gl=class r{constructor(){this.cache=new Map;this.TTL=300*1e3;this.MAX_CACHE_ENTRIES=100;this.MAX_VALUES_PER_ENTRY=1e3;this.cleanupInterval=null;this.revision=0}static getInstance(){return r.instance||(r.instance=new r),r.instance}startAutomaticCleanup(e){if(this.cleanupInterval===null&&typeof window<"u"){let t=window.setInterval(()=>{this.cleanExpired()},6e4);this.cleanupInterval=e(t)}}registerInvalidationListeners(e,t){let n=()=>this.clear();t(e.metadataCache.on("changed",n)),t(e.metadataCache.on("deleted",n)),t(e.vault.on("rename",n))}get(e,t){let n=this.makeKey(e,t),i=this.cache.get(n);return i?Date.now()-i.timestamp>this.TTL?(this.cache.delete(n),null):new Set(i.values):null}set(e,t,n){let i=this.makeKey(e,n),o=new Set,s=0;for(let a of t){if(s>=this.MAX_VALUES_PER_ENTRY)break;o.add(a),s++}this.cache.size>=this.MAX_CACHE_ENTRIES&&!this.cache.has(i)&&this.evictOldestEntries(1),this.cache.set(i,{values:o,timestamp:Date.now()})}getRevision(){return this.revision}setIfRevision(e,t,n,i){return this.revision!==i?!1:(this.set(e,t,n),!0)}evictOldestEntries(e){let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp-i.timestamp).slice(0,e);for(let[n]of t)this.cache.delete(n)}clear(e){if(this.revision++,e){let t=[];for(let n of this.cache.keys())this.keyFieldName(n)===e&&t.push(n);for(let n of t)this.cache.delete(n)}else this.cache.clear()}cleanExpired(){let e=Date.now(),t=[];for(let[n,i]of this.cache.entries())e-i.timestamp>this.TTL&&t.push(n);for(let n of t)this.cache.delete(n)}getStats(){return{size:this.cache.size,maxSize:this.MAX_CACHE_ENTRIES,cleanupInterval:this.cleanupInterval}}destroy(){this.cleanupInterval=null,this.clear()}makeKey(e,t){return JSON.stringify([e,t||null])}keyFieldName(e){try{let t=JSON.parse(e);if(Array.isArray(t)&&typeof t[0]=="string")return t[0]}catch{}}}});var Xm,Oz=k(()=>{Xm=class{static deduplicate(e,t={}){let{strategy:n="case-insensitive",preserveFirstOccurrence:i=!0,sortResult:o=!0}=t,s=e.length,a;switch(n){case"exact":a=this.deduplicateExact(e);break;case"case-sensitive":a=this.deduplicateCaseSensitive(e,i);break;default:a=this.deduplicateCaseInsensitive(e,i);break}return o&&(a=this.sortValues(a,n)),{values:a,duplicatesRemoved:s-a.length,strategy:n}}static deduplicateExact(e){return this.deduplicateWithSet(e)}static deduplicateCaseSensitive(e,t){if(t){let n=new Set;return e.filter(i=>n.has(i)?!1:(n.add(i),!0))}return this.deduplicateWithSet(e)}static deduplicateWithSet(e){return Array.from(new Set(e))}static deduplicateCaseInsensitive(e,t){let n=new Map;for(let i of e){let o=this.normalizeForComparison(i);n.has(o)&&t||n.set(o,i)}return Array.from(n.values())}static normalizeForComparison(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}static sortValues(e,t){return e.sort((n,i)=>{if(t==="case-insensitive"){let o=n.toLowerCase(),s=i.toLowerCase();return o===s?this.getCasePriority(n)-this.getCasePriority(i):o.localeCompare(s)}return n.localeCompare(i)})}static getCasePriority(e){return e===e.toUpperCase()?3:e===e.toLowerCase()?2:e[0]===e[0].toUpperCase()?1:0}static analyzeVariations(e){let t=new Map;for(let o of e){let s=this.normalizeForComparison(o);t.has(s)||t.set(s,[]);let a=t.get(s);a&&a.push(o)}let n=0,i="";for(let[o,s]of t)s.length>n&&(n=s.length,i=o);return{totalValues:e.length,uniqueValues:t.size,caseVariations:t,mostCommonCase:i}}static getSuggestions(e,t,n=.8){let i=this.normalizeForComparison(e),o=[];for(let s of t){let a=this.normalizeForComparison(s);this.calculateSimilarity(i,a)>=n&&i!==a&&o.push(s)}return o.slice(0,5)}static calculateSimilarity(e,t){if(e.length===0)return t.length===0?1:0;if(t.length===0)return 0;let n=[];for(let o=0;o<=t.length;o++)n[o]=[o];for(let o=0;o<=e.length;o++)n[0][o]=o;for(let o=1;o<=t.length;o++)for(let s=1;s<=e.length;s++)t.charAt(o-1)===e.charAt(s-1)?n[o][s]=n[o-1][s-1]:n[o][s]=Math.min(n[o-1][s-1]+1,n[o][s-1]+1,n[o-1][s]+1);let i=Math.max(e.length,t.length);return 1-n[t.length][e.length]/i}}});var ta,$0=k(()=>{Je();Oz();ta=class{static processValues(e,t){let n=e.size,i=Array.from(e).filter(c=>!this.isUnresolvedFieldToken(c)),o={strategy:t.caseSensitive?"case-sensitive":"case-insensitive",preserveFirstOccurrence:!0,sortResult:!0},s=Xm.deduplicate(i,o);i=s.values;let{processedValues:a,hasDefault:l}=this.applyDefaultValues(i,t);return i=a,{values:i,hasDefaultValue:l,duplicatesRemoved:s.duplicatesRemoved,totalProcessed:n}}static isUnresolvedFieldToken(e){return this.unresolvedFieldTokenRegex.test(e.trim())}static applyDefaultValues(e,t){if(!t.defaultValue)return{processedValues:e,hasDefault:!1};let n=t.defaultValue,i=[...e],o=!1,s=a=>t.caseSensitive?a===n:this.normalizeForComparison(a)===this.normalizeForComparison(n);return t.defaultAlways?(i=i.filter(a=>!s(a)),i.unshift(n),o=!0):t.defaultEmpty&&e.length===0?(i=[n],o=!0):!t.defaultEmpty&&!t.defaultAlways&&(i.some(s)||(i.unshift(n),o=!0)),{processedValues:i,hasDefault:o}}static promoteValueToFront(e,t,n=!1){let i=o=>n?o===t:this.normalizeForComparison(o)===this.normalizeForComparison(t);return[t,...e.filter(o=>!i(o))]}static canonicalizeAgainst(e,t,n=!1){if(n)return t;let i=this.normalizeForComparison(t);return e.find(o=>this.normalizeForComparison(o)===i)??t}static normalizeForComparison(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}static getSmartDefaults(e,t){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=e.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(t.length>0){let o=new Map;for(let s of t)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[]}static validateDefaultValue(e,t,n){let i=[],o=[];if(t.length>0){let l=Xm.analyzeVariations(t),c=e.toLowerCase();for(let[d,f]of l.caseVariations)if(d===c){f.includes(e)||(o.push(...f.slice(0,3)),i.push(`Consider using existing case: ${f[0]}`));break}let u=Xm.getSuggestions(e,t,.8);u.length>0&&(o.push(...u),i.push(`Similar existing values found: ${u.slice(0,3).join(", ")}`))}let a=this.getSmartDefaults(n,t);return a.length>0&&!a.includes(e)&&(a.map(c=>c.toLowerCase()).includes(e.toLowerCase())||(o.push(...a.slice(0,3)),i.push(`Consider common values for ${n}: ${a.slice(0,3).join(", ")}`))),{isValid:!0,suggestions:[...new Set(o)],warnings:i}}};ta.unresolvedFieldTokenRegex=new RegExp(`^${Ow.source}$`,"i")});var Yl,Zm,M0=k(()=>{F0();Yl=class Yl{static parseInlineFields(e,t){let n=new Map,i=this.removeCodeBlocksAndFrontmatter(e,t),o;for(;(o=Yl.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 ab(a))n.get(s)?.add(l)}}return Yl.INLINE_FIELD_REGEX.lastIndex=0,n}static removeCodeBlocksAndFrontmatter(e,t){return e=e.replace(this.FRONTMATTER_REGEX,""),e=this.filterFencedCodeBlocks(e,t?.includeCodeBlocks),e.replace(this.INLINE_CODE_SPAN_REGEX,"")}static filterFencedCodeBlocks(e,t){if(!e.includes("```"))return e;let n=new Set((t??[]).map(u=>u.trim().toLowerCase()).filter(u=>u.length>0)),i=e.split(`
`),o=[],s=!1,a=0,l="",c=[];for(let u of i){if(!s){let d=this.matchFenceOpen(u);d?(s=!0,a=d.length,l=d.info,c=[u]):o.push(u);continue}if(this.matchFenceClose(u,a)){let d=l.trim().split(/\s+/)[0]?.toLowerCase();if(n.size>0&&d!==void 0&&d.length>0&&n.has(d))for(let p=1;p<c.length;p++)o.push(c[p]);s=!1,c=[]}else c.push(u)}if(s)for(let u of c)o.push(u);return o.join(`
`)}static matchFenceOpen(e){let t=this.FENCE_OPEN_REGEX.exec(this.stripTrailingCarriage(e));return t?{length:t[1].length,info:t[2]}:null}static matchFenceClose(e,t){let n=this.FENCE_CLOSE_REGEX.exec(this.stripTrailingCarriage(e));return n!==null&&n[1].length>=t}static stripTrailingCarriage(e){return e.endsWith("\r")?e.slice(0,-1):e}static getFieldValues(e,t,n){return this.parseInlineFields(e,n).get(t)||new Set}};Yl.INLINE_FIELD_REGEX=/(?:^|[\n\r])(?![ \t]*[-*+][ \t]+\[[ xX]\])([^:\n\r]+?)::[ \t]*(.*)$/gmu,Yl.FRONTMATTER_REGEX=/^---\r?\n[\s\S]*?\r?\n---\r?\n/,Yl.INLINE_CODE_SPAN_REGEX=/`[^`]*`/g,Yl.FENCE_OPEN_REGEX=/^[ \t]*(`{3,})([^`]*)$/,Yl.FENCE_CLOSE_REGEX=/^[ \t]*(`{3,})[ \t]*$/;Zm=Yl});function O0(r){let e=[];return r.folder&&e.push(`folder:${r.folder}`),r.folders?.length&&e.push(`folders:${r.folders.join(",")}`),r.tags&&e.push(`tags:${r.tags.join(",")}`),r.inline&&e.push("inline:true"),r.inlineCodeBlocks?.length&&e.push(`inline-code-blocks:${r.inlineCodeBlocks.join(",")}`),r.caseSensitive&&e.push("case-sensitive:true"),r.excludeFolders&&e.push(`exclude-folders:${r.excludeFolders.join(",")}`),r.excludeTags&&e.push(`exclude-tags:${r.excludeTags.join(",")}`),r.excludeFiles&&e.push(`exclude-files:${r.excludeFiles.join(",")}`),r.defaultValue&&e.push(`default:${r.defaultValue}`),r.defaultEmpty&&e.push("default-empty:true"),r.defaultAlways&&e.push("default-always:true"),e.join("|")}async function Rz(r,e,t){let n=await Nz(r,e,t);return ta.processValues(n,t).values}async function Lz(r,e,t){let n=await Nz(r,e,t),i=ta.processValues(n,t);return{values:i.values,hasDefaultValue:i.hasDefaultValue}}async function Nz(r,e,t){let n=Gl.getInstance(),i=O0(t),o=n.get(e,i);if(o)return o;let s=n.getRevision(),a=await R0(r,e,t);return n.setIfRevision(e,a,i,s),a}async function R0(r,e,t){let n=e.trim().toLowerCase();if(n==="tags"||n==="tag"){let i=await xre(r,t);if(i.size>0)return i}try{if(!t.inline&&cb.isAvailable(r)){let i=await cb.getFieldValuesWithFilter(r,e,t);if(i.size>0)return i}}catch{}return await _re(r,e,t)}async function xre(r,e){if(!(!!e.folder||!!e.folders?.length||!!e.tags?.length||!!e.excludeFolders?.length||!!e.excludeTags?.length||!!e.excludeFiles?.length)){let n=Tre(r);if(n.size>0)return n}return await Sre(r,e)}function Tre(r){let e=new Set;try{let t=r.metadataCache.getTags?.();if(!t)return e;for(let n of Object.keys(t)){let o=(n.startsWith("#")?n.substring(1):n).trim();o&&e.add(o)}}catch{}return e}async function Sre(r,e){let t=new Set,n=r.vault.getMarkdownFiles();n=di.filterFiles(n,e,o=>r.metadataCache.getFileCache(o));let i=50;for(let o=0;o<n.length;o+=i){let a=n.slice(o,o+i).map(async c=>{let u=new Set;try{let d=r.metadataCache.getFileCache(c),f=d?.frontmatter?.tags;if(f!=null){let m=Array.isArray(f)?f:[f];for(let v of m){let g=String(v).trim();g&&u.add(g)}}let p=d?.frontmatter?.tag;if(p!=null){let m=Array.isArray(p)?p:[p];for(let v of m){let g=String(v).trim();g&&u.add(g)}}if(d?.tags)for(let m of d.tags){let v=String(m.tag??"").trim(),g=v.startsWith("#")?v.substring(1):v;g&&u.add(g)}}catch{}return u}),l=await Promise.all(a);for(let c of l)for(let u of c)t.add(u)}return t}async function _re(r,e,t){let n=new Set,i=r.vault.getMarkdownFiles();i=di.filterFiles(i,t,s=>r.metadataCache.getFileCache(s));let o=50;for(let s=0;s<i.length;s+=o){let l=i.slice(s,s+o).map(async u=>{let d=new Set;try{let p=r.metadataCache.getFileCache(u)?.frontmatter?.[e];if(p!=null){if(Array.isArray(p))p.forEach(m=>{let v=String(m).trim();v&&d.add(v)});else if(typeof p!="object"){let m=String(p).trim();m&&d.add(m)}}if(t.inline)try{let m=await r.vault.read(u);Zm.getFieldValues(m,e,{includeCodeBlocks:t.inlineCodeBlocks}).forEach(g=>{let y=String(g).trim();y&&d.add(y)})}catch{}}catch{}return d}),c=await Promise.all(l);for(let u of c)for(let d of u)n.add(d)}return n}var L0=k(()=>{Mz();ud();dS();$0();M0()});function kre(r,e){let t=e.trim();if(!t||!r)return null;let n=r[t];if(n===void 0){let i=t.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=Bz(o);s!==null&&i.push(s)}return i.length>0?i:null}return Bz(n)}function pS(r,e,t){if(!e||e.extension!=="md")return null;let n=r.metadataCache.getFileCache(e)?.frontmatter;return kre(n,t)}function Bz(r){if(r==null)return null;let e=typeof r;if(e==="string"||e==="number"||e==="boolean"){let t=String(r).trim();return t.length>0?t:null}return null}var N0=k(()=>{});function ub(r){return r.replace(Are," ").replace(/\s+/g," ").trim()}function Vz(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 qz(r){let e=[],t=!1,n="",i=0;for(let o=0;o<r.length;o++){let s=r[o];if(o===0&&/^---\s*$/.test(s)){let c=o+1;for(;c<r.length&&!/^---\s*$/.test(r[c]);)c++;o=c;continue}if(t){let c=s.match(/^ {0,3}(`{3,}|~{3,})\s*$/);c&&c[1][0]===n&&c[1].length>=i&&(t=!1,n="",i=0);continue}else{let c=s.match(/^ {0,3}(`{3,}|~{3,})/);if(c){t=!0,n=c[1][0],i=c[1].length;continue}}let a=s.match(/^ {0,3}(#{1,6})[ \t]+(.*)$/);if(a){e.push({heading:a[2],level:a[1].length,line:o});continue}let l=s.match(/^ {0,3}(=+|-+)\s*$/);if(l&&o>0){let c=r[o-1],u=e.length>0&&e[e.length-1].line===o-1,d=o<2||!Vz(r[o-2]);!u&&d&&Vz(c)&&e.push({heading:c.trim(),level:l[1][0]==="="?1:2,line:o-1});continue}}return e}function Dre(r,e){let t=[],n=ub(r[e].heading);n&&t.push(n);let i=r[e].level;for(let o=e-1;o>=0&&i>1;o--)if(r[o].level<i){i=r[o].level;let s=ub(r[o].heading);s&&t.unshift(s)}return t}function Uz(r,e){if(r.length===0)return null;let t=-1;for(let u=0;u<r.length&&r[u].line<=e;u++)t=u;if(t===-1)return null;let n=ub(r[t].heading);if(!n)return null;let i=n.toLowerCase();if(!r.some((u,d)=>d!==t&&ub(u.heading).toLowerCase()===i))return`#${n}`;let s=Dre(r,t);if(s.length<2)return null;let a=s.join("#"),l=a.toLowerCase();return Ire(r).some((u,d)=>d!==t&&u===l)?null:`#${a}`}function Ire(r){let e=new Array(r.length),t=[];for(let n=0;n<r.length;n++){for(;t.length>0&&r[t[t.length-1]].level>=r[n].level;)t.pop();let i=t.length>0?e[t[t.length-1]]:[],o=ub(r[n].heading);e[n]=o?[...i,o]:i,t.push(n)}return e.map(n=>n.join("#").toLowerCase())}var Are,zz=k(()=>{Are=/[!"#$%&()*+,.:;<=>?@^`{|}~/[\]\\\r\n]/g});function bu(r,{logPrefix:e,noticePrefix:t=e,defaultReason:n}){if(!(r instanceof Tt))return!1;let i=typeof r.message=="string"&&r.message.trim().length>0?r.message:n;return P.logMessage(`${e}: ${i}`),(!(r instanceof dt||typeof r.message=="string"&&r.message.toLowerCase().includes("cancelled by user"))||ne.getState().showInputCancellationNotification)&&new Hz.Notice(`${t}: ${i}`),!0}var Hz,db=k(()=>{Hz=require("obsidian");jo();Er();ht();De()});var Wz={};Nb(Wz,{SingleMacroEngine:()=>B0});function Pre(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 Fre,B0,jz=k(()=>{De();Tr();Dt();It();xx();Bl();pb();db();Qn();jo();Fre=new Set(["settings","entry","quickadd"]);B0=class{constructor(e,t,n,i,o){this.app=e;this.plugin=t;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(e,t){this.emittedConflictNotice=!1;let{basename:n,memberAccess:i}=cd(e),o=c=>(c??"").trim(),s=dn(this.choices).find(c=>c.type==="Macro"&&o(c.name)===o(n));if(!s){let c=d=>o(d).toLowerCase(),u=dn(this.choices).filter(d=>d.type==="Macro"&&c(d.name)===c(n));if(u.length>1)throw P.logError(`Ambiguous macro reference '${e}'. Multiple choices match when ignoring case.`),new Error(`Ambiguous macro reference '${e}'. Please disambiguate by renaming macros.`);s=u[0]}if(!s)throw P.logError(`macro '${e}' does not exist.`),new Error(`macro '${e}' does not exist.`);let a=new Wa(this.app,this.plugin,s,this.choiceExecutor,this.variables,void 0,t?.label);if(i?.length){let c=await this.tryExecuteExport(a,s,i);if(this.ensureNotAborted(),c.executed)return this.formatResult(c.result)}await a.run(),this.ensureNotAborted();let l=a.getOutput();if(i?.length){let c=this.resolveMemberAccess(l,i);c.found||P.logWarning(`Macro '${s.name}' was asked for member '${i.join("::")}', but it has no user script exporting it; the result is empty.`),l=c.value}return typeof l=="function"?l=await l():l&&typeof l=="object"&&(l=JSON.stringify(l)),Pre(l)}getVariables(){return this.variables}async tryExecuteExport(e,t,n){let i=ar(t.macro?.commands);if(!i.length)return{executed:!1};let o=i.map((c,u)=>({command:c,index:u})).filter(c=>mn(c.command)&&c.command.type==="UserScript");if(o.length===0)return{executed:!1};let s=await this.selectUserScriptCandidate(t,o,n),a=s.candidate.command.id,l=i.slice(0,s.candidate.index);try{l.length&&(await e.runSubset(l),this.ensureNotAborted());let c=t.macro?.commands,u=xy(c)?c:i,d;a!==void 0?d=u.findIndex(b=>mn(b)&&b.id===a&&b.type==="UserScript"):d=s.candidate.index;let f=d>=0?u[d]:void 0;if(!f||f.type!=="UserScript")throw new Tt(`Could not resolve the member-access script for '${t.name}'.`);let p=f;p.settings||(p.settings={});let m=s.candidate.exportsRef!==void 0?s.candidate.exportsRef:await Fs(p,this.app);if(m==null)throw new Tt(`Macro '${t.name}' could not load '${p.name}' for member access.`);let v=typeof m=="object"||typeof m=="function"?m.settings:void 0;v&&typeof v=="object"&&nm(p.settings,v);let g=s.candidate.resolvedMember??this.resolveMemberAccess(m,s.memberAccess);if(!g.found)throw new Tt(`Macro '${t.name}' routes member access to '${p.name}', but that script does not export '${s.memberAccess.join("::")}'.`);let y=u.slice(d+1),w=p.settings;typeof g.value=="function"&&(await tm(this.app,p,v&&typeof v=="object"?v:void 0)&&await this.plugin.saveSettings?.(),w=await Cx(this.app,p,v&&typeof v=="object"?v:void 0));let T=await this.executeResolvedMember(g.value,e,w);return this.ensureNotAborted(),e.setOutput(T),this.syncVariablesFromParams(e),y.length&&(await e.runSubset(y),this.ensureNotAborted()),{executed:!0,result:T}}catch(c){throw bu(c,{logPrefix:"Macro execution aborted",noticePrefix:"Macro execution aborted",defaultReason:"Macro execution aborted"})&&this.choiceExecutor.signalAbort?.(c),c}}resolveMemberAccess(e,t){let n=e;for(let i of t){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(e,t,n){return typeof e=="function"?await e(t.params,n):e}async selectUserScriptCandidate(e,t,n){if(t.length===1)return{candidate:{command:t[0].command,index:t[0].index},memberAccess:n};let i=this.resolveScriptSelector(e,t,n);if(i)return{candidate:{command:i.command,index:i.index},memberAccess:i.memberAccess};let o=[];for(let l of t){let c=await Fs(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 Tt(`Macro '${e.name}' could not find '${n.join("::")}' in any user script.`);if(Fre.has(n[0])){let l=s[0];return this.warnReservedKeyConflict(e,n,l,s),{candidate:l,memberAccess:n}}let a=s.map(l=>`'${l.command.name}'`).join(", ");throw new Tt(`Macro '${e.name}' has multiple user scripts exporting '${n.join("::")}': ${a}. Disambiguate with '{{MACRO:${e.name}::<Script Name>::${n.join("::")}}}'.`)}warnReservedKeyConflict(e,t,n,i){if(this.emittedConflictNotice)return;this.emittedConflictNotice=!0;let o=i.map(s=>`'${s.command.name}'`).join(", ");P.logWarning(`Macro '${e.name}': multiple user scripts export '${t.join("::")}' (${o}); using '${n.command.name}'. Disambiguate with '{{MACRO:${e.name}::<Script Name>::${t.join("::")}}}'.`)}resolveScriptSelector(e,t,n){if(n.length<2)return null;let i=n[0]?.trim(),o=t.filter(s=>s.command.name.trim()===i);if(o.length===0)return null;if(o.length>1)throw new Tt(`Macro '${e.name}' has multiple user scripts named '${i}'. Rename one of them before using '{{MACRO:${e.name}::${i}::${n.slice(1).join("::")}}}'.`);return{command:o[0].command,index:o[0].index,memberAccess:n.slice(1)}}syncVariablesFromParams(e){Object.keys(e.params.variables).forEach(t=>{this.choiceExecutor.variables.set(t,e.params.variables[t])})}formatResult(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return e.toString();if(typeof e=="object")try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)}ensureNotAborted(){let e=this.choiceExecutor.consumeAbortSignal?.();if(e)throw e}}});var fb,Jm,V0=k(()=>{fb=require("obsidian");Je();De();Dt();Sa();Jm=class{constructor(e){this.app=e}async createFolder(e){await this.app.vault.adapter.exists(e)||await this.app.vault.createFolder(e)}stripLeadingSlash(e){return e.replace(/^\/+/,"")}normalizeMarkdownFilePath(e,t){let n=this.stripLeadingSlash(e),i=n?`${n}/`:"",o=this.stripLeadingSlash(t).replace(Ht,"");return`${i}${o}.md`}async fileExists(e){return await this.app.vault.adapter.exists(e)}getFileByPath(e){let t=this.app.vault.getAbstractFileByPath(e);if(!t)throw P.logError(`${e} not found`),new Error(`${e} not found`);if(t instanceof fb.TFolder)throw P.logError(`${e} found but it's a folder`),new Error(`${e} found but it's a folder`);if(!(t instanceof fb.TFile))throw new Error(`${e} is not a file`);return t}async createFileWithInput(e,t,n={}){if(Pr(e))throw new Error(`Refusing to create a file outside the vault: "${e}".`);let i=e.match(/(.*)[/\\]/),o="";i&&(o=i[1]);let s=this.app.vault.getAbstractFileByPath(o);(!s||!(s instanceof fb.TFolder))&&await this.createFolder(o);let a=()=>this.app.vault.create(e,t);return n.suppressTemplaterOnCreate&&e.toLowerCase().endsWith(".md")?await Mk(this.app,e,a):await a()}}});function Mre(r){let e=[],t=[];for(let[n,i]of r){let o=U0(n,i,new Set,0);e.push(...o.warnings),t.push(...o.errors)}return{isValid:t.length===0,warnings:e,errors:t}}function U0(r,e,t,n){let i=[],o=[];if(typeof e=="function")return o.push(`Variable "${r}" contains a function, which cannot be serialized to YAML`),{warnings:i,errors:o};if(typeof e=="symbol")return o.push(`Variable "${r}" contains a symbol, which cannot be serialized to YAML`),{warnings:i,errors:o};if(typeof e=="bigint")return i.push(`Variable "${r}" contains a BigInt, which will be converted to a string`),{warnings:i,errors:o};if(e==null)return{warnings:i,errors:o};if(typeof e!="object")return{warnings:i,errors:o};if(t.has(e))return o.push(`Variable "${r}" contains a circular reference`),{warnings:i,errors:o};if(n>=q0.MAX_NESTING_DEPTH)return o.push(`Variable "${r}" exceeds maximum nesting depth of ${q0.MAX_NESTING_DEPTH}`),{warnings:i,errors:o};t.add(e);try{if(Array.isArray(e))for(let s=0;s<e.length;s++){let a=U0(`${r}[${s}]`,e[s],t,n+1);i.push(...a.warnings),o.push(...a.errors)}else for(let[s,a]of Object.entries(e)){let l=U0(`${r}.${s}`,a,t,n+1);i.push(...l.warnings),o.push(...l.errors)}}finally{t.delete(e)}return{warnings:i,errors:o}}function eh(r,e){return $re.includes(r.extension)&&e.size>0}async function th(r,e,t){let n=Mre(t);if(n.warnings.length>0)for(let i of n.warnings)P.logWarning(`Structured variable validation warning: ${i}`);if(!n.isValid){let i=n.errors.join("; ");P.logError(`Cannot post-process front matter for file ${e.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 ${q0.MAX_NESTING_DEPTH}, or contain unsupported types (functions, symbols).`);return}try{P.logMessage(`Post-processing front matter for ${e.path} with ${t.size} structured variables`),P.logMessage(`Variable types: ${Array.from(t.entries()).map(([i,o])=>`${i}:${typeof o}`).join(", ")}`),await r.fileManager.processFrontMatter(e,i=>{for(let[o,s]of t){let a=o.includes(Bs.PATH_SEPARATOR)?o.split(Bs.PATH_SEPARATOR):[o],l=eE(s);H0(i,a,l)}}),P.logMessage(`Successfully post-processed front matter for ${e.path}`)}catch(i){P.logError(`Failed to post-process front matter for file ${e.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 z0(r){return r.some((e,t)=>e==="__proto__"?!0:!(t===r.length-1)&&Ore.has(e))}function H0(r,e,t){if(e.length===0)return;if(z0(e)){P.logWarning(`Skipping front matter assignment for unsafe key path "${e.join(".")}" to avoid prototype pollution.`);return}let n=r;for(let i=0;i<e.length-1;i++){let o=e[i],s=n[o];(typeof s!="object"||s===null||Array.isArray(s))&&(n[o]={}),n=n[o]}n[e[e.length-1]]=t}var q0,$re,Ore,fS=k(()=>{De();rv();tE();q0={MAX_NESTING_DEPTH:10},$re=["md"];Ore=new Set(["prototype","constructor"])});function rh(r){return((0,W0.normalizePath)(r).split("/").pop()??"").replace(/\.(md|canvas|base)$/i,"")}function ro(r){let e=(0,W0.normalizePath)(r),t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}var W0,nh=k(()=>{W0=require("obsidian")});async function cs(r,e){try{return r.promptProvider?await e.remote(r.promptProvider):r.interactive===!1?await e.headless():await e.app()}catch(t){throw pt(t)?new dt("Input cancelled by user"):t}}var ih=k(()=>{Er();rr()});async function us(r,e){let t=e.items.map((s,a)=>`${Rre}${a}`),n=await r.suggester(e.items.map(s=>s.title),t,e.placeholder,e.allowCustomInput??!1),i=n==null?"":String(n),o=t.indexOf(i);if(o!==-1)return e.items[o].value;if(i==="")throw new dt("Input cancelled by user");if(e.allowCustomInput)return i;throw new Error(`A reply to ${e.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 Rre,oh=k(()=>{Er();Rre="\0qa-eng:"});function mb(r){let e=Id(r);if(e.length!==0)throw new ve(K1(e,r))}function Gz(r){return Id(r).length===0}var mS=k(()=>{Bi();Aa()});function hS(r){let e=r.map(n=>n||"/");return`Folder must be under: ${e.length>3?`${e.slice(0,3).join(", ")}...`:e.join(", ")}`}function j0(r){return r instanceof Tt||!!r&&typeof r=="object"&&"name"in r&&r.name==="MacroAbortError"}var sh,Lre,ja,wu,gS=k(()=>{V0();fS();ah();sh=require("obsidian");Dt();Ul();lu();Je();rr();Aa();Sa();nh();Gg();jo();Bi();ih();oh();De();mS();Lre=3,ja=class extends Error{constructor(e){super(e),this.name="InvalidFolderPathError"}};wu=class extends Jm{constructor(t,n,i,o){super(t);this.plugin=n;this.lastTemplateFileFailure=null;this.templater=Uw(t),this.formatter=new Do(t,n,i),o&&this.formatter.setTemplateInclusionState(o)}async getOrCreateFolder(t,n){let i=this.buildFolderSelectionContext(t,{...n,topItems:t.length>0?[]:n.topItems??[]});if(!this.shouldPromptForFolder(i))return await this.handleSingleSelection(i);let o=this.buildFolderSelectionContext(t,n),s=await this.promptUntilAllowed(o,n.executor);return s.isEmpty?"":s.resolved}buildFolderSelectionContext(t,n){let i=n.allowCreate??!1,o=n.allowedRoots?.map(d=>this.normalizeFolderPath(d))??[],{items:s,displayItems:a,normalizedItems:l,canonicalByNormalized:c,displayByNormalized:u}=this.buildFolderSuggestions(t,n.topItems??[],o.length>0?o:void 0);return{items:s,displayItems:a,normalizedItems:l,canonicalByNormalized:c,displayByNormalized:u,existingSet:new Set(l),allowCreate:i,allowedRoots:o,placeholder:n.placeholder}}shouldPromptForFolder(t){return t.items.length>1||t.allowCreate&&t.items.length===0}async promptForFolder(t,n){let i=t.placeholder??"Choose a folder or type to create one";return String(await cs(n,{remote:o=>us(o,{items:t.items.map((s,a)=>({value:s,title:t.displayItems[a]??s})),placeholder:i,allowCustomInput:t.allowCreate,what:"the folder chooser"}),headless:()=>{throw new ve("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?Or.Suggest(this.app,t.displayItems,t.items,{placeholder:i,renderItem:(o,s)=>{this.renderFolderSuggestion(o,s,t.existingSet,t.displayByNormalized)}}):hr.Suggest(this.app,t.displayItems,t.items,t.placeholder)}))}async resolveSelection(t,n){let i=this.normalizeFolderPath(t),o=i.length===0,s=n.canonicalByNormalized.get(i),a=s??i,l=o?!1:s!==void 0||await this.app.vault.adapter.exists(a),c=n.allowedRoots.length===0?!0:this.isPathAllowed(o?"":a,n.allowedRoots);return{raw:t,normalized:i,resolved:a,exists:l,isAllowed:c,isEmpty:o}}async promptUntilAllowed(t,n){let i=n.promptProvider?Lre:0,o=null;for(;;){if(n.promptProvider&&i--<=0)throw new ve(o??hS(t.allowedRoots));let s=await this.promptForFolder(t,n),a=await this.resolveSelection(s,t);if(a.isEmpty){if(!a.isAllowed){o=hS(t.allowedRoots),this.showFolderNotAllowedNotice(t.allowedRoots);continue}return a}if(!a.isAllowed){o=hS(t.allowedRoots),this.showFolderNotAllowedNotice(t.allowedRoots);continue}try{this.validateFolderPath(a.resolved)}catch(l){if(l instanceof ja){o=l.message,new sh.Notice(l.message);continue}throw l}return await this.ensureFolderExists(a),a}}async ensureFolderExists(t){t.isEmpty||t.exists||await this.createFolder(t.resolved)}async handleSingleSelection(t){let n=t.items[0]??"",i=await this.resolveSelection(n,t);if(i.isEmpty)return"";if(!i.isAllowed)throw this.showFolderNotAllowedNotice(t.allowedRoots),new Tt("Selected folder not allowed.");if(i.resolved)try{this.validateFolderPath(i.resolved)}catch(o){if(o instanceof ja)return new sh.Notice(o.message),"";throw o}return await this.ensureFolderExists(i),i.resolved}normalizeFolderPath(t){return t.trim().replace(/^\/+/,"").replace(/\/+$/,"")}validateFolderPath(t){let n=t.trim();if(!n)return;let i=n.split("/");for(let o of i)this.validateFolderSegment(o)}validateFolderSegment(t){if(!t)throw new ja("Folder name cannot be empty.");if(t==="."||t==="..")throw new ja("Folder name cannot be '.' or '..'.");if(Hg.test(t))throw new ja("Folder name cannot contain control characters.");if(Wg.test(t))throw new ja('Folder name cannot contain any of the following characters: \\ / : * ? " < > |');if(jg.test(t))throw new ja("Folder name cannot end with a space or a period.");let n=t.split(".")[0]??"";if(n&&xd(n))throw new ja("Folder name cannot be a reserved name like CON, PRN, AUX, NUL, COM1-9, or LPT1-9.")}isPathAllowed(t,n){let i=this.normalizeFolderPath(t);for(let o of n)if(!o||i===o||i.startsWith(`${o}/`))return!0;return!1}showFolderNotAllowedNotice(t){new sh.Notice(hS(t))}buildFolderSuggestions(t,n,i){let o=[],s=[],a=[],l=new Map,c=new Map,u=new Set,d=(f,p)=>{let m=this.normalizeFolderPath(f);u.has(m)||i&&i.length>0&&!this.isPathAllowed(m,i)||(u.add(m),o.push(f),s.push(p??f),a.push(m),l.set(m,f),p&&c.set(m,p))};for(let f of n)d(f.path,f.label);for(let f of t)d(f);return{items:o,displayItems:s,normalizedItems:a,canonicalByNormalized:l,displayByNormalized:c}}renderFolderSuggestion(t,n,i,o){n.empty(),n.classList.add("mod-complex");let s=this.normalizeFolderPath(t),a=o.get(s),l=t||"/",c=i.has(s),u="";a==="<current folder>"?u="Current folder":c||(u="Create folder"),n.createDiv("suggestion-content").createDiv("suggestion-title").createSpan({text:l}),u&&n.createDiv("suggestion-aux").createEl("kbd",{cls:"suggestion-hotkey",text:u})}stripDuplicateFolderPrefix(t,n){let i=this.stripLeadingSlash(n),o=this.stripLeadingSlash(t);return i?o.startsWith(`${i}/`)?{fileName:o.slice(i.length+1),strippedPrefix:!0}:{fileName:o,strippedPrefix:!1}:{fileName:o,strippedPrefix:!1}}shouldTreatFormattedNameAsVaultRelativePath(t,n,i){if(i||n)return!1;let o=t.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 sh.TFolder:!1}getTemplateExtension(t){return Cr.test(t)?".canvas":li.test(t)?".base":".md"}normalizeTemplateFilePath(t,n,i){let o=this.stripLeadingSlash(t),s=o?`${o}/`:"",a=this.getTemplateExtension(i),l=In(this.stripLeadingSlash(n),"File name"),c=In(l.replace(Ht,"").replace(Cr,"").replace(li,""),"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 d=`${s}${c}${a}`;if(Pr(d))throw new Error(`Refusing to build a file path outside the vault: "${d}".`);return d}noteTemplateFileFailure(t,n){this.lastTemplateFileFailure=t instanceof Error&&t.message?t.message:n}async createFileWithTemplate(t,n){this.lastTemplateFileFailure=null,mb(t);try{let i=await this.getTemplateContent(n),o=rh(t);this.formatter.setTitle(o),this.formatter.setTargetFolderPath(ro(t)),this.formatter.setPromptRunContext({destination:t,destinationKind:"file"});let s=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",i,()=>this.formatter.formatFileContent(i))),a=this.formatter.getAndClearTemplatePropertyVars();P.logMessage(`TemplateEngine.createFileWithTemplate: Collected ${a.size} template property variables for ${t}`),a.size>0&&P.logMessage(`Variables: ${Array.from(a.keys()).join(", ")}`);let l=t.toLowerCase().endsWith(".md"),c=await this.createFileWithInput(t,s,{suppressTemplaterOnCreate:l});return eh(c,a)&&await th(this.app,c,a),await td(this.app,c),c}catch(i){if(j0(i))throw i;return this.noteTemplateFileFailure(i,`Could not create file with template at ${t}`),We(i,`Could not create file with template at ${t}`),null}}setLinkToCurrentFileBehavior(t){this.formatter.setLinkToCurrentFileBehavior(t)}setTargetFolderPath(t){this.formatter.setTargetFolderPath(t)}setPromptRunContext(t){this.formatter.setPromptRunContext(t)}async resolveTemplateSourcePath(t){return this.formatter.formatTemplateFilePath(t)}async overwriteFileWithTemplate(t,n){this.lastTemplateFileFailure=null;try{let i=await this.getTemplateContent(n),o=t.basename;this.formatter.setTitle(o),this.formatter.setTargetFolderPath(ro(t.path)),this.formatter.setPromptRunContext({destination:t.path,destinationKind:"file"});let s=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",i,()=>this.formatter.formatFileContent(i))),a=this.formatter.getAndClearTemplatePropertyVars();return P.logMessage(`TemplateEngine.overwriteFileWithTemplate: Collected ${a.size} template property variables for ${t.path}`),a.size>0&&P.logMessage(`Variables: ${Array.from(a.keys()).join(", ")}`),await this.app.vault.modify(t,s),eh(t,a)&&await th(this.app,t,a),await td(this.app,t),t}catch(i){if(j0(i))throw i;return this.noteTemplateFileFailure(i,"Could not overwrite file with template"),We(i,"Could not overwrite file with template"),null}}async appendToFileWithTemplate(t,n,i){this.lastTemplateFileFailure=null;try{let o=await this.getTemplateContent(n),s=t.basename;this.formatter.setTitle(s),this.formatter.setTargetFolderPath(ro(t.path)),this.formatter.setPromptRunContext({destination:t.path,destinationKind:"file"});let a=await this.formatter.withPromptScope("noteBody",o,()=>this.formatter.formatFileContent(o));t.extension==="md"&&(a=await hl(this.app,a,t));let l=await this.app.vault.cachedRead(t),c=i==="top"?`${a}
${l}`:`${l}
${a}`;return await this.app.vault.modify(t,c),t}catch(o){if(j0(o))throw o;return this.noteTemplateFileFailure(o,"Could not append to file with template"),We(o,"Could not append to file with template"),null}}async getTemplateContent(t){let n=Mi(this.app,t);if(!n)throw new Error(`Template file not found at path "${t}".`);return await this.app.vault.cachedRead(n)}}});var Yz={};Nb(Yz,{SingleTemplateEngine:()=>hb});var hb,G0=k(()=>{gS();De();hb=class extends wu{constructor(t,n,i,o,s){super(t,n,o,s);this.templatePath=i;this.promptScope="noteBody"}setPromptScope(t){this.promptScope=t}async run(){let t=await this.resolveTemplateSourcePath(this.templatePath),n=await this.getTemplateContent(t);return n||P.logError(`Template ${t} not found.`),n=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope(this.promptScope,n,()=>this.formatter.formatFileContent(n))),n}getAndClearTemplatePropertyVars(){return this.formatter.getAndClearTemplatePropertyVars()}}});var Kz={};Nb(Kz,{SingleInlineScriptEngine:()=>Y0});var Y0,Qz=k(()=>{pb();Y0=class extends Wa{constructor(e,t,n,i){super(e,t,null,n,i)}async runAndGetOutput(e){let t=Object.getPrototypeOf(async function(){}).constructor;return await new t(e).bind(this.params,this).call()}}});var Xz,Do,ah=k(()=>{Xz=require("obsidian");Ns();lu();zq();BT();Je();Ul();Qq();eU();Dd();Lc();ud();wo();es();L0();$0();N0();wa();De();bf();ev();zz();Er();Bi();rr();Do=class extends _a{constructor(t,n,i,o){super(t);this.app=t;this.plugin=n;this.choiceExecutor=i;this.contentValuePromptsAcceptImagePaste=!1;this.dateParser=o||ns,i&&(this.variables=i?.variables)}runClocks(){return this.choiceExecutor?.clocks??this.clocks}async format(t){let n=t;return n=await this.replaceInlineJavascriptInString(n),n=await this.replaceMacrosInString(n),n=await this.replaceTemplateInString(n),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),n}async replaceGlobalVarInString(t){let n=t,i=0,o=new RegExp(ba.source,"gi");for(;o.test(n)&&!(++i>5);)n=n.replace(o,(s,a)=>{let l=String(a??"").trim();if(!l)return s;let c=this.plugin?.settings?.globalVariables?.[l];return typeof c=="string"?c:""});return n}async formatFileName(t,n="generic"){if(Wo.test(t))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,t,()=>this.format(t));if(Wo.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"}),i}async formatFileContent(t){let n=t,i=this.contentValuePromptsAcceptImagePaste;this.contentValuePromptsAcceptImagePaste=!XC(this.promptScope);try{n=await this.format(n)}finally{this.contentValuePromptsAcceptImagePaste=i}return n=this.replaceCurrentFileTokensInString(n,{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0}),n}async formatFolderPath(t){if(Wo.test(t))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",t,()=>this.format(t));if(Wo.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.");return this.replaceCurrentFileTokensInString(n,{folder:!0,activeFolder:"path"}).replace(/^\/+/,"")}async formatTemplateFilePath(t){if(Wo.test(t))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=t;if(n=await this.replaceGlobalVarInString(n),Wo.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",t,async()=>{let i=this.replaceDateInString(n);return 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),this.replaceRandomInString(i)}),n.trim()}async formatLocationString(t){let n=await this.withPromptScope("lineTarget",t,()=>this.format(t));return n=this.replaceCurrentFileTokensInString(n,{links:!0,fileName:!0,title:!0}),n}getCurrentFileLink(){let t=this.app.workspace.getActiveFile();return t?this.app.fileManager.generateMarkdownLink(t,""):null}getCurrentFileName(){let t=this.app.workspace.getActiveFile();return t?t.basename:null}getCurrentFolderPath(){let t=this.app.workspace.getActiveFile();if(!t)return null;let n=t.parent?.path??"";return n==="/"?"":n}getCurrentFileLinkToSection(){let t=this.app.workspace.getActiveFile();if(!t)return null;let n=this.getLinkSourcePath()??"",i=null;try{i=this.getActiveHeadingSubpath(t)}catch{i=null}return i?this.app.fileManager.generateMarkdownLink(t,n,i):this.app.fileManager.generateMarkdownLink(t,n)}getActiveHeadingSubpath(t){let n=this.app.workspace.getActiveViewOfType(Xz.MarkdownView);if(!n||n.file?.path!==t.path||n.getMode()==="preview")return null;let i=n.editor,o=i?.getCursor();if(!i||!o)return null;let s=qz(i.getValue().split(/\r?\n/));return Uz(s,o.line)}getVariableValue(t){return this.variables.get(t)??""}shouldUseSelectionForValue(){return!0}async getSelectedTextForValue(){return await this.getSelectedText()}assertInteractivePrompt(t){if(this.choiceExecutor?.interactive===!1)throw new ve(`This run is non-interactive but a value for ${t} was not provided up front. Pass it (e.g. a value- flag) or re-run with the ui flag.`)}describeAnonymousValuePrompt(){let t=ZC(this.promptScope,this.promptScopeSoleValue),n=t.title??(this.promptRunContext?.choiceName?.trim()||"Enter value"),i=JA(this.promptScope);return{title:n,placeholder:t.placeholder,contextLine:Jg(this.promptRunContext,n,{showDestination:i}),contextLineFull:Jg(this.promptRunContext,n,{elide:!1,showDestination:i})}}async promptForValue(t){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.valuePromptContext.description??this.describeAnonymousValuePrompt().title,!1)),this.value;try{return this.value=await hr.Suggest(this.app,["true","false"],["true","false"],this.valuePromptContext.description??this.describeAnonymousValuePrompt().title,void 0,this.valuePromptContext.optional?{skippable:!0}:void 0),this.value}catch(s){throw pt(s)?new dt("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 Vm().factory(this.valuePromptContext?.inputTypeOverride),a=this.valuePromptContext?.defaultValue,l=this.valuePromptContext?.description,c=this.buildInputPromptOptions(this.valuePromptContext,n.contextLine,n.contextLineFull),u=this.valuePromptContext?.placeholder??n.placeholder;o?this.value=await s.PromptWithContext(this.app,n.title,u,a,o,l,c):this.value=await s.Prompt(this.app,n.title,u,a,l,c)}catch(o){throw pt(o)?new dt("Input cancelled by user"):o}}return this.value}normalizeSelectedTextForPrompt(t){let n=this.valuePromptContext;if(n?.inputTypeOverride==="checkbox"){let s=t.trim().toLowerCase();return s==="true"||s==="false"?s:void 0}if(n?.inputTypeOverride!=="number"&&n?.inputTypeOverride!=="slider")return t;let i=n.sliderConfig??n.numericConfig,o=Vs(t,i);return o===""?void 0:o}buildInputPromptOptions(t,n,i){let o=this.contentValuePromptsAcceptImagePaste&&t?.inputTypeOverride!=="number"&&t?.inputTypeOverride!=="slider"?{sourcePath:this.getLinkSourcePath()??""}:void 0,s=this.promptRunContext?.draftScopeId;return{optional:t?.optional,numeric:t?.numericConfig,slider:t?.sliderConfig,imagePaste:o,contextLine:n,contextLineFull:i,draftScopeId:s,allowPeek:!0}}async promptForVariable(t,n){let i=this.choiceExecutor?.promptProvider;if(i)return n?.type==="VDATE"?await i.datePrompt(t??n.label??"Enter date",{defaultValue:n.defaultValue,dateFormat:n.dateFormat??"YYYY-MM-DD",withTime:n.withTime}):n?.inputTypeOverride==="checkbox"?String(await i.suggester(["true","false"],["true","false"],n.description??t??n.label??"Choose value",!1)):await i.inputPrompt(t??n?.label??"Enter value",n?.placeholder,n?.defaultValue);this.assertInteractivePrompt(t?`{{VALUE:${t}}}`:"a template variable");try{let o=t??n?.label??"Enter value",s=JA(this.promptScope),a=Jg(this.promptRunContext,o,{showDestination:s}),l=Jg(this.promptRunContext,o,{elide:!1,showDestination:s});return n?.type==="VDATE"?await Hl.Prompt(this.app,t??n.label??"Enter date",n.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')",n.defaultValue,n.dateFormat??"YYYY-MM-DD",{optional:n.optional,contextLine:a,contextLineFull:l,draftScopeId:this.promptRunContext?.draftScopeId},n.withTime):n?.inputTypeOverride==="checkbox"?await hr.Suggest(this.app,["true","false"],["true","false"],n.description??t??n.label??"Choose value",void 0,n.optional?{skippable:!0}:void 0):await new Vm().factory(n?.inputTypeOverride).Prompt(this.app,o,n?.placeholder??(n?.defaultValue?n.defaultValue:void 0),n?.defaultValue,n?.description,this.buildInputPromptOptions(n,a,l))}catch(o){throw pt(o)?new dt("Input cancelled by user"):o}}async promptForMathValue(){let t=this.choiceExecutor?.promptProvider;if(t)return await t.inputPrompt("Enter a math expression");this.assertInteractivePrompt("a {{MVALUE}} math expression");try{return await qT.Prompt()}catch(n){throw pt(n)?new dt("Input cancelled by user"):n}}async suggestForValue(t,n=!1,i){let o=this.choiceExecutor?.promptProvider;if(o)return String(await o.suggester(i?.displayValues??t,t,i?.placeholder,n));this.assertInteractivePrompt(i?.variableKey?`{{VALUE:${i.variableKey}}}`:"a value choice");try{let s=i?.displayValues??t;return n?await Or.Suggest(this.app,s,t,{...i?.placeholder?{placeholder:i.placeholder}:{},...i?.optional?{skippable:!0}:{}}):await hr.Suggest(this.app,s,t,i?.placeholder,void 0,i?.optional?{skippable:!0}:void 0)}catch(s){throw pt(s)?new dt("Input cancelled by user"):s}}async suggestForValueMulti(t,n=!1,i){let o=i?.displayValues??t,s=this.choiceExecutor?.promptProvider;if(s)return await s.suggesterMulti(o,t,{placeholder:i?.placeholder,allowCustomInput:n});this.assertInteractivePrompt(i?.variableKey?`{{VALUE:${i.variableKey}}}`:"a multi-select value");try{return await Vd.Suggest(this.app,o,t,{...i?.placeholder?{placeholder:i.placeholder}:{},allowCustomValue:n,...i?.optional?{skippable:!0}:{}})}catch(a){throw pt(a)?new dt("Input cancelled by user"):a}}async suggestForField(t){this.assertInteractivePrompt(`{{FIELD:${t}}}`);let n=this.choiceExecutor?.promptProvider;try{let{fieldName:i,filters:o,multiSelect:s}=hi.parse(t),a=o.defaultFrom==="active"?pS(this.app,this.choiceExecutor?.triggerContext?.activeFile??null,i):null,{values:l,hasDefaultValue:c}=await Lz(this.app,i,o),u=l,d=c,f=o.defaultValue;!s&&typeof a=="string"?(u=ta.promoteValueToFront(u,a,o.caseSensitive),f=a,d=!0):!s&&Array.isArray(a)&&a.length>0&&P.logMessage(`{{FIELD:${i}|default-from:active}}: the active note's "${i}" is a list value, which applies only to |multi FIELD prompts, so no default was prefilled.`);let p=s?`Select values for ${i}`:`Enter value for ${i}`;if(d&&f&&(p=s?`Select values for ${i} (default: ${f})`:`Enter value for ${i} (default: ${f})`),s){let m=u;if(u.length===0&&!o.defaultValue){let g=ta.getSmartDefaults(i,[]);g.length>0&&(m=g)}let v=a===null?void 0:(Array.isArray(a)?a:[a]).map(g=>ta.canonicalizeAgainst(m,g,o.caseSensitive));return n?await n.suggesterMulti(m,m,{placeholder:p,allowCustomInput:!0,preselected:v&&v.length>0?v:void 0}):await Vd.Suggest(this.app,m,m,{placeholder:p,allowCustomValue:!0,...v&&v.length>0?{preselected:v}:{}})}if(u.length===0){let m="No existing values were found in your vault.";if(!o.defaultValue){let v=ta.getSmartDefaults(i,[]);v.length>0&&(m+=`
Suggested values for ${i}: ${v.slice(0,3).join(", ")}`)}return n?await n.inputPrompt(`Enter value for ${i}`,m):await sr.PromptWithContext(this.app,`Enter value for ${i}`,m,void 0,this.getLinkSourcePath()??void 0,void 0,{allowPeek:!0})}return n?String(await n.suggester(u,u,p,!0)):await Or.Suggest(this.app,u,u,{placeholder:p})}catch(i){throw pt(i)?new dt("Input cancelled by user"):i}}generateCacheKey(t){return O0(t)}async suggestForFile(t){this.assertInteractivePrompt(`{{FILE}} (pick a file from ${t.folderPath})`);let n=this.choiceExecutor?.promptProvider;try{let i=di.filterFiles(this.app.vault.getMarkdownFiles(),t.filter,c=>this.app.metadataCache.getFileCache(c)),o=t.label??`Select a file from ${t.folderPath}`;if(i.length===0){let c=`No markdown files found in "${t.folderPath}". Type a value or leave empty.`,u=n?await n.inputPrompt(o,c):await sr.Prompt(this.app,o,c,void 0,void 0,{optional:t.optional||void 0,allowPeek:!0});return t.multiSelect?u?[`${bo}${u}`]:[]:u?`${bo}${u}`:""}let s=Sl(i,c=>this.app.metadataCache.getFileCache(c)),a=i.map(c=>`${Ta}${c.path}`);if(t.multiSelect)return(n?await n.suggesterMulti(s,a,{placeholder:o,allowCustomInput:t.allowCustomInput}):await Vd.Suggest(this.app,s,a,{placeholder:o,allowCustomValue:t.allowCustomInput,...t.optional?{skippable:!0}:{}})).map(u=>a.includes(u)?u:`${bo}${u}`);if(n){let c=String(await n.suggester(s,a,o,t.allowCustomInput));return c?a.includes(c)?c:`${bo}${c}`:""}if(t.allowCustomInput){let c=new Set(i.map(f=>f.basename.toLowerCase())),u=new Set(s.map(f=>f.toLowerCase())),d=await Or.Suggest(this.app,s,a,{placeholder:o,valueExists:f=>c.has(f.toLowerCase())||u.has(f.toLowerCase()),...t.optional?{skippable:!0}:{}});return d?a.includes(d)?d:`${bo}${d}`:""}return await hr.Suggest(this.app,s,a,o,void 0,t.optional?{skippable:!0}:void 0)??""}catch(i){throw pt(i)?new dt("Input cancelled by user"):i}}async getMacroValue(t,n){let{SingleMacroEngine:i}=await Promise.resolve().then(()=>(jz(),Wz)),o=new i(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),s=await o.runAndGetOutput(t,n)??"";return o.getVariables().forEach((a,l)=>{this.variables.set(l,a)}),s}async getTemplateContent(t){let{SingleTemplateEngine:n}=await Promise.resolve().then(()=>(G0(),Yz));this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0});let i={visited:this.templateInclusion.visited,depth:this.templateInclusion.depth+1},o=new n(this.app,this.plugin,t,this.choiceExecutor,i);o.setTargetFolderPath(this.targetFolderPath),this.promptScope!=="generic"&&o.setPromptScope(this.promptScope),this.promptRunContext&&o.setPromptRunContext({...this.promptRunContext,draftScopeId:`${this.promptRunContext.draftScopeId??""}#${t}`});let s=await o.run();return this.mergeTemplatePropertyVars(o.getAndClearTemplatePropertyVars()),s}async getSelectedText(){let t=ln(this.app);return t?t.editor.getSelection():""}async getClipboardContent(){try{return await navigator.clipboard.readText()}catch{return""}}isTemplatePropertyTypesEnabled(){return this.plugin.settings.enableTemplatePropertyTypes}async replaceInlineJavascriptInString(t){let n=t;for(;fl.test(n);){let i=fl.exec(n);if(!i)break;let o=i.at(1)?.trim();if(o){let{SingleInlineScriptEngine:s}=await Promise.resolve().then(()=>(Qz(),Kz)),a=new s(this.app,this.plugin,this.choiceExecutor,this.variables),l=await a.runAndGetOutput(o);for(let u in a.params.variables)this.variables.set(u,a.params.variables[u]);let c="";typeof l=="string"?c=l:(typeof l=="number"||typeof l=="boolean"||Array.isArray(l))&&(c=this.renderCollectedOrArrayValue({input:n,matchStart:i.index,matchEnd:i.index+i[0].length,rawValue:l,fallbackKey:"inlineScript",heuristicEnabled:this.isTemplatePropertyTypesEnabled()})??String(l)),n=this.replacer(n,fl,c)}else n=this.replacer(n,fl,"")}return n}async collectValuesManually(t,n){return await R0(this.app,t,n)}}});function Gd(r){return new TextEncoder().encode(r).length}function Nre(r){let e=0;for(let t of r){if(t.role==="tool"){for(let n of t.results)e+=Gd(n.content);continue}if(e+=Gd(t.content),t.role==="assistant"&&t.toolCalls){for(let n of t.toolCalls)if(typeof n.rawArgs=="string")e+=Gd(n.rawArgs);else if(n.args)try{e+=Gd(JSON.stringify(n.args))}catch{}}}return e}function Bre(r,e){let t;if(typeof r=="string")t=r;else if(r==null)t='{"ok":true}';else try{t=JSON.stringify(r)}catch{return{content:"tool returned a value that could not be serialized",isError:!0}}if(Gd(t)>e){let n=" \u2026[truncated]",i=Math.max(0,e-Gd(n)),o=Math.min(t.length,i);for(;o>0&&Gd(t.slice(0,o))>i;)o=Math.floor(o*.9)||o-1;t=t.slice(0,o)+n}return{content:t,isError:!1}}async function Zz(r){let e=r.maxResultBytes??32768,t=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 p=0;p<n;p++){if(p>0&&r.isOnlineDisabled?.())return u("aborted");let m=p===n-1,v=l||m,g={...r.request,messages:i,...v?{toolChoice:"none"}:{}};a+=Nre(i);let y;try{y=await r.dispatch(g,{isFinalStep:v})}catch(T){if(r.isContextOverflow?.(T))return u("context-overflow");throw T}if(c=y,s.promptTokens+=y.usage.promptTokens,s.completionTokens+=y.usage.completionTokens,s.totalTokens+=y.usage.totalTokens,y.normalizedStopReason!=="tool_calls"||y.toolCalls.length===0||v){o.push({stepNumber:p,text:y.content,toolCalls:y.toolCalls,toolResults:[],finishReason:y.rawStopReason,usage:y.usage}),await r.onStepFinish?.(o[o.length-1]);let T=y.normalizedStopReason==="length"?"length":m&&!l&&p>0?"max-steps":"stop";return u(T)}i.push({role:"assistant",content:y.content,toolCalls:y.toolCalls,providerRaw:y.providerRaw});let w=[];for(let T of y.toolCalls)w.push(await d(T));i.push({role:"tool",results:w}),o.push({stepNumber:p,text:y.content,toolCalls:y.toolCalls,toolResults:w,finishReason:y.rawStopReason,usage:y.usage}),await r.onStepFinish?.(o[o.length-1]),a>t&&(l=!0),r.shouldStop?.({steps:o})&&(l=!0)}return u("max-steps");function u(p){return{text:c?.content??"",steps:o,finishReason:p,usage:s,messages:i,finalTurn:c??{content:"",toolCalls:[],normalizedStopReason:"stop",rawStopReason:"",usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}}async function d(p){if(p.parseError)return f(p,"could not parse the tool arguments as JSON");let m=r.getTool(p.name);if(!m)return f(p,`unknown tool "${p.name}"`);let v=p.args??{},g=r.validateArgs(m,v);if(g)return f(p,`invalid arguments: ${g}`);if(!await r.confirm(p,m))return f(p,"tool call denied by user");let w;try{w=await m.execute(v,{toolCallId:p.id,toolName:p.name})}catch(E){if(r.isAbortError(E))throw E;return f(p,`tool execution failed: ${E instanceof Error?E.message:String(E)}`)}let{content:T,isError:b}=Bre(w,e);return{toolCallId:p.id,name:p.name,content:T,isError:b}}function f(p,m){return{toolCallId:p.id,name:p.name,content:m,isError:!0}}}var Jz=k(()=>{});function yS(r,e="schema"){if(r===null||typeof r!="object"||Array.isArray(r))throw new Kl(`${e} must be a JSON Schema object.`);for(let t of Object.keys(r))if(!eH.has(t))throw new Kl(`${e} uses unsupported JSON Schema keyword "${t}". QuickAdd tool schemas support only: ${[...eH].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 t=Array.isArray(r.type)?r.type:[r.type];for(let n of t)if(!Vre.has(n))throw new Kl(`${e} has invalid type "${String(n)}".`)}if(r.properties!==void 0){if(r.properties===null||typeof r.properties!="object"||Array.isArray(r.properties))throw new Kl(`${e}.properties must be an object.`);for(let[t,n]of Object.entries(r.properties))yS(n,`${e}.properties.${t}`)}if(r.required!==void 0&&(!Array.isArray(r.required)||r.required.some(t=>typeof t!="string")))throw new Kl(`${e}.required must be an array of strings.`);if(r.items!==void 0){if(Array.isArray(r.items))throw new Kl(`${e}.items as an array (tuple validation) is not supported in QuickAdd's schema subset.`);yS(r.items,`${e}.items`)}if(r.enum!==void 0&&!Array.isArray(r.enum))throw new Kl(`${e}.enum must be an array.`)}function vS(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 qre(r,e){let t=vS(r);return t===e||e==="number"&&t==="integer"}function gb(r,e,t="$"){if(e.type!==void 0){let n=Array.isArray(e.type)?e.type:[e.type];if(!n.some(i=>qre(r,i)))return`${t}: expected ${n.join(" | ")}, got ${vS(r)}`}if(Array.isArray(e.enum)&&!e.enum.some(i=>bS(i,r)))return`${t}: value is not one of the allowed enum values`;if("const"in e&&!bS(e.const,r))return`${t}: value does not equal the required const`;if(vS(r)==="object"){let n=r;if(Array.isArray(e.required)){for(let i of e.required)if(!Object.prototype.hasOwnProperty.call(n,i))return`${t}.${i}: required property is missing`}if(e.properties){for(let[i,o]of Object.entries(e.properties))if(i in n){let s=gb(n[i],o,`${t}.${i}`);if(s)return s}}}if(vS(r)==="array"&&e.items&&!Array.isArray(e.items)){let n=r;for(let i=0;i<n.length;i++){let o=gb(n[i],e.items,`${t}[${i}]`);if(o)return o}}return null}function bS(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(r===null||e===null)return r===e;if(Array.isArray(r)&&Array.isArray(e))return r.length===e.length&&r.every((t,n)=>bS(t,e[n]));if(typeof r=="object"&&typeof e=="object"){let t=Object.keys(r),n=Object.keys(e);return t.length!==n.length?!1:t.every(i=>bS(r[i],e[i]))}return!1}var eH,Vre,Kl,tH=k(()=>{eH=new Set(["type","properties","required","items","enum","const","description","title"]),Vre=new Set(["object","array","string","number","integer","boolean","null"]),Kl=class extends Error{constructor(e){super(e),this.name="ToolSchemaError"}}});function wS(r){return r.toLowerCase().startsWith(Nw)}var K0=k(()=>{Je()});function vb(r){let e=r.trim();if(!e)throw new Error("assignToVariable cannot be empty.");if(new Set(["value","title","text","meta"]).has(e.toLowerCase()))throw new Error(`assignToVariable "${e}" is reserved (it would hijack a built-in formatter token).`);if(e.toLowerCase().endsWith("-quoted"))throw new Error(`assignToVariable "${e}" cannot end with "-quoted" (collides with the quoted output variable).`);if(wS(e))throw new Error(`assignToVariable "${e}" uses the reserved "__qa." prefix for QuickAdd internal variables.`);if(/[|,]/.test(e))throw new Error(`assignToVariable "${e}" contains characters unreachable by {{VALUE:name}}.`)}var Q0=k(()=>{K0()});function Ure(r,e){if(!e||typeof e!="object")return"";let t=e,n=typeof t.path=="string"?t.path.trim():"",i=typeof t.heading=="string"?t.heading.trim():"";if(!n&&!i)return"";let o=[];return n&&o.push(`Target: ${n}`),i&&o.push(`Heading: ${i}`),o.join(" \xB7 ")}function zre(r){try{return JSON.stringify(r,null,2)??String(r)}catch{return String(r)}}function Hre(r){r.forEach(e=>{e.addEventListener("keydown",t=>{if(t.key==="ArrowRight"||t.key==="ArrowLeft"){let i=(r.indexOf(e)+(t.key==="ArrowRight"?1:-1)+r.length)%r.length;r[i].focus(),t.preventDefault()}})})}var Yd,yb,rH=k(()=>{Yd=require("obsidian"),yb=class r extends Yd.Modal{constructor(t,n,i){super(t);this.toolName=n;this.args=i;this.outcome=null;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Prompt(t,n,i){return new r(t,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 t=Ure(this.toolName,this.args);t&&this.contentEl.createEl("p",{cls:"qaAIToolSummary",text:t});let n=this.contentEl.createEl("pre",{cls:"qaAIToolArgs"});n.textContent=zre(this.args),n.setCssStyles({whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"16rem",overflowY:"auto"});let i=this.contentEl.createDiv({cls:"yesNoPromptButtonContainer"}),o=new Yd.ButtonComponent(i).setButtonText("Abort run").onClick(()=>this.submit("abort")),s=new Yd.ButtonComponent(i).setButtonText("Deny").onClick(()=>this.submit("deny")),a=new Yd.ButtonComponent(i).setButtonText("Approve all this run").onClick(()=>this.submit("allow-all")),l=new Yd.ButtonComponent(i).setButtonText("Approve").onClick(()=>this.submit("allow"));s.buttonEl.focus(),Hre([o.buttonEl,s.buttonEl,a.buttonEl,l.buttonEl])}submit(t){this.outcome=t,this.close()}onClose(){super.onClose(),this.resolvePromise(this.outcome??"deny")}}});function Gre(r){return r instanceof Tt}function Yre(r){return{content:r.content,toolCalls:r.toolCalls??[],normalizedStopReason:r.normalizedStopReason??"stop",rawStopReason:r.stopReason,usage:r.usage,providerRaw:r.providerRaw}}function Kre(r){if(r)return typeof r=="string"?r:{name:r.toolName}}function Qre(r){return{toolCallId:r.id,toolName:r.name,input:r.args}}function Xre(r){return{toolCallId:r.toolCallId,toolName:r.name,output:r.content,isError:r.isError??!1}}function iH(r,e){let t;try{t=JSON.parse(Zre(r))}catch(i){return{ok:!1,error:`not valid JSON (${i instanceof Error?i.message:String(i)})`}}let n=gb(t,e);return n?{ok:!1,error:n}:{ok:!0,value:t}}function Zre(r){let e=r.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);return t?t[1]:e}var nH,Wre,jre,X0,CS,oH=k(()=>{ht();ah();OF();Bi();jo();om();Nd();Ry();DF();$F();Jz();tH();Q0();rH();nH=/^[a-zA-Z0-9_-]{1,64}$/,Wre=20,jre=100,X0=new WeakSet;CS=class{constructor(e,t,n,i){this.app=e;this.plugin=t;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(!nH.test(s))throw new Error(`Invalid tool name "${s}". Tool names must match ${nH}.`);if(o.has(s))throw new Error(`Duplicate tool name "${s}".`);o.add(s),yS(a.inputSchema,`tool "${s}".inputSchema`)}}async generate(e={}){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 t=typeof e.assignToVariable=="string"&&e.assignToVariable.length>0;if(t&&(this.assertAssignableName(e.assignToVariable),X0.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,t&&X0.add(this.choiceExecutor);let n=MT(this.app);try{return await this.run(e,n)}finally{this.running=!1,t&&X0.delete(this.choiceExecutor);try{n()}catch{}}}async run(e,t){this.approveAllThisRun=!1;let n=ne.getState();if(n.disableOnlineFeatures)throw new Error("Rejecting AI request: Online features are disabled in settings.");let{model:i,provider:o}=im(this.config.model),s=await Gs(this.app,o),a=await this.buildSeedMessages(e),l=this.buildToolDefinitions(),c=this.buildRegistry(),u=e.schema?{schema:e.schema,name:"response",strict:!0}:void 0,d={messages:a,...l.length>0?{tools:l}:{},toolChoice:Kre(e.toolChoice??this.config.toolChoice)??"auto",maxOutputTokens:e.maxOutputTokens??this.config.maxOutputTokens,modelParams:this.config.modelOptions},f=Math.max(1,Math.min(this.config.maxSteps??Wre,jre)),p=Om(n.ai.showAssistant);p.setMessage("starting","QuickAdd is running the AI agent.");try{let m=await Zz({request:d,maxSteps:f,dispatch:async(g,y)=>{let w=this.buildTurnRequest(g,y.isFinalStep,u),T=await PF(this.app,s,i,o,w,t);return Yre(T)},getTool:g=>c.get(g),confirm:(g,y)=>this.confirm(g,y),validateArgs:(g,y)=>gb(y,g.definition.parameters),isAbortError:Gre,isContextOverflow:g=>Oy(g)==="input_context",isOnlineDisabled:()=>ne.getState().disableOnlineFeatures,shouldStop:this.buildShouldStop(),onStepFinish:g=>this.reportStep(p,g)}),v=this.toGenerateResult(m);return e.schema&&(v.object=await this.resolveStructuredObject(m,d,i,o,s,e.schema,t)),typeof e.assignToVariable=="string"&&e.assignToVariable&&this.assignVariable(e.assignToVariable,v.text),p.setMessage("finished",`Ran ${v.steps.length} step${v.steps.length===1?"":"s"}.`),window.setTimeout(()=>p.hide(),5e3),v}catch(m){throw p.setMessage("dead",m?.message??""),window.setTimeout(()=>p.hide(),5e3),m}}reportStep(e,t){let n=t.toolCalls.map(o=>o.name),i=n.length>0?`Step ${t.stepNumber+1}: running ${n.join(", ")}.`:`Step ${t.stepNumber+1}: generating a response.`;e.setMessage("thinking",i)}async buildSeedMessages(e){let t=[],n=e.system??this.config.system??ne.getState().ai.defaultSystemPrompt;n&&n.trim().length>0&&t.push({role:"system",content:n});let i=e.prompt??"",o=i?await new Do(this.app,this.plugin,this.choiceExecutor).formatFileContent(i):"";return t.push({role:"user",content:o}),t}buildToolDefinitions(){return Object.entries(this.config.tools??{}).map(([e,t])=>({name:e,description:t.description,parameters:t.inputSchema,...t.strict?{strict:!0}:{}}))}buildRegistry(){let e=new Map;for(let[t,n]of Object.entries(this.config.tools??{}))e.set(t,{definition:{name:t,description:n.description,parameters:n.inputSchema,strict:n.strict},execute:(i,o)=>n.execute(i,o),readOnly:n.readOnly});return e}buildShouldStop(){let e=this.config.stopWhen?Array.isArray(this.config.stopWhen)?this.config.stopWhen:[this.config.stopWhen]:[];if(e.length!==0)return({steps:t})=>{let n=t.flatMap(i=>i.toolCalls.map(o=>o.name));return e.some(i=>i({stepNumber:t.length,toolCallNames:n}))}}buildTurnRequest(e,t,n){return!!(e.tools&&e.tools.length>0)&&!t?{...e,responseFormat:void 0}:{...e,tools:void 0,toolChoice:t?"none":e.toolChoice,responseFormat:n}}async confirm(e,t){let n=e.args??{},i=await this.resolvePerToolApproval(t,n);if(!(i||this.needsGlobalConfirmation(t))||this.approveAllThisRun&&!i)return!0;if(this.choiceExecutor.interactive===!1)throw new ve(`'${e.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 yb.Prompt(this.app,e.name,e.args??{});if(s==="abort")throw new Tt("AI tool run aborted by user");return s==="allow-all"?(this.approveAllThisRun=!0,!0):s==="allow"}async resolvePerToolApproval(e,t){let i=this.config.tools?.[e.definition.name]?.needsApproval;return typeof i=="function"?await i({args:t}):i===!0}needsGlobalConfirmation(e){let t=ne.getState().ai.confirmToolCalls??"destructive";return t==="always"?!0:t==="destructive"?e.readOnly!==!0:!1}async resolveStructuredObject(e,t,n,i,o,s,a){let l=iH(e.finalTurn.content,s);if(l.ok)return l.value;if(e.finishReason==="aborted"||e.finishReason==="context-overflow"||ne.getState().disableOnlineFeatures)return;let c=[...e.messages,{role:"assistant",content:e.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.`}],u={...t,messages:c,tools:void 0,toolChoice:"none",responseFormat:{schema:s,name:"response",strict:!0}};try{let d=await PF(this.app,o,n,i,u,a),f=iH(d.content,s);return f.ok?f.value:void 0}catch{return}}toGenerateResult(e){let t=e.steps.map(i=>({stepNumber:i.stepNumber,text:i.text,toolCalls:i.toolCalls.map(Qre),toolResults:i.toolResults.map(Xre),finishReason:i.finishReason})),n=t[t.length-1];return{text:e.text,steps:t,toolCalls:n?.toolCalls??[],toolResults:n?.toolResults??[],usage:{inputTokens:e.usage.promptTokens,outputTokens:e.usage.completionTokens,totalTokens:e.usage.totalTokens},finishReason:e.finishReason}}assignVariable(e,t){let n=e.trim(),i=("> "+t).replace(/\n/g,`
> `);this.choiceExecutor.variables.set(n,t),this.choiceExecutor.variables.set(`${n}-quoted`,i)}assertAssignableName(e){vb(e)}}});function Z0(r){let e=(0,aH.getFrontMatterInfo)(r);return e.exists?e.contentStart:0}function ene(r,e){let t=Z0(r);if(t===0)return 0;if(sH.test(e))return t;let n=sH.exec(r.slice(t));return n?t+n[0].length:t}function J0(r,e){if(e.length===0)return{content:r,insertedStartOffset:null,insertedEndOffset:null};let t=ene(r,e),n=r.slice(0,t),i=r.slice(t),o=n.length>0&&!n.endsWith(`
`)&&!Jre.test(e)?`
`:"",s=i.length>0&&!e.endsWith(`
`)?`
`:"",a=n.length+o.length,l=a+e.length;return{content:`${n}${o}${e}${s}${i}`,insertedStartOffset:a,insertedEndOffset:l}}function ES(r,e){return J0(r,e).content}var aH,sH,Jre,bb=k(()=>{aH=require("obsidian"),sH=/^[^\S\r\n]*\r?\n/,Jre=/^\r?\n/});function eP(r){return(r??"").trim().replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"").normalize("NFC")}function tP(r,e){return e.some(t=>r===t||r.startsWith(`${t}/`))}function Kd(r,e){let t=(e??[]).map(n=>eP(n)).filter(n=>n.length>0);return t.length===0?!0:r?tP(r.normalize("NFC"),t):!1}var xS=k(()=>{});function Qd(r,e={}){let t=(r??"").trim();if(!t)throw new ds("Path is empty.");let n=t.replace(/\\/g,"/").normalize("NFC");if(n.startsWith("/")||/^[a-zA-Z]:/.test(n))throw new ds(`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 ds("Path is empty after normalization.");for(let a of o){if(a==="."||a==="..")throw new ds(`Refusing path with a traversal segment ("${a}"): "${i}".`);if(a.startsWith("."))throw new ds(`Refusing to write into a dot/config path segment ("${a}"): "${i}".`);tne(a,i)}let s=(e.allowedRoots??[]).map(a=>eP(a)).filter(a=>a.length>0);if(s.length>0&&!tP(i,s))throw new ds(`Path "${i}" is not under an allowed root (${s.join(", ")}).`);return i}function tne(r,e){if(Hg.test(r))throw new ds(`Path segment "${r}" contains control characters: "${e}".`);if(Wg.test(r))throw new ds(`Path segment "${r}" contains an illegal character (\\ : * ? " < > |): "${e}".`);if(jg.test(r))throw new ds(`Path segment "${r}" cannot end with a space or a period: "${e}".`);let t=r.split(".")[0]??"";if(t&&xd(t))throw new ds(`Path segment "${r}" is a reserved device name: "${e}".`)}var ds,lH=k(()=>{Gg();xS();ds=class extends Error{constructor(e){super(e),this.name="UnsafeVaultPathError"}}});function lh(r,e){let t=Object.entries(r),n=new Set(t.map(([o])=>o));if(cH(e.only,n,"only"),cH(e.exclude,n,"exclude"),e.only){let o=new Set(e.only);t=t.filter(([s])=>o.has(s))}if(e.exclude){let o=new Set(e.exclude);t=t.filter(([s])=>!o.has(s))}let i=e.prefix??"";return Object.fromEntries(t.map(([o,s])=>[i+o,s]))}function wb(r){return{...r,__qaTool:!0}}function cH(r,e,t){if(!r)return;let n=r.filter(i=>!e.has(i));n.length!==0&&P.logWarning(`AI tools: ${t} listed unknown tool name(s) ${n.map(i=>`"${i}"`).join(", ")}. Valid names: ${[...e].join(", ")}.`)}var TS=k(()=>{De()});function gH(r,e={}){let t=e.allowedRoots,n={read_note:Xd({description:"Read a note's full markdown content by vault path.",inputSchema:Zd({path:ps("Vault path to the note, e.g. Notes/Foo.md")},["path"]),readOnly:!0,execute:async({path:i})=>{let o=Qd(String(i),{allowedRoots:t}),s=r.vault.getAbstractFileByPath(o);if(!(s instanceof nP.TFile))return{found:!1,path:o};let a=await r.vault.cachedRead(s);return{found:!0,path:o,content:a.length>uH?a.slice(0,uH)+`
\u2026[truncated]`:a}}}),list_notes:Xd({description:"List markdown notes, optionally within a folder.",inputSchema:Zd({folder:ps("Folder to list (omit for the whole vault)."),limit:dH("Max results (default 100, capped at 200).")},[]),readOnly:!0,execute:async({folder:i,limit:o})=>{let s=i?Qd(String(i),{allowedRoots:t}):"",a=mH(fH(o,rne),1,nne),l=ho(r,s).filter(c=>Kd(c.path,t));return{total:l.length,notes:l.slice(0,a).map(c=>({path:c.path,basename:c.basename}))}}}),search_notes:Xd({description:"Search notes by name and/or content. Returns matching paths with a short snippet.",inputSchema:Zd({query:ps("Text to search for."),in:pH(["name","content","both"],"Where to search (default both)."),limit:dH("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=mH(fH(s,ine),1,one),u=r.vault.getMarkdownFiles().filter(m=>Kd(m.path,t)),d=[],f=0,p=!1;for(let m of u){if(d.length>=c)break;if(l!=="content"&&m.basename.toLowerCase().includes(a)){d.push({path:m.path});continue}if(l!=="name"){if(f>=sne){p=!0;continue}f++;let g=await r.vault.cachedRead(m),y=g.toLowerCase().indexOf(a);y>=0&&d.push({path:m.path,snippet:lne(g,y)})}}return{results:d,scannedFiles:f,truncated:d.length>=c||p}}}),get_property_values:Xd({description:"List the distinct values a frontmatter property takes across the vault (e.g. existing tags or statuses).",inputSchema:Zd({field:ps("Frontmatter property name."),folder:ps("Optional folder scope.")},["field"]),readOnly:!0,execute:async({field:i,folder:o})=>{let s=o?Qd(String(o),{allowedRoots:t}):"",a=(o?ho(r,s):r.vault.getMarkdownFiles()).filter(c=>Kd(c.path,t)),l=new Set;for(let c of a){let d=r.metadataCache.getFileCache(c)?.frontmatter?.[String(i)];if(d!=null){for(let f of Array.isArray(d)?d:[d])if(typeof f!="object"){let p=String(f).trim();p&&l.add(p)}}}return{field:String(i),values:[...l].sort().slice(0,200)}}}),create_note:Xd({description:"Create a new markdown note. Fails if the path already exists.",inputSchema:Zd({path:ps("Vault path for the new note."),content:ps("Initial markdown content.")},["path"]),needsApproval:!0,execute:async({path:i,content:o})=>{let s=Qd(rP(String(i)),{allowedRoots:t});return await Im(r,s),await ane(r,s),{created:!0,path:(await r.vault.create(s,String(o??""))).path}}}),append_to_note:Xd({description:"Append text to an existing note (frontmatter-aware for top inserts).",inputSchema:Zd({path:ps("Vault path to the existing note."),content:ps("Markdown to append."),position:pH(["top","bottom"],"Where to add it (default bottom).")},["path","content"]),needsApproval:!0,execute:async({path:i,content:o,position:s})=>{let a=Qd(rP(String(i)),{allowedRoots:t}),l=hH(r,a);await Im(r,a);let c=await r.vault.read(l),u=String(o),d=s==="top"?ES(c,u.endsWith(`
`)?u:u+`
`):`${c}${c.endsWith(`
`)||c.length===0?"":`
`}${u}`;return await r.vault.modify(l,d),{appended:!0,path:a}}}),insert_under_heading:Xd({description:"Insert markdown under an existing heading (matched exactly). Errors if the heading is not found.",inputSchema:Zd({path:ps("Vault path to the existing note."),heading:ps("Exact heading text (without the # markers)."),content:ps("Markdown to insert under the heading.")},["path","heading","content"]),needsApproval:!0,execute:async({path:i,heading:o,content:s})=>{let a=Qd(rP(String(i)),{allowedRoots:t}),l=hH(r,a);await Im(r,a);let c=r.metadataCache.getFileCache(l)?.headings??[],u=c.find(p=>p.heading===String(o));if(!u)throw new Error(`Heading "${o}" not found in ${a}`);let d=await r.vault.read(l),f=cne(d,u.position.start.line,u.level,String(s),c);return await r.vault.modify(l,f),{inserted:!0,path:a,heading:String(o)}}})};return lh(n,e)}function Xd(r){return{...r,__qaTool:!0}}function Zd(r,e){return{type:"object",properties:r,required:e}}function ps(r){return{type:"string",description:r}}function dH(r){return{type:"integer",description:r}}function pH(r,e){return{type:"string",enum:r,description:e}}function fH(r,e){let t=Number(r);return Number.isFinite(t)?Math.floor(t):e}function mH(r,e,t){return Math.max(e,Math.min(t,r))}function rP(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 hH(r,e){let t=r.vault.getAbstractFileByPath(e);if(!(t instanceof nP.TFile))throw new Error(`Note not found: ${e}`);return t}async function ane(r,e){let t=e.lastIndexOf("/");if(t<=0)return;let n=e.slice(0,t);if(!r.vault.getAbstractFileByPath(n))try{await r.vault.createFolder(n)}catch{}}function lne(r,e){let t=Math.max(0,e-40);return r.slice(t,e+80).replace(/\s+/g," ").trim()}function cne(r,e,t,n,i){let o=r.split(`
`),s=o.length;for(let u of i)if(u.position.start.line>e&&u.level<=t){s=u.position.start.line;break}let a=n.endsWith(`
`)?n:n+`
`,l=o.slice(0,s),c=o.slice(s);for(;l.length>e+1&&l[l.length-1].trim()==="";)l.pop();return[...l,a.replace(/\n$/,""),...c].join(`
`)}var nP,uH,rne,nne,ine,one,sne,vH=k(()=>{nP=require("obsidian");Dt();bb();xS();lH();aF();TS();uH=16e3,rne=100,nne=200,ine=25,one=50,sne=400});function bH(r,e={}){let t=e.allowedRoots,n=()=>{let s=r.workspace.getActiveFile();return!(s instanceof SS.TFile)||s.extension!=="md"?null:Kd(s.path,t)?s:null},i=()=>{let s=r.workspace.getActiveViewOfType(SS.MarkdownView);return s&&Kd(s.file?.path,t)?s:null},o={get_active_note:wb({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>yH?a.slice(0,yH)+`
\u2026[truncated]`:a}}}}),get_selection:wb({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 lh(o,e)}var SS,yH,wH=k(()=>{SS=require("obsidian");xS();TS();yH=16e3});function CH(r={}){let e={get_date:wb({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:t,offset:n})=>({date:Ko({format:t!=null?String(t):void 0,offset:n!=null?Number(n):void 0})})})};return lh(e,r)}var EH=k(()=>{Dt();TS()});var Cb,ch,xH=k(()=>{Cb=require("obsidian");Er();VF();ch=class r extends Cb.Modal{constructor(t,n,i=[],o){super(t);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(t,n,i,o){return new r(t,n,i,o).promise}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(Ir())}addSearchableOptions(){this.picker=new Bd(this.contentEl,{items:this.items.map(t=>({key:t,value:t,label:t})),isSelected:({value:t})=>this._selectedItems.includes(t),onToggle:({value:t},n)=>{if(n){this._selectedItems.includes(t)||this._selectedItems.push(t);return}this._selectedItems=this._selectedItems.filter(i=>i!==t)},getSelectedCount:()=>new Set(this._selectedItems).size})}addSubmitButton(){let t=this.contentEl.createDiv("submitButtonContainer");new Cb.ButtonComponent(t).setButtonText("Submit").setCta().onClick(()=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()}),new Cb.ButtonComponent(t).setButtonText("Cancel").onClick(()=>{this.close()})}}});var _S,Eb,TH=k(()=>{_S=require("obsidian"),Eb=class r extends _S.Modal{constructor(t,n,i){super(t);this.header=n;this.text=i;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Show(t,n,i){return new r(t,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 t=this.contentEl.createDiv(),n=new _S.ButtonComponent(t).setButtonText("OK").onClick(()=>this.close());Object.assign(t.style,{display:"flex",justifyContent:"flex-end"}),n.buttonEl.focus()}onClose(){super.onClose(),this.resolvePromise()}}});var kS,SH=k(()=>{Lc();L0();Ca();kS=class extends Hr{constructor(e,t,n){super(e,t),this.fieldInput=n;let i=hi.parse(n);this.fieldName=i.fieldName,this.filters=i.filters}async getSuggestions(e){let t=await Rz(this.app,this.fieldName,this.filters),n=(e||"").toLowerCase();return n?t.filter(i=>i.toLowerCase().includes(n)).slice(0,200):t.slice(0,200)}renderSuggestion(e,t){this.renderMatch(t,e,this.getCurrentQuery())}selectSuggestion(e){this.inputEl.value=e;let t=new Event("input",{bubbles:!0});t.fromCompletion=!0,this.inputEl.dispatchEvent(t),this.close()}}});var _H,iP,AS,kH=k(()=>{_H=require("obsidian");Ca();iP=200,AS=class extends Hr{constructor(t,n,i,o,s,a,l){super(t,n);this.getOptions=i;this.isSelected=o;this.onSelect=s;this.multiSelect=a;this.allowCustomInput=l;a&&n.setAttribute("aria-multiselectable","true")}getSuggestions(t){let n=t.trim(),i=this.getOptions().filter(u=>!this.isSelected(u.value));if(!n)return i.slice(0,iP);let o=(0,_H.prepareFuzzySearch)(n),s=i.map(u=>({option:u,match:o(`${u.label} ${u.path}`)})).filter(u=>u.match!==null).sort((u,d)=>d.match.score-u.match.score).slice(0,iP).map(({option:u})=>u);if(!this.allowCustomInput)return s;let a=n.toLocaleLowerCase(),l=this.getOptions().some(u=>u.label.toLocaleLowerCase()===a||u.path.toLocaleLowerCase()===a),c=this.isSelected(n);return l||c?s:[{value:n,label:`Use \u201C${n}\u201D`,path:"Custom value",isCustom:!0},...s].slice(0,iP)}renderSuggestion(t,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"});t.isCustom?o.setText(t.label):this.renderMatch(o,t.label,this.getCurrentQuery().trim()),i.createDiv({cls:"qa-onepage-file-suggestion__path",text:t.path})}selectSuggestion(t){if(this.onSelect(t),this.inputEl.value="",!this.multiSelect){this.close();return}let n=new Event("input",{bubbles:!0});n.fromCompletion=!0,n.keepOpen=!0,this.inputEl.dispatchEvent(n),this.inputEl.focus()}}});var DS,AH=k(()=>{Ca();Qi();DS=class extends Hr{constructor(e,t,n,i=!1,o=!1,s){super(e,t),this.options=n.map(a=>zr(a)),this.caseSensitive=i,this.multiSelect=o,this.onSelect=s,this.multiSelect&&this.inputEl.setAttribute("aria-multiselectable","true")}parseMultiSelectInput(e){if(!this.multiSelect)return{alreadySelected:[],activeTerm:e};let t=e.split(",").map(n=>n.trim());return{alreadySelected:t.slice(0,-1).filter(Boolean),activeTerm:t[t.length-1]||""}}getRemainingOptions(e){return this.options.filter(t=>!e.includes(t))}getSuggestions(e){let t=xl(e),{alreadySelected:n,activeTerm:i}=this.parseMultiSelectInput(t),o=this.caseSensitive?i:i.toLowerCase(),s=this.getRemainingOptions(n);return o?s.filter(a=>(this.caseSensitive?a:a.toLowerCase()).includes(o)).slice(0,200):s.slice(0,200)}renderSuggestion(e,t){this.renderMatch(t,e,this.getCurrentQuery())}selectSuggestion(e){this.multiSelect?this.selectMultipleItem(e):this.selectSingleItem(e)}selectSingleItem(e){this.inputEl.value=e;let t=new Event("input",{bubbles:!0});t.fromCompletion=!0,this.inputEl.dispatchEvent(t),this.close()}selectMultipleItem(e){let{alreadySelected:t}=this.parseMultiSelectInput(this.inputEl.value);t.push(e),this.onSelect?.(e);let n=this.getRemainingOptions(t).length>0;this.inputEl.value=n?t.join(", ")+", ":t.join(", "),this.inputEl.setSelectionRange(this.inputEl.value.length,this.inputEl.value.length);let i=new Event("input",{bubbles:!0}),o=i;o.fromCompletion=!0,n?(o.keepOpen=!0,this.inputEl.dispatchEvent(i),this.inputEl.focus()):(this.inputEl.dispatchEvent(i),this.close())}}});function DH(r,e,t){return t?e.get(r)??r:r}function IH(r,e){return e.length===0?r:r===""?e[0]??"":e.includes(r)?r:e[0]??""}var FH=k(()=>{});function une(r){let e=[];for(let t of r){let n=e.at(-1);n&&n.group?.id===t.group?.id?n.fields.push(t):e.push({group:t.group,fields:[t]})}return e}function dne(r){let e=new Set;for(let t of r)t.group&&e.add(t.group.id);return e.size>=2}var Et,uh,oP=k(()=>{Et=require("obsidian");Je();zF();GC();YC();df();SH();kH();AC();AH();IC();Rm();Ku();ht();Kg();FH();es();Er();wo();uh=class extends Et.Modal{constructor(t,n,i,o){super(t);this.result=new Map;this.multiSelections=new Map;this.fileSelections=new Map;this.dateParseErrors=new Set;this.previewContainerEl=null;this.previewToken=0;this.settled=!1;this.imagePasteHandles=[];this.freeTextFields=[];this.filePickerSuggesters=[];this.requirements=n,this.initialValues=new Map,this.computePreview=o,i?.forEach((s,a)=>{typeof s=="string"&&this.initialValues.set(a,s)}),this.updatePreviewDebounced=(0,Et.debounce)(this.updatePreviews.bind(this),150,!0),this.peek=new Vc({app:t,title:"Provide inputs",containerEl:this.containerEl,scope:this.scope,getField:()=>this.insertTarget()?.el,getValue:()=>this.insertTarget()?.el.value??"",setValue:s=>{let a=this.insertTarget();a&&(this.result.set(a.id,s),this.updatePreviewDebounced())},persistDraft:()=>{},markDraftChanged:()=>{let s=this.insertTarget();s&&(this.result.set(s.id,s.el.value),this.updatePreviewDebounced())},close:()=>this.close()}),this.waitForClose=new Promise((s,a)=>{this.resolvePromise=s,this.rejectPromise=a}),this.display(),this.open()}display(){if(this.containerEl.addClass("quickAddModal","onePageInputModal"),pf(this.containerEl),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")),dne(this.requirements))for(let s of une(this.requirements)){s.group&&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.computePreview&&this.updatePreviews();let n=this.contentEl.createDiv({cls:"qa-prompt-actions"}),i=n.createDiv({cls:"qa-prompt-actions-primary"});new Et.ButtonComponent(i).setButtonText("Submit").setCta().onClick(()=>this.submit()),new Et.ButtonComponent(i).setButtonText("Cancel").onClick(()=>this.cancel());let o=n.createDiv({cls:"qa-prompt-actions-secondary"});ff(new Et.ButtonComponent(o).setButtonText("Peek at note").onClick(()=>this.peek.peek()))}onOpen(){this.peek.onHostOpened(),this.contentEl.querySelector("input, textarea, select")?.focus();let n=this.scope;typeof n?.register=="function"&&(n.register(["Mod"],"Enter",()=>(this.submit(),!1)),n.register(["Mod","Shift"],Qg,()=>(this.peek.peek(),!1)))}renderField(t){let n=(o,s)=>{this.result.set(o,s),this.updatePreviewDebounced()},i=this.initialValues.get(t.id)??t.defaultValue??"";switch(t.type){case"textarea":{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));t.description&&o.setDesc(t.description);let s=new Et.TextAreaComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(a=>n(t.id,a)),s.inputEl.addClass("qa-onepage-textarea"),this.enableImagePaste(t,s.inputEl),this.attachFreeTextBehaviors(t.id,s.inputEl,o);break}case"text":{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));t.description&&o.setDesc(t.description);let s=new Et.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(a=>n(t.id,a)),this.enableImagePaste(t,s.inputEl),this.attachFreeTextBehaviors(t.id,s.inputEl,o);break}case"number":{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));t.description&&o.setDesc(t.description);let s=new Et.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?Vs(i,t.numericConfig):i;s.setPlaceholder(t.placeholder??"").setValue(a).onChange(l=>n(t.id,t.numericConfig?Vs(l,t.numericConfig):l)),n(t.id,a);break}case"slider":{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));o.controlEl.parentElement?.addClass("qa-onepage-slider-setting"),t.description&&o.setDesc(t.description);let s=t.sliderConfig??{min:0,max:100,step:1},a=t.optional&&i==="",l=lv(i,s),c=o.controlEl.createDiv({cls:"qa-onepage-slider"}),u=c.createEl("input");u.type="range",u.min=String(s.min),u.max=String(s.max),u.step=String(s.step),u.value=l;let d=new Et.TextComponent(c);d.inputEl.type="number",d.inputEl.inputMode="decimal",d.inputEl.min=String(s.min),d.inputEl.max=String(s.max),d.inputEl.step=String(s.step),d.setValue(a?"":l),n(t.id,a?"":l),u.addEventListener("input",()=>{d.inputEl.value=u.value,n(t.id,u.value)}),d.onChange(f=>{if(f===""&&t.optional){n(t.id,"");return}let p=Vs(f,s);p!==""&&(u.value=p,d.inputEl.value=p,n(t.id,p))});break}case"dropdown":{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));t.description&&o.setDesc(t.description);let s=new Et.DropdownComponent(o.controlEl),a=t.options??[],l=t.displayOptions??a;if(a.length>0){t.optional&&s.addOption("","Skip (leave empty)"),a.forEach((u,d)=>{let f=l[d]??u;s.addOption(u,f)});let c=IH(i,a);s.setValue(c),n(t.id,c),s.onChange(u=>n(t.id,u))}else s.setDisabled(!0),o.controlEl.createDiv({text:t.placeholder||"No options available"}).addClass("qa-onepage-dropdown-note");break}case"date":{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));o.settingEl.addClass("qa-onepage-date-setting"),t.description&&o.setDesc(t.description);let s=o.controlEl.createDiv({cls:"qa-date-input"}),a=new Et.TextComponent(s),l="Enter a date (e.g., 'today', 'next friday', '2025-12-25')",c,u=i;i?.startsWith("@date:")&&(c=i.slice(6),u=(t.dateFormat?qa(c,t.dateFormat):void 0)??(c.length>=10?c.slice(0,10):c)),a.setPlaceholder(l).setValue(u??"");let d=s.createDiv();d.addClass("qa-date-preview-text");let f=s.createDiv({cls:"qa-date-picker-container"}),p=NT({container:f,initialIso:c,withTime:t.withTime===!0,onSelect:E=>{E?w(E):T()}}),m=cg(ne.getState().dateAliases);if(m.length>0){let E=s.createEl("details");E.addClass("qa-date-alias-details"),E.createEl("summary",{text:`Aliases (${m.length})`}).addClass("qa-date-alias-summary");let _=E.createEl("div");_.textContent=Pw(ne.getState().dateAliases),_.addClass("qa-date-alias-list")}let v=E=>{if(t.dateFormat){let C=qa(E,t.dateFormat);if(C)return C}return E.length>=10?E.slice(0,10):E},g=(E,C)=>{d.setText(E),d.toggleClass("is-error",C)},y=E=>{p.setSelectedIso(E)},w=E=>{c=E,this.dateParseErrors.delete(t.id);let C=v(E);a.inputEl.value=C,n(t.id,`@date:${E}`),g(C,!1),y(E)},T=()=>{a.inputEl.value="",b("")},b=E=>{let C=(E??"").trim();if(!C&&t.defaultValue&&!t.optional){let I=zl(t.defaultValue,t.dateFormat);if(I.isValid&&I.isoString){c=I.isoString,this.dateParseErrors.delete(t.id),n(t.id,`@date:${I.isoString}`),y(I.isoString);let q=I.formatted??v(I.isoString);g(q,!1);return}g(I.error||"Unable to parse date",!0),this.dateParseErrors.add(t.id),n(t.id,""),y();return}if(!C){c=void 0,this.dateParseErrors.delete(t.id),n(t.id,""),y(),g(t.optional?"Will be left empty":"Preview will appear here",!1);return}if(C.startsWith("@date:")){let I=C.slice(6).trim();if(I){this.dateParseErrors.delete(t.id),w(I);return}}let _=zl(C,t.dateFormat);if(_.isValid&&_.isoString){c=_.isoString,this.dateParseErrors.delete(t.id),n(t.id,`@date:${_.isoString}`),y(_.isoString);let I=_.formatted??v(_.isoString);g(I,!1)}else c=void 0,this.dateParseErrors.add(t.id),n(t.id,""),y(),g(_.error||"Unable to parse date",!0)};a.onChange(E=>b(E)),c?w(c):b(u??"");break}case"field-suggest":{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));t.description&&o.setDesc(t.description);let s=new Et.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(l=>n(t.id,l));let a=t.id.startsWith(Zu)?t.id.slice(Zu.length):t.id;try{new kS(this.app,s.inputEl,a)}catch{}break}case"suggester":{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));t.description&&o.setDesc(t.description);let s=t.options??[],a=t.displayOptions??s,l=new Map,c=new Map;s.forEach((f,p)=>{let m=a[p]??f;l.set(m,f),c.has(f)||c.set(f,m)});let u=c.get(i)??i,d=new Et.TextComponent(o.controlEl);if(d.setPlaceholder(t.placeholder??"Type to search...").setValue(u).onChange(f=>n(t.id,f)),d.inputEl.addEventListener("input",f=>{let p=!!f.fromCompletion,m=d.inputEl.value,v=DH(m,l,p);(v!==m||p)&&n(t.id,v)}),a.length>0)try{let f=t.suggesterConfig?.caseSensitive??!1,p=t.suggesterConfig?.multiSelect??!1;new DS(this.app,d.inputEl,a,f,p,p?m=>{let v=this.multiSelections.get(t.id)??[];v.push(m),this.multiSelections.set(t.id,v)}:void 0)}catch{}break}case"file-picker":{this.renderFilePickerField(t,i,n);break}default:{let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t)),s=new Et.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(a=>n(t.id,a)),this.enableImagePaste(t,s.inputEl),this.attachFreeTextBehaviors(t.id,s.inputEl,o)}}this.result.has(t.id)||this.result.set(t.id,i)}renderFilePickerField(t,n,i){let o=new Et.Setting(this.contentEl).setName(this.decorateLabel(t));o.settingEl.addClass("qa-onepage-file-picker-setting"),t.description&&o.setDesc(t.description);let s=t.options??[],a=t.displayOptions??s,l=s.map((E,C)=>{let _=Ed(E);return{value:E,label:a[C]??E,path:_.kind==="file"?_.path:E}}),c=new Map(l.map(E=>[E.value,E])),u=t.suggesterConfig?.multiSelect??!1,d=t.suggesterConfig?.allowCustomInput??!1,f=new Set,p=new Map,m=E=>{let C=p.get(E);if(C)return C;let _={value:E,label:E,path:"Custom value",isCustom:!0};return p.set(E,_),_};if(n&&c.has(n))f.add(n);else if(n&&d){let E=Ed(n),C=E.kind==="custom"?E.text:n;m(C),f.add(C)}else!u&&l.length>0&&f.add(l[0].value);let v=o.controlEl.createDiv({cls:"qa-onepage-file-picker"}),g=v.createDiv({cls:"qa-onepage-file-picker__selection"});g.setAttribute("aria-live","polite");let y=new Et.TextComponent(v);y.inputEl.addClass("qa-onepage-file-picker__input"),y.setPlaceholder(t.placeholder??(u?"Search and add files...":"Search files...")),y.inputEl.setAttribute("aria-label",u?`Add files for ${t.label}`:`Choose file for ${t.label}`);let w=()=>{let E=l.filter(C=>f.has(C.value));for(let C of p.values())f.has(C.value)&&E.push(C);return E},T=()=>{let E=w(),C=E.map(_=>_.value);this.fileSelections.set(t.id,C),i(t.id,u?C.join(", "):C[0]??""),g.empty(),g.toggleClass("qa-hidden",E.length===0);for(let _ of E){let I=g.createDiv({cls:"qa-onepage-file-picker__chip"});I.setAttribute("title",_.path),I.createSpan({cls:"qa-onepage-file-picker__chip-label",text:_.label});let q=I.createEl("button",{cls:"qa-onepage-file-picker__remove",text:"\xD7"});q.type="button",q.setAttribute("aria-label",`Remove ${_.label}`),q.addEventListener("click",()=>{f.delete(_.value),T(),y.inputEl.focus()})}},b=E=>{let C=E.isCustom?m(E.value):E;u||f.clear(),f.add(C.value),T()};y.inputEl.addEventListener("keydown",E=>{if(E.key==="Backspace"&&y.inputEl.value===""&&f.size>0){let C=w().at(-1);if(!C)return;E.preventDefault(),f.delete(C.value),T()}});try{let E=new AS(this.app,y.inputEl,()=>[...l,...p.values()],C=>f.has(C),b,u,d);this.filePickerSuggesters.push(E)}catch{y.setDisabled(!0)}T()}attachFreeTextBehaviors(t,n,i){i.nameEl.id||(i.nameEl.id=`qa-onepage-label-${t}`),n.setAttribute("aria-labelledby",i.nameEl.id);let o={id:t,el:n,fileSuggester:new Oc(this.app,n),tagSuggester:new Rc(this.app,n,{refreshIndex:this.freeTextFields.length===0})};this.freeTextFields.push(o),n.addEventListener("focus",()=>{this.lastFocusedFreeText=o})}insertTarget(){return this.lastFocusedFreeText??this.freeTextFields[0]}enableImagePaste(t,n){t.pathContext||this.imagePasteHandles.push(uf(this.app,n,{}))}decorateLabel(t){if(!t.optional)return t.label;let n=this.contentEl.ownerDocument,i=n.createDocumentFragment();i.appendChild(n.createTextNode(t.label));let o=n.createElement("span");return o.textContent=" (optional)",o.className="qa-onepage-optional-badge",i.appendChild(o),i}submit(){if(this.settled)return;let t=this.imagePasteHandles.find(o=>o.isBusy());if(t){t.whenIdle().then(()=>this.submit());return}let n={},i=this.requirements.find(o=>o.type==="date"&&!o.optional&&this.dateParseErrors.has(o.id));if(i){new Et.Notice(`QuickAdd: "${i.label}" is not a valid date. Fix it or clear it before submitting.`);return}for(let[o,s]of this.multiSelections){let a=(this.result.get(o)??"").replace(/,\s*$/,"").trim();s.join(", ")!==a&&this.multiSelections.delete(o)}Object.assign(n,this.collectAnswers()),this.settled=!0,this.close(),this.resolvePromise(n)}collectAnswers(){let t=new Map(this.requirements.map(i=>[i.id,i])),n={};return this.result.forEach((i,o)=>{let s=t.get(o);if(s?.type==="date"&&i===""){let a=this.dateParseErrors.has(o);if(!s.optional||a)return}n[o]=i}),n}collectPreviewAnswers(){let t=this.collectAnswers(),n=new Map(this.requirements.map(i=>[i.id,i]));for(let[i,o]of this.fileSelections)t[i]=n.get(i)?.suggesterConfig?.multiSelect?[...o]:o[0]??"";return t}cancel(){this.settled=!0,this.close(),this.rejectPromise(Ir())}onClose(){this.peek.onHostClosed();for(let t of this.imagePasteHandles)t.detach();this.imagePasteHandles.length=0;for(let t of this.freeTextFields)t.fileSuggester.destroy(),t.tagSuggester.destroy();this.freeTextFields.length=0,this.lastFocusedFreeText=void 0;for(let t of this.filePickerSuggesters)t.destroy();this.filePickerSuggesters.length=0,this.settled||(this.settled=!0,this.rejectPromise(Ir()))}async updatePreviews(){if(!this.computePreview||!this.previewContainerEl)return;let t=++this.previewToken;try{let n=await this.computePreview(this.collectPreviewAnswers());if(t!==this.previewToken||!this.previewContainerEl)return;this.previewContainerEl.empty(),this.previewContainerEl.toggleClass("qa-hidden",n.length===0);for(let i of n){let o=i.diagnostics.filter(u=>u.severity==="error"),a=o.some(u=>u.kind!=="path")?"Unresolved":o.length>0?"Won't be created":i.label,l=this.previewContainerEl.createDiv({cls:"qa-onepage-preview-row"});l.createEl("div",{text:`${a}:`,cls:"qa-preview-key"}),l.createEl("div",{text:i.text,cls:"qa-preview-val"}).setAttribute("title",i.text);for(let u of i.diagnostics){let d=this.previewContainerEl.createDiv({cls:"qa-preview-issue"});d.toggleClass("qa-preview-issue--error",u.severity==="error"),d.createSpan({cls:"qa-visually-hidden",text:u.severity==="error"?"Error: ":"Warning: "}),d.appendText(u.message),d.setAttribute("title",u.message)}}}catch{}}}});function pne(r,e,t){return window.moment(r).add(e,t).startOf("day").toDate()}function xb(r){if(r instanceof Date&&!Number.isNaN(r.getTime()))return r;if(typeof r!="string")return;let e=r.trim();if(!e)return;if(e.toLowerCase().startsWith("@date:")){let n=e.slice(6),i=window.moment(n);return i.isValid()?i.toDate():void 0}let t=zl(e,void 0,ns);if(t.isValid&&t.isoString){let n=window.moment(t.isoString);return n.isValid()?n.toDate():void 0}}function IS(r){if(r.clocks?.date)return{status:"inherit"};if(r.reservedSeed!==void 0){let o=xb(r.reservedSeed);return o?{status:"set",date:o}:{status:"error",message:"Could not parse the seeded date origin."}}let e=r.setting;if(!e||e.kind==="now")return{status:"inherit"};if(e.kind==="ask")return{status:"ask",defaultValue:e.defaultValue};if(e.kind==="relative"){let o=r.clocks?.now??new Date;return{status:"set",date:pne(o,e.offset,e.unit)}}let t=r.variables;if(!t)return{status:"error",message:`Date origin variable "${e.name}" is not available.`};let n=qc(t,e.name);if(!n)return{status:"error",message:`Date origin variable "${e.name}" is not set.`};let i=xb(t.get(n));return i?{status:"set",date:i}:{status:"error",message:`Date origin variable "${e.name}" is not a date.`}}function dh(r,e){if(e==null||typeof e=="string"&&!e.trim())return!0;if(i2(e))return r.pickDate=!0,!0;let t=xb(e);return t?(r.clocks={now:r.clocks?.now??new Date,date:t},!0):!1}var ph=k(()=>{Dd();Jc();Rm();es()});var FS,PH=k(()=>{rC();FS=class{static filterFiles(e,t,n){return Object.keys(t).length===0?e:e.filter(i=>{let o=this.getIncludeFolders(t);return!(o.length>0&&!o.some(s=>this.matchesFolder(i,s))||t.tags&&t.tags.length>0&&!this.matchesTags(i,t.tags,n))})}static getIncludeFolders(e){let t=e.folders?.length?e.folders:e.folder?[e.folder]:[];return[...new Set(t.map(n=>this.normalizePath(n)).filter(Boolean))]}static matchesFolder(e,t){let n=this.normalizePath(t),i=this.normalizePath(e.path);return i.startsWith(n+"/")||i.substring(0,i.lastIndexOf("/"))===n}static matchesTags(e,t,n){let i=n(e);if(!i)return!1;let o=this.getAllTags(i);return t.map(yl).filter(Boolean).every(a=>o.some(l=>l===a||l.startsWith(a+"/")))}static getAllTags(e){let t=[];return e.frontmatter?.tags&&t.push(...Tc(e.frontmatter.tags)),e.frontmatter?.tag&&t.push(...Tc(e.frontmatter.tag)),e.tags&&t.push(...e.tags.map(n=>yl(n.tag))),t.filter(Boolean)}static normalizePath(e){return e.replace(/^\/+|\/+$/g,"")}}});function RH(r){return Tb.some(e=>e.id===r)}function $H(r){let e=(0,PS.getFrontMatterInfo)(r);return e.exists?{frontmatterYaml:e.frontmatter,body:r.slice(e.contentStart)}:{frontmatterYaml:null,body:r}}function fne(r,e,t){return t==="bottom"?`${r}
${e}`:ES(r,`${e}
`)}function mne(r){return r==null||r===""||Array.isArray(r)&&r.length===0}function MH(r){return typeof r=="string"?r.length>0?[r]:[]:!Array.isArray(r)||!r.every(e=>typeof e=="string")?null:r}function OH(r,e){let t=MH(r),n=MH(e);if(t===null||n===null)return;let i=[],o=new Set(t);for(let s of n)s.length===0||o.has(s)||(o.add(s),i.push(s));if(i.length!==0)return[...t,...i]}var PS,Tb,fh,$S=k(()=>{PS=require("obsidian");De();Dt();fS();zy();tE();rv();nh();bb();gS();Aa();JC();Tb=[{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."}];fh=class extends wu{constructor(t,n,i,o,s,a,l){super(t,n,a);this.targetFile=i;this.templatePath=o;this.mode=s;this.resolvedTemplatePath=l??null}async run(){await this.apply()}async getResolvedTemplatePath(){return this.resolvedTemplatePath===null&&(this.resolvedTemplatePath=await this.resolveTemplateSourcePath(this.templatePath)),this.resolvedTemplatePath}async apply(){switch(Jn(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(t){let n=t.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(t.fileNameFormat?.enabled&&t.fileNameFormat.format){this.formatter.setTargetFolderPath(i);let a=await this.formatter.formatFileName(t.fileNameFormat.format,"generic"),l=In(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(t){let{formatted:n,templatePropertyVars:i}=await this.formatTemplateForTargetFile(),{frontmatterYaml:o,body:s}=$H(n);return s.trim().length>0&&await this.app.vault.process(this.targetFile,a=>fne(a,s,t)),await this.mergeFrontmatterProperties(o,i),this.targetFile}async insertTemplateAtCursor(){let t=wg(this.app,this.targetFile);Jn(t,"Cannot insert at cursor: the note is not open in the active editor.");let{formatted:n,templatePropertyVars:i}=await this.formatTemplateForTargetFile(),{frontmatterYaml:o,body:s}=$H(n);return s.trim().length>0&&t.editor.replaceSelection(s),await this.mergeFrontmatterProperties(o,i),this.targetFile}async formatTemplateForTargetFile(){let t=await this.getTemplateContent(await this.getResolvedTemplatePath());this.formatter.setTitle(this.targetFile.basename),this.formatter.setTargetFolderPath(ro(this.targetFile.path));let n=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",t,()=>this.formatter.formatFileContent(t))),i=this.formatter.getAndClearTemplatePropertyVars();return this.targetFile.extension==="md"&&(n=await hl(this.app,n,this.targetFile)),{formatted:n,templatePropertyVars:i}}async mergeFrontmatterProperties(t,n){if(!t||this.targetFile.extension!=="md")return;let i;try{i=(0,PS.parseYaml)(t)}catch(o){P.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(Bs.PATH_SEPARATOR)?o.split(Bs.PATH_SEPARATOR):[o];H0(i,a,eE(s))}await this.app.fileManager.processFrontMatter(this.targetFile,o=>{for(let[s,a]of Object.entries(i)){if(z0([s])){P.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=eN(this.app,s);if(mne(l)){c&&Array.isArray(a)?o[s]=OH([],a)??[]:o[s]=a;continue}if(c){let u=OH(l,a);u!==void 0&&(o[s]=u)}}})}}}});function hne(r){return r.trim().length===0}function hh(r){return!Cr.test(r)&&!li.test(r)}function gne(r){return r.kind==="choice"?`Choice: ${r.choice.name}`:`Template: ${r.path}`}function LH(r){let e=r.replace(/^\/+/,"").toLowerCase();return/\.(md|canvas|base)$/.test(e)?e:`${e}.md`}function vne(r,e){let t=dn(r).filter(o=>o.type==="Template"&&!!o.templatePath&&hh(o.templatePath)),n=new Set(t.map(o=>LH(o.templatePath))),i=t.map(o=>({kind:"choice",choice:o}));for(let o of e)hh(o)&&(n.has(LH(o))||i.push({kind:"file",path:o}));return i}async function Sb(r,e,t){let n=t.file??r.workspace.getActiveFile();if(!n||n.extension!=="md")return new mh.Notice("QuickAdd: No active markdown note to apply a template to."),null;let i=t.choiceExecutor.triggerContext;i==null&&(t.choiceExecutor.triggerContext={activeFile:n});try{let o=!t.templatePath,s;if(t.templatePath)s={kind:"file",path:t.templatePath};else{let m=await yne(r,e);if(!m)return null;s=m}let a=s.kind==="choice"?s.choice.templatePath:s.path;if(!hh(a))return new mh.Notice("QuickAdd: Only markdown templates can be applied to a note. Canvas and base templates create their own file types."),null;let l=await r.vault.cachedRead(n),c=hne(l),u;if(t.mode)u=t.mode;else if(c)u="replace";else if(!o)u="bottom";else{let m=await bne(r,n);if(!m)return null;u=m}t.choiceExecutor.variables.has("value")||t.choiceExecutor.variables.set("value",n.basename);let d=new fh(r,e,n,a,u,t.choiceExecutor);d.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 f=await d.getResolvedTemplatePath();return hh(f)?await d.apply()?(o&&s.kind==="choice"&&(d.setPromptRunContext({destination:void 0,destinationKind:void 0}),await wne(r,d,s.choice,n)),await Ec(r,n),new mh.Notice(`Applied template to '${n.basename}'.`),n):null:(new mh.Notice("QuickAdd: Only markdown templates can be applied to a note. Canvas and base templates create their own file types."),null)}catch(o){return pt(o)||NH(o)||We(o,"Error applying template to note"),null}finally{t.choiceExecutor.triggerContext=i}}function NH(r){return!!r&&typeof r=="object"&&r.name==="MacroAbortError"}async function yne(r,e){let t=vne(e.settings.choices,e.getTemplateFiles().map(n=>n.path));if(t.length===0)return new mh.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 hr.Suggest(r,t.map(gne),t,"Apply template to note")}catch(n){if(pt(n))return null;throw n}}async function bne(r,e){let t=!!wg(r,e),n=Tb.filter(i=>i.id!=="cursor"||t);try{return await hr.Suggest(r,n.map(i=>i.label),n.map(i=>i.id),"How should the template be applied?")}catch(i){if(pt(i))return null;throw i}}async function wne(r,e,t,n){try{let i=await e.computeChoiceTargetPath(t);if(!i||i===n.path||await r.vault.adapter.exists(i)||!Gz(i)||!await vi.Prompt(r,"Move note to match choice settings?",`'${t.name}' creates notes at '${i}'. Move '${n.path}' there? Links to the note will be updated.`))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(pt(i)||NH(i))return;P.logWarning(`Could not move note to match choice settings: ${i}`)}}var mh,sP=k(()=>{mh=require("obsidian");Je();Ul();Pd();De();Dt();It();mS();rr();$S()});function VH(r){return Array.from(r.entries())}function qH(r,e){r.clear();for(let[t,n]of e)r.set(t,n)}function Cne(r){if(!r||typeof r!="object")return;let e={};return typeof r.min=="number"&&Number.isFinite(r.min)&&(e.min=r.min),typeof r.max=="number"&&Number.isFinite(r.max)&&(e.max=r.max),e.min!==void 0&&e.max!==void 0&&e.max<e.min&&(delete e.min,delete e.max),typeof r.step=="number"&&Number.isFinite(r.step)&&r.step>0&&(e.step=r.step),Object.keys(e).length>0?e:void 0}function Ene(r){if(!r||typeof r!="object")return;let{min:e,max:t}=r,n=r.step??1;if(!(typeof e!="number"||typeof t!="number"||typeof n!="number"||!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)||t<=e||n<=0))return{min:e,max:t,step:n}}function Ql(r){throw r instanceof Tt?r:pt(r)?new dt(wc):r}var BH,gh,aP=k(()=>{wa();RT();ky();om();Nd();oH();vH();wH();EH();Q0();ah();xH();TH();Ns();Ul();HF();Pd();lu();BT();Qi();oP();ht();De();Dt();ph();rr();dS();PH();M0();jo();Er();Rm();sP();$S();BH=!1;gh=class r{static GetApi(e,t,n){return{requestInputs:async i=>{let o={},s=[];for(let u of i){let d=n.variables.get(u.id);if(d!=null){o[u.id]=String(d);continue}let f=Ene(u.sliderConfig),p=f??Cne(u.numericConfig),m=u.type==="slider"&&!f?"number":u.type;s.push({id:u.id,label:u.label??u.id,type:m,placeholder:u.placeholder,defaultValue:u.defaultValue,numericConfig:p,sliderConfig:f,options:u.options,dateFormat:u.dateFormat,description:u.description,optional:u.optional,suggesterConfig:u.suggesterConfig,source:"script"})}let a={};if(s.length>0){let u=n?.promptProvider;if(u)try{let d=await u.requestInputs(s);a=Object.fromEntries(Object.entries(d).map(([f,p])=>[f,Array.isArray(p)?p.join(", "):p]))}catch(d){Ql(d)}else{let d=new uh(e,s,n.variables);try{a=await d.waitForClose}catch(f){Ql(f)}}}let l={...o,...a};for(let u of i)l[u.id]===void 0&&(l[u.id]="");Object.entries(l).forEach(([u,d])=>n.variables.set(u,d));let c={};for(let u of i){let d=l[u.id];if(d===void 0)continue;let f=d;if(u.type==="date"&&u.dateFormat&&typeof d=="string"&&d.startsWith("@date:")){let p=d.slice(6),m=qa(p,u.dateFormat);m&&(f=m)}c[u.id]=f}return c},inputPrompt:(i,o,s,a)=>{let l=n?.promptProvider;return l?l.inputPrompt(i,o,s):r.inputPrompt(e,i,o,s,a)},datePrompt:(i,o)=>{let s=n?.promptProvider;return s?s.datePrompt(i,o):r.datePrompt(e,i,o)},wideInputPrompt:(i,o,s,a)=>{let l=n?.promptProvider;return l?l.wideInputPrompt(i,o,s):r.wideInputPrompt(e,i,o,s,a)},yesNoPrompt:(i,o)=>{let s=n?.promptProvider;return s?s.yesNoPrompt(i,o):r.yesNoPrompt(e,i,o)},infoDialog:(i,o)=>{let s=n?.promptProvider;return s?s.infoDialog(i,o):r.infoDialog(e,i,o)},suggester:(i,o,s,a=!1,l)=>{let c=n?.promptProvider;return c?c.suggester(i,o,s,a):r.suggester(e,i,o,s,a,l)},checkboxPrompt:(i,o,s)=>{let a=n?.promptProvider;return a?a.checkboxPrompt(i,o,s):r.checkboxPrompt(e,i,o,s)},executeChoice:async(i,o,s)=>{let a;try{a=t.getChoiceByName(i)}catch{a=void 0}if(!a){We(new Error(`Choice named '${i}' not found`),"API executeChoice error");return}if(!dh(n,s?.date)){We(new Error(`Could not parse date origin '${String(s?.date)}'`),"API executeChoice error");return}o&&Object.keys(o).forEach(c=>{n.variables.set(c,o[c])}),await n.execute(a);let l=n.consumeAbortSignal?.();if(n.variables.clear(),l)throw l},applyTemplateToActiveFile:async(i,o)=>{if(!i)throw new Error("applyTemplateToActiveFile requires a template path.");if(!hh(i))throw new Error("applyTemplateToActiveFile only supports markdown templates. Canvas and base templates cannot be applied to a markdown note.");if(o?.mode!==void 0&&!RH(o.mode))throw new Error(`Invalid mode '${String(o.mode)}'. Valid modes: ${Tb.map(a=>a.id).join(", ")}.`);let s=VH(n.variables);try{return await Sb(e,t,{templatePath:i,mode:o?.mode,choiceExecutor:n})}finally{qH(n.variables,s)}},format:async(i,o,s=!0)=>{let a=s?VH(n.variables):null;o&&Object.keys(o).forEach(c=>{n.variables.set(c,o[c])});let l=await new Do(e,t,n).formatFileContent(i);return s&&a&&qH(n.variables,a),l},ai:{prompt:async(i,o,s)=>{let a=ne.getState(),l=a.ai;if(a.disableOnlineFeatures)throw new Error("Rejecting request to `prompt` via API AI module. Online features are disabled in settings.");let c=r.GetApi(e,t,n).format,{model:u,provider:d}=im(o),f=await Gs(e,d);s?.assignToVariable&&vb(s.assignToVariable);let p=await Lq(e,{model:u,provider:d,prompt:i,apiKey:f,modelOptions:s?.modelOptions??{},outputVariableName:s?.assignToVariable||s?.variableName||"output",showAssistantMessages:s?.showAssistantMessages??!0,systemPrompt:s?.systemPrompt??l.defaultSystemPrompt},(m,v)=>c(m,v,!1));return p?((s?.shouldAssignVariables||s?.assignToVariable)&&Object.entries(p).forEach(([m,v])=>{n.variables.set(m,v)}),p):(We(new Error("AI Assistant returned null"),"AI Prompt error"),{})},chunkedPrompt:async(i,o,s,a,l)=>{let c=ne.getState(),u=c.ai;if(c.disableOnlineFeatures)throw new Error("Rejecting request to `prompt` via API AI module. Online features are disabled in settings.");let d=r.GetApi(e,t,n).format,{model:f,provider:p}=im(s),m=await Gs(e,p);a?.assignToVariable&&vb(a.assignToVariable);let v=await qq(e,{model:f,provider:p,text:i,promptTemplate:o,chunkSeparator:a?.chunkSeparator??/\n/,apiKey:m,modelOptions:a?.modelOptions??{},outputVariableName:a?.assignToVariable||a?.variableName||"output",showAssistantMessages:a?.showAssistantMessages??!0,systemPrompt:a?.systemPrompt??u.defaultSystemPrompt,resultJoiner:a?.chunkJoiner??`
`,shouldMerge:a?.shouldMerge??!0,maxChunkTokens:a?.maxChunkTokens},(g,y)=>{let w={...l,...y};return d(g,w,!1)});return v?((a?.shouldAssignVariables||a?.assignToVariable)&&Object.entries(v).forEach(([g,y])=>{n.variables.set(g,y)}),v):(We(new Error("AI Assistant returned null"),"Chunked AI Prompt error"),{})},getModels:()=>PB(),getMaxTokens:i=>im(i).model.maxTokens,estimateTokens(i){return Ji(i)},countTokens(i,o){return BH||(BH=!0,P.logMessage("quickAddApi.ai.countTokens is deprecated and now returns a provider-agnostic estimate (the model argument is ignored). Use estimateTokens(text) instead.")),Ji(i)},getRequestLogs(i=10){return Fq(i)},getRequestLogById(i){return $q(i)},getLastRequestLog(){return Mq()},clearRequestLogs(){Oq()},agent:i=>new CS(e,t,n,i),tool:i=>({...i,__qaTool:!0}),stepCountIs:i=>({stepNumber:o})=>o>=i,hasToolCall:i=>({toolCallNames:o})=>o.includes(i),tools:{vault:i=>gH(e,i),workspace:i=>bH(e,i),system:i=>CH(i)}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async i=>await navigator.clipboard.writeText(i),getSelection:()=>rd(e),getSelectedText:()=>{let i=ln(e);return i?i.editor.somethingSelected()?i.editor.getSelection():(We(new Error("No text selected"),"Could not get selected text"),""):(We(new Error("No active Markdown editor"),"Could not get selected text"),"")}},date:{now:(i,o)=>Ko({format:i,offset:o}),tomorrow:i=>Ko({format:i,offset:1}),yesterday:i=>Ko({format:i,offset:-1})},fieldSuggestions:{getFieldValues:async(i,o)=>{let s=o?.includeInlineCodeBlocks?.map(u=>u.trim().toLowerCase()).filter(u=>u.length>0),a={folder:o?.folder,folders:o?.folders,tags:o?.tags,inline:o?.includeInline??!1,inlineCodeBlocks:s},l=e.vault.getMarkdownFiles();l=FS.filterFiles(l,a,u=>e.metadataCache.getFileCache(u));let c=new Set;for(let u of l){let f=e.metadataCache.getFileCache(u)?.frontmatter?.[i];if(f!=null){if(Array.isArray(f))f.forEach(p=>{if(p==null||typeof p=="object")return;let m=String(p).trim();m&&c.add(m)});else if(typeof f!="object"){let p=String(f).trim();p&&c.add(p)}}if(a.inline)try{let p=await e.vault.read(u);Zm.getFieldValues(p,i,{includeCodeBlocks:s}).forEach(v=>c.add(v))}catch{}}return Array.from(c).sort()},clearCache:i=>{Gl.getInstance().clear(i)}}}}static async inputPrompt(e,t,n,i,o){try{return await sr.Prompt(e,t,n,i,void 0,{allowPeek:!0,...o})}catch(s){Ql(s)}}static async datePrompt(e,t,n){try{let i=await Hl.Prompt(e,t,n?.placeholder,n?.defaultValue,n?.dateFormat);if(i&&i.startsWith("@date:")){let o=i.slice(6);return(n?.dateFormat?qa(o,n.dateFormat):null)??o}return i}catch(i){Ql(i)}}static async wideInputPrompt(e,t,n,i,o){try{return await fu.Prompt(e,t,n,i,void 0,{allowPeek:!0,...o})}catch(s){Ql(s)}}static async yesNoPrompt(e,t,n){let i;try{i=await vi.Ask(e,t,n)}catch(o){Ql(o)}if(i===null)throw new dt(wc);return i}static async infoDialog(e,t,n){try{return await Eb.Show(e,t,n)}catch(i){Ql(i)}}static async suggester(e,t,n,i,o=!1,s){try{let a;return typeof t=="function"?a=n.map((l,c,u)=>zr(t(l,c,u))):a=t.map(l=>zr(l)),o?await Or.Suggest(e,a,n,{...i?{placeholder:i}:{},...s?.renderItem?{renderItem:s.renderItem}:{}}):await hr.Suggest(e,a,n,i,s?.renderItem)}catch(a){Ql(a)}}static async checkboxPrompt(e,t,n,i){try{return await(i===void 0?ch.Open(e,t,n):ch.Open(e,t,n,i))}catch(o){Ql(o)}}}});var vh,lP=k(()=>{V0();vh=class extends Jm{}});function UH(r){return new Promise(e=>window.setTimeout(e,r))}function Jd(r){return r.split(`
`)}var MS=k(()=>{});async function HH(r,e){return r.mode==="script"?await e.evaluateScriptCondition(r):xne(r,e.variables)}function xne(r,e){let t=r.variableName?.trim();if(!t)return P.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(t in e))return P.logWarning(`Conditional command skipped: Variable '${t}' is not defined.`),!1;let n=e[t];switch(r.operator){case"isTruthy":return!!n;case"isFalsy":return!n}if(zc(r.operator)){let i=wN(r);return i===void 0?(P.logWarning(`Conditional command: Operator '${r.operator}' requires a comparison value.`),!1):r.operator==="contains"?zH(n,i,r):r.operator==="notContains"?!zH(n,i,r):Tne(n,i,r)}return!1}function zH(r,e,t){if(r==null)return!1;if(typeof e=="string"&&e.length===0)return P.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1;if(Array.isArray(r))return r.map(o=>lD(o,t.valueType)).some(o=>o===e);if(typeof r=="string")return r.includes(Uc(e));if(typeof r=="number"&&typeof e=="number")return r===e;let n=Uc(r),i=Uc(e);return typeof n=="string"&&n.includes(i)}function Tne(r,e,t){let n=lD(r,t.valueType);switch(t.operator){case"equals":return n===e;case"notEquals":return n!==e;case"lessThan":return OS(n,e,(i,o)=>i<o);case"lessThanOrEqual":return OS(n,e,(i,o)=>i<=o);case"greaterThan":return OS(n,e,(i,o)=>i>o);case"greaterThanOrEqual":return OS(n,e,(i,o)=>i>=o);default:return!1}}function OS(r,e,t){let n=Number(r),i=Number(e);return Number.isNaN(n)||Number.isNaN(i)?(P.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):t(n,i)}var WH=k(()=>{De();yf()});function jH(r,e=void 0){return r==="horizontal"?"horizontal":r==="vertical"?"vertical":e}function Cu(r,e,t){return t?{location:r,direction:t,focus:e,mode:"default"}:{location:r,focus:e,mode:"default"}}function GH(r){let e=r.focus??!0;if(r.location)switch(r.location){case"reuse":return Cu("reuse",e);case"tab":return Cu("tab",e);case"split":return Cu("split",e,jH(r.direction,"vertical"));case"window":return Cu("window",e);case"left-sidebar":return Cu("left-sidebar",e);case"right-sidebar":return Cu("right-sidebar",e);default:break}let t=r.openInNewTab??!1,n=jH(r.direction);return t?Cu("split",e,n??"vertical"):Cu("reuse",e)}var YH=k(()=>{Dx()});function KH(r){let e={hasOwnProperty:t=>r.has(t)};return new Proxy(e,{get(t,n){if(n==="hasOwnProperty")return e.hasOwnProperty;if(typeof n=="string")return r.get(n)},set(t,n,i){return typeof n!="string"||r.set(n,i),!0},deleteProperty(t,n){return typeof n!="string"||r.delete(n),!0},has(t,n){return typeof n=="string"&&r.has(n)},ownKeys(){return Array.from(r.keys())},getOwnPropertyDescriptor(t,n){if(n==="hasOwnProperty")return{value:e.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 QH=k(()=>{});function eW(r){return r!==null&&typeof r=="object"}function _ne(r){return typeof r=="function"}function tW(r){return eW(r)}function kne(r){if(!tW(r))return;let{settings:e}=r;return eW(e)?e:void 0}function XH(r,e="command"){if(typeof r!="string"||!r.trim())return`the saved entry has no ${e} type, so QuickAdd cannot tell what it was meant to do. It is in .obsidian/plugins/quickadd/data.json.`;let t=e==="command"?Ane.get(r):void 0;return t||`QuickAdd does not recognise the ${e} type '${r}'. It can come from a newer version of QuickAdd, an imported package, or a hand-edited .obsidian/plugins/quickadd/data.json.`}function ZH(r){return`${r.scriptPath}::${r.exportName??"default"}`}var Sne,JH,Ane,Wa,pb=k(()=>{Sne=QP(require("obsidian"));De();rr();Tr();aP();lP();Ul();ih();oh();xa();Dt();So();AI();kI();DI();II();FI();PI();$I();MI();OI();RI();MS();RT();Nd();ht();ah();om();fo();Dt();JH=require("obsidian");jo();Er();Bi();xx();tC();Bl();WH();db();YH();QH();Qn();Ane=new Map([["InfiniteAIAssistant",'QuickAdd has removed the "Infinite AI Assistant" command type - 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.']]);Wa=class extends vh{constructor(t,n,i,o,s,a,l,c=null){super(t);this.originLeaf=c;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,this.userScriptSettingsDefinition=void 0;let u=this.initSharedVariables(o,s);this.choiceExecutor.variables=u,this.params=this.buildParams(t,n,o,u)}buildParams(t,n,i,o){let s=KH(o),a={app:t,quickAddApi:gh.GetApi(t,n,i),obsidian:Sne,abort:l=>{throw new Tt(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(([u])=>typeof u=="string"):l&&typeof l=="object"?Object.entries(l):null;c&&(o.clear(),c?.forEach(([u,d])=>o.set(u,d)))},enumerable:!0,configurable:!1}),a}initSharedVariables(t,n){let i=t.variables;return n?(i&&n!==i&&i.forEach((o,s)=>{n.has(s)||n.set(s,o)}),n):i??new Map}async run(){if(Kn(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 t=ar(this.macro?.commands);if(t.length===0){xy(this.macro?.commands)||P.logError(`No commands in the macro for choice '${this.choice.name}'`);return}await this.executeCommands(t)}getOutput(){return this.output}async executeCommands(t){try{for(let n of t)if(n)switch(n.type){case"Obsidian":this.executeObsidianCommand(n);break;case"UserScript":await this.executeUserScript(n);break;case"Choice":await this.executeChoice(n);break;case"Wait":await UH(n.time);break;case"NestedChoice":await this.executeNestedChoice(n);break;case"EditorCommand":await this.executeEditorCommand(n);break;case"AIAssistant":await this.executeAIAssistant(n);break;case"OpenFile":await this.executeOpenFile(n);break;case"Conditional":await this.executeConditional(n);break;default:{let i=n.type;this.reportUnrunnableCommand(n,XH(i));break}}}catch(n){if(bu(n,{logPrefix:"Macro execution aborted",noticePrefix:"Macro execution aborted",defaultReason:"Macro execution aborted"})){this.choiceExecutor.signalAbort?.(n);return}throw n}}reportUnrunnableCommand(t,n){let i=typeof t?.name=="string"&&t.name.trim()?`'${t.name}'`:"an unnamed command";P.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(t){let n=eC(t),i;if(n!==void 0){let s=this.preloadedUserScripts.get(n);s!==void 0&&(i=s,this.preloadedUserScripts.delete(n))}if(i===void 0&&(i=await Fs(t,this.app)),!i){P.logError(`failed to load user script ${t.path}.`);return}t.settings||(t.settings={});let o=kne(i);o&&nm(t.settings,o),this.userScriptCommand=t,this.userScriptSettingsDefinition=o;try{await this.userScriptDelegator(i)}catch(s){throw s instanceof Tt||We(s,`Failed to run user script ${t.name} in "${this.choice.name}"`),s}finally{this.userScriptCommand=null,this.userScriptSettingsDefinition=void 0}}async getResolvedUserScriptSettings(t){return await tm(this.app,t,this.userScriptSettingsDefinition)&&await this.plugin.saveSettings?.(),Cx(this.app,t,this.userScriptSettingsDefinition)}async runScriptWithSettings(t,n){if(typeof t!="function"&&t.entry&&typeof t.entry=="function")return await this.onExportIsFunction(t.entry,await this.getResolvedUserScriptSettings(n));if(typeof t=="function")return await this.onExportIsFunction(t,await this.getResolvedUserScriptSettings(n))}async userScriptDelegator(t){switch(typeof t){case"function":if(!_ne(t))break;this.userScriptCommand?await this.runScriptWithSettings(t,this.userScriptCommand):await this.onExportIsFunction(t);break;case"object":tW(t)&&await this.onExportIsObject(t);break;case"bigint":case"boolean":case"number":case"string":this.output=t.toString();break;default:P.logError(`user script in macro for '${this.choice.name}' is invalid`)}}async onExportIsFunction(t,n){this.output=await t(this.params,n||{})}async onExportIsObject(t){if(Object.keys(t).length===0)throw new Error(`user script in macro for '${this.choice.name}' is an empty object`);if(this.userScriptCommand&&typeof t.entry=="function"){await this.runScriptWithSettings(t,this.userScriptCommand);return}let n=Object.keys(t);try{let i=String(await cs(this.choiceExecutor,{remote:o=>us(o,{items:n.map(s=>({value:s,title:s})),placeholder:this.promptLabel,what:"the user-script member picker"}),headless:()=>{if(n.length===1)return Promise.resolve(n[0]);throw new ve("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:()=>hr.Suggest(this.app,n,n,this.promptLabel)}));if(!Object.hasOwn(t,i))throw new Error(`This macro's user script does not export a member named "${i}".`);await this.userScriptDelegator(t[i])}catch(i){throw i instanceof Tt?i:pt(i)?new dt("Input cancelled by user"):i}}executeObsidianCommand(t){let n=this.app.commands.commands;if(n&&!n[t.commandId]){P.logError(`Obsidian command '${t.name}' is no longer available.`);return}this.app.commands.executeCommandById(t.commandId)}async executeChoice(t){let n;try{n=this.plugin.getChoiceById(t.choiceId)}catch(o){let s=o instanceof Error?o.message:String(o);if(!/not found/i.test(s))throw o;P.logError(`choice '${t.name}' could not be found.`);return}await this.choiceExecutor.execute(n);let i=this.choiceExecutor.consumeAbortSignal?.();if(i)throw i}async executeNestedChoice(t){let n=t.choice;if(!n){P.logError(`choice in ${t.name} is invalid`);return}await this.choiceExecutor.execute(n);let i=this.choiceExecutor.consumeAbortSignal?.();if(i)throw i}async executeEditorCommand(t){switch(t.editorCommandType){case"Cut":await um.run(this.app);break;case"Copy":await cm.run(this.app);break;case"Paste":await dm.run(this.app);break;case"Paste with format":await pm.run(this.app);break;case"Select active line":fm.run(this.app);break;case"Select link on active line":mm.run(this.app);break;case"Move cursor to file start":hm.run(this.app);break;case"Move cursor to file end":gm.run(this.app);break;case"Move cursor to line start":vm.run(this.app);break;case"Move cursor to line end":ym.run(this.app);break;default:{let n=t.editorCommandType;this.reportUnrunnableCommand(t,XH(n,"editor command"))}}}async executeAIAssistant(t){if(ne.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let n=ne.getState().ai,i;if(t.model==="Ask me")i=await this.pickModelInteractively();else if(i=Ld(gc(t.model,t.modelRef)??t.model),!i)throw new Error(`Model ${t.model} not found with any provider.`);let{model:o,provider:s}=i,a=new Do(this.app,kn(),this.choiceExecutor);a.setPromptRunContext({choiceName:this.choice?.name,draftScopeId:`${this.choice?.id??"macro"}#aiAssistant:${t.id}`});let l=await Gs(this.app,s),c=await Rq(this.app,{apiKey:l,model:o,provider:s,outputVariableName:t.outputVariableName,promptTemplate:t.promptTemplate,promptTemplateFolder:n.promptTemplatesFolderPath,systemPrompt:t.systemPrompt,showAssistantMessages:n.showAssistant,modelOptions:t.modelParameters,interactive:this.choiceExecutor.interactive,promptProvider:this.choiceExecutor.promptProvider},async u=>a.formatFileContent(u));for(let u in c)this.choiceExecutor.variables.set(u,c[u])}async pickModelInteractively(){let n=ne.getState().ai.providers.flatMap(o=>o.models.map(s=>({label:`${s.name} (${o.name})`,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=this.choiceExecutor.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(this.choiceExecutor.interactive===!1)throw new ve('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 hr.Suggest(this.app,n.map(o=>o.label),n.map(o=>o.resolved),"Select a model")}catch(o){throw pt(o)?new dt("Input cancelled by user"):o}}async executeConditional(t){let n=await HH(t.condition,{variables:this.params.variables,evaluateScriptCondition:async s=>await this.evaluateScriptCondition(s)}),i=n?t.thenCommands:t.elseCommands;if(Kn(i))throw new Error(`Could not read the ${n?"then":"else"} commands for '${t.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(t){t?.length&&await this.executeCommands(t)}setOutput(t){this.output=t}async evaluateScriptCondition(t){let n=ZH(t),i=this.conditionalScriptCache.get(n);if(!i){if(i=await this.loadConditionalScript(t),!i)return!1;this.conditionalScriptCache.set(n,i)}let o;try{o=await i()}catch(s){throw We(s,`Failed to evaluate conditional script '${t.scriptPath}'.`),s}return typeof o!="boolean"?(P.logWarning(`Conditional script '${t.scriptPath}' must return a boolean result.`),!1):o}async loadConditionalScript(t){try{let n=await Fs(this.buildConditionalUserScript(t),this.app);return n==null?void 0:typeof n=="function"?async()=>await n(this.params):async()=>n}catch(n){throw We(n,`Failed to load conditional script '${t.scriptPath}'.`),n}}buildConditionalUserScript(t){return{id:`conditional-script-${ZH(t)}`,name:t.exportName?`${t.scriptPath}::${t.exportName}`:t.scriptPath,type:"UserScript",path:t.scriptPath,settings:{}}}async executeOpenFile(t){try{let n=new Do(this.app,kn(),this.choiceExecutor);n.setPromptRunContext({choiceName:this.choice?.name,draftScopeId:`${this.choice?.id??"macro"}#openFile:${t.id}`});let o=(await n.formatFileName(t.filePath,"filePath")).replace(/\\/g,"/"),s=o.split("/");if(s.some((u,d)=>u===".."||u===""&&d!==0&&d!==s.length-1)){P.logError(`OpenFile: Path traversal not allowed in '${o}'`);return}let l=this.app.vault.getAbstractFileByPath(o);if(!l||!(l instanceof JH.TFile)){P.logError(`OpenFile: '${o}' does not exist or is not a file`);return}let c=GH(t);await gl(this.app,l,{...c,originLeaf:this.originLeaf})}catch(n){P.logError(`OpenFile: Failed to open file '${t.filePath}': ${n.message}`)}}}});var tse={};Nb(tse,{default:()=>l_});module.exports=V6(tse);var Sh=require("obsidian");var uu=require("obsidian");var XP;typeof window<"u"&&((XP=window.__svelte??(window.__svelte={})).v??(XP.v=new Set)).add("5");var Qa={};var Kt=Symbol("uninitialized"),$o=Symbol("filename");var Bb="http://www.w3.org/1999/xhtml";var Vb=!0;var ZP=globalThis.process?.env?.NODE_ENV,ee=ZP&&!ZP.toLowerCase().startsWith("prod");var gs=Array.isArray,JP=Array.prototype.indexOf,oc=Array.prototype.includes,ap=Array.from,p_=Object.keys,ni=Object.defineProperty,Hi=Object.getOwnPropertyDescriptor,qb=Object.getOwnPropertyDescriptors,Ub=Object.prototype,e$=Array.prototype,sc=Object.getPrototypeOf,f_=Object.isExtensible;function m_(r){return typeof r=="function"}var At=()=>{};function zb(r){for(var e=0;e<r.length;e++)r[e]()}function Hb(){var r,e,t=new Promise((n,i)=>{r=n,e=i});return{promise:t,resolve:r,reject:e}}var Jr=Symbol("$state"),Ah=Symbol("legacy props"),t$=Symbol(""),Wb=Symbol("proxy path"),jb=Symbol("attributes"),Dh=Symbol("class"),Ih=Symbol("style"),Fh=Symbol("text"),ac=Symbol("form reset"),h_=Symbol("hmr anchor"),Xa=new class extends Error{constructor(){super(...arguments);pe(this,"name","StaleReactionError");pe(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},Gb=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");var _u=3,io=8;function r$(r){if(ee){let e=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 e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/invariant_violation")}function Yb(r){if(ee){let e=new Error(`lifecycle_outside_component
\`${r}(...)\` can only be used during component initialisation
https://svelte.dev/e/lifecycle_outside_component`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function i$(){if(ee){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 g_(){if(ee){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 o$(){if(ee){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 v_(r,e,t){if(ee){let n=new Error(`each_key_duplicate
${t?`Keyed each block has duplicate key \`${t}\` at indexes ${r} and ${e}`:`Keyed each block has duplicate key at indexes ${r} and ${e}`}
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 s$(r,e,t){if(ee){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 \`${e}\` but is now \`${t}\`. 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 a$(r){if(ee){let e=new Error(`effect_in_teardown
\`${r}\` cannot be used inside an effect cleanup function
https://svelte.dev/e/effect_in_teardown`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_in_teardown")}function l$(){if(ee){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 c$(r){if(ee){let e=new Error(`effect_orphan
\`${r}\` can only be used inside an effect (e.g. during component initialisation)
https://svelte.dev/e/effect_orphan`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_orphan")}function u$(){if(ee){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 d$(){if(ee){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 p$(){if(ee){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 f$(r){if(ee){let e=new Error(`props_invalid_value
Cannot do \`bind:${r}={undefined}\` when \`${r}\` has a fallback value
https://svelte.dev/e/props_invalid_value`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/props_invalid_value")}function m$(r){if(ee){let e=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 e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/rune_outside_svelte")}function h$(){if(ee){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 g$(){if(ee){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 v$(){if(ee){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 y$(){if(ee){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 oa="font-weight: bold",sa="font-weight: normal";function b$(r){ee?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`,oa,sa):console.warn("https://svelte.dev/e/await_reactivity_loss")}function w$(r,e){ee?console.warn(`%c[svelte] await_waterfall
%cAn async derived, \`${r}\` (${e}) 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`,oa,sa):console.warn("https://svelte.dev/e/await_waterfall")}function C$(){ee?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`,oa,sa):console.warn("https://svelte.dev/e/derived_inert")}function E$(r,e,t){ee?console.warn(`%c[svelte] hydration_attribute_changed
%cThe \`${r}\` attribute on \`${e}\` changed its value between server and client renders. The client value, \`${t}\`, will be ignored in favour of the server value
https://svelte.dev/e/hydration_attribute_changed`,oa,sa):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function ku(r){ee?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`,oa,sa):console.warn("https://svelte.dev/e/hydration_mismatch")}function x$(){ee?console.warn(`%c[svelte] lifecycle_double_unmount
%cTried to unmount a component that was not mounted
https://svelte.dev/e/lifecycle_double_unmount`,oa,sa):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function T$(){ee?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",oa,sa):console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function Kb(r){ee?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`,oa,sa):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function S$(){ee?console.warn(`%c[svelte] state_proxy_unmount
%cTried to unmount a state proxy, rather than a component
https://svelte.dev/e/state_proxy_unmount`,oa,sa):console.warn("https://svelte.dev/e/state_proxy_unmount")}function _$(){ee?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",oa,sa):console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var Fe=!1;function en(r){Fe=r}var ze;function qt(r){if(r===null)throw ku(),Qa;return ze=r}function bn(){return qt(Bn(ze))}function D(r){if(Fe){if(Bn(ze)!==null)throw ku(),Qa;ze=r}}function tn(r=1){if(Fe){for(var e=r,t=ze;e--;)t=Bn(t);ze=t}}function aa(r=!0){for(var e=0,t=ze;;){if(t.nodeType===io){var n=t.data;if(n==="]"){if(e===0)return t;e-=1}else(n==="["||n==="[!"||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(e+=1)}var i=Bn(t);r&&t.remove(),t=i}}function $h(r){if(!r||r.nodeType!==io)throw ku(),Qa;return r.data}function Qb(r){return r===this.v}function Xb(r,e){return r!=r?e==e:r!==e||r!==null&&typeof r=="object"||typeof r=="function"}function Zb(r){return!Xb(r,this.v)}var Ar=!1,Za=!1,vs=!1;var U6="font-weight: bold",z6="font-weight: normal";function y_(r){ee?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`,U6,z6):console.warn("https://svelte.dev/e/state_snapshot_uncloneable")}var H6=[];function ys(r,e=!1,t=!1){if(ee&&!e){let n=[],i=Mh(r,new Map,"",n,null,t);if(n.length===1&&n[0]==="")y_();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`),y_(a)}return i}return Mh(r,new Map,"",H6,null,t)}function Mh(r,e,t,n,i=null,o=!1){if(typeof r=="object"&&r!==null){var s=e.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(gs(r)){var a=Array(r.length);e.set(r,a),i!==null&&e.set(i,a);for(var l=0;l<r.length;l+=1){var c=r[l];l in r&&(a[l]=Mh(c,e,ee?`${t}[${l}]`:t,n,null,o))}return a}if(sc(r)===Ub){a={},e.set(r,a),i!==null&&e.set(i,a);for(var u of Object.keys(r))a[u]=Mh(r[u],e,ee?`${t}.${u}`:t,n,null,o);return a}if(r instanceof Date)return structuredClone(r);if(typeof r.toJSON=="function"&&!o)return Mh(r.toJSON(),e,ee?`${t}.toJSON()`:t,n,r)}if(r instanceof EventTarget)return r;try{return structuredClone(r)}catch{return ee&&n.push(t),r}}var Oh=null;function ii(r,e){return r.label=e,Jb(r.v,e),r}function Jb(r,e){return r?.[Wb]?.(e),r}function bs(r){let e=new Error,t=W6();return t.length===0?null:(t.unshift(`
`),ni(e,"stack",{value:t.join(`
`)}),ni(e,"name",{value:r}),e)}function W6(){let r=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let e=new Error().stack;if(Error.stackTraceLimit=r,!e)return[];let t=e.split(`
`),n=[];for(let i=0;i<t.length;i++){let o=t[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 A$(r,e){if(!ee)throw new Error("invariant(...) was not guarded by if (DEV)");r||r$(e)}var ut=null;function Ja(r){ut=r}var la=null;function up(r){la=r}var ws=null;function ew(r){ws=r}function fe(r,e=!1,t){ut={p:ut,i:!1,c:null,e:null,s:r,x:null,r:ke,l:Za&&!e?{s:null,u:null,$:[]}:null},ee&&(ut.function=t,ws=t)}function me(r){var e=ut,t=e.e;if(t!==null){e.e=null;for(var n of t)b_(n)}return r!==void 0&&(e.x=r),e.i=!0,ut=e.p,ee&&(ws=ut?.function??null),r??{}}function Cs(){return!Za||ut!==null&&ut.l===null}var Au=[];function D$(){var r=Au;Au=[],zb(r)}function yr(r){if(Au.length===0&&!Du){var e=Au;queueMicrotask(()=>{e===Au&&D$()})}Au.push(r)}function I$(){for(;Au.length>0;)D$()}var w_=new WeakMap;function tw(r){var e=ke;if(e===null)return Le.f|=8388608,r;if(ee&&r instanceof Error&&!w_.has(r)&&w_.set(r,j6(r,e)),(e.f&32768)===0&&(e.f&4)===0)throw ee&&!e.parent&&r instanceof Error&&F$(r),r;xs(r,e)}function xs(r,e){if(!(e!==null&&(e.f&16384)!==0)){for(;e!==null;){if((e.f&128)!==0){if((e.f&32768)===0)throw r;try{e.b.error(r);return}catch(t){r=t}}e=e.parent}throw ee&&r instanceof Error&&F$(r),r}}function j6(r,e){let t=Hi(r,"message");if(!(t&&!t.configurable)){for(var n=Lh?" ":" ",i=`
${n}in ${e.fn?.name||"<unknown>"}`,o=e.ctx;o!==null;)i+=`
${n}in ${o.function?.[$o].split("/").pop()}`,o=o.p;return{message:r.message+`
${i}
`,stack:r.stack?.split(`
`).filter(s=>!s.includes("svelte/src/internal")).join(`
`)}}}function F$(r){let e=w_.get(r);e&&(ni(r,"message",{value:e.message}),ni(r,"stack",{value:e.stack}))}var G6=-7169;function Ut(r,e){r.f=r.f&G6|e}function dp(r){(r.f&512)!==0||r.deps===null?Ut(r,1024):Ut(r,4096)}function P$(r){if(r!==null)for(let e of r)(e.f&2)===0||(e.f&65536)===0||(e.f^=65536,P$(e.deps))}function rw(r,e,t){(r.f&2048)!==0?e.add(r):(r.f&4096)!==0&&t.add(r),P$(r.deps),Ut(r,1024)}var $$=!1,nw=!1;function C_(r){var e=nw;try{return nw=!1,[r(),nw]}finally{nw=e}}function Pu(r){Fe&&Vn(r)!==null&&fp(r)}var M$=!1;function iw(){M$||(M$=!0,document.addEventListener("reset",r=>{Promise.resolve().then(()=>{if(!r.defaultPrevented)for(let e of r.target.elements)e[ac]?.()})},{capture:!0}))}function Ro(r){var e=Le,t=ke;on(null),sn(null);try{return r()}finally{on(e),sn(t)}}function ow(r,e,t,n=t){r.addEventListener(e,()=>Ro(t));let i=r[ac];i?r[ac]=()=>{i(),n(!0)}:r[ac]=()=>n(!0),iw()}function O$(r){let e=0,t=ai(0),n;return ee&&ii(t,"createSubscriber version"),()=>{lc()&&(h(t),En(()=>(e===0&&(n=xt(()=>r(()=>$u(t)))),e+=1,()=>{yr(()=>{e-=1,e===0&&(n?.(),n=void 0,$u(t))})})))}}var K6=589824;function qh(r,e,t,n){new E_(r,e,t,n)}var oo,Nh,Lo,Mu,Gi,No,_i,so,tl,Ou,cc,mp,Bh,Vh,ca,lw,Wt,L$,N$,x_,B$,T_,sw,aw,S_,__,E_=class{constructor(e,t,n,i){Ye(this,Wt);pe(this,"parent");pe(this,"is_pending",!1);pe(this,"transform_error");Ye(this,oo);Ye(this,Nh,Fe?ze:null);Ye(this,Lo);Ye(this,Mu);Ye(this,Gi);Ye(this,No,null);Ye(this,_i,null);Ye(this,so,null);Ye(this,tl,null);Ye(this,Ou,0);Ye(this,cc,0);Ye(this,mp,!1);Ye(this,Bh,new Set);Ye(this,Vh,new Set);Ye(this,ca,null);Ye(this,lw,O$(()=>(He(this,ca,ai(z(this,Ou))),ee&&ii(z(this,ca),"$effect.pending()"),()=>{He(this,ca,null)})));He(this,oo,e),He(this,Lo,t),He(this,Mu,o=>{var s=ke;s.b=this,s.f|=128,n(o)}),this.parent=ke.b,this.transform_error=i??this.parent?.transform_error??(o=>o),He(this,Gi,ki(()=>{if(Fe){let o=z(this,Nh);bn();let s=o.data==="[!";if(o.data.startsWith("[?")){let l=JSON.parse(o.data.slice("[?".length));ct(this,Wt,N$).call(this,l)}else s?ct(this,Wt,B$).call(this):ct(this,Wt,L$).call(this)}else ct(this,Wt,T_).call(this)},K6)),Fe&&He(this,oo,ze)}defer_effect(e){rw(e,z(this,Bh),z(this,Vh))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!z(this,Lo).pending}update_pending_count(e,t){ct(this,Wt,S_).call(this,e,t),He(this,Ou,z(this,Ou)+e),!(!z(this,ca)||z(this,mp))&&(He(this,mp,!0),yr(()=>{He(this,mp,!1),z(this,ca)&&Ts(z(this,ca),z(this,Ou))}))}get_effect_pending(){return z(this,lw).call(this),h(z(this,ca))}error(e){if(!z(this,Lo).onerror&&!z(this,Lo).failed)throw e;Oe?.is_fork?(z(this,No)&&Oe.skip_effect(z(this,No)),z(this,_i)&&Oe.skip_effect(z(this,_i)),z(this,so)&&Oe.skip_effect(z(this,so)),Oe.oncommit(()=>{ct(this,Wt,__).call(this,e)})):ct(this,Wt,__).call(this,e)}};oo=new WeakMap,Nh=new WeakMap,Lo=new WeakMap,Mu=new WeakMap,Gi=new WeakMap,No=new WeakMap,_i=new WeakMap,so=new WeakMap,tl=new WeakMap,Ou=new WeakMap,cc=new WeakMap,mp=new WeakMap,Bh=new WeakMap,Vh=new WeakMap,ca=new WeakMap,lw=new WeakMap,Wt=new WeakSet,L$=function(){try{He(this,No,an(()=>z(this,Mu).call(this,z(this,oo))))}catch(e){this.error(e)}},N$=function(e){let t=z(this,Lo).failed,{reset:n,invoke_onerror:i}=ct(this,Wt,x_).call(this,e);yr(i),t&&He(this,so,an(()=>{t(z(this,oo),()=>e,()=>n)}))},x_=function(e){var t=!1,n=!1;let i=()=>{if(t){_$();return}t=!0,n&&y$(),z(this,so)!==null&&ua(z(this,so),()=>{He(this,so,null)}),ct(this,Wt,aw).call(this,()=>{ct(this,Wt,T_).call(this)})};return{reset:i,invoke_onerror:()=>{try{n=!0,z(this,Lo).onerror?.(e,i),n=!1}catch(s){xs(s,z(this,Gi)&&z(this,Gi).parent)}}}},B$=function(){let e=z(this,Lo).pending;e&&(this.is_pending=!0,He(this,_i,an(()=>e(z(this,oo)))),yr(()=>{var t=He(this,tl,document.createDocumentFragment()),n=Dr();t.append(n),He(this,No,ct(this,Wt,aw).call(this,()=>an(()=>z(this,Mu).call(this,n)))),z(this,cc)===0&&(z(this,oo).before(t),He(this,tl,null),ua(z(this,_i),()=>{He(this,_i,null)}),ct(this,Wt,sw).call(this,Oe))}))},T_=function(){try{if(this.is_pending=this.has_pending_snippet(),He(this,cc,0),He(this,Ou,0),He(this,No,an(()=>{z(this,Mu).call(this,z(this,oo))})),z(this,cc)>0){var e=He(this,tl,document.createDocumentFragment());hp(z(this,No),e);let t=z(this,Lo).pending;He(this,_i,an(()=>t(z(this,oo))))}else ct(this,Wt,sw).call(this,Oe)}catch(t){this.error(t)}},sw=function(e){this.is_pending=!1,e.transfer_effects(z(this,Bh),z(this,Vh))},aw=function(e){var t=ke,n=Le,i=ut;sn(z(this,Gi)),on(z(this,Gi)),Ja(z(this,Gi).ctx);try{return ao.ensure(),e()}catch(o){return tw(o),null}finally{sn(t),on(n),Ja(i)}},S_=function(e,t){var n;if(!this.has_pending_snippet()){this.parent&&ct(n=this.parent,Wt,S_).call(n,e,t);return}He(this,cc,z(this,cc)+e),z(this,cc)===0&&(ct(this,Wt,sw).call(this,t),z(this,_i)&&ua(z(this,_i),()=>{He(this,_i,null)}),z(this,tl)&&(z(this,oo).before(z(this,tl)),He(this,tl,null)))},__=function(e){z(this,No)&&(wr(z(this,No)),He(this,No,null)),z(this,_i)&&(wr(z(this,_i)),He(this,_i,null)),z(this,so)&&(wr(z(this,so)),He(this,so,null)),Fe&&(qt(z(this,Nh)),tn(),qt(aa()));let t=z(this,Lo).failed,n=i=>{let{reset:o,invoke_onerror:s}=ct(this,Wt,x_).call(this,i);s(),t&&He(this,so,ct(this,Wt,aw).call(this,()=>{try{return an(()=>{var a=ke;a.b=this,a.f|=128,t(z(this,oo),()=>i,()=>o)})}catch(a){return xs(a,z(this,Gi).parent),null}}))};yr(()=>{var i;try{i=this.transform_error(e)}catch(o){xs(o,z(this,Gi)&&z(this,Gi).parent);return}i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(n,o=>xs(o,z(this,Gi)&&z(this,Gi).parent)):n(i)})};function cw(r,e,t,n){let i=Cs()?uc:Ru;var o=r.filter(p=>!p.settled),s=e.map(i);if(ee&&s.forEach((p,m)=>{p.label=e[m].toString().replace("() => ","").replaceAll("$.eager(() => ","$state.eager(").replace(/\$\.get\((.+?)\)/g,(v,g)=>g)}),t.length===0&&o.length===0){n(s);return}var a=ke,l=V$(),c=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(p=>p.promise)):null;function u(p){if((a.f&16384)===0){l();try{n([...s,...p])}catch(m){xs(m,a)}gp()}}var d=k_();if(t.length===0){c.then(()=>u([])).finally(d);return}function f(){Promise.all(t.map(p=>D_(p))).then(u).catch(p=>xs(p,a)).finally(d)}c?c.then(()=>{l(),f(),gp()}):f()}function V$(){var r=ke,e=Le,t=ut,n=Oe;if(ee)var i=la;return function(s=!0){sn(r),on(e),Ja(t),s&&(r.f&16384)===0&&(n?.activate(),n?.apply()),ee&&(A_(null),up(i))}}function gp(r=!0){sn(null),on(null),Ja(null),r&&Oe?.deactivate(),ee&&(A_(null),up(null))}function k_(){var r=ke,e=r.b,t=Oe,n=!!e?.is_rendered();return e?.update_pending_count(1,t),t.increment(n,r),()=>{e?.update_pending_count(-1,t),t.decrement(n,r)}}var Ki=null;function A_(r){Ki=r}var Uh=new Set;function uc(r){var e=2050;ke!==null&&(ke.f|=524288);let t={ctx:ut,deps:null,effects:null,equals:Qb,f:e,fn:r,reactions:null,rv:0,v:Kt,wv:0,parent:ke,ac:null};return ee&&vs&&(t.created=bs("created at")),t}var vp=Symbol("obsolete");function D_(r,e,t){let n=ke;n===null&&i$();var i=void 0,o=ai(Kt);ee&&(o.label=e??r.toString());var s=!Le,a=new Set;return z$(()=>{var l=ke;ee&&(Ki={effect:l,effect_deps:new Set,warned:!1});var c=Hb();i=c.promise;try{Promise.resolve(r()).then(c.resolve,p=>{p!==Xa&&c.reject(p)}).finally(gp)}catch(p){c.reject(p),gp()}if(ee){if(Ki){if(l.deps!==null)for(let p=0;p<Ai;p+=1)Ki.effect_deps.add(l.deps[p]);if(xn!==null)for(let p=0;p<xn.length;p+=1)Ki.effect_deps.add(xn[p])}Ki=null}var u=Oe;if(s){if((l.f&32768)!==0)var d=k_();if(n.b?.is_rendered())u.async_deriveds.get(l)?.reject(vp);else for(let p of a.values())p.reject(vp);a.add(c),u.async_deriveds.set(l,c)}let f=(p,m=void 0)=>{ee&&(Ki=null),d?.(),a.delete(c),m!==vp&&(u.activate(),m?(o.f|=8388608,Ts(o,m)):((o.f&8388608)!==0&&(o.f^=8388608),ee&&t!==void 0&&!o.equals(p)&&(Uh.add(o),setTimeout(()=>{Uh.has(o)&&(l.f&16384)===0&&(w$(o.label,t),Uh.delete(o))})),Ts(o,p)),u.deactivate())};c.promise.then(f,p=>f(null,p||"unknown"))}),Cn(()=>{for(let l of a)l.reject(vp)}),ee&&(o.f|=4194304),new Promise(l=>{function c(u){function d(){u===i?l(o):c(i)}u.then(d,d)}c(i)})}function M(r){let e=uc(r);return Ar||pw(e),e}function Ru(r){let e=uc(r);return e.equals=Zb,e}function q$(r){var e=r.effects;if(e!==null){r.effects=null;for(var t=0;t<e.length;t+=1)wr(e[t])}}var I_=[];function zh(r){var e,t=ke,n=r.parent;if(!lo&&n!==null&&r.v!==Kt&&(n.f&24576)!==0)return C$(),r.v;if(sn(n),ee){let i=Lu;uw(new Set);try{oc.call(I_,r)&&o$(),I_.push(r),r.f&=-65537,q$(r),e=dw(r)}finally{sn(t),uw(i),I_.pop()}}else try{r.f&=-65537,q$(r),e=dw(r)}finally{sn(t)}return e}function F_(r){var e=zh(r);if(!r.equals(e)&&(r.wv=yp(),(!Oe?.is_fork||r.deps===null)&&(Oe!==null?(Oe.capture(r,e,!0),da?.capture(r,e,!0)):r.v=e,r.deps===null))){Ut(r,1024);return}lo||(Tn!==null?(lc()||Oe?.is_fork)&&Tn.set(r,e):dp(r))}function U$(r){if(r.effects!==null)for(let e of r.effects)(e.teardown||e.ac)&&(e.teardown?.(),e.ac!==null&&Ro(()=>{e.ac.abort(Xa),e.ac=null}),e.fn!==null&&(e.teardown=At),Nu(e,0),Hh(e))}function P_(r){if(r.effects!==null)for(let e of r.effects)e.teardown&&e.fn!==null&&pa(e)}var fw=null,bp=null,Oe=null,da=null,Tn=null,O_=null,Du=!1,$_=!1,Bu=null,Gh=null,H$=0,M_=new Set,Z6=1,Cp,nl,il,Ep,xp,Tp,ol,Sp,Di,Yh,sl,Ss,fa,_p,dc,Nt,R_,Wh,L_,j$,G$,wp,Y$,jh,mw=class mw{constructor(){Ye(this,Nt);pe(this,"id",Z6++);Ye(this,Cp,!1);pe(this,"linked",!0);Ye(this,nl,null);Ye(this,il,null);pe(this,"async_deriveds",new Map);pe(this,"current",new Map);pe(this,"previous",new Map);Ye(this,Ep,new Set);Ye(this,xp,new Set);Ye(this,Tp,0);Ye(this,ol,new Map);Ye(this,Sp,null);Ye(this,Di,[]);Ye(this,Yh,[]);Ye(this,sl,new Set);Ye(this,Ss,new Set);Ye(this,fa,new Map);Ye(this,_p,new Set);pe(this,"is_fork",!1);Ye(this,dc,!1);bp===null?fw=bp=this:(He(bp,il,this),He(this,nl,bp)),bp=this}skip_effect(e){z(this,fa).has(e)||z(this,fa).set(e,{d:[],m:[]}),z(this,_p).delete(e)}unskip_effect(e,t=n=>this.schedule(n)){var n=z(this,fa).get(e);if(n){z(this,fa).delete(e);for(var i of n.d)Ut(i,2048),t(i);for(i of n.m)Ut(i,4096),t(i)}z(this,_p).add(e)}capture(e,t,n=!1){e.v!==Kt&&!this.previous.has(e)&&this.previous.set(e,e.v),(e.f&8388608)===0&&(this.current.set(e,[t,n]),Tn?.set(e,t)),this.is_fork||(e.v=t)}activate(){Oe=this}deactivate(){Oe=null,Tn=null}flush(){try{ee&&M_.clear(),$_=!0,Oe=this,ct(this,Nt,Wh).call(this)}finally{if(H$=0,O_=null,Bu=null,Gh=null,$_=!1,Oe=null,Tn=null,Vo.clear(),ee)for(let e of M_)e.updated=null}}discard(){for(let e of z(this,xp))e(this);z(this,xp).clear();for(let e of this.async_deriveds.values())e.reject(vp);ct(this,Nt,jh).call(this),z(this,Sp)?.resolve()}register_created_effect(e){z(this,Yh).push(e)}increment(e,t){if(He(this,Tp,z(this,Tp)+1),e){let n=z(this,ol).get(t)??0;z(this,ol).set(t,n+1)}}decrement(e,t){if(He(this,Tp,z(this,Tp)-1),e){let n=z(this,ol).get(t)??0;n===1?z(this,ol).delete(t):z(this,ol).set(t,n-1)}z(this,dc)||(He(this,dc,!0),yr(()=>{He(this,dc,!1),this.linked&&this.flush()}))}transfer_effects(e,t){for(let n of e)z(this,sl).add(n);for(let n of t)z(this,Ss).add(n);e.clear(),t.clear()}oncommit(e){z(this,Ep).add(e)}ondiscard(e){z(this,xp).add(e)}settled(){return(z(this,Sp)??He(this,Sp,Hb())).promise}static ensure(){if(Oe===null){let e=Oe=new mw;!$_&&!Du&&yr(()=>{z(e,Cp)||e.flush()})}return Oe}apply(){if(!Ar||!this.is_fork&&z(this,nl)===null&&z(this,il)===null){Tn=null;return}Tn=new Map;for(let[t,[n]]of this.current)Tn.set(t,n);for(let t=fw;t!==null;t=z(t,il))if(!(t===this||t.is_fork)){var e=!1;if(t.id<this.id){for(let[n,[,i]]of t.current)if(!i&&this.current.has(n)){e=!0;break}}if(!e)for(let[n,i]of t.previous)Tn.has(n)||Tn.set(n,i)}}schedule(e){if(O_=e,e.b?.is_pending&&(e.f&16777228)!==0&&(e.f&32768)===0){e.b.defer_effect(e);return}for(var t=e;t.parent!==null;){t=t.parent;var n=t.f;if(Bu!==null&&t===ke&&(Ar||(Le===null||(Le.f&2)===0)&&!$$))return;if((n&96)!==0){if((n&1024)===0)return;t.f^=1024}}z(this,Di).push(t)}};Cp=new WeakMap,nl=new WeakMap,il=new WeakMap,Ep=new WeakMap,xp=new WeakMap,Tp=new WeakMap,ol=new WeakMap,Sp=new WeakMap,Di=new WeakMap,Yh=new WeakMap,sl=new WeakMap,Ss=new WeakMap,fa=new WeakMap,_p=new WeakMap,dc=new WeakMap,Nt=new WeakSet,R_=function(){if(this.is_fork)return!0;for(let n of z(this,ol).keys()){for(var e=n,t=!1;e.parent!==null;){if(z(this,fa).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1},Wh=function(){var l,c,u;if(He(this,Cp,!0),H$++>1e3&&(ct(this,Nt,jh).call(this),J6()),ee)for(let d of this.current.keys())M_.add(d);for(let d of z(this,sl))z(this,Ss).delete(d),Ut(d,2048),this.schedule(d);for(let d of z(this,Ss))Ut(d,4096),this.schedule(d);let e=z(this,Di);He(this,Di,[]),this.apply();var t=Bu=[],n=[],i=Gh=[];for(let d of e)try{ct(this,Nt,L_).call(this,d,t,n)}catch(f){throw X$(d),ct(this,Nt,R_).call(this)||this.discard(),f}if(Oe=null,i.length>0){var o=mw.ensure();for(let d of i)o.schedule(d)}if(Bu=null,Gh=null,ct(this,Nt,R_).call(this)){ct(this,Nt,wp).call(this,n),ct(this,Nt,wp).call(this,t);for(let[d,f]of z(this,fa))Q$(d,f);i.length>0&&ct(l=Oe,Nt,Wh).call(l);return}let s=ct(this,Nt,j$).call(this);if(s){ct(this,Nt,wp).call(this,n),ct(this,Nt,wp).call(this,t),ct(c=s,Nt,G$).call(c,this);return}z(this,sl).clear(),z(this,Ss).clear();for(let d of z(this,Ep))d(this);z(this,Ep).clear(),da=this,W$(n),W$(t),da=null,z(this,Sp)?.resolve();var a=Oe;if(z(this,Tp)===0&&(z(this,Di).length===0||a!==null)&&(ct(this,Nt,jh).call(this),Ar&&(ct(this,Nt,Y$).call(this),Oe=a)),z(this,Di).length>0)if(a!==null){let d=a;z(d,Di).push(...z(this,Di).filter(f=>!z(d,Di).includes(f)))}else a=this;a!==null&&(Vo.clear(),ct(u=a,Nt,Wh).call(u))},L_=function(e,t,n){e.f^=1024;for(var i=e.first;i!==null;){var o=i.f,s=(o&96)!==0,a=s&&(o&1024)!==0,l=a||(o&8192)!==0||z(this,fa).has(i);if(!l&&i.fn!==null){s?i.f^=1024:(o&4)!==0?t.push(i):Ar&&(o&16777224)!==0?n.push(i):pc(i)&&((o&16)!==0&&z(this,Ss).add(i),pa(i));var c=i.first;if(c!==null){i=c;continue}}for(;i!==null;){var u=i.next;if(u!==null){i=u;break}i=i.parent}}},j$=function(){for(var e=z(this,nl);e!==null;){if(!e.is_fork){for(let[t,[,n]]of this.current)if(e.current.has(t)&&!n)return e}e=z(e,nl)}return null},G$=function(e){var n;for(let[i,o]of e.current)!this.previous.has(i)&&e.previous.has(i)&&this.previous.set(i,e.previous.get(i)),this.current.set(i,o);for(let[i,o]of e.async_deriveds){let s=this.async_deriveds.get(i);s&&o.promise.then(s.resolve).catch(s.reject)}e.async_deriveds.clear(),this.transfer_effects(z(e,sl),z(e,Ss));let t=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)t(l);else{var a=l;s&4194320&&!this.async_deriveds.has(a)&&(z(this,Ss).delete(a),Ut(a,2048),this.schedule(a))}}};for(let i of this.current.keys())t(i);this.oncommit(()=>e.discard()),ct(n=e,Nt,jh).call(n),Oe=this,ct(this,Nt,Wh).call(this)},wp=function(e){for(var t=0;t<e.length;t+=1)rw(e[t],z(this,sl),z(this,Ss))},Y$=function(){var d;for(let f=fw;f!==null;f=z(f,il)){var e=f.id<this.id,t=[];for(let[p,[m,v]]of this.current){if(f.current.has(p)){var n=f.current.get(p)[0];if(e&&m!==n)f.current.set(p,[m,v]);else continue}t.push(p)}if(e)for(let[p,m]of this.async_deriveds){let v=f.async_deriveds.get(p);v&&m.promise.then(v.resolve).catch(v.reject)}var i=[...f.current.keys()].filter(p=>!f.current.get(p)[1]);if(!(!z(f,Cp)||i.length===0)){var o=i.filter(p=>!this.current.has(p));if(o.length===0)e&&f.discard();else if(t.length>0){if(ee&&!z(f,dc)&&A$(z(f,Di).length===0,"Batch has scheduled roots"),e)for(let p of z(this,_p))f.unskip_effect(p,m=>{var v;(m.f&4194320)!==0?f.schedule(m):ct(v=f,Nt,wp).call(v,[m])});f.activate();var s=new Set,a=new Map;for(var l of t)K$(l,o,s,a);a=new Map;var c=[...f.current].filter(([p,m])=>{let v=this.current.get(p);return v?v[0]!==m[0]||v[1]!==m[1]:!0}).map(([p])=>p);if(c.length>0)for(let p of z(this,Yh))(p.f&155648)===0&&N_(p,c,a)&&((p.f&4194320)!==0?(Ut(p,2048),f.schedule(p)):z(f,sl).add(p));if(z(f,Di).length>0&&!z(f,dc)){f.apply();for(var u of z(f,Di))ct(d=f,Nt,L_).call(d,u,[],[]);He(f,Di,[])}f.deactivate()}}}},jh=function(){if(this.linked){var e=z(this,nl),t=z(this,il);e===null?fw=t:He(e,il,t),t===null?bp=e:He(t,nl,e),this.linked=!1}};var ao=mw;function qu(r){var e=Du;Du=!0;try{var t;for(r&&(Oe!==null&&!Oe.is_fork&&Oe.flush(),t=r());;){if(I$(),Oe===null)return t;Oe.flush()}}finally{Du=e}}function J6(){if(ee){var r=new Map;for(let t of Oe.current.keys())for(let[n,i]of t.updated??[]){var e=r.get(n);e||(e={error:i.error,count:0},r.set(n,e)),e.count+=i.count}for(let t of r.values())t.error&&console.error(t.error)}try{u$()}catch(t){ee&&ni(t,"stack",{value:""}),xs(t,O_)}}var Bo=null;function W$(r){var e=r.length;if(e!==0){for(var t=0;t<e;){var n=r[t++];if((n.f&24576)===0&&pc(n)&&(Bo=new Set,pa(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&B_(n),Bo?.size>0)){Vo.clear();for(let i of Bo){if((i.f&24576)!==0)continue;let o=[i],s=i.parent;for(;s!==null;)Bo.has(s)&&(Bo.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&&pa(l)}}Bo.clear()}}Bo=null}}function K$(r,e,t,n){if(!t.has(r)&&(t.add(r),r.reactions!==null))for(let i of r.reactions){let o=i.f;(o&2)!==0?K$(i,e,t,n):(o&4194320)!==0&&(o&2048)===0&&N_(i,e,n)&&(Ut(i,2048),Qh(i))}}function N_(r,e,t){let n=t.get(r);if(n!==void 0)return n;if(r.deps!==null)for(let i of r.deps){if(oc.call(e,i))return!0;if((i.f&2)!==0&&N_(i,e,t))return t.set(i,!0),!0}return t.set(r,!1),!1}function Qh(r){Oe.schedule(r)}function Q$(r,e){if(!((r.f&32)!==0&&(r.f&1024)!==0)){(r.f&2048)!==0?e.d.push(r):(r.f&4096)!==0&&e.m.push(r),Ut(r,1024);for(var t=r.first;t!==null;)Q$(t,e),t=t.next}}function X$(r){Ut(r,1024);for(var e=r.first;e!==null;)X$(e),e=e.next}var Lu=new Set,Vo=new Map;function uw(r){Lu=r}var V_=!1;function J$(){V_=!0}function ai(r,e){var t={f:0,v:r,reactions:null,equals:Qb,rv:0,wv:0};return ee&&vs&&(t.created=e??bs("created at"),t.updated=null,t.set_during_effect=!1,t.trace=null),t}function Ee(r,e){let t=ai(r,e);return pw(t),t}function Iu(r,e=!1,t=!0){var i;let n=ai(r);return e||(n.equals=Zb),Za&&t&&ut!==null&&ut.l!==null&&((i=ut.l).s??(i.s=[])).push(n),n}function Q(r,e,t=!1){Le!==null&&(!Ii||(Le.f&131072)!==0)&&Cs()&&(Le.f&4325394)!==0&&(qo===null||!qo.has(r))&&v$();let n=t?st(e):e;return ee&&Jb(n,r.label),Ts(r,n,Gh)}function Ts(r,e,t=null){if(!r.equals(e)){lo?Vo.set(r,e):Vo.has(r)||Vo.set(r,r.v);var n=ao.ensure();if(n.capture(r,e),ee){if(vs||ke!==null){r.updated??(r.updated=new Map);let i=(r.updated.get("")?.count??0)+1;if(r.updated.set("",{error:null,count:i}),vs||i>5){let o=bs("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++}}}ke!==null&&(r.set_during_effect=!0)}if((r.f&2)!==0){let i=r;(r.f&2048)!==0&&zh(i),Tn===null&&dp(i)}r.wv=yp(),eM(r,2048,t),Cs()&&ke!==null&&(ke.f&1024)!==0&&(ke.f&96)===0&&(co===null?tM([r]):co.push(r)),!n.is_fork&&Lu.size>0&&!V_&&hw()}return e}function hw(){V_=!1;for(let r of Lu){(r.f&1024)!==0&&Ut(r,4096);let e;try{e=pc(r)}catch{e=!0}e&&pa(r)}Lu.clear()}function q_(r,e=1){var t=h(r);return Q(r,e===1?++t:--t)}function $u(r){Q(r,r.v+1)}function eM(r,e,t){var n=r.reactions;if(n!==null)for(var i=Cs(),o=n.length,s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===ke)){var c=(l&2048)===0;if(c&&Ut(a,e),(l&131072)!==0)Lu.add(a);else if((l&2)!==0){var u=a;Tn?.delete(u),(l&65536)===0&&(l&512&&(ke===null||(ke.f&2097152)===0)&&(a.f|=65536),eM(u,4096,t))}else if(c){var d=a;(l&16)!==0&&Bo!==null&&Bo.add(d),t!==null?t.push(d):Qh(d)}}}}var t3=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function st(r){if(typeof r!="object"||r===null||Jr in r)return r;let e=sc(r);if(e!==Ub&&e!==e$)return r;var t=new Map,n=gs(r),i=Ee(0),o=ee&&vs?bs("created at"):null,s=fc,a=d=>{if(fc===s)return d();var f=Le,p=fc;on(null),U_(s);var m=d();return on(f),U_(p),m};n&&(t.set("length",Ee(r.length,o)),ee&&(r=n3(r)));var l="";let c=!1;function u(d){if(!c){c=!0,l=d,ii(i,`${l} version`);for(let[f,p]of t)ii(p,Uu(l,f));c=!1}}return new Proxy(r,{defineProperty(d,f,p){(!("value"in p)||p.configurable===!1||p.enumerable===!1||p.writable===!1)&&h$();var m=t.get(f);return m===void 0?a(()=>{var v=Ee(p.value,o);return t.set(f,v),ee&&typeof f=="string"&&ii(v,Uu(l,f)),v}):Q(m,p.value,!0),!0},deleteProperty(d,f){var p=t.get(f);if(p===void 0){if(f in d){let m=a(()=>Ee(Kt,o));t.set(f,m),$u(i),ee&&ii(m,Uu(l,f))}}else Q(p,Kt),$u(i);return!0},get(d,f,p){if(f===Jr)return r;if(ee&&f===Wb)return u;var m=t.get(f),v=f in d;if(m===void 0&&(!v||Hi(d,f)?.writable)&&(m=a(()=>{var y=st(v?d[f]:Kt),w=Ee(y,o);return ee&&ii(w,Uu(l,f)),w}),t.set(f,m)),m!==void 0){var g=h(m);return g===Kt?void 0:g}return Reflect.get(d,f,p)},getOwnPropertyDescriptor(d,f){var p=Reflect.getOwnPropertyDescriptor(d,f);if(p&&"value"in p){var m=t.get(f);m&&(p.value=h(m))}else if(p===void 0){var v=t.get(f),g=v?.v;if(v!==void 0&&g!==Kt)return{enumerable:!0,configurable:!0,value:g,writable:!0}}return p},has(d,f){if(f===Jr)return!0;var p=t.get(f),m=p!==void 0&&p.v!==Kt||Reflect.has(d,f);if(p!==void 0||ke!==null&&(!m||Hi(d,f)?.writable)){p===void 0&&(p=a(()=>{var g=m?st(d[f]):Kt,y=Ee(g,o);return ee&&ii(y,Uu(l,f)),y}),t.set(f,p));var v=h(p);if(v===Kt)return!1}return m},set(d,f,p,m){var v=t.get(f),g=f in d;if(n&&f==="length")for(var y=p;y<v.v;y+=1){var w=t.get(y+"");w!==void 0?Q(w,Kt):y in d&&(w=a(()=>Ee(Kt,o)),t.set(y+"",w),ee&&ii(w,Uu(l,y)))}if(v===void 0)(!g||Hi(d,f)?.writable)&&(v=a(()=>Ee(void 0,o)),ee&&ii(v,Uu(l,f)),Q(v,st(p)),t.set(f,v));else{g=v.v!==Kt;var T=a(()=>st(p));Q(v,T)}var b=Reflect.getOwnPropertyDescriptor(d,f);if(b?.set&&b.set.call(m,p),!g){if(n&&typeof f=="string"){var E=t.get("length"),C=Number(f);Number.isInteger(C)&&C>=E.v&&Q(E,C+1)}$u(i)}return!0},ownKeys(d){h(i);var f=Reflect.ownKeys(d).filter(v=>{var g=t.get(v);return g===void 0||g.v!==Kt});for(var[p,m]of t)m.v!==Kt&&!(p in d)&&f.push(p);return f},setPrototypeOf(){g$()}})}function Uu(r,e){return typeof e=="symbol"?`${r}[Symbol(${e.description??""})]`:t3.test(e)?`${r}.${e}`:/^\d+$/.test(e)?`${r}[${e}]`:`${r}['${e}']`}function Ap(r){try{if(r!==null&&typeof r=="object"&&Jr in r)return r[Jr]}catch{}return r}function z_(r,e){return Object.is(Ap(r),Ap(e))}var r3=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function n3(r){return new Proxy(r,{get(e,t,n){var i=Reflect.get(e,t,n);return r3.has(t)?function(...o){J$();var s=i.apply(this,o);return hw(),s}:i}})}function rM(){let r=Array.prototype,e=Array.__svelte_cleanup;e&&e();let{indexOf:t,lastIndexOf:n,includes:i}=r;r.indexOf=function(o,s){let a=t.call(this,o,s);if(a===-1){for(let l=s??0;l<this.length;l+=1)if(Ap(this[l])===o){Kb("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(Ap(this[l])===o){Kb("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(Ap(this[l])===o){Kb("array.includes(...)");break}}return a},Array.__svelte_cleanup=()=>{r.indexOf=t,r.lastIndexOf=n,r.includes=i}}var H_,nM,Lh,iM,oM;function gw(){if(H_===void 0){H_=window,nM=document,Lh=/Firefox/.test(navigator.userAgent);var r=Element.prototype,e=Node.prototype,t=Text.prototype;iM=Hi(e,"firstChild").get,oM=Hi(e,"nextSibling").get,f_(r)&&(r[Dh]=void 0,r[jb]=null,r[Ih]=void 0,r.__e=void 0),f_(t)&&(t[Fh]=void 0),ee&&(r.__svelte_meta=null,rM())}}function Dr(r=""){return document.createTextNode(r)}function Vn(r){return iM.call(r)}function Bn(r){return oM.call(r)}function F(r,e){if(!Fe)return Vn(r);var t=Vn(ze);if(t===null)t=ze.appendChild(Dr());else if(e&&t.nodeType!==_u){var n=Dr();return t?.before(n),qt(n),n}return e&&Xh(t),qt(t),t}function Te(r,e=!1){if(!Fe){var t=Vn(r);return t instanceof Comment&&t.data===""?Bn(t):t}if(e){if(ze?.nodeType!==_u){var n=Dr();return ze?.before(n),qt(n),n}Xh(ze)}return ze}function S(r,e=1,t=!1){let n=Fe?ze:r;for(var i;e--;)i=n,n=Bn(n);if(!Fe)return n;if(t){if(n?.nodeType!==_u){var o=Dr();return n===null?i?.after(o):n.before(o),qt(o),o}Xh(n)}return qt(n),n}function fp(r){r.textContent=""}function vw(){if(!Ar||Bo!==null)return!1;var r=ke.f;return(r&32768)!==0}function ma(r,e,t){return e==null||e===Bb?t?document.createElement(r,{is:t}):document.createElement(r):t?document.createElementNS(e,r,{is:t}):document.createElementNS(e,r)}function Xh(r){if(r.nodeValue.length<65536)return;let e=r.nextSibling;for(;e!==null&&e.nodeType===_u;)e.remove(),r.nodeValue+=e.nodeValue,e=r.nextSibling}function aM(r){ke===null&&(Le===null&&c$(r),l$()),lo&&a$(r)}function o3(r,e){var t=e.last;t===null?e.last=e.first=r:(t.next=r,r.prev=t,e.last=r)}function ha(r,e){var t=ke;if(ee)for(;t!==null&&(t.f&131072)!==0;)t=t.parent;t!==null&&(t.f&8192)!==0&&(r|=8192);var n={ctx:ut,deps:null,nodes:null,f:r|2048|512,first:null,fn:e,last:null,next:null,parent:t,b:t&&t.b,prev:null,teardown:null,wv:0,ac:null};ee&&(n.component_function=ws),Oe?.register_created_effect(n);var i=n;if((r&4)!==0)Bu!==null?Bu.push(n):ao.ensure().schedule(n);else if(e!==null){try{pa(n)}catch(s){throw wr(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=t,t!==null&&o3(i,t),Le!==null&&(Le.f&2)!==0&&(r&64)===0)){var o=Le;(o.effects??(o.effects=[])).push(i)}return n}function lc(){return Le!==null&&!Ii}function Cn(r){let e=ha(8,null);return Ut(e,1024),e.teardown=r,e}function Xt(r){aM("$effect"),ee&&ni(r,"name",{value:"$effect"});var e=ke.f,t=!Le&&(e&32)!==0&&ut!==null&&!ut.i;if(t){var n=ut;(n.e??(n.e=[])).push(r)}else return b_(r)}function b_(r){return ha(1048580,r)}function j_(r){ao.ensure();let e=ha(524352,r);return()=>{wr(e)}}function lM(r){ao.ensure();let e=ha(524352,r);return(t={})=>new Promise(n=>{t.outro?ua(e,()=>{wr(e),n(void 0)}):(wr(e),n(void 0))})}function Br(r){return ha(4,r)}function z$(r){return ha(4718592,r)}function En(r,e=0){return ha(8|e,r)}function ae(r,e=[],t=[],n=[]){cw(n,e,t,i=>{ha(8,()=>{r(...i.map(h))})})}function ki(r,e=0){var t=ha(16|e,r);return ee&&(t.dev_stack=la),t}function an(r){return ha(524320,r)}function G_(r){var e=r.teardown;if(e!==null){let t=lo,n=Le;W_(!0),on(null);try{e.call(null)}finally{W_(t),on(n)}}}function Hh(r,e=!1){var t=r.first;for(r.first=r.last=null;t!==null;){let i=t.ac;i!==null&&Ro(()=>{i.abort(Xa)});var n=t.next;(t.f&64)!==0?t.parent=null:wr(t,e),t=n}}function cM(r){for(var e=r.first;e!==null;){var t=e.next;(e.f&32)===0&&wr(e),e=t}}function wr(r,e=!0){var t=!1;(e||(r.f&262144)!==0)&&r.nodes!==null&&r.nodes.end!==null&&(uM(r.nodes.start,r.nodes.end),t=!0),r.f|=33554432,Hh(r,e&&!t),Nu(r,0);var n=r.nodes&&r.nodes.t;if(n!==null)for(let o of n)o.stop();G_(r),r.f^=33554432,r.f|=16384;var i=r.parent;i!==null&&i.first!==null&&B_(r),ee&&(r.component_function=null),r.next=r.prev=r.teardown=r.ctx=r.deps=r.fn=r.nodes=r.ac=r.b=null}function uM(r,e){for(;r!==null;){var t=r===e?null:Bn(r);r.remove(),r=t}}function B_(r){var e=r.parent,t=r.prev,n=r.next;t!==null&&(t.next=n),n!==null&&(n.prev=t),e!==null&&(e.first===r&&(e.first=n),e.last===r&&(e.last=t))}function ua(r,e,t=!0){var n=[];dM(r,n,!0);var i=()=>{t&&wr(r),e&&e()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function dM(r,e,t){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||t)&&e.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;dM(i,e,s?t:!1)}i=o}}}function Dp(r){pM(r,!0)}function pM(r,e){if((r.f&8192)!==0){r.f^=8192,(r.f&1024)===0&&(Ut(r,2048),ao.ensure().schedule(r));for(var t=r.first;t!==null;){var n=t.next,i=(t.f&65536)!==0||(t.f&32)!==0;pM(t,i?e:!1),t=n}var o=r.nodes&&r.nodes.t;if(o!==null)for(let s of o)(s.is_global||e)&&s.in()}}function hp(r,e){if(r.nodes)for(var t=r.nodes.start,n=r.nodes.end;t!==null;){var i=t===n?null:Bn(t);e.append(t),t=i}}var fM=null;var yw=!1,lo=!1;function W_(r){lo=r}var Le=null,Ii=!1;function on(r){Le=r}var ke=null;function sn(r){ke=r}var qo=null;function pw(r){Le!==null&&(!Ar||(Le.f&2)!==0)&&(qo??(qo=new Set)).add(r)}var xn=null,Ai=0,co=null;function tM(r){co=r}var mM=1,zu=0,fc=zu;function U_(r){fc=r}function yp(){return++mM}function pc(r){var e=r.f;if((e&2048)!==0)return!0;if(e&2&&(r.f&=-65537),(e&4096)!==0){for(var t=r.deps,n=t.length,i=0;i<n;i++){var o=t[i];if(pc(o)&&F_(o),o.wv>r.wv)return!0}(e&512)!==0&&Tn===null&&Ut(r,1024)}return!1}function hM(r,e,t=!0){var n=r.reactions;if(n!==null&&!(!Ar&&qo!==null&&qo.has(r)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&2)!==0?hM(o,e,!1):e===o&&(t?Ut(o,2048):(o.f&1024)!==0&&Ut(o,4096),Qh(o))}}function dw(r){var v;var e=xn,t=Ai,n=co,i=Le,o=qo,s=ut,a=Ii,l=fc,c=r.f;xn=null,Ai=0,co=null,Le=(c&96)===0?r:null,qo=null,Ja(r.ctx),Ii=!1,fc=++zu,r.ac!==null&&(Ro(()=>{r.ac.abort(Xa)}),r.ac=null);try{r.f|=2097152;var u=r.fn,d=u();r.f|=32768;var f=r.deps,p=Oe?.is_fork;if(xn!==null){var m;if(p||Nu(r,Ai),f!==null&&Ai>0)for(f.length=Ai+xn.length,m=0;m<xn.length;m++)f[Ai+m]=xn[m];else r.deps=f=xn;if(lc()&&(r.f&512)!==0)for(m=Ai;m<f.length;m++)((v=f[m]).reactions??(v.reactions=[])).push(r)}else!p&&f!==null&&Ai<f.length&&(Nu(r,Ai),f.length=Ai);if(Cs()&&co!==null&&!Ii&&f!==null&&(r.f&6146)===0)for(m=0;m<co.length;m++)hM(co[m],r);if(i!==null&&i!==r){if(zu++,i.deps!==null)for(let g=0;g<t;g+=1)i.deps[g].rv=zu;if(e!==null)for(let g of e)g.rv=zu;co!==null&&(n===null?n=co:n.push(...co))}return(r.f&8388608)!==0&&(r.f^=8388608),d}catch(g){return tw(g)}finally{r.f^=2097152,xn=e,Ai=t,co=n,Le=i,qo=o,Ja(s),Ii=a,fc=l}}function s3(r,e){let t=e.reactions;if(t!==null){var n=JP.call(t,r);if(n!==-1){var i=t.length-1;i===0?t=e.reactions=null:(t[n]=t[i],t.pop())}}if(t===null&&(e.f&2)!==0&&(xn===null||!oc.call(xn,e))){var o=e;(o.f&512)!==0&&(o.f^=512,o.f&=-65537),o.v!==Kt&&dp(o),o.ac!==null&&Ro(()=>{o.ac.abort(Xa),o.ac=null,Ut(o,2048)}),U$(o),Nu(o,0)}}function Nu(r,e){var t=r.deps;if(t!==null)for(var n=e;n<t.length;n++)s3(r,t[n])}function pa(r){var e=r.f;if((e&16384)===0){Ut(r,1024);var t=ke,n=yw;if(ke=r,yw=(e&96)===0,ee){var i=ws;ew(r.component_function);var o=la;up(r.dev_stack??la)}try{(e&16777232)!==0?cM(r):Hh(r),G_(r);var s=dw(r);if(r.teardown=typeof s=="function"?s:null,r.wv=mM,ee&&vs&&(r.f&2048)!==0&&r.deps!==null)for(var a of r.deps)a.set_during_effect&&(a.wv=yp(),a.set_during_effect=!1)}finally{yw=n,ke=t,ee&&(ew(i),up(o))}}}async function Ip(){if(Ar)return new Promise(r=>{requestAnimationFrame(()=>r()),setTimeout(()=>r())});await Promise.resolve(),qu()}function h(r){var e=r.f,t=(e&2)!==0;if(fM?.add(r),Le!==null&&!Ii){var n=ke!==null&&(ke.f&16384)!==0;if(!n&&(qo===null||!qo.has(r))){var i=Le.deps;if((Le.f&2097152)!==0)r.rv<zu&&(r.rv=zu,xn===null&&i!==null&&i[Ai]===r?Ai++:xn===null?xn=[r]:xn.push(r));else{Le.deps??(Le.deps=[]),oc.call(Le.deps,r)||Le.deps.push(r);var o=r.reactions;o===null?r.reactions=[Le]:oc.call(o,Le)||o.push(Le)}}}if(ee){if(!Ii&&Ki&&Oe===null&&da===null&&!Ki.warned&&(Ki.effect.f&2097152)===0&&!Ki.effect_deps.has(r)){Ki.warned=!0,b$(r.label);var s=bs("traced at");s&&console.warn(s)}if(Uh.delete(r),vs&&!Ii&&Oh!==null&&Le!==null&&Oh.reaction===Le){if(r.trace)r.trace();else if(s=bs("traced at"),s){var a=Oh.entries.get(r);a===void 0&&(a={traces:[]},Oh.entries.set(r,a));var l=a.traces[a.traces.length-1];s.stack!==l?.stack&&a.traces.push(s)}}}if(lo&&Vo.has(r))return Vo.get(r);if(t){var c=r;if(lo){var u=c.v;return((c.f&1024)===0&&c.reactions!==null||vM(c))&&(u=zh(c)),Vo.set(c,u),u}var d=(c.f&512)===0&&!Ii&&Le!==null&&(yw||(Le.f&512)!==0),f=(c.f&32768)===0;pc(c)&&(d&&(c.f|=512),F_(c)),d&&!f&&(P_(c),gM(c))}if(Tn?.has(r))return Tn.get(r);if((r.f&8388608)!==0)throw r.v;return r.v}function gM(r){if(r.f|=512,r.deps!==null)for(let e of r.deps)(e.reactions??(e.reactions=[])).push(r),(e.f&2)!==0&&(e.f&512)===0&&(P_(e),gM(e))}function vM(r){if(r.v===Kt)return!0;if(r.deps===null)return!1;for(let e of r.deps)if(Vo.has(e)||(e.f&2)!==0&&vM(e))return!0;return!1}function xt(r){var e=Ii;try{return Ii=!0,r()}finally{Ii=e}}function ww(r){if(!(typeof r!="object"||!r||r instanceof EventTarget)){if(Jr in r)bw(r);else if(!Array.isArray(r))for(let e in r){let t=r[e];typeof t=="object"&&t&&Jr in t&&bw(t)}}}function bw(r,e=new Set){if(typeof r=="object"&&r!==null&&!(r instanceof EventTarget)&&!e.has(r)){e.add(r),r instanceof Date&&r.getTime();for(let n in r)try{bw(r[n],e)}catch{}let t=sc(r);if(t!==Object.prototype&&t!==Array.prototype&&t!==Map.prototype&&t!==Set.prototype&&t!==Date.prototype){let n=qb(t);for(let i in n){let o=n[i].get;if(o)try{o.call(r)}catch{}}}}}var Hu=Symbol("events"),Q_=new Set,Cw=new Set;function yM(r,e,t,n={}){function i(o){if(n.capture||Ew.call(e,o),!o.cancelBubble)return Ro(()=>t?.call(this,o))}return r.startsWith("pointer")||r.startsWith("touch")||r==="wheel"?yr(()=>{e.addEventListener(r,i,n)}):e.addEventListener(r,i,n),i}function al(r,e,t,n,i){var o={capture:n,passive:i},s=yM(r,e,t,o);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&Cn(()=>{e.removeEventListener(r,s,o)})}function _e(r,e,t){(e[Hu]??(e[Hu]={}))[r]=t}function nt(r){for(var e=0;e<r.length;e++)Q_.add(r[e]);for(var t of Cw)t(r)}var Y_=null,K_=!1;function Ew(r){var e=this,t=e.ownerDocument,n=r.type,i=r.composedPath?.()||[],o=i[0]||r.target;Y_=r,K_||(K_=!0,setTimeout(()=>{K_=!1,Y_=null}));var s=0,a=Y_===r&&r[Hu];if(a){var l=i.indexOf(a);if(l!==-1&&(e===document||e===window)){r[Hu]=e;return}var c=i.indexOf(e);if(c===-1)return;l<=c&&(s=l)}if(o=i[s]||r.target,o!==e){ni(r,"currentTarget",{configurable:!0,get(){return o||t}});var u=Le,d=ke;on(null),sn(null);try{for(var f,p=[];o!==null&&o!==e;){try{var m=o[Hu]?.[n];m!=null&&(!o.disabled||r.target===o)&&m.call(o,r)}catch(v){f?p.push(v):f=v}if(r.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(f){for(let v of p)queueMicrotask(()=>{throw v});throw f}}finally{r[Hu]=e,delete r.currentTarget,on(u),sn(d)}}}var a3=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:r=>r});function bM(r){return a3?.createHTML(r)??r}function X_(r){var e=ma("template");return e.innerHTML=bM(r.replaceAll("<!>","<!---->")),e.content}function uo(r,e){var t=ke;t.nodes===null&&(t.nodes={start:r,end:e,a:null,t:null})}function V(r,e){var t=(e&1)!==0,n=(e&2)!==0,i,o=!r.startsWith("<!>");return()=>{if(Fe)return uo(ze,null),ze;i===void 0&&(i=X_(o?r:"<!>"+r),t||(i=Vn(i)));var s=n||Lh?document.importNode(i,!0):i.cloneNode(!0);if(t){var a=Vn(s),l=s.lastChild;uo(a,l)}else uo(s,s);return s}}function ga(r=""){if(!Fe){var e=Dr(r+"");return uo(e,e),e}var t=ze;return t.nodeType!==_u?(t.before(t=Dr()),qt(t)):Xh(t),uo(t,t),t}function Vr(){if(Fe)return uo(ze,null),ze;var r=document.createDocumentFragment(),e=document.createComment(""),t=Dr();return r.append(e,t),uo(e,t),r}function O(r,e){if(Fe){var t=ke;((t.f&32768)===0||t.nodes.end===null)&&(t.nodes.end=ze),bn();return}r!==null&&r.before(e)}function Zh(){var r;if(Fe&&ze&&ze.nodeType===io&&ze.textContent?.startsWith("$")){let e=ze.textContent.substring(1);return bn(),e}return(r=window.__svelte??(window.__svelte={})).uid??(r.uid=1),`c${window.__svelte.uid++}`}var f3=["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 nde=[...f3,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"];var m3=["touchstart","touchmove"];function wM(r){return m3.includes(r)}var h3=["$state","$state.raw","$derived","$derived.by"],ide=[...h3,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"];var J_=!0;function ue(r,e){var n;var t=e==null?"":typeof e=="object"?`${e}`:e;t!==(r[n=Fh]??(r[n]=r.nodeValue))&&(r[Fh]=t,r.nodeValue=`${t}`)}function Wu(r,e){return CM(r,e)}function tk(r,e){gw(),e.intro=e.intro??!1;let t=e.target,n=Fe,i=ze;try{for(var o=Vn(t);o&&(o.nodeType!==io||o.data!=="[");)o=Bn(o);if(!o)throw Qa;en(!0),qt(o);let s=CM(r,{...e,anchor:o});return en(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
`).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==Qa&&console.warn("Failed to hydrate: ",s),e.recover===!1&&d$(),gw(),fp(t),en(!1),Wu(r,e)}finally{en(n),qt(i)}}var xw=new Map;function CM(r,{target:e,anchor:t,props:n={},events:i,context:o,intro:s=!0,transformError:a}){gw();var l=void 0,c=lM(()=>{var u=t??e.appendChild(Dr());qh(u,{pending:()=>{}},p=>{fe({});var m=ut;if(o&&(m.c=o),i&&(n.$$events=i),Fe&&uo(p,null),J_=s,l=r(p,n)||{},J_=!0,Fe&&(ke.nodes.end=ze,ze===null||ze.nodeType!==io||ze.data!=="]"))throw ku(),Qa;me()},a);var d=new Set,f=p=>{for(var m=0;m<p.length;m++){var v=p[m];if(!d.has(v)){d.add(v);var g=wM(v);for(let T of[e,document]){var y=xw.get(T);y===void 0&&(y=new Map,xw.set(T,y));var w=y.get(v);w===void 0?(T.addEventListener(v,Ew,{passive:g}),y.set(v,1)):y.set(v,w+1)}}}};return f(ap(Q_)),Cw.add(f),()=>{for(var p of d)for(let g of[e,document]){var m=xw.get(g),v=m.get(p);--v==0?(g.removeEventListener(p,Ew),m.delete(p),m.size===0&&xw.delete(g)):m.set(p,v)}Cw.delete(f),u!==t&&u.parentNode?.removeChild(u)}});return ek.set(l,c),l}var ek=new WeakMap;function Fp(r,e){let t=ek.get(r);return t?(ek.delete(r),t(e)):(ee&&(Jr in r?S$():x$()),Promise.resolve())}var _s,va,po,ju,Jh,eg,Tw,ks=class{constructor(e,t=!0){pe(this,"anchor");Ye(this,_s,new Map);Ye(this,va,new Map);Ye(this,po,new Map);Ye(this,ju,new Set);Ye(this,Jh,!0);Ye(this,eg,e=>{if(z(this,_s).has(e)){var t=z(this,_s).get(e),n=z(this,va).get(t);if(n)Dp(n),z(this,ju).delete(t);else{var i=z(this,po).get(t);i&&(Dp(i.effect),z(this,va).set(t,i.effect),z(this,po).delete(t),ee&&(i.fragment.lastChild[h_]=this.anchor),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),n=i.effect)}for(let[o,s]of z(this,_s)){if(z(this,_s).delete(o),o===e)break;let a=z(this,po).get(s);a&&(wr(a.effect),z(this,po).delete(s))}for(let[o,s]of z(this,va)){if(o===t||z(this,ju).has(o))continue;let a=()=>{if(Array.from(z(this,_s).values()).includes(o)){var c=document.createDocumentFragment();hp(s,c),c.append(Dr()),z(this,po).set(o,{effect:s,fragment:c})}else wr(s);z(this,ju).delete(o),z(this,va).delete(o)};z(this,Jh)||!n?(z(this,ju).add(o),ua(s,a,!1)):a()}}});Ye(this,Tw,e=>{z(this,_s).delete(e);let t=Array.from(z(this,_s).values());for(let[n,i]of z(this,po))t.includes(n)||(wr(i.effect),z(this,po).delete(n))});this.anchor=e,He(this,Jh,t)}ensure(e,t){var n=Oe,i=vw();if(t&&!z(this,va).has(e)&&!z(this,po).has(e))if(i){var o=document.createDocumentFragment(),s=Dr();o.append(s),z(this,po).set(e,{effect:an(()=>t(s)),fragment:o})}else z(this,va).set(e,an(()=>t(this.anchor)));if(z(this,_s).set(n,e),i){for(let[a,l]of z(this,va))a===e?n.unskip_effect(l):n.skip_effect(l);for(let[a,l]of z(this,po))a===e?n.unskip_effect(l.effect):n.skip_effect(l.effect);n.oncommit(z(this,eg)),n.ondiscard(z(this,Tw))}else Fe&&(this.anchor=ze),z(this,eg).call(this,n)}};_s=new WeakMap,va=new WeakMap,po=new WeakMap,ju=new WeakMap,Jh=new WeakMap,eg=new WeakMap,Tw=new WeakMap;function tg(r,e,...t){var n=new ks(r);ki(()=>{let i=e()??null;ee&&i==null&&p$(),n.ensure(i,i&&(o=>i(o,...t)))},65536)}if(ee){let r=function(e){if(!(e in globalThis)){let t;Object.defineProperty(globalThis,e,{configurable:!0,get:()=>{if(t!==void 0)return t;m$(e)},set:n=>{t=n}})}};r("$state"),r("$effect"),r("$derived"),r("$inspect"),r("$props"),r("$bindable")}function Sw(r){ut===null&&Yb("onMount"),Za&&ut.l!==null?y3(ut).m.push(r):Xt(()=>{let e=xt(r);if(typeof e=="function")return e})}function y3(r){var e=r.l;return e.u??(e.u={a:[],b:[],m:[]})}var TM=new Map;function SM(r,e){var t=TM.get(r);t||(t=new Set,TM.set(r,t)),t.add(e)}function X(r,e,t=!1){var n;Fe&&(n=ze,bn());var i=new ks(r),o=t?65536:0;function s(a,l){if(Fe){var c=$h(n);if(a!==parseInt(c.substring(1))){var u=aa();qt(u),i.anchor=u,en(!1),i.ensure(a,l),en(!0);return}}i.ensure(a,l)}ki(()=>{var a=!1;e((l,c=0)=>{a=!0,s(c,l)}),a||s(-1,null)},o)}var E3=Symbol("NaN");function rk(r,e,t){Fe&&bn();var n=new ks(r),i=!Cs();ki(()=>{var o=e();o!==o&&(o=E3),i&&o!==null&&typeof o=="object"&&(o={}),n.ensure(o,t)})}function ig(r,e){return e}function k3(r,e,t){for(var n=[],i=e.length,o,s=e.length,a=0;a<i;a++){let d=e[a];ua(d,()=>{if(o){if(o.pending.delete(d),o.done.add(d),o.pending.size===0){var f=r.outrogroups;nk(r,ap(o.done)),f.delete(o),f.size===0&&(r.outrogroups=null)}}else s-=1},!1)}if(s===0){var l=n.length===0&&t!==null&&r.pending.size===0;if(l){var c=t,u=c.parentNode;fp(u),u.append(c),r.items.clear()}nk(r,e,!l)}else o={pending:new Set(e),done:new Set},(r.outrogroups??(r.outrogroups=new Set)).add(o)}function nk(r,e,t=!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<e.length;i++){var o=e[i];if(n?.has(o)){o.f|=33554432;let s=document.createDocumentFragment();hp(o,s)}else wr(e[i],t)}}var _w;function jt(r,e,t,n,i,o=null){var s=r,a=new Map,l=(e&4)!==0;if(l){var c=r;s=Fe?qt(Vn(c)):c.appendChild(Dr())}Fe&&bn();var u=null,d=Ru(()=>{var T=t();return gs(T)?T:T==null?[]:ap(T)});ee&&ii(d,"{#each ...}");var f,p=new Map,m=!0;function v(T){(w.effect.f&16384)===0&&(w.pending.delete(T),w.fallback=u,A3(w,f,s,e,n),u!==null&&(f.length===0?(u.f&33554432)===0?Dp(u):(u.f^=33554432,ng(u,null,s)):ua(u,()=>{u=null})))}function g(T){w.pending.delete(T)}var y=ki(()=>{f=h(d);var T=f.length;let b=!1;if(Fe){var E=$h(s)==="[!";E!==(T===0)&&(s=aa(),qt(s),en(!1),b=!0)}for(var C=new Set,_=Oe,I=vw(),q=0;q<T;q+=1){Fe&&ze.nodeType===io&&ze.data==="]"&&(s=ze,b=!0,en(!1));var B=f[q],J=n(B,q);if(ee){var re=n(B,q);J!==re&&s$(String(q),String(J),String(re))}var L=m?null:a.get(J);L?(L.v&&Ts(L.v,B),L.i&&Ts(L.i,q),I&&_.unskip_effect(L.e)):(L=D3(a,m?s:_w??(_w=Dr()),B,J,q,i,e,t),m||(L.e.f|=33554432),a.set(J,L)),C.add(J)}if(T===0&&o&&!u&&(m?u=an(()=>o(s)):(u=an(()=>o(_w??(_w=Dr()))),u.f|=33554432)),T>C.size&&(ee?I3(f,n):v_("","","")),Fe&&T>0&&qt(aa()),!m)if(p.set(_,C),I){for(let[W,j]of a)C.has(W)||_.skip_effect(j.e);_.oncommit(v),_.ondiscard(g)}else v(_);b&&en(!0),h(d)}),w={effect:y,flags:e,items:a,pending:p,outrogroups:null,fallback:u};m=!1,Fe&&(s=ze)}function rg(r){for(;r!==null&&(r.f&32)===0;)r=r.next;return r}function A3(r,e,t,n,i){var o=(n&8)!==0,s=e.length,a=r.items,l=rg(r.effect.first),c,u=null,d,f=[],p=[],m,v,g,y;if(o)for(y=0;y<s;y+=1)m=e[y],v=i(m,y),g=a.get(v).e,(g.f&33554432)===0&&(g.nodes?.a?.measure(),(d??(d=new Set)).add(g));for(y=0;y<s;y+=1){if(m=e[y],v=i(m,y),g=a.get(v).e,r.outrogroups!==null)for(let B of r.outrogroups)B.pending.delete(g),B.done.delete(g);if((g.f&8192)!==0&&(Dp(g),o&&(g.nodes?.a?.unfix(),(d??(d=new Set)).delete(g))),(g.f&33554432)!==0)if(g.f^=33554432,g===l)ng(g,null,t);else{var w=u?u.next:l;g===r.effect.last&&(r.effect.last=g.prev),g.prev&&(g.prev.next=g.next),g.next&&(g.next.prev=g.prev),mc(r,u,g),mc(r,g,w),ng(g,w,t),u=g,f=[],p=[],l=rg(u.next);continue}if(g!==l){if(c!==void 0&&c.has(g)){if(f.length<p.length){var T=p[0],b;u=T.prev;var E=f[0],C=f[f.length-1];for(b=0;b<f.length;b+=1)ng(f[b],T,t);for(b=0;b<p.length;b+=1)c.delete(p[b]);mc(r,E.prev,C.next),mc(r,u,E),mc(r,C,T),l=T,u=C,y-=1,f=[],p=[]}else c.delete(g),ng(g,l,t),mc(r,g.prev,g.next),mc(r,g,u===null?r.effect.first:u.next),mc(r,u,g),u=g;continue}for(f=[],p=[];l!==null&&l!==g;)(c??(c=new Set)).add(l),p.push(l),l=rg(l.next);if(l===null)continue}(g.f&33554432)===0&&f.push(g),u=g,l=rg(g.next)}if(r.outrogroups!==null){for(let B of r.outrogroups)B.pending.size===0&&(nk(r,ap(B.done)),r.outrogroups?.delete(B));r.outrogroups.size===0&&(r.outrogroups=null)}if(l!==null||c!==void 0){var _=[];if(c!==void 0)for(g of c)(g.f&8192)===0&&_.push(g);for(;l!==null;)(l.f&8192)===0&&l!==r.fallback&&_.push(l),l=rg(l.next);var I=_.length;if(I>0){var q=(n&4)!==0&&s===0?t:null;if(o){for(y=0;y<I;y+=1)_[y].nodes?.a?.measure();for(y=0;y<I;y+=1)_[y].nodes?.a?.fix()}k3(r,_,q)}}o&&yr(()=>{if(d!==void 0)for(g of d)g.nodes?.a?.apply()})}function D3(r,e,t,n,i,o,s,a){var l=(s&1)!==0?(s&16)===0?Iu(t,!1,!1):ai(t):null,c=(s&2)!==0?ai(i):null;return ee&&l&&(l.trace=()=>{a()[c?.v??i]}),{v:l,i:c,e:an(()=>(o(e,l??t,c??i,a),()=>{r.delete(n)}))}}function ng(r,e,t){if(r.nodes)for(var n=r.nodes.start,i=r.nodes.end,o=e&&(e.f&33554432)===0?e.nodes.start:t;n!==null;){var s=Bn(n);if(o.before(n),n===i)return;n=s}}function mc(r,e,t){e===null?r.effect.first=t:e.next=t,t===null?r.effect.last=e:t.prev=e}function I3(r,e){let t=new Map,n=r.length;for(let i=0;i<n;i++){let o=e(r[i],i);if(t.has(o)){let s=String(t.get(o)),a=String(i),l=String(o);l.startsWith("[object ")&&(l=null),v_(s,a,l)}t.set(o,i)}}var F3=Vb?()=>performance.now():()=>Date.now(),As={tick:r=>(Vb?requestAnimationFrame:At)(r),now:()=>F3(),tasks:new Set};function kM(){let r=As.now();As.tasks.forEach(e=>{e.c(r)||(As.tasks.delete(e),e.f())}),As.tasks.size!==0&&As.tick(kM)}function AM(r){let e;return As.tasks.size===0&&As.tick(kM),{promise:new Promise(t=>{As.tasks.add(e={c:r,f:t})}),abort(){As.tasks.delete(e)}}}function P3(r){if(r==="float")return"cssFloat";if(r==="offset")return"cssOffset";if(r.startsWith("--"))return r;let e=r.split("-");return e.length===1?e[0]:e[0]+e.slice(1).map(t=>t[0].toUpperCase()+t.slice(1)).join("")}function DM(r){let e={},t=r.split(";");for(let n of t){let[i,o]=n.split(":");if(!i||o===void 0)break;let s=P3(i.trim());e[s]=o.trim()}return e}var $3=r=>r,M3=null;function ik(r,e,t){var n=M3??ke,i=n.nodes,o,s,a,l=null;i.a??(i.a={element:r,measure(){o=this.element.getBoundingClientRect()},apply(){if(a?.abort(),s=this.element.getBoundingClientRect(),o.left!==s.left||o.right!==s.right||o.top!==s.top||o.bottom!==s.bottom){let c=e()(this.element,{from:o,to:s},t?.());a=IM(this.element,c,void 0,1,()=>{},()=>{a?.abort(),a=void 0})}},fix(){if(!r.getAnimations().length){var{position:c,width:u,height:d}=getComputedStyle(r);if(c!=="absolute"&&c!=="fixed"){var f=r.style;l={position:f.position,width:f.width,height:f.height,transform:f.transform},f.position="absolute",f.width=u,f.height=d;var p=r.getBoundingClientRect();if(o.left!==p.left||o.top!==p.top){var m=`translate(${o.left-p.left}px, ${o.top-p.top}px)`;f.transform=f.transform?`${f.transform} ${m}`:m}}}},unfix(){if(l){var c=r.style;c.position=l.position,c.width=l.width,c.height=l.height,c.transform=l.transform}}}),i.a.element=r}function IM(r,e,t,n,i,o){var s=n===1;if(m_(e)){var a,l=!1;return yr(()=>{if(!l){var y=e({direction:s?"in":"out"});a=IM(r,y,t,n,i,o)}}),{abort:()=>{l=!0,a?.abort()},deactivate:()=>a.deactivate(),reset:()=>a.reset(),t:()=>a.t()}}if(t?.deactivate(),!e?.duration&&!e?.delay)return i(),o(),{abort:At,deactivate:At,reset:At,t:()=>n};let{delay:c=0,css:u,tick:d,easing:f=$3}=e;var p=[];if(s&&t===void 0&&(d&&d(0,1),u)){var m=DM(u(0,1));p.push(m,m)}var v=()=>1-n,g=r.animate(p,{duration:c,fill:"forwards"});return g.onfinish=()=>{g.cancel(),i();var y=t?.t()??1-n;t?.abort();var w=n-y,T=e.duration*Math.abs(w),b=[];if(T>0){var E=!1;if(u)for(var C=Math.ceil(T/16.666666666666668),_=0;_<=C;_+=1){var I=y+w*f(_/C),q=DM(u(I,1-I));b.push(q),E||(E=q.overflow==="hidden")}E&&(r.style.overflow="hidden"),v=()=>{var B=g.currentTime;return y+w*f(B/T)},d&&AM(()=>{if(g.playState!=="running")return!1;var B=v();return d(B,1-B),!0})}g=r.animate(b,{duration:T,fill:"forwards"}),g.onfinish=()=>{v=()=>n,d?.(n,1-n),o()}},{abort:()=>{g&&(g.cancel(),g.effect=null,g.onfinish=At)},deactivate:()=>{o=At},reset:()=>{n===0&&d?.(1,0)},t:()=>v()}}function Ke(r,e){Br(()=>{r=ke?.parent?.nodes?.start??r;var t=r.getRootNode(),n=t.host?t:t.head??t.ownerDocument.head;if(!n.querySelector("#"+e.hash)){let i=ma("style");i.id=e.hash,i.textContent=e.code,n.appendChild(i),ee&&SM(e.hash,i)}})}function dr(r,e,t){Br(()=>{var n=xt(()=>e(r,t?.())||{});if(t&&n?.update){var i=!1,o={};En(()=>{var s=t();ww(s),i&&Xb(o,s)&&(o=s,n.update(s))}),i=!0}if(n?.destroy)return()=>n.destroy()})}var FM=[...`
\r\f\xA0\v\uFEFF`];function $M(r,e,t){var n=r==null?"":""+r;if(e&&(n=n?n+" "+e:e),t){for(var i of Object.keys(t))if(t[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||FM.includes(n[s-1]))&&(a===n.length||FM.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function PM(r,e=!1){var t=e?" !important;":";",n="";for(var i of Object.keys(r)){var o=r[i];o!=null&&o!==""&&(n+=" "+i+": "+o+t)}return n}function ok(r){return r[0]!=="-"||r[1]!=="-"?r.toLowerCase():r}function MM(r,e){if(e){var t="",n,i;if(Array.isArray(e)?(n=e[0],i=e[1]):n=e,r){r=String(r).replaceAll(/\/\*.*?\*\//g,"").trim();var o=!1,s=0,a=!1,l=[];n&&l.push(...Object.keys(n).map(ok)),i&&l.push(...Object.keys(i).map(ok));var c=0,u=-1;let v=r.length;for(var d=0;d<v;d++){var f=r[d];if(a?f==="/"&&r[d-1]==="*"&&(a=!1):o?o===f&&(o=!1):f==="/"&&r[d+1]==="*"?a=!0:f==='"'||f==="'"?o=f:f==="("?s++:f===")"&&s--,!a&&o===!1&&s===0){if(f===":"&&u===-1)u=d;else if(f===";"||d===v-1){if(u!==-1){var p=ok(r.substring(c,u).trim());if(!l.includes(p)){f!==";"&&d++;var m=r.substring(c,d).trim();t+=" "+m+";"}}c=d+1,u=-1}}}}return n&&(t+=PM(n)),i&&(t+=PM(i,!0)),t=t.trim(),t===""?null:t}return r==null?null:String(r)}function at(r,e,t,n,i,o){var s=r[Dh];if(Fe||s!==t||s===void 0){var a=$M(t,n,o);(!Fe||a!==r.getAttribute("class"))&&(a==null?r.removeAttribute("class"):e?r.className=a:r.setAttribute("class",a)),r[Dh]=t}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 sk(r,e={},t,n){for(var i in t){var o=t[i];e[i]!==o&&(t[i]==null?r.style.removeProperty(i):r.style.setProperty(i,o,n))}}function Pp(r,e,t,n){var i=r[Ih];if(Fe||i!==e){var o=MM(e,n);(!Fe||o!==r.getAttribute("style"))&&(o==null?r.removeAttribute("style"):r.style.cssText=o),r[Ih]=e}else n&&(Array.isArray(n)?(sk(r,t?.[0],n[0]),sk(r,t?.[1],n[1],"important")):sk(r,t,n));return n}function hc(r,e,t=!1){if(r.multiple){if(e==null)return;if(!gs(e))return T$();for(var n of r.options)n.selected=e.includes(og(n));return}for(n of r.options){var i=og(n);if(z_(i,e)){n.selected=!0;return}}(!t||e!==void 0)&&(r.selectedIndex=-1)}function Gu(r){var e=new MutationObserver(()=>{"__value"in r&&hc(r,r.__value)});e.observe(r,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),Cn(()=>{e.disconnect()})}function ak(r,e,t=e){var n=new WeakSet,i=!0;ow(r,"change",o=>{var s=o?"[selected]":":checked",a;if(r.multiple)a=[].map.call(r.querySelectorAll(s),og);else{var l=r.querySelector(s)??r.querySelector("option:not([disabled])");a=l&&og(l)}t(a),r.__value=a,Oe!==null&&n.add(Oe)}),Br(()=>{var o=e();if(r===document.activeElement){var s=Ar?da:Oe;if(n.has(s))return}if(hc(r,o,i),i&&o===void 0){var a=r.querySelector(":checked");a!==null&&(o=og(a),t(o))}r.__value=o,i=!1}),Gu(r)}function og(r){return"__value"in r?r.__value:r.value}var N3=Symbol("is custom element"),B3=Symbol("is html"),V3=Gb?"link":"LINK";var q3=Gb?"progress":"PROGRESS";function Bt(r){if(Fe){var e=!1,t=()=>{if(!e){if(e=!0,r.hasAttribute("value")){var n=r.value;Ce(r,"value",null),r.value=n}if(r.hasAttribute("checked")){var i=r.checked;Ce(r,"checked",null),r.checked=i}}};r[ac]=t,yr(t),iw()}}function Fi(r,e){var t=ck(r);t.value===(t.value=e??void 0)||r.value===e&&(e!==0||r.nodeName!==q3)||(r.value=e??"")}function Yu(r,e){var t=ck(r);t.checked!==(t.checked=e??void 0)&&(r.checked=e)}function Ce(r,e,t,n){var i=ck(r);if(Fe&&(i[e]=r.getAttribute(e),e==="src"||e==="srcset"||e==="href"&&r.nodeName===V3)){n||z3(r,e,t??"");return}i[e]!==(i[e]=t)&&(e==="loading"&&(r[t$]=t),t==null?r.removeAttribute(e):typeof t!="string"&&U3(r).includes(e)?r[e]=t:r.setAttribute(e,t))}function ck(r){var e;return r[e=jb]??(r[e]={[N3]:r.nodeName.includes("-"),[B3]:r.namespaceURI===Bb})}var OM=new Map;function U3(r){var e=r.getAttribute("is")||r.nodeName,t=OM.get(e);if(t)return t;OM.set(e,t=[]);for(var n,i=r,o=Element.prototype;o!==i;){n=qb(i);for(var s in n)n[s].set&&s!=="innerHTML"&&s!=="textContent"&&s!=="innerText"&&t.push(s);i=sc(i)}return t}function z3(r,e,t){ee&&(e==="srcset"&&H3(r,t)||lk(r.getAttribute(e)??"",t)||E$(e,r.outerHTML.replace(r.innerHTML,r.innerHTML&&"..."),String(t)))}function lk(r,e){return r===e?!0:new URL(r,document.baseURI).href===new URL(e,document.baseURI).href}function RM(r){return r.split(",").map(e=>e.trim().split(" ").filter(Boolean))}function H3(r,e){var t=RM(r.srcset),n=RM(e);return n.length===t.length&&n.every(([i,o],s)=>o===t[s][1]&&(lk(t[s][0],i)||lk(i,t[s][0])))}function Pi(r,e,t=e){var n=new WeakSet;ow(r,"input",async i=>{ee&&r.type==="checkbox"&&g_();var o=i?r.defaultValue:r.value;if(o=uk(r)?dk(o):o,t(o),Oe!==null&&n.add(Oe),await Ip(),o!==(o=e())){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))}}}),(Fe&&r.defaultValue!==r.value||xt(e)==null&&r.value)&&(t(uk(r)?dk(r.value):r.value),Oe!==null&&n.add(Oe)),En(()=>{ee&&r.type==="checkbox"&&g_();var i=e();if(r===document.activeElement){var o=Ar?da:Oe;if(n.has(o))return}uk(r)&&i===dk(r.value)||r.type==="date"&&!i&&!r.value||i!==r.value&&(r.value=i??"")})}function uk(r){var e=r.type;return e==="number"||e==="range"}function dk(r){return r===""?null:+r}function pk(r,e){return r===e||r?.[Jr]===e}function ll(r={},e,t,n){var i=ut.r,o=ke;return Br(()=>{var s,a;return En(()=>{s=a,a=n?.()||[],xt(()=>{pk(t(...a),r)||(e(r,...a),s&&pk(t(...s),r)&&e(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;let c=()=>{a&&pk(t(...a),r)&&e(null,...a)},u=l.teardown;l.teardown=()=>{c(),u?.()}}}),r}function le(r,e,t,n){var i=!Za||(t&2)!==0,o=(t&8)!==0,s=(t&16)!==0,a=n,l=!0,c=void 0,u=()=>s&&i?(c??(c=uc(n)),h(c)):(l&&(l=!1,a=s?xt(n):n),a);let d;if(o){var f=Jr in r||Ah in r;d=Hi(r,e)?.set??(f&&e in r?b=>r[e]=b:void 0)}var p,m=!1;o?[p,m]=C_(()=>r[e]):p=r[e],p===void 0&&n!==void 0&&(p=u(),d&&(i&&f$(e),d(p)));var v;if(i?v=()=>{var b=r[e];return b===void 0?u():(l=!0,b)}:v=()=>{var b=r[e];return b!==void 0&&(a=void 0),b===void 0?a:b},i&&(t&4)===0)return v;if(d){var g=r.$$legacy;return(function(b,E){return arguments.length>0?((!i||!E||g||m)&&d(E?v():b),b):v()})}var y=!1,w=((t&1)!==0?uc:Ru)(()=>(y=!1,v()));ee&&(w.label=e),o&&h(w);var T=ke;return(function(b,E){if(arguments.length>0){let C=E?h(w):i&&o?st(b):b;return Q(w,C),y=!0,a!==void 0&&(a=C),b}return lo&&y||(T.f&16384)!==0?w.v:h(w)})}function NM(r){return new mk(r)}var cl,Uo,mk=class{constructor(e){Ye(this,cl);Ye(this,Uo);var t=new Map,n=(o,s)=>{var a=Iu(s,!1,!1);return t.set(o,a),a};let i=new Proxy({...e.props||{},$$events:{}},{get(o,s){return h(t.get(s)??n(s,Reflect.get(o,s)))},has(o,s){return s===Ah?!0:(h(t.get(s)??n(s,Reflect.get(o,s))),Reflect.has(o,s))},set(o,s,a){return Q(t.get(s)??n(s,a),a),Reflect.set(o,s,a)}});He(this,Uo,(e.hydrate?tk:Wu)(e.component,{target:e.target,anchor:e.anchor,props:i,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError})),!Ar&&(!e?.props?.$$host||e.sync===!1)&&qu(),He(this,cl,i.$$events);for(let o of Object.keys(z(this,Uo)))o==="$set"||o==="$destroy"||o==="$on"||ni(this,o,{get(){return z(this,Uo)[o]},set(s){z(this,Uo)[o]=s},enumerable:!0});z(this,Uo).$set=o=>{Object.assign(i,o)},z(this,Uo).$destroy=()=>{Fp(z(this,Uo))}}$set(e){z(this,Uo).$set(e)}$on(e,t){z(this,cl)[e]=z(this,cl)[e]||[];let n=(...i)=>t.call(this,...i);return z(this,cl)[e].push(n),()=>{z(this,cl)[e]=z(this,cl)[e].filter(i=>i!==n)}}$destroy(){z(this,Uo).$destroy()}};cl=new WeakMap,Uo=new WeakMap;var nj;typeof HTMLElement=="function"&&(nj=class extends HTMLElement{constructor(e,t,n){super();pe(this,"$$ctor");pe(this,"$$s");pe(this,"$$c");pe(this,"$$cn",!1);pe(this,"$$d",{});pe(this,"$$r",!1);pe(this,"$$p_d",{});pe(this,"$$l",{});pe(this,"$$l_u",new Map);pe(this,"$$me");pe(this,"$$shadowRoot",null);this.$$ctor=e,this.$$s=t,n&&(this.$$shadowRoot=this.attachShadow(n))}addEventListener(e,t,n){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){let i=this.$$c.$on(e,t);this.$$l_u.set(t,i)}super.addEventListener(e,t,n)}removeEventListener(e,t,n){if(super.removeEventListener(e,t,n),this.$$c){let i=this.$$l_u.get(t);i&&(i(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(i){return o=>{let s=ma("slot");i!=="default"&&(s.name=i),O(o,s)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let t={},n=ij(this);for(let i of this.$$s)i in n&&(i==="default"&&!this.$$d.children?(this.$$d.children=e(i),t.default=!0):t[i]=e(i));for(let i of this.attributes){let o=this.$$g_p(i.name);o in this.$$d||(this.$$d[o]=hk(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=NM({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=j_(()=>{En(()=>{this.$$r=!0;for(let i of p_(this.$$c)){if(!this.$$p_d[i]?.reflect)continue;this.$$d[i]=this.$$c[i];let o=hk(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(e,t,n){this.$$r||(e=this.$$g_p(e),this.$$d[e]=hk(e,n,this.$$p_d,"toProp"),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return p_(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function hk(r,e,t,n){let i=t[r]?.type;if(e=i==="Boolean"&&typeof e!="boolean"?e!=null:e,!n||!t[r])return e;if(n==="toAttribute")switch(i){case"Object":case"Array":return e==null?null:JSON.stringify(e);case"Boolean":return e?"":null;case"Number":return e??null;default:return e}else switch(i){case"Object":case"Array":return e&&JSON.parse(e);case"Boolean":return e;case"Number":return e!=null?+e:e;default:return e}}function ij(r){let e={};return r.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}var km=require("obsidian");ht();De();var HB=require("obsidian");Je();var pg={location:"tab",direction:"vertical",mode:"default",focus:!0};function qr(r,e){if(!(e?.fillMissingOnly??!0))return{...pg,...r??{}};let n={...r??{}};return n.location==null&&(n.location=pg.location),n.direction==null&&(n.direction=pg.direction),n.mode==null&&(n.mode=pg.mode),n.focus==null&&(n.focus=pg.focus),n}rr();var CO=require("obsidian"),fj=V('<span class="quickadd-icon svelte-1fiwm9k"></span>'),mj={hash:"svelte-1fiwm9k",code:".quickadd-icon.svelte-1fiwm9k {display:inline-flex;align-items:center;}.quickadd-icon.svelte-1fiwm9k svg {display:inline-block;vertical-align:middle;}"};function bt(r,e){fe(e,!0),Ke(r,mj);let t=le(e,"size",3,16),n=Ee(void 0);Xt(()=>{if(!h(n)||!e.iconId)return;(0,CO.setIcon)(h(n),e.iconId);let o=h(n).querySelector("svg");o&&(o.setAttribute("width",`${t()}`),o.setAttribute("height",`${t()}`))});var i=fj();ll(i,o=>Q(n,o),()=>h(n)),O(r,i),me()}var hj=V('<pre class="qaMountFailedDetail svelte-bhgeqn"> </pre>'),gj=V(`<div class="qaMountFailed svelte-bhgeqn"><div class="qaMountFailedHead svelte-bhgeqn"><!> <span class="qaMountFailedTitle svelte-bhgeqn"> </span></div> <p class="qaMountFailedBody svelte-bhgeqn">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>`),vj={hash:"svelte-bhgeqn",code:".qaMountFailed.svelte-bhgeqn {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-bhgeqn {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaMountFailedTitle.svelte-bhgeqn {font-weight:var(--font-semibold);color:var(--text-normal);}.qaMountFailedBody.svelte-bhgeqn {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}.qaMountFailedDetail.svelte-bhgeqn {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 kk(r,e){Ke(r,vj);let t=le(e,"detail",3,"");var n=gj(),i=F(n),o=F(i);bt(o,{iconId:"alert-triangle",size:16});var s=S(o,2),a=F(s);D(s),D(i);var l=S(i,4);{var c=u=>{var d=hj(),f=F(d,!0);D(d),ae(()=>ue(f,t())),O(u,d)};X(l,u=>{t()&&u(c)})}D(n),ae(()=>ue(a,`QuickAdd couldn't display ${e.what??""}`)),O(r,n)}var yj="this part of QuickAdd";function ci(r,e,t,n={}){let i=new Set(r.childNodes),o;try{o=Wu(e,{target:r,props:t})}catch(a){return bj(r,i,Ju(a),n)}let s=!1;return{ok:!0,destroy(){s||(s=!0,Fp(o))}}}function bj(r,e,t,n){let i=n.what??yj;for(let l of Array.from(r.childNodes))e.has(l)||l.remove();We(t,`Couldn't display ${i}`);let o=r.ownerDocument.createElement("div");o.className="qa-mount-failed-host",r.appendChild(o);let s=null;try{s=Wu(n.fallbackComponent??kk,{target:o,props:{what:i,detail:t.message}})}catch{o.textContent=`QuickAdd couldn't display ${i}.`}let a=!1;return{ok:!1,destroy(){a||(a=!0,s&&Fp(s),o.remove())}}}var EO=require("obsidian");Je();function Bp(r){return r.trim().replace(/^\/+/,"")}function Cc(r){return r.trim().toLowerCase().endsWith(".canvas")}function Dk(r,e){let t=Bp(e);if(!t||t.includes("{{"))return null;let n=r.vault.getAbstractFileByPath(t);return!n||!(n instanceof EO.TFile)||n.extension!=="canvas"?null:n}function xO(r,e){let n=r.workspace.getMostRecentLeaf?.()?.view;if(!n||n.getViewType?.()!=="canvas")return null;let i=Bp(e),o=Bp(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 wj(r){return typeof r=="string"?r:r&&typeof r=="object"&&"path"in r&&typeof r.path=="string"?r.path:"(missing file path)"}function Cj(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 Ak(r,e){return r.length<=e?r:r.slice(0,e-1)+"\u2026"}async function TO(r,e){try{let t=await r.vault.cachedRead(e),n=JSON.parse(t);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=Cj(a);if(l==="text"){let m=(typeof a.text=="string"?a.text:"").split(`
`).map(w=>w.trim()).filter(w=>w.length>0),v=Ak(m[0]??"(empty text card)",90),g=[`${m.length} line${m.length===1?"":"s"}`];c&&g.push(c);let y=g.join(" \xB7 ");return{id:a.id,type:l,title:v,subtitle:y,searchText:`${a.id} ${v} ${y}`.toLowerCase(),capturable:!0,capturableReason:""}}if(l==="file"){let p=wj(a.file),m=Ht.test(p),v=m?"":"Canvas file cards must link to markdown files (.md).",g=Ak(p.split("/").pop()??p,90),y=[Ak(p,120)];c&&y.push(c),m||y.push("Not capturable in this version");let w=y.join(" \xB7 ");return{id:a.id,type:l,title:g,subtitle:w,searchText:`${a.id} ${g} ${w}`.toLowerCase(),capturable:m,capturableReason:v}}let d=`Unsupported node (${typeof a.type=="string"&&a.type.length>0?a.type:"unknown"})`,f=c||"Type is not currently capturable";return{id:a.id,type:l,title:d,subtitle:f,searchText:`${a.id} ${d} ${f}`.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[]}}Dt();function _c(r){return/\{\{[^}]*\}\}/.test(r)}Ca();Qi();It();Je();var n4=["noteContent","captureTarget","fileName","lineTarget"],i4=["captureTarget","fileName"],Hn=n4,eL=3;function Be(r,e,t=r.endsWith(":}}")?2:0){return{insert:r,description:e,caretOffset:t}}var o4=[{regex:XM,contexts:Hn,suggestion:Be("{{VALUE}}","Asks you for text when the choice runs")},{regex:ZM,contexts:Hn,suggestion:Be("{{VALUE:}}","Asks once and reuses the answer by name, or lists options to pick from"),expansions:()=>[Be("{{VALUE:title}}",'Asks once, then reuses the answer as "title"'),Be("{{VALUE:option1,option2,option3}}","Asks you to pick one of these options"),Be("{{VALUE:option1,option2,option3|custom}}","Same, but you can also type your own"),Be("{{VALUE:title|label:Note title}}","Words the prompt yourself"),Be("{{VALUE:option1,option2|label:Pick one}}","A list with your own prompt text"),Be("{{VALUE:title|label:Note title|default:Untitled}}","Opens the prompt with an answer already filled in"),Be("{{VALUE:<items>|text:<display items>}}","Shows one label in the list and inserts another"),Be("{{VALUE:option1,option2|name:category}}","Names the pick, so {{VALUE:category}} reuses it"),Be("{{VALUE:title|case:kebab}}","Reshapes the answer; type |case: for every style"),Be("{{VALUE:title|trim}}","Trims whitespace off the answer"),Be("{{VALUE:title|optional}}","Lets the prompt be skipped, leaving it empty")]},{regex:QM,contexts:Hn,suggestion:Be("{{NAME}}","Another name for {{VALUE}}; they do the same thing")},{regex:JM,contexts:Hn,suggestion:Be("{{VDATE:}}",'Asks you for a date; "tomorrow" works'),expansions:()=>[Be("{{VDATE:date,YYYY-MM-DD}}",'Asks for a date, reused by name as "date"'),Be("{{VDATE:date,YYYY-MM-DD|today}}","Same, with today filled in"),Be("{{VDATE:dueDate,YYYY-MM-DD|next monday}}","Same, starting at next Monday"),Be("{{VDATE:dueDate,YYYY-MM-DD|optional}}","Same, but skippable"),Be("{{VDATE:date,dddd, MMMM Do, YYYY|case:lower}}","Lowercases the picked date after formatting")]},{regex:oO,contexts:Hn,suggestion:Be("{{FIELD:}}","Suggests values a property already has in your vault, like {{FIELD:project}}")},{regex:iO,contexts:Hn,suggestion:Be("{{FILE:}}","Picks a note from a folder"),expansions:({context:r})=>{let e=[Be("{{FILE:<folder>}}","Picks a note from that folder and inserts its name")];return i4.includes(r)||e.push(Be("{{FILE:<folder>|link}}","Same, but inserts a link to the note"),Be("{{FILE:<folder>|path}}","Same, but inserts its full path"),Be("{{FILE:<folder>|optional}}","Same, but skippable")),e.push(Be("{{FILE:<folder>|custom}}","Same, but you can also type a name that is not there yet")),e}},{regex:lO,contexts:Hn,suggestion:Be("{{MVALUE}}","Asks you for a math formula (LaTeX), with a live preview")},{regex:YM,contexts:Hn,suggestion:Be("{{DATE}}","Today's date, as YYYY-MM-DD")},{regex:KM,contexts:Hn,suggestion:Be("{{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(e=>Be(`{{DATE:${e}}}`,r(e))),Be("{{DATE+7}}","Seven days from today"),Be("{{DATE:YYYY-MM-DD|startof:week}}","Snapped to the start of the week, month, quarter or year"),Be("{{DATE:dddd, MMMM Do, YYYY|case:lower}}","Lowercases the formatted date")]},{regex:mO,contexts:Hn,suggestion:Be("{{TIME}}","The current time, as HH:mm")},{regex:hO,contexts:Hn,suggestion:Be("{{TIME:}}","The current time in a format you choose, like {{TIME:HH.mm}}"),expansions:()=>[Be("{{TIME:A|case:lower}}","Lowercases formatted text, such as AM to am")]},{regex:eO,contexts:["noteContent","lineTarget"],suggestion:Be("{{LINKCURRENT}}","A link to that note: [[That note]]")},{regex:tO,contexts:["noteContent","lineTarget"],suggestion:Be("{{LINKSECTION}}","A link to the section your cursor is in")},{regex:rO,contexts:["noteContent","captureTarget","fileName","lineTarget"],suggestion:Be("{{FILENAMECURRENT}}","That note's file name")},{regex:Sk,contexts:["noteContent","captureTarget"],suggestion:Be("{{FOLDERCURRENT}}","That note's folder")},{regex:Sk,contexts:["fileName"],suggestion:Be("{{FOLDERCURRENT|name}}","That note's folder name, without the path")},{regex:uO,contexts:Hn,suggestion:Be("{{SELECTED}}","The text you had selected in the editor")},{regex:cO,contexts:["noteContent","lineTarget"],suggestion:Be("{{TITLE}}","The new note's file name")},{regex:nO,contexts:["fileName"],suggestion:Be("{{FOLDER|name}}","The name of the folder the new note lands in")},{regex:dO,contexts:Hn,suggestion:Be("{{CLIPBOARD}}","Whatever you copied last")},{regex:sO,contexts:Hn,suggestion:Be("{{TEMPLATE:}}","The contents of a template file"),expansions:({templatePaths:r})=>r.map(e=>Be(`{{TEMPLATE:${e}}}`,"Inserts this template's contents"))},{regex:aO,contexts:Hn,suggestion:Be("{{MACRO:}}","Whatever a macro returns"),expansions:({macroNames:r})=>[...r.map(e=>Be(`{{MACRO:${e}}}`,`Runs your "${e}" macro`)),Be("{{MACRO:MyMacro|label:Label}}","Word the macro's own prompt yourself")]},{regex:fO,contexts:Hn,suggestion:Be("{{GLOBAL_VAR:}}","A snippet you defined in QuickAdd's settings"),expansions:({globalVariableNames:r})=>r.map(e=>Be(`{{GLOBAL_VAR:${e}}}`,`Inserts your "${e}" snippet`))},{regex:pO,contexts:Hn,suggestion:Be("{{RANDOM:}}","A random ID of the length you give, like {{RANDOM:6}}")}],tL=[{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 rL(r){return o4.filter(e=>e.contexts.includes(r))}var s4=/^\{\{(VALUE|NAME|DATE|TIME|VDATE)([^\n\r}]*)\|case:([a-z-]*)$/i,a4=new Set(["DATE","TIME","VDATE"]),l4=/<[^<>\n\r]+>/,pi=class extends Hr{constructor(t,n,i,o="noteContent"){super(t,n);this.app=t;this.inputEl=n;this.plugin=i;this.context=o;this.replaceFrom=0;this.matchedQuery="";this.macroNames=dn(this.plugin.settings.choices).filter(s=>s.type==="Macro").map(s=>s.name),this.templatePaths=this.plugin.getTemplateFiles().map(s=>s.path)}getSuggestions(t){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=t.lastIndexOf("{{",n-1);if(i===-1)return[];let o=t.slice(i,n);if(o.includes("}}"))return[];let s=o.match(s4);if(s){let m=s[1]?.toUpperCase()??"",v=s[2]??"";if(a4.has(m)&&v.lastIndexOf("[")>v.lastIndexOf("]"))return[];let g=s[3]??"";this.matchedQuery=g,this.replaceFrom=n-g.length;let y=g.toLowerCase();return tL.filter(w=>w.insert.startsWith(y)).map(w=>({...w}))}if(o.includes(":"))return[];let a=[],l=new Set,c=m=>{l.has(m.insert)||(l.add(m.insert),a.push(m))};this.replaceFrom=i,this.matchedQuery=o.slice(2);let u=rL(this.context).filter(m=>{let v=m.regex.exec(o);return v!==null&&v.index+v[0].length===o.length}),d=this.matchedQuery.toLowerCase(),f=m=>m.suggestion.insert.slice(2).toLowerCase().startsWith(d),p=[...u.filter(f),...u.filter(m=>!f(m))];for(let m of p)if(c(m.suggestion),!!m.expansions&&!(this.matchedQuery.length<eL))for(let v of m.expansions({templatePaths:this.templatePaths,macroNames:this.macroNames,globalVariableNames:Object.keys(this.plugin?.settings?.globalVariables??{}),context:this.context,formatDate:g=>typeof window.moment=="function"?window.moment().format(g):g}))c(v);return a}selectSuggestion(t){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.replaceFrom;vC(this.inputEl,i,n,t.insert,{fromCompletion:!0});let o=l4.exec(t.insert);if(o){let s=i+o.index;this.inputEl.setSelectionRange(s,s+o[0].length)}else if(t.caretOffset>0){let s=i+t.insert.length-t.caretOffset;this.inputEl.setSelectionRange(s,s)}this.close()}renderSuggestion(t,n){if(!t)return;n.classList.add("qa-format-suggestion");let i=n.ownerDocument.createElement("span");i.className=t.isFragment?"qa-format-suggestion-token qa-format-suggestion-token-fragment":"qa-format-suggestion-token",this.renderMatch(i,t.insert,this.matchedQuery),n.appendChild(i);let o=n.ownerDocument.createElement("span");o.className="qa-format-suggestion-description",o.textContent=t.description,n.appendChild(o)}};var c4=V('<label class="setting-item-name"> </label>'),u4=V('<div class="setting-item-name"> </div>'),d4=V('<div class="setting-item-description"> </div>'),p4=V('<div><div class="setting-item-info"><!> <!></div> <div class="setting-item-control"><!></div></div>');function Se(r,e){let t=le(e,"name",3,void 0),n=le(e,"desc",3,void 0),i=le(e,"heading",3,!1),o=le(e,"labelFor",3,void 0),s=le(e,"control",3,void 0),a=le(e,"children",3,void 0);var l=p4();let c;var u=F(l),d=F(u);{var f=y=>{var w=Vr(),T=Te(w);{var b=C=>{var _=c4(),I=F(_,!0);D(_),ae(()=>{Ce(_,"for",o()),ue(I,t())}),O(C,_)},E=C=>{var _=u4(),I=F(_,!0);D(_),ae(()=>ue(I,t())),O(C,_)};X(T,C=>{o()?C(b):C(E,-1)})}O(y,w)};X(d,y=>{t()&&y(f)})}var p=S(d,2);{var m=y=>{var w=d4(),T=F(w,!0);D(w),ae(()=>ue(T,n())),O(y,w)};X(p,y=>{n()&&y(m)})}D(u);var v=S(u,2),g=F(v);tg(g,()=>s()??a()??At),D(v),D(l),ae(()=>c=at(l,1,"setting-item",null,c,{"setting-item-heading":i()})),O(r,l)}var f4=V('<div role="switch"><input type="checkbox" tabindex="-1" aria-hidden="true" class="svelte-1bigjf0"/></div>'),m4={hash:"svelte-1bigjf0",code:`
/* Let clicks fall through to the container so a single handler owns toggling. */.checkbox-container.svelte-1bigjf0 > input:where(.svelte-1bigjf0) {pointer-events:none;}`};function Ot(r,e){fe(e,!0),Ke(r,m4);let t=le(e,"checked",15),n=le(e,"disabled",3,!1),i=le(e,"ariaLabel",3,void 0),o=le(e,"onchange",3,void 0),s=M(()=>t()??!1);function a(){n()||(t(!h(s)),o()?.(t()))}function l(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),a())}var c=f4();let u;var d=F(c);Bt(d),D(c),ae(()=>{u=at(c,1,"checkbox-container svelte-1bigjf0",null,u,{"is-enabled":h(s),"is-disabled":n()}),Ce(c,"aria-checked",h(s)),Ce(c,"aria-label",i()),Ce(c,"tabindex",n()?-1:0),Yu(d,h(s))}),_e("click",c,a),_e("keydown",c,l),O(r,c),me()}nt(["click","keydown"]);var h4=V("<option> </option>"),g4=V('<select class="dropdown"></select>');function wt(r,e){fe(e,!0);let t=le(e,"value",15,""),n=le(e,"disabled",3,!1),i=le(e,"ariaLabel",3,void 0),o=le(e,"onchange",3,void 0);var s=g4();jt(s,21,()=>e.options,a=>a.value,(a,l)=>{var c=h4(),u=F(c,!0);D(c);var d={};ae(()=>{ue(u,h(l).label),d!==(d=h(l).value)&&(c.value=(c.__value=h(l).value)??"")}),O(a,c)}),D(s),ae(()=>{s.disabled=n(),Ce(s,"aria-label",i())}),_e("change",s,()=>o()?.(t())),ak(s,t),O(r,s),me()}nt(["change"]);Ns();De();rr();function hf(r){return r==="Multi"?"folder":"choice"}function KL(r){return r==="Multi"?"Folder":"Choice"}function UY(r){return`${KL(r)} name`}async function KC(r,e,t){try{let i=(await sr.Prompt(r,UY(t),void 0,e)).trim();return!i||i===e?null:i}catch(n){return pt(n)||P.logError(Ju(n,"Could not rename")),null}}var zY=V('<h2 class="choiceNameHeader"><button type="button" class="choiceNameHeaderButton qa-rename-title-button"><span class="choiceNameHeaderText"> </span> <span class="choiceNameHeaderIcon" aria-hidden="true"><!></span></button></h2>');function Zg(r,e){fe(e,!0);let t=le(e,"name",15);async function n(){let u=await KC(e.app,t());u&&t(u)}var i=zY(),o=F(i),s=F(o),a=F(s,!0);D(s);var l=S(s,2),c=F(l);bt(c,{iconId:"pencil",size:16}),D(l),D(o),D(i),ae(()=>{Ce(o,"aria-label",`Rename ${t()}`),ue(a,t())}),_e("click",o,n),O(r,i),me()}nt(["click"]);Ca();Qi();var An=class extends Hr{constructor(t,n,i,o=1/0){super(t,n);this.app=t;this.inputEl=n;this.items=i;this.maxSuggestions=o;this.items=i.map(s=>zr(s))}getSuggestions(t){let n=xl(t).toLowerCase(),i=this.items.filter(s=>s.toLowerCase().includes(n));return i.length===0&&this.close(),i.slice(0,this.maxSuggestions)}selectSuggestion(t){this.inputEl.value=t,this.inputEl.trigger("input"),this.close()}renderSuggestion(t,n){if(!t)return;let i=$g(t),o=$g(this.getCurrentQuery());t.toLowerCase().endsWith(".md")&&o.toLowerCase().startsWith(`${i.toLowerCase()}.`)&&(o=i),this.renderMatch(n,i,o)}getCurrentQuery(){return this.inputEl.value}};function HY(r){return r?Array.isArray(r)?r:[r]:[]}function Td(r,e){let t=HY(e(r));return{destroy(){t.forEach(n=>n.destroy())}}}var WY=V("<textarea></textarea>"),jY=V('<input type="text"/>'),GY=V('<!> <div aria-live="polite"> </div>',1);function jn(r,e){fe(e,!0);let t=le(e,"value",15,""),n=le(e,"placeholder",3,void 0),i=le(e,"inputKind",3,"text"),o=le(e,"required",3,!1),s=le(e,"requiredMessage",3,"This field is required"),a=le(e,"disabled",3,!1),l=le(e,"validator",3,void 0),c=le(e,"trim",3,!0),u=le(e,"suggestions",3,void 0),d=le(e,"maxSuggestions",3,1/0),f=le(e,"makeSuggesters",19,()=>[]),p=le(e,"app",3,void 0),m=le(e,"id",3,void 0),v=le(e,"ariaLabel",3,void 0),g=le(e,"onChange",3,void 0),y=Ee(!1),w=Ee(""),T=Ee("neutral"),b=0,E=!1,C=`qa-hint-${Math.random().toString(36).slice(2)}`,_=H=>c()?H.trim():H;function I(H,Y=!1,ie="neutral"){Q(y,Y,!0),Q(w,H??"",!0),Q(T,Y?"neutral":ie,!0)}async function q(H){if(o()&&_(H).length===0)return I(s(),!0),!1;if(!l())return I(void 0),!0;let Y=++b,ie=await Promise.resolve(l()(H));return Y!==b||E?!0:typeof ie=="boolean"?(I(ie?void 0:"Invalid value",!ie),ie):typeof ie=="string"?(I(ie,!0),!1):(I(ie.message??(ie.valid?void 0:"Invalid value"),!ie.valid,ie.valid?ie.variant??"neutral":"neutral"),ie.valid)}function B(H){let Y=H.currentTarget.value;t(Y),g()?.(Y)}Xt(()=>{o();let H=t();q(H)}),Xt(()=>()=>{E=!0});function J(H){let Y=[];p()&&u()&&u().length&&Y.push(new An(p(),H,u(),d()));for(let ie of f()){let oe=ie(H);oe&&Y.push(oe)}return Y}var re=GY(),L=Te(re);{var W=H=>{var Y=WY();Pu(Y);let ie;dr(Y,(oe,ce)=>Td?.(oe,ce),()=>J),ae(()=>{ie=at(Y,1,"qa-validated-input-full-width qa-validated-input-margin-8 qa-validated-input-textarea",null,ie,{"is-invalid":h(y),"is-valid":!h(y)&&h(T)==="success"&&h(w).length>0}),Ce(Y,"id",m()),Ce(Y,"placeholder",n()),Y.disabled=a(),Ce(Y,"aria-label",v()),Ce(Y,"aria-invalid",h(y)),Ce(Y,"aria-describedby",C),Fi(Y,t())}),_e("input",Y,B),O(H,Y)},j=H=>{var Y=jY();Bt(Y);let ie;dr(Y,(oe,ce)=>Td?.(oe,ce),()=>J),ae(()=>{ie=at(Y,1,"qa-validated-input-full-width qa-validated-input-margin-8",null,ie,{"is-invalid":h(y),"is-valid":!h(y)&&h(T)==="success"&&h(w).length>0}),Ce(Y,"id",m()),Ce(Y,"placeholder",n()),Y.disabled=a(),Ce(Y,"aria-label",v()),Ce(Y,"aria-invalid",h(y)),Ce(Y,"aria-describedby",C),Fi(Y,t())}),_e("input",Y,B),O(H,Y)};X(L,H=>{i()==="textarea"?H(W):H(j,-1)})}var $=S(L,2);let G;var U=F($,!0);D($),ae(()=>{G=at($,1,"qa-field-hint",null,G,{"qa-field-hint--neutral":!h(y)&&h(T)==="neutral","qa-field-hint--success":!h(y)&&h(T)==="success"}),Ce($,"id",C),ue(U,h(w))}),O(r,re),me()}nt(["input"]);var YY=V('<div class="qa-field-body"><!></div>'),KY=V('<div class="qa-field"><!> <!></div>');function Co(r,e){let t=Zh(),n=le(e,"desc",3,void 0),i=le(e,"control",3,void 0),o=le(e,"bodyVisible",3,!0);var s=KY(),a=F(s);{let u=M(()=>o()?t:void 0);Se(a,{get name(){return e.name},get desc(){return n()},get control(){return i()},get labelFor(){return h(u)}})}var l=S(a,2);{var c=u=>{var d=YY(),f=F(d);tg(f,()=>e.children,()=>t),D(d),O(u,d)};X(l,u=>{o()&&u(c)})}D(s),O(r,s)}bf();rr();var Hc=class{constructor(){this.entries=[];this.seen=new Set}add(e,t,n){let i=I8(t).trim();if(!i)return;let o=`${e} ${i}`;this.seen.has(o)||(this.seen.add(o),this.entries.push({severity:e,message:i,...n?{kind:n}:{}}))}list(){return this.entries}get hasError(){return this.entries.some(e=>e.severity==="error")}};function I8(r){return r.replace(/^\[(QuickAdd:[\s\S]*)\]$/i,"$1").replace(/^QuickAdd:\s*/i,"")}function wf(r){if(pt(r))return null;if(!(r instanceof Error))return xN;let e=r.message??"";return pt(e)?null:e.startsWith("Unable to parse variable")?"This token is incomplete. {{VALUE:}} needs a name, for example {{VALUE:title}}.":e.trim()?e:xN}var xN="Preview unavailable - this format could not be resolved.";Xw();Je();Dd();Aa();var tK={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"},rK={clipboard:"clipboard_content",date:"formatted_date",time:"current_time",random:"random_value",uuid:"unique_id"},nK=[{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 vE(r){let e=r.toLowerCase(),t=tK[e];return t||`${r}_example`}function yE(r){return rK[r.toLowerCase()]||`${r}_output`}function bE(r){for(let{pattern:e,example:t}of nK)if(e.test(r))return t;return`${r}_value`}function wE(r){return r.length>0?`${r[0]} (${r.length} options)`:"suggestion_list"}function Af(r,e){return Id(r).length>0?e:r}function CE(r){let e=r.fieldName.trim();return e?`${e}_field_value`:"field_value"}function EE(r){return r?.path?r.basename:"current_file"}function Df(r){return`${r?.path?r.basename:"current_file"}#Section`}function xE(r){return r?.basename||"current_filename"}function TE(r){if(!r)return"current_folder";let e=r.parent?.path??"";return e==="/"?"":e}var Da=class{static generate(e,t=new Date){let n=t.getFullYear(),i=this.getWeekNumber(t),o=t.getDate(),s=[["YYYY",n.toString()],["YY",n.toString().slice(-2)],["MMMM",this.MONTH_NAMES[t.getMonth()]],["MMM",this.MONTH_NAMES_SHORT[t.getMonth()]],["MM",(t.getMonth()+1).toString().padStart(2,"0")],["M",(t.getMonth()+1).toString()],["dddd",this.DAY_NAMES[t.getDay()]],["ddd",this.DAY_NAMES_SHORT[t.getDay()]],["Do",`${o}${this.ordinalSuffix(o)}`],["DD",t.getDate().toString().padStart(2,"0")],["D",o.toString()],["HH",t.getHours().toString().padStart(2,"0")],["H",t.getHours().toString()],["mm",t.getMinutes().toString().padStart(2,"0")],["m",t.getMinutes().toString()],["ss",t.getSeconds().toString().padStart(2,"0")],["s",t.getSeconds().toString()],["ww",i.toString().padStart(2,"0")],["w",i.toString()]],a="",l=0;for(;l<e.length;){let c=!1;for(let[u,d]of s)if(e.startsWith(u,l)){a+=d,l+=u.length,c=!0;break}c||(a+=e[l],l+=1)}return a}static ordinalSuffix(e){let t=e%100;if(t>=11&&t<=13)return"th";switch(e%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}}static getWeekNumber(e){let t=new Date(e.getFullYear(),0,1),n=(e.getTime()-t.getTime())/864e5;return Math.ceil((n+t.getDay()+1)/7)}};Da.MONTH_NAMES=["January","February","March","April","May","June","July","August","September","October","November","December"],Da.MONTH_NAMES_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Da.DAY_NAMES=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Da.DAY_NAMES_SHORT=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];es();dv();Tg();function SE(r){let e=new Date;return r?jp(window.moment(e),r).toDate():e}ud();wo();var If=class extends _a{constructor(t,n,i,o={}){super(t);this.plugin=n;this.opts=o;this.diagnostics=new Hc;this.dateParser=i||ns}warn(t){this.diagnostics.add("warning",t)}reportProblem(t){this.diagnostics.add("error",t)}async format(t){this.diagnostics=new Hc;try{return await this.formatInternal(t,{expandLinebreakEscapes:!0})}catch(n){let i=wf(n);return i&&this.diagnostics.add("error",i),t}}async formatInternal(t,{expandLinebreakEscapes:n}){let i=t;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(t){let n=t,i=0,o=new RegExp(ba.source,"gi");for(;o.test(n)&&!(++i>5);)n=n.replace(o,(s,a)=>{let l=String(a??"").trim();if(!l)return s;let c=this.plugin?.settings?.globalVariables?.[l];return typeof c=="string"?c:""});return n}promptForValue(t){return t||"user input"}getVariableValue(t){let n=this.variables.get(t);if(typeof n=="string")return n;let i=av(t);return vE(i)}getCurrentFileLink(){return this.app?EE(this.app.workspace.getActiveFile()):null}getCurrentFileLinkToSection(){return this.app?Df(this.app.workspace.getActiveFile()):Df(null)}getCurrentFileName(){return this.app?xE(this.app.workspace.getActiveFile()):"current_filename"}getCurrentFolderPath(){return this.app?TE(this.app.workspace.getActiveFile()):"current_folder"}suggestForValue(t,n=!1,i){return wE(i?.displayValues??t)}getMacroValue(t,n){return yE(t)}promptForMathValue(){return Promise.resolve("calculation_result")}promptForVariable(t,n){return Promise.resolve(bE(t))}async getTemplateContent(t){let n=this.app;if(!n)return this.reportProblem(`Template preview unavailable: ${t}`),`[QuickAdd: template preview unavailable] ${t}`;let i=Mi(n,t);if(!i)return this.reportProblem(`Template not found: ${t}`),`[QuickAdd: template not found] ${t}`;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=wf(o);return s&&this.diagnostics.add("error",s),`[QuickAdd: template preview failed] ${t}`}finally{this.templateInclusion.depth--}}async getSelectedText(){return"selected_text"}async getClipboardContent(){return"clipboard_content"}async suggestForField(t,n){return Promise.resolve(CE(n))}suggestForFile(t){let n=this.app?di.filterFiles(this.app.vault.getMarkdownFiles(),t.filter,i=>this.app.metadataCache.getFileCache(i)):[];return n.length>0?`${Ta}${n[0].path}`:`${bo}${t.folderPath||"file"}`}async replaceDateVariableInString(t){let n=t;return n=n.replace(new RegExp(yc.source,"gi"),(i,o,s,a)=>{let l=o?.trim(),{options:c,error:u}=aE(a);u&&this.reportProblem(u);let{defaultValue:d,optional:f,withTime:p,snap:m,caseStyle:v}=c,g=s?.trim()||fv(p);if(!l)return i;let y=mv(this.variables.get(l),g,m,this.dateParser);if(y)return this.applyCaseOption(y.text,v,i);let w;try{w=this.applyCaseOption(Da.generate(g,SE(m)),v,i)}catch{w=`[${g} format]`}return d&&(w+=` (default: ${d})`),f&&(w+=" (optional)"),w}),n}replaceRandomInString(t){let n=t;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}isTemplatePropertyTypesEnabled(){return!1}};bf();dv();var Ff=require("obsidian");Je();Dd();Aa();Xw();es();ud();wo();var e2=25;function iK(r){let e=r.lastIndexOf("{{");return e===-1?!1:r.indexOf("}}",e+2)===-1}function oK(r){let e=pv(r);if(e.length===0)return r;let t="",n=0;for(let i of e)t+=r.slice(n,i.start),n=i.end;return t+r.slice(n)}var Pf=class extends _a{constructor(t,n,i){super(t);this.plugin=n;this.diagnostics=new Hc;this.templateIncludeBudget=e2;this.dateParser=i||ns}setRunClocks(t){this.clocks=t}warn(t){this.diagnostics.add("warning",t)}reportProblem(t){this.diagnostics.add("error",t)}async format(t){let n=t;this.diagnostics=new Hc,this.templateIncludeBudget=e2;try{n=await this.formatInternal(t,{included:!1})}catch(o){let s=wf(o);return s&&this.diagnostics.add("error",s),t}this.reportCircularTitle(t,n);let i=Z1(n);for(let o of i.problems)this.diagnostics.add("error",o,"path");return this.reportIllegalChars(t,n),i.path}reportCircularTitle(t,n){!Wo.test(t)&&!Wo.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(t,n){if(this.diagnostics.hasError||iK(t)||EN(t))return;let i=Id(oK(n));i.length!==0&&(this.existsInVault(n)||this.diagnostics.add("error",Y1(i),"path"))}existsInVault(t){let n=this.app?.vault;if(typeof n?.getAbstractFileByPath!="function")return!1;let i=t.trim();return i?i.endsWith("/")?n.getAbstractFileByPath(i.slice(0,-1))instanceof Ff.TFolder:n.getAbstractFileByPath(i)instanceof Ff.TFile||n.getAbstractFileByPath(`${i}.md`)instanceof Ff.TFile?!0:n.getAbstractFileByPath(i)instanceof Ff.TFolder:!1}async formatInternal(t,{included:n}){let i=t;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(t){let n=t,i=0,o=new RegExp(ba.source,"gi");for(;o.test(n)&&!(++i>5);)n=n.replace(o,(s,a)=>{let l=String(a??"").trim();if(!l)return s;let c=this.plugin?.settings?.globalVariables?.[l];return typeof c=="string"?c:""});return n}promptForValue(t){return Af(t||"user input","user input")}getVariableValue(t){let n=this.variables.get(t);if(typeof n=="string")return n;let i=av(t);return Af(vE(i),"user input")}getCurrentFileLink(){return this.app?EE(this.app.workspace.getActiveFile()):null}getCurrentFileName(){return this.app?xE(this.app.workspace.getActiveFile()):"current_filename"}getCurrentFolderPath(){return this.app?TE(this.app.workspace.getActiveFile()):"current_folder"}suggestForValue(t,n=!1,i){return t[0]??wE(t)}promptForMathValue(){return Promise.resolve("calculation_result")}getMacroValue(t,n){return Af(yE(t),"macro_output")}async promptForVariable(t,n){return Af(bE(t),"user input")}async replaceTemplateOutsideScripts(t){let n=pv(t);if(n.length===0)return this.replaceTemplateInString(t);let i="",o=0;for(let s of n)i+=await this.replaceTemplateInString(t.slice(o,s.start)),i+=t.slice(s.start,s.end),o=s.end;return i+await this.replaceTemplateInString(t.slice(o))}async getTemplateContent(t){let n=this.app;if(!n)return this.reportProblem(`Template preview unavailable: ${t}`),`[QuickAdd: template preview unavailable] ${t}`;if(this.templateIncludeBudget<=0){let o="[QuickAdd: too many template includes to preview]";return this.reportProblem(o),o}let i=Mi(n,t);if(!i)return this.reportProblem(`Template not found: ${t}`),`[QuickAdd: template not found] ${t}`;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(t,s),s}catch(o){let s=wf(o);return s&&this.diagnostics.add("error",s),`[QuickAdd: template preview failed] ${t}`}finally{this.templateInclusion.depth--}}resolveTitleInIncludedBody(t){if(!Wo.test(t))return t;let n=this.variables.get("title"),i=typeof n=="string"?n:"";return t.replace(new RegExp(Wo.source,"gi"),()=>i)}warnIfJoinedIntoOneLine(t,n){let i=n.split(/\r?\n/).filter(o=>o.trim());i.length<2||this.warn(`Template "${t}" is ${i.length} lines; a file name is one line, so they are joined with spaces.`)}getCurrentFileLinkToSection(){return this.app?Df(this.app.workspace.getActiveFile()):Df(null)}async getSelectedText(){return"selected_text"}async getClipboardContent(){return"clipboard_content"}async suggestForField(t,n){return Af(CE(n),"field_value")}suggestForFile(t){let n=this.app?di.filterFiles(this.app.vault.getMarkdownFiles(),t.filter,i=>this.app.metadataCache.getFileCache(i)):[];return n.length>0?`${Ta}${n[0].path}`:`${bo}${t.folderPath||"file"}`}async replaceDateVariableInString(t){let n=t;return n=n.replace(new RegExp(yc.source,"gi"),(i,o,s,a)=>{let l=o?.trim();if(!l)return i;let{options:c,error:u}=aE(a);u&&this.reportProblem(u);let{withTime:d,snap:f,caseStyle:p}=c,m=s?.trim()||fv(d),v=mv(this.variables.get(l),m,f,this.dateParser);if(v)return this.applyCaseOption(v.text,p,i);try{return this.applyCaseOption(Da.generate(m,SE(f)),p,i)}catch{return`[${m}]`}}),n}replaceRandomInString(t){let n=t;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}isTemplatePropertyTypesEnabled(){return!1}};var sK=V('<div><span class="qa-visually-hidden"> </span> </div>'),aK=V('<div class="qa-preview-issues"></div>'),lK=V('<div><span class="qa-preview-label"> </span><span class="qa-preview-value" aria-live="polite"> </span></div> <!>',1);function xo(r,e){fe(e,!0);let t=le(e,"formatterKind",3,"format"),n=500,i=Ee(""),o=Ee(st([])),s=Ee(!1),a=0,l=M(()=>e.value.trim().length>0),c=M(()=>e.hideWhen?e.hideWhen(h(i))&&!h(o).some(g=>g.severity==="error"&&g.kind!=="path"):!1),u=M(()=>h(s)?h(o).filter(g=>g.severity==="error"):[]),d=M(()=>h(u).some(g=>g.kind!=="path")),f=M(()=>!h(d)&&h(u).length>0);Xt(()=>{let g=e.value;if(!g.trim()){a++,Q(i,""),Q(o,[],!0);return}let y=t()==="fileName"?new Pf(e.app,e.plugin):new If(e.app,e.plugin,void 0,{resolveActiveFolder:t()!=="lineTarget"});y.setTargetFolderPath(e.targetFolderPath===null?null:e.targetFolderPath?.trim()?e.targetFolderPath:"Folder/Name");let w=++a;(async()=>{try{let T=await y.format(g);if(w!==a)return;Q(i,T,!0),Q(o,y.diagnostics.list(),!0)}catch{if(w!==a)return;Q(i,g,!0),Q(o,[{severity:"error",message:"Preview unavailable."}],!0)}})()}),Xt(()=>{e.value,Q(s,!1);let g=setTimeout(()=>{Q(s,!0)},n);return()=>clearTimeout(g)});var p=Vr(),m=Te(p);{var v=g=>{var y=lK(),w=Te(y);let T;var b=F(w),E=F(b,!0);D(b);var C=S(b),_=F(C,!0);D(C),D(w);var I=S(w,2);{var q=B=>{var J=aK();jt(J,21,()=>h(o),re=>re.severity+re.message,(re,L)=>{var W=sK();let j;var $=F(W),G=F($,!0);D($);var U=S($,1,!0);D(W),ae(()=>{j=at(W,1,"qa-preview-issue",null,j,{"qa-preview-issue--error":h(L).severity==="error"}),Ce(W,"title",h(L).message),ue(G,h(L).severity==="error"?"Error: ":"Warning: "),ue(U,h(L).message)}),O(re,W)}),D(J),O(B,J)};X(I,B=>{h(s)&&h(o).length>0&&B(q)})}ae(()=>{T=at(w,1,"qa-preview-row",null,T,{"qa-preview-row--one-line":t()==="fileName"}),Ce(w,"title",t()==="fileName"?h(i):void 0),ue(E,h(d)?"Unresolved: ":h(f)?"Won't be created: ":"Preview: "),ue(_,h(i))}),O(g,y)};X(m,g=>{h(l)&&!h(c)&&g(v)})}O(r,p),me()}Is();De();var jv="https://quickadd.obsidian.guide",Ia={gettingStarted:`${jv}/docs/`,formatSyntax:`${jv}/docs/FormatSyntax/`,onePageInputs:`${jv}/docs/Advanced/onePageInputs/`,userScripts:`${jv}/docs/Choices/MacroChoice/#user-scripts`,packages:`${jv}/docs/Choices/Packages/`};function t2(r,e){try{(e?sd(e):window).open(r,"_blank","noopener,noreferrer")}catch(t){P.logError(`QuickAdd: Failed to open documentation (${r}): ${t}`)}}function _E(r,e,t){let n=nr(r,"a");return n.textContent=t,n.href=e,n.target="_blank",n.rel="noopener noreferrer",n.classList.add("quickadd-docs-link"),r.append(n),n}var cK=V('<div class="qa-token-hint">Type <code>&#123;&#123;</code> to insert a token &middot; <a class="quickadd-docs-link" target="_blank" rel="noopener noreferrer">Format syntax</a></div>');function Fd(r,e){fe(e,!0);let t=M(()=>!e.value.includes("{{"));var n=Vr(),i=Te(n);{var o=s=>{var a=cK(),l=S(F(a),3);D(a),ae(()=>Ce(l,"href",Ia.formatSyntax)),O(s,a)};X(i,s=>{h(t)&&s(o)})}O(r,n),me()}var r2=require("obsidian");od();yg();var uK=V('<input type="text" class="text-input" aria-label="Frontmatter property" placeholder="related" required=""/>'),kD=V("<!> <!>",1),dK=V("<!> <!> <!> <!>",1);function Gv(r,e){fe(e,!0);let t=le(e,"appendLink",15),n=le(e,"app",3,void 0),i=M(()=>xc(t())),o=M(()=>h(i).linkType??"link"),s=M(()=>h(i).displayText),a=M(()=>h(i).frontmatterHandling??nd),l=M(()=>h(i).destination.type==="specifiedFile"?h(i).destination.path:""),c=M(()=>h(i).enabled?h(i).requireActiveFile?"required":"optional":"disabled"),u=M(()=>h(i).destination.type),d=M(()=>n()?n().vault.getMarkdownFiles().map($=>$.path):[]),f=[{value:"required",label:"Enabled (strict)"},{value:"optional",label:"Enabled (skip if unavailable)"},{value:"disabled",label:"Disabled"}],p=[{value:"activeFile",label:"Current note"},{value:"specifiedFile",label:"Specified note"}],m=[{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"}],v=[{value:"link",label:"Link"},{value:"embed",label:"Embed"}],g=[{value:"none",label:"Default"},{value:"selection",label:"Selected text"}],y=[{value:"alwaysAppend",label:"Create or convert"},{value:"createProperty",label:"Create if missing"},{value:"error",label:"Require list"}];function w($){let G=t(),U=typeof G=="boolean"?h(i):G,H=$.placement??U.placement,Y=$.destination??U.destination??h(i).destination,ie=Y.type==="activeFile"&&Vp(H)?$.linkType??U.linkType??h(o):"link",oe=Y.type==="activeFile"&&zw(H)&&ie==="link"?$.displayText??h(s):"none";return{enabled:$.enabled??!0,placement:H,requireActiveFile:$.requireActiveFile??U.requireActiveFile??h(i).requireActiveFile,linkType:ie,displayText:oe,destination:Y,frontmatterProperty:$.frontmatterProperty??U.frontmatterProperty,frontmatterHandling:$.frontmatterHandling??U.frontmatterHandling}}function T($){switch($){case"disabled":t(w({enabled:!1}));break;case"required":t(w({requireActiveFile:!0}));break;case"optional":t(w({requireActiveFile:!1}));break}}function b($){t(w({placement:$}))}function E($){t(w({linkType:$}))}function C($){t(w({displayText:$}))}function _($){t(w({frontmatterProperty:$.currentTarget.value}))}function I($){t(w({frontmatterHandling:$}))}function q($){let G=$==="specifiedFile"?{type:"specifiedFile",path:h(l)}:{type:"activeFile"};t(w({destination:G}))}function B($){t(w({destination:{type:"specifiedFile",path:$.trim()}}))}function J($){let G=$.trim();if(!G)return"Destination file is required";if(!n())return!0;let U=n().vault.getAbstractFileByPath(Ok(G));return U instanceof r2.TFile&&U.extension==="md"?!0:"Markdown file not found"}var re=kD(),L=Te(re);{let $=H=>{wt(H,{get value(){return h(c)},get options(){return f},onchange:T})},G=M(()=>`Link to ${e.fileLabel} file`),U=M(()=>`Choose whether QuickAdd should insert a link to the ${e.fileLabel} file.`);Se(L,{get name(){return h(G)},get desc(){return h(U)},control:$,$$slots:{control:!0}})}var W=S(L,2);{var j=$=>{var G=kD(),U=Te(G);{let oe=he=>{wt(he,{get value(){return h(u)},get options(){return p},onchange:q})},ce=M(()=>`Where QuickAdd writes the link to the ${e.fileLabel} file.`);Se(U,{name:"Link destination",get desc(){return h(ce)},control:oe,$$slots:{control:!0}})}var H=S(U,2);{var Y=oe=>{var ce=dK(),he=Te(ce);Se(he,{name:"Link placement",desc:"Where to place the link when appending",control:ge=>{wt(ge,{get value(){return h(i).placement},get options(){return m},onchange:b})},$$slots:{control:!0}});var Ie=S(he,2);{var we=$e=>{Se($e,{name:"Link type",desc:"Choose whether to insert a link or an embed. Embeds transclude the note's contents at the placement position.",control:xe=>{wt(xe,{get value(){return h(o)},get options(){return v},onchange:E})},$$slots:{control:!0}})},Ge=M(()=>Vp(h(i).placement));X(Ie,$e=>{h(Ge)&&$e(we)})}var Pe=S(Ie,2);{var Ve=$e=>{Se($e,{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:xe=>{wt(xe,{get value(){return h(s)},get options(){return g},onchange:C})},$$slots:{control:!0}})},qe=M(()=>zw(h(i).placement)&&h(o)==="link");X(Pe,$e=>{h(qe)&&$e(Ve)})}var et=S(Pe,2);{var _t=$e=>{var ge=kD(),xe=Te(ge);Se(xe,{name:"Frontmatter property",desc:"Required property to insert the link into.",control:Pt=>{var gt=uK();Bt(gt),ae(Lt=>{Fi(gt,h(i).frontmatterProperty??""),Ce(gt,"aria-invalid",Lt)},[()=>!h(i).frontmatterProperty?.trim()]),_e("input",gt,_),O(Pt,gt)},$$slots:{control:!0}});var tt=S(xe,2);Se(tt,{name:"Property handling",desc:"Choose how strict QuickAdd should be when the property is missing or not a list.",control:Pt=>{wt(Pt,{get value(){return h(a)},get options(){return y},onchange:I})},$$slots:{control:!0}}),O($e,ge)},ye=M(()=>id(h(i).placement));X(et,$e=>{h(ye)&&$e(_t)})}O(oe,ce)},ie=oe=>{Se(oe,{name:"Destination file",desc:"Existing Markdown note that receives the link at the bottom.",control:he=>{jn(he,{get value(){return h(l)},placeholder:"Index.md",get app(){return n()},get suggestions(){return h(d)},maxSuggestions:50,required:!0,requiredMessage:"Destination file is required",validator:J,ariaLabel:"Append link destination file",onChange:B})},$$slots:{control:!0}})};X(H,oe=>{h(u)==="activeFile"?oe(Y):oe(ie,-1)})}O($,G)};X(W,$=>{h(c)!=="disabled"&&$(j)})}O(r,re),me()}nt(["input"]);function Yv(r,e){fe(e,!0);let t=le(e,"openFile",15);Se(r,{name:"Open",get desc(){return e.description},control:i=>{Ot(i,{get checked(){return t()},set checked(o){t(o)}})},$$slots:{control:!0}}),me()}var pK=V("<!> <!> <!> <!>",1);function Kv(r,e){fe(e,!0);let t=le(e,"fileOpening",15);t(qr(t()));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=M(()=>typeof t().mode=="string"?t().mode:"default");var a=pK(),l=Te(a);{let m=g=>{wt(g,{get value(){return t().location},get options(){return n},onchange:y=>t(t().location=y,!0)})},v=M(()=>`Where to open the ${e.contextLabel} file`);Se(l,{name:"File opening location",get desc(){return h(v)},control:m,$$slots:{control:!0}})}var c=S(l,2);{var u=m=>{Se(m,{name:"Split direction",desc:"How to arrange the new pane relative to the current one",control:g=>{wt(g,{get value(){return t().direction},get options(){return i},onchange:y=>t(t().direction=y,!0)})},$$slots:{control:!0}})};X(c,m=>{t().location==="split"&&m(u)})}var d=S(c,2);Se(d,{name:"View mode",desc:"How to display the opened file",control:v=>{wt(v,{get value(){return h(s)},get options(){return o},onchange:g=>t(t().mode=g,!0)})},$$slots:{control:!0}});var f=S(d,2);{var p=m=>{Se(m,{name:"Focus new pane",desc:"Focus the opened tab immediately after opening",control:g=>{Ot(g,{get checked(){return t().focus},set checked(y){t(t().focus=y,!0)}})},$$slots:{control:!0}})};X(f,m=>{t().location!=="reuse"&&m(p)})}O(r,a),me()}function Qv(r,e){fe(e,!0);let t=le(e,"onePageInput",15),n=[{value:"",label:"Follow global setting"},{value:"always",label:"Always"},{value:"never",label:"Never"}],i=M(()=>t()??"");function o(s){t(s==="always"||s==="never"?s:void 0)}Se(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=>{wt(a,{get value(){return h(i)},get options(){return n},onchange:o})},$$slots:{control:!0}}),me()}var Xv=["days","weeks","months","years"];function Zv(r){return typeof r=="string"&&Xv.includes(r)}function Ml(r){if(!r||typeof r!="object")return;let e=r;switch(e.kind){case"now":return{kind:"now"};case"ask":{let t=typeof e.defaultValue=="string"?e.defaultValue.trim():"";return t?{kind:"ask",defaultValue:t}:{kind:"ask"}}case"relative":return typeof e.offset!="number"||!Number.isInteger(e.offset)||!Zv(e.unit)?void 0:{kind:"relative",offset:e.offset,unit:e.unit};case"variable":return typeof e.name!="string"||!e.name.trim()?void 0:{kind:"variable",name:e.name.trim()};default:return}}Jc();var hK=V('<input type="text" class="qa-validated-input-full-width" placeholder="-2"/> <!>',1),gK=V('<input type="text" class="qa-validated-input-full-width" placeholder="day"/>'),vK=V("<!> <!> <!> <!>",1);function ry(r,e){fe(e,!0);let t=le(e,"dateOrigin",15),n=Xv.map(_=>({value:_,label:_})),i=M(()=>Ol(t())),o=M(()=>t()?.kind==="ask"?t():void 0),s=M(()=>h(i)==="custom"&&t()?.kind==="relative"?t():void 0),a=M(()=>t()?.kind==="variable"?t():void 0),l=M(()=>ty(h(o)?.defaultValue)),c=M(()=>LE(h(o)?.defaultValue));function u(_){OE(_)&&t(RE({preset:_,previous:t()}))}function d(_){if(t()?.kind!=="ask")return;let I=NE(_,t().defaultValue);t(I?{kind:"ask",defaultValue:I}:{kind:"ask"})}function f(_){if(t()?.kind!=="relative")return;let I=_.trim();/^[+-]?\d+$/.test(I)&&t({...t(),offset:Number(I)})}function p(_){t()?.kind==="relative"&&Zv(_)&&t({...t(),unit:_})}function m(_){t()?.kind==="variable"&&t({kind:"variable",name:_})}var v=vK(),g=Te(v);Se(g,{get name(){return kE},get desc(){return AE},control:I=>{wt(I,{get value(){return h(i)},get options(){return $E},onchange:u})},$$slots:{control:!0}});var y=S(g,2);{var w=_=>{Se(_,{get name(){return DE},get desc(){return IE},control:q=>{wt(q,{get value(){return h(l)},get options(){return h(c)},onchange:d})},$$slots:{control:!0}})};X(y,_=>{h(o)&&_(w)})}var T=S(y,2);{var b=_=>{Se(_,{get name(){return Jv},get desc(){return FE},control:q=>{var B=hK(),J=Te(B);Bt(J);var re=S(J,2);wt(re,{get value(){return h(s).unit},get options(){return n},onchange:p}),ae(L=>{Fi(J,L),Ce(J,"aria-label",Jv)},[()=>String(h(s).offset)]),_e("input",J,L=>{let W=L.currentTarget;W instanceof HTMLInputElement&&f(W.value)}),O(q,B)},$$slots:{control:!0}})};X(T,_=>{h(s)&&_(b)})}var E=S(T,2);{var C=_=>{Se(_,{get name(){return ey},get desc(){return PE},control:q=>{var B=gK();Bt(B),ae(()=>{Fi(B,h(a).name),Ce(B,"aria-label",ey)}),_e("input",B,J=>{let re=J.currentTarget;re instanceof HTMLInputElement&&m(re.value)}),O(q,B)},$$slots:{control:!0}})};X(E,_=>{h(a)&&_(C)})}O(r,v),me()}nt(["input"]);Jc();var ny="Add to command palette",BE="Run this choice from the command palette or a hotkey.",VE="A second command that asks which day first. Your hotkey for the main command still uses Which day.";function iy(r){return`Also add "${ID(r)}"`}function qE(r){return`choice:${r}`}function DD(r){return`${qE(r)}:pick-day`}function ID(r){return`${r} (pick a day)`}function oy(r){return Ol(r)!=="ask"}function o2(r){return!!r.enabled&&oy(r.origin)}var yK=V("<!> <!>",1);function sy(r,e){fe(e,!0);let t=le(e,"command",15),n=le(e,"pickDayCommand",15),i=M(()=>t()&&oy(e.dateOrigin));var o=yK(),s=Te(o);Se(s,{get name(){return ny},get desc(){return BE},control:u=>{Ot(u,{get ariaLabel(){return ny},get checked(){return t()},set checked(d){t(d)}})},$$slots:{control:!0}});var a=S(s,2);{var l=c=>{{let u=f=>{{let p=M(()=>iy(e.name));Ot(f,{get ariaLabel(){return h(p)},get checked(){return n()},set checked(m){n(m)}})}},d=M(()=>iy(e.name));Se(c,{get name(){return h(d)},get desc(){return VE},control:u,$$slots:{control:!0}})}};X(a,c=>{h(i)&&c(l)})}O(r,o),me()}Dt();var bK=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),wK=new Intl.Collator(void 0,{numeric:!0,sensitivity:"variant"});function UE(r){return r.trim().replace(/^\/+/,"").replace(/\/+$/,"")}function CK(r,e){let t=UE(r),n=UE(e);if(t===n)return 0;let i=t===""?[]:t.split("/"),o=n===""?[]:n.split("/"),s=Math.min(i.length,o.length);for(let a=0;a<s;a++){let l=bK.compare(i[a],o[a]);if(l!==0)return l;let c=wK.compare(i[a],o[a]);if(c!==0)return c}return i.length-o.length}function Rl(r){return[...r].sort(CK)}function EK(r,e){let t=UE(r),n=UE(e);return n?t===n||t.startsWith(`${n}/`):!0}function s2(r,e){return r.filter(t=>e.some(n=>EK(t,n)))}var eu=require("obsidian");var xK=V('<div class="qa-canvas-node-empty"> </div>'),TK=V('<div class="qa-canvas-node-empty">No nodes match the current filter.</div>'),SK=V('<button type="button"> </button>'),_K=V('<button type="button" disabled="">Unavailable</button>'),kK=V('<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>'),AK=V('<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 FD(r,e){fe(e,!0);let t=le(e,"nodeId",15),n=Ee(st([])),i=Ee("loading"),o=Ee(""),s=Ee(""),a=M(()=>{let L=h(s).trim().toLowerCase();return L.length?h(n).filter(W=>W.searchText.includes(L)):h(n)}),l=M(()=>(t()??"").trim()),c=M(()=>h(i)==="ready"?`Showing ${h(a).length} of ${h(n).length} nodes`:h(i)==="empty"?h(o):"Loading canvas nodes\u2026");Sw(()=>{(async()=>{let L=Dk(e.app,e.canvasTargetPath);if(!L){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 TO(e.app,L),!0),h(n).length===0){Q(o,"No selectable nodes found in the target canvas."),Q(i,"empty");return}Q(i,"ready")})()});function u(L){t(L)}function d(){let L=Dk(e.app,e.canvasTargetPath);if(!L){new eu.Notice("Target canvas file was not found.");return}e.app.workspace.getLeaf(!0).openFile(L).catch(()=>new eu.Notice("Could not open target canvas."))}function f(){let L=xO(e.app,e.canvasTargetPath);if(!L){new eu.Notice("Open the target canvas and select exactly one card to use this action.");return}let W=h(n).find(j=>j.id===L);if(!W){new eu.Notice(h(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(!W.capturable){new eu.Notice(W.capturableReason);return}u(L)}function p(L){(async()=>{try{await navigator.clipboard.writeText(L),new eu.Notice(`Copied node id ${L}`)}catch{new eu.Notice("Could not copy node id automatically.")}})()}function m(L){return L==="text"?"TEXT":L==="file"?"FILE":"NODE"}var v=AK(),g=F(v),y=F(g),w=S(y,2),T=S(w,2);D(g);var b=S(g,2),E=F(b);Bt(E),D(b);var C=S(b,2),_=F(C,!0);D(C);var I=S(C,2),q=F(I);{var B=L=>{var W=xK(),j=F(W,!0);D(W),ae(()=>ue(j,h(o))),O(L,W)},J=L=>{var W=TK();O(L,W)},re=L=>{var W=Vr(),j=Te(W);jt(j,17,()=>h(a),$=>$.id,($,G)=>{let U=M(()=>h(l)===h(G).id);var H=kK();let Y;var ie=F(H),oe=F(ie),ce=F(oe,!0);D(oe);var he=S(oe,2),Ie=F(he,!0);D(he),D(ie);var we=S(ie,2),Ge=F(we,!0);D(we);var Pe=S(we,2),Ve=F(Pe),qe=F(Ve,!0);D(Ve),D(Pe);var et=S(Pe,2),_t=F(et);{var ye=xe=>{var tt=SK();let kt;var Pt=F(tt,!0);D(tt),ae(()=>{kt=at(tt,1,"",null,kt,{"mod-cta":h(U)}),ue(Pt,h(U)?"Selected":"Use node")}),_e("click",tt,()=>u(h(G).id)),O(xe,tt)},$e=xe=>{var tt=_K();ae(()=>Ce(tt,"title",h(G).capturableReason)),O(xe,tt)};X(_t,xe=>{h(G).capturable?xe(ye):xe($e,-1)})}var ge=S(_t,2);D(et),D(H),ae(xe=>{Y=at(H,1,"qa-canvas-node-item",null,Y,{"is-selected":h(U)}),at(oe,1,`qa-canvas-node-type is-${h(G).type??""}`),ue(ce,xe),ue(Ie,h(G).title),ue(Ge,h(G).subtitle),ue(qe,h(G).id)},[()=>m(h(G).type)]),_e("click",ge,()=>p(h(G).id)),O($,H)}),O(L,W)};X(q,L=>{h(i)==="empty"?L(B):h(i)==="ready"&&h(a).length===0?L(J,1):L(re,-1)})}D(I),D(v),ae(()=>ue(_,h(c))),_e("click",y,d),_e("click",w,f),_e("click",T,()=>u("")),Pi(E,()=>h(s),L=>Q(s,L)),O(r,v),me()}nt(["click"]);Lc();dd();var DK=new Set(["folder","tag","exclude-folder","exclude-tag","exclude-file"]);function IK(r,e){let t=[r,...e??[]].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return t.length>0?t:void 0}function a2(r){let e=hi.parse(`__capture_scope|${r}`);return{filter:e.filters,multiSelect:e.multiSelect??!1}}function FK(r){return!!(r.folder||r.folders?.length||r.tags?.length||r.excludeFolders?.length||r.excludeTags?.length||r.excludeFiles?.length)}function Mf(r){let e=r.trim();if(!e)return null;if(e.startsWith("#")){let o=Yo(e),s=(o.shift()??"").replace(/^#/,"").replace(/\.md$/i,"").trim();if(!s)return null;let a=o.length>0?a2(o.join("|")):{filter:{},multiSelect:!1};return{filter:{...a.filter,tags:IK(s,a.filter.tags)},multiSelect:a.multiSelect}}let t=Yo(e)[0]??"",n=Oi(t);if(!n||!DK.has(n.key))return null;let i=a2(e);return FK(i.filter)?i:null}Lc();var l2=/^property:/i;function Of(r){let e=r.trim();if(!l2.test(e))return null;let t=e.replace(l2,""),{fieldName:n,filters:i}=hi.parse(t),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}}function PK(r){return r.trim().replace(/^\/+/,"")}function ay(r){return[...new Set((r??[]).map(e=>e.trim()).filter(Boolean))]}function ly(r,e="or"){return r.length<=1?r[0]??"":e==="+"?r.join(" + "):r.length===2?`${r[0]} ${e} ${r[1]}`:`${r.slice(0,-1).join(", ")}, ${e} ${r[r.length-1]}`}function c2(r){let e=ay(r.folders??(r.folder?[r.folder]:[])),t=ay(r.tags),n=ay(r.excludeFolders),i=ay(r.excludeTags),o=ay(r.excludeFiles),s=[];return e.length>0&&s.push(`${e.length===1?"folder":"folders"} ${ly(e)}`),t.length>0&&s.push(`${t.length===1?"tag":"tags"} ${ly(t,"+")}`),n.length>0&&s.push(`excluding ${n.length===1?"folder":"folders"} ${ly(n)}`),i.length>0&&s.push(`excluding ${i.length===1?"tag":"tags"} ${ly(i,"+")}`),o.length>0&&s.push(`excluding ${o.length===1?"file":"files"} ${ly(o)}`),s.length>0?s.join("; "):"all notes"}function cy(r){let e=PK(r),t=Of(e);if(t){if(!t.field)return{recognized:!0,valid:!1,variant:"error",message:"Property capture target needs a field name, e.g. property:type=draft."};let i=t.value?`frontmatter ${t.field} = ${t.value}`:`frontmatter field ${t.field}`,o=c2(t.filter),s=o==="all notes"?"":`; ${o}`;return{recognized:!0,valid:!0,variant:"success",message:`Recognized property target: ${i}${s}.`}}let n=Mf(e);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: ${c2(n.filter)}.`}:null}var $K=V("<!> <!> <!>",1),MK=V('<!> <div class="qa-canvas-node-helper">Tip: open this canvas and select one card to grab its id instantly.</div> <!>',1),u2=V("<!> <!>",1);function PD(r,e){fe(e,!0);let t=le(e,"choice",15),n=M(()=>{let g=Rl(Go(e.app)).filter(T=>T.length>0).map(T=>T.endsWith("/")?T:T+"/"),y=e.app.vault.getMarkdownFiles().map(T=>T.path),w=e.app.vault.getFiles().filter(T=>T.extension==="canvas").map(T=>T.path);return Array.from(new Set([...g,...y,...w]))}),i=[g=>new pi(e.app,g,e.plugin,"captureTarget")],o=M(()=>cy(t().captureTo??"")),s=M(()=>h(o)!==null),a=g=>cy(g)!==null,l=M(()=>!h(s)&&Cc(t().captureTo));function c(g){let y=!!t().captureToActiveFile&&t().activeFileWritePosition==="bottom";t(t().captureToActiveFile=g,!0),!g&&y&&t(t().prepend=!0,!0),!g&&t().newLineCapture?.enabled&&t(t().newLineCapture.enabled=!1,!0)}function u(g){let y=Bp(t().captureTo),w=Cc(t().captureTo),T=cy(g)!==null;t(t().captureTo=g,!0);let b=Bp(g),E=Cc(g);(T||!E||w&&E&&y!==b)&&t(t().captureToCanvasNodeId="",!0)}function d(g){let y=cy(g);return y?{valid:y.valid,message:y.message,variant:y.valid?"success":void 0}:g.trim()?!0:{valid:!0,message:"Leave empty to pick the note each time this choice runs."}}var f=u2(),p=Te(f);Se(p,{name:"Capture to active file",desc:"Capture into whichever note is open when the choice runs, instead of a fixed target.",control:y=>{Ot(y,{get checked(){return t().captureToActiveFile},onchange:c})},$$slots:{control:!0}});var m=S(p,2);{var v=g=>{var y=u2(),w=Te(y);Co(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.",children:(C,_=At)=>{var I=$K(),q=Te(I);jn(q,{get id(){return _()},get value(){return t().captureTo},placeholder:"Daily/{{DATE}}.md",get app(){return e.app},get suggestions(){return h(n)},maxSuggestions:50,get makeSuggesters(){return i},validator:d,onChange:u});var B=S(q,2);Fd(B,{get value(){return t().captureTo}});var J=S(B,2);{var re=L=>{xo(L,{get value(){return t().captureTo},formatterKind:"fileName",get app(){return e.app},get plugin(){return e.plugin},hideWhen:a})};X(J,L=>{h(s)||L(re)})}O(C,I)},$$slots:{default:!0}});var T=S(w,2);{var b=E=>{var C=MK(),_=Te(C);Se(_,{name:"Target canvas node",desc:"Choose a card from the canvas below, or paste an exact node id.",control:B=>{{let J=M(()=>t().captureToCanvasNodeId??"");jn(B,{get value(){return h(J)},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:re=>t(t().captureToCanvasNodeId=re.trim(),!0)})}},$$slots:{control:!0}});var I=S(_,4);rk(I,()=>t().captureTo,q=>{FD(q,{get canvasTargetPath(){return t().captureTo},get app(){return e.app},get nodeId(){return t().captureToCanvasNodeId},set nodeId(B){t(t().captureToCanvasNodeId=B,!0)}})}),O(E,C)};X(T,E=>{h(l)&&E(b)})}O(g,y)};X(m,g=>{t().captureToActiveFile||g(v)})}O(r,f),me()}var m2=require("obsidian");var f2=require("obsidian");Je();function $D(r){let t=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(t)return t;let i=r.match(/\{\{VDATE:[^,}]+,([^}\n\r]*)\}\}/i)?.[1]?.split("|")[0]?.trim();if(i)return i}var OK=V(`<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>`),d2=V("<!> <!>",1),RK=V(`<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>`),p2=V("<!> <!> <!>",1),LK=V(`<div class="setting-item-description">No sorting: newest-first prepends the new section above existing ones;
oldest-first appends it below.</div>`),NK=V(`<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>`),BK=V(`<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),VK=V("<!> <!> <!> <!> <!>",1);function MD(r,e){fe(e,!0);let t=le(e,"insertAfter",15);t().inline===void 0&&t(t().inline=!1,!0),t().replaceExisting===void 0&&t(t().replaceExisting=!1,!0),t().promptHeading===void 0&&t(t().promptHeading=!1,!0),t().insertAtEnd===void 0&&t(t().insertAtEnd=!1,!0),t().considerSubsections===void 0&&t(t().considerSubsections=!1,!0),t().blankLineAfterMatchMode||t(t().blankLineAfterMatchMode="auto",!0),t().createIfNotFound||t(t().createIfNotFound=!1,!0),t().createIfNotFoundLocation||t(t().createIfNotFoundLocation=$i,!0);let n=[$=>new pi(e.app,$,e.plugin,"lineTarget")],i=[{value:"auto",label:"Auto (headings only)"},{value:"skip",label:"Always skip"},{value:"none",label:"Never skip"}],o=M(()=>t().inline?[{value:$i,label:"Top"},{value:ul,label:"Bottom"},{value:dl,label:"Cursor"}]:[{value:$i,label:"Top"},{value:ul,label:"Bottom"},{value:dl,label:"Cursor"},{value:Ds,label:"Ordered (place new section 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 existing unparseable headings to bottom"},{value:"top",label:"Sort existing unparseable headings to top"}],c=Ee(!!t().orderBy),u=M(()=>t().createIfNotFoundLocation===Ds),d=M(()=>t().createIfNotFound&&h(u)),f=M(()=>new If(e.app,e.plugin)),p=Ee(!1);Xt(()=>{let $=t().after??"",G=h(f);if(!t().inline||$===""){Q(p,!1);return}let U=!1;return G.format($).then(H=>{U||Q(p,/[\n\r]/.test(H),!0)}).catch(()=>{U||Q(p,!1)}),()=>{U=!0}});let m=M(()=>t().orderBy??{by:"insertion",direction:"desc",unparseable:"bottom"}),v=M(()=>/\{\{V?DATE\b/i.test(t().after??"")),g=M(()=>h(d)&&t().orderBy?.by==="insertion"&&h(v)&&!$D(t().after??""));Xt(()=>{if(!h(d))return;let $=$D(t().after??"");if(!t().orderBy){t(t().orderBy={by:$?"date":"insertion",direction:"desc",dateFormat:$,unparseable:"bottom"},!0);return}!h(c)&&(t().orderBy.by==="insertion"||t().orderBy.by==="date")&&(t(t().orderBy.by=$?"date":"insertion",!0),t(t().orderBy.dateFormat=$,!0))});function y($){t(t().createIfNotFoundLocation=$,!0),$===Ds?t(t().inline=!1,!0):(t(t().orderBy=void 0,!0),Q(c,!1))}function w($){Q(c,!0),t().orderBy&&t(t().orderBy.by=$,!0)}function T($){t().promptHeading||$&&!t().after.startsWith("#")&&(t(t().considerSubsections=!1,!0),new f2.Notice("Consider subsections requires the target to be a heading (starts with #)"))}function b($){$&&(t(t().inline=!1,!0),t(t().replaceExisting=!1,!0))}var E=VK(),C=Te(E);Se(C,{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:G=>{Ot(G,{onchange:b,get checked(){return t().promptHeading},set checked(U){t(t().promptHeading=U,!0)}})},$$slots:{control:!0}});var _=S(C,2);{var I=$=>{var G=OK();O($,G)},q=$=>{var G=p2(),U=Te(G);Co(U,{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:(ce,he=At)=>{var Ie=d2(),we=Te(Ie);jn(we,{get id(){return he()},placeholder:"Insert after",required:!0,requiredMessage:"Insert after text is required",get makeSuggesters(){return n},get value(){return t().after},set value(Pe){t(t().after=Pe,!0)}});var Ge=S(we,2);xo(Ge,{get value(){return t().after},formatterKind:"lineTarget",get app(){return e.app},get plugin(){return e.plugin}}),O(ce,Ie)},$$slots:{default:!0}});var H=S(U,2);{let oe=he=>{Ot(he,{get disabled(){return h(u)},get checked(){return t().inline},set checked(Ie){t(t().inline=Ie,!0)}})},ce=M(()=>h(u)?"Inline insertion can't be combined with ordered placement.":"Insert captured content on the same line, immediately after the matched text (no newline added).");Se(H,{name:"Inline insertion",get desc(){return h(ce)},control:oe,$$slots:{control:!0}})}var Y=S(H,2);{var ie=oe=>{var ce=RK();O(oe,ce)};X(Y,oe=>{h(p)&&oe(ie)})}O($,G)};X(_,$=>{t().promptHeading?$(I):$(q,-1)})}var B=S(_,2);{var J=$=>{Se($,{name:"Replace existing value",desc:"Replace everything after the matched text up to end-of-line.",control:U=>{Ot(U,{get checked(){return t().replaceExisting},set checked(H){t(t().replaceExisting=H,!0)}})},$$slots:{control:!0}})},re=$=>{var G=p2(),U=Te(G);Se(U,{name:"Insert at end of section",desc:"Place the text at the end of the matched section instead of the top.",control:oe=>{Ot(oe,{get checked(){return t().insertAtEnd},set checked(ce){t(t().insertAtEnd=ce,!0)}})},$$slots:{control:!0}});var H=S(U,2);{let ie=ce=>{{let he=M(()=>t().blankLineAfterMatchMode??"auto");wt(ce,{get value(){return h(he)},get options(){return i},get disabled(){return t().insertAtEnd},onchange:Ie=>t(t().blankLineAfterMatchMode=Ie,!0)})}},oe=M(()=>t().insertAtEnd?"Not used when inserting at end of section.":"Controls whether Insert After skips existing blank lines after the matched line.");Se(H,{name:"Blank lines after match",get desc(){return h(oe)},control:ie,$$slots:{control:!0}})}var Y=S(H,2);{let ie=ce=>{{let he=M(()=>!t().insertAtEnd);Ot(ce,{get disabled(){return h(he)},onchange:T,get checked(){return t().considerSubsections},set checked(Ie){t(t().considerSubsections=Ie,!0)}})}},oe=M(()=>t().insertAtEnd?t().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.");Se(Y,{name:"Consider subsections",get desc(){return h(oe)},control:ie,$$slots:{control:!0}})}O($,G)};X(B,$=>{t().inline?$(J):$(re,-1)})}var L=S(B,2);Se(L,{name:"Create line if not found",desc:"Creates the 'insert after' line if it is not found.",control:G=>{var U=d2(),H=Te(U);Ot(H,{get checked(){return t().createIfNotFound},set checked(ie){t(t().createIfNotFound=ie,!0)}});var Y=S(H,2);{let ie=M(()=>t().createIfNotFoundLocation||$i);wt(Y,{get value(){return h(ie)},get options(){return h(o)},onchange:y})}O(G,U)},$$slots:{control:!0}});var W=S(L,2);{var j=$=>{var G=BK(),U=S(Te(G),2);Se(U,{name:"Sort sections by",control:Ve=>{wt(Ve,{get value(){return h(m).by},get options(){return s},onchange:w})},$$slots:{control:!0}});var H=S(U,2);Se(H,{name:"Section order",control:Ve=>{wt(Ve,{get value(){return h(m).direction},get options(){return a},onchange:qe=>{t().orderBy&&t(t().orderBy.direction=qe,!0)}})},$$slots:{control:!0}});var Y=S(H,2);{var ie=Pe=>{Se(Pe,{name:"Date format",desc:"Moment format used to parse existing heading dates for sorting (e.g. YYYY-MM-DD).",control:qe=>{{let et=M(()=>h(m).dateFormat??"");jn(qe,{get value(){return h(et)},placeholder:"YYYY-MM-DD",ariaLabel:"Date format",onChange:_t=>{Q(c,!0),t().orderBy&&t(t().orderBy.dateFormat=_t,!0)}})}},$$slots:{control:!0}})};X(Y,Pe=>{h(m).by==="date"&&Pe(ie)})}var oe=S(Y,2);{var ce=Pe=>{Se(Pe,{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:qe=>{{let et=M(()=>h(m).unparseable??"bottom");wt(qe,{get value(){return h(et)},get options(){return l},onchange:_t=>{t().orderBy&&t(t().orderBy.unparseable=_t,!0)}})}},$$slots:{control:!0}})};X(oe,Pe=>{(h(m).by==="date"||h(m).by==="numeric"||h(m).by==="semver")&&Pe(ce)})}var he=S(oe,2);{var Ie=Pe=>{var Ve=LK();O(Pe,Ve)};X(he,Pe=>{h(m).by==="insertion"&&Pe(Ie)})}var we=S(he,2);{var Ge=Pe=>{var Ve=NK();O(Pe,Ve)};X(we,Pe=>{h(g)&&Pe(Ge)})}O($,G)};X(W,$=>{h(d)&&t().orderBy&&$(j)})}O(r,E),me()}Je();var OD=V("<!> <!>",1);function RD(r,e){fe(e,!0);let t=le(e,"insertBefore",15);t().createIfNotFound===void 0&&t(t().createIfNotFound=!1,!0),t().createIfNotFoundLocation||t(t().createIfNotFoundLocation=$i,!0);let n=[l=>new pi(e.app,l,e.plugin,"lineTarget")],i=[{value:$i,label:"Top"},{value:ul,label:"Bottom"},{value:dl,label:"Cursor"}];var o=OD(),s=Te(o);Co(s,{name:"Insert before",desc:"Insert capture before specified text. Accepts format syntax.",children:(c,u=At)=>{var d=OD(),f=Te(d);jn(f,{get id(){return u()},placeholder:"Insert before",required:!0,requiredMessage:"Insert before text is required",get makeSuggesters(){return n},get value(){return t().before},set value(m){t(t().before=m,!0)}});var p=S(f,2);xo(p,{get value(){return t().before},formatterKind:"lineTarget",get app(){return e.app},get plugin(){return e.plugin}}),O(c,d)},$$slots:{default:!0}});var a=S(s,2);Se(a,{name:"Create line if not found",desc:"Creates the 'insert before' line if it is not found.",control:c=>{var u=OD(),d=Te(u);Ot(d,{get checked(){return t().createIfNotFound},set checked(p){t(t().createIfNotFound=p,!0)}});var f=S(d,2);{let p=M(()=>t().createIfNotFoundLocation||$i);wt(f,{get value(){return h(p)},get options(){return i},onchange:m=>t(t().createIfNotFoundLocation=m,!0)})}O(c,u)},$$slots:{control:!0}}),O(r,o),me()}var qK=V(`<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>`),UK=V("<!> <!> <!> <!>",1);function LD(r,e){fe(e,!0);let t=le(e,"choice",15),n=M(()=>!!t().captureToActiveFile),i=M(()=>t().insertAfter?.enabled?"after":t().insertBefore?.enabled?"before":t().newLineCapture?.enabled?t().newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":h(n)?t().activeFileWritePosition==="top"?"activeTop":t().activeFileWritePosition==="bottom"||t().prepend?"bottom":"top":t().prepend?"bottom":"top"),o=M(()=>[{value:"top",label:h(n)?"At cursor":"Top of file"},...h(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"}]);function s(g){if(t(t().prepend=!1,!0),t(t().insertAfter.enabled=!1,!0),t(t().insertAfter.promptHeading=!1,!0),t(t().insertAfter.inline=!1,!0),t(t().insertAfter.replaceExisting=!1,!0),t().insertBefore||t(t().insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"},!0),t(t().insertBefore.enabled=!1,!0),t().newLineCapture||t(t().newLineCapture={enabled:!1,direction:"below"},!0),t(t().newLineCapture.enabled=!1,!0),t(t().activeFileWritePosition="cursor",!0),g==="top"){h(n)||t(t().prepend=!1,!0);return}if(g==="activeTop"){h(n)&&t(t().activeFileWritePosition="top",!0);return}if(g==="bottom"){h(n)?t(t().activeFileWritePosition="bottom",!0):t(t().prepend=!0,!0);return}if(g==="newLineAbove"){t(t().newLineCapture.enabled=!0,!0),t(t().newLineCapture.direction="above",!0);return}if(g==="newLineBelow"){t(t().newLineCapture.enabled=!0,!0),t(t().newLineCapture.direction="below",!0);return}if(g==="before"){t(t().insertBefore.enabled=!0,!0);return}t(t().insertAfter.enabled=!0,!0)}let a=M(()=>{let g=typeof t().captureTo=="string"&&Cc(t().captureTo),y=e.app.workspace.getActiveViewOfType(m2.FileView)?.getViewType()==="canvas",w=h(n)&&!t().insertAfter.enabled&&!t().insertBefore?.enabled&&!t().newLineCapture?.enabled&&(t().activeFileWritePosition??"cursor")==="cursor"&&!t().prepend;return!(!(t().newLineCapture?.enabled||w)||(h(n)?!y:!g))});var l=UK(),c=Te(l);{let g=w=>{wt(w,{get value(){return h(i)},get options(){return h(o)},onchange:s})},y=M(()=>h(n)?"Where to place the capture in the current file.":"Where to place the capture in the target file.");Se(c,{name:"Write position",get desc(){return h(y)},control:g,$$slots:{control:!0}})}var u=S(c,2);{var d=g=>{MD(g,{get app(){return e.app},get plugin(){return e.plugin},get insertAfter(){return t().insertAfter},set insertAfter(y){t(t().insertAfter=y,!0)}})};X(u,g=>{t().insertAfter.enabled&&g(d)})}var f=S(u,2);{var p=g=>{RD(g,{get app(){return e.app},get plugin(){return e.plugin},get insertBefore(){return t().insertBefore},set insertBefore(y){t(t().insertBefore=y,!0)}})};X(f,g=>{t().insertBefore?.enabled&&g(p)})}var m=S(f,2);{var v=g=>{var y=qK();O(g,y)};X(m,g=>{h(a)&&g(v)})}O(r,l),me()}var zK=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"]),zE=Array.from(zK);It();var HK=V('<div class="qa-choice-icon-setting-control svelte-p1gcdx"><span class="qa-choice-icon-setting-preview svelte-p1gcdx" aria-hidden="true"><!></span> <input type="text" class="qa-choice-icon-input svelte-p1gcdx" aria-label="Choice icon"/></div>'),WK={hash:"svelte-p1gcdx",code:".qa-choice-icon-setting-control.svelte-p1gcdx {display:flex;align-items:center;gap:8px;min-width:min(18rem, 100%);}.qa-choice-icon-setting-preview.svelte-p1gcdx {display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--text-muted);}.qa-choice-icon-input.svelte-p1gcdx {width:100%;min-width:0;}"};function uy(r,e){fe(e,!0),Ke(r,WK);let t=le(e,"icon",15),n=M(()=>nf(e.type)),i=M(()=>typeof t()=="string"?t():""),o=M(()=>h(i).trim()||h(n));function s(l){return new An(e.app,l,zE,50)}function a(l){let c=l.currentTarget.value.trim();t(c||void 0)}{let l=u=>{var d=HK(),f=F(d),p=F(f);bt(p,{get iconId(){return h(o)},size:18}),D(f);var m=S(f,2);Bt(m),dr(m,(v,g)=>Td?.(v,g),()=>s),D(d),ae(()=>{Fi(m,h(i)),Ce(m,"placeholder",h(n))}),_e("input",m,a),O(u,d)},c=M(()=>`Lucide/Obsidian icon id. Leave empty to use ${h(n)}.`);Se(r,{name:"Icon",get desc(){return h(c)},control:l,$$slots:{control:!0}})}me()}nt(["input"]);var h2=V("<!> <!>",1),jK=V("<!> <!> <!>",1),GK=V("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);function ND(r,e){fe(e,!0);let t=le(e,"choice",15),n=M(()=>e.plugin.getTemplateFiles().map(G=>G.path)),i=[G=>new pi(e.app,G,e.plugin)];function o(G){let U=G.trim();return U?_c(U)?{valid:!0,message:"Contains format syntax \u2014 resolved at run time."}:Mi(e.app,U)!==null||"Template not found":!0}let s=[{value:"",label:"Follow global setting"},{value:"enabled",label:"Use selection"},{value:"disabled",label:"Ignore selection"}],a=M(()=>typeof t().useSelectionAsCaptureValue=="boolean"?t().useSelectionAsCaptureValue?"enabled":"disabled":"");function l(G){if(G===""){t(t().useSelectionAsCaptureValue=void 0,!0);return}t(t().useSelectionAsCaptureValue=G==="enabled",!0)}function c(G){t().templater||t(t().templater={},!0),t(t().templater.afterCapture=G?"wholeFile":"none",!0)}var u=GK(),d=Te(u);Zg(d,{get app(){return e.app},get name(){return t().name},set name(G){t(t().name=G,!0)}});var f=S(d,2);Se(f,{name:"Location",heading:!0});var p=S(f,2);PD(p,{get app(){return e.app},get plugin(){return e.plugin},get choice(){return t()},set choice(G){t(G)}});var m=S(p,2);{var v=G=>{var U=h2(),H=Te(U);Se(H,{name:"Create file if it doesn't exist",control:ce=>{Ot(ce,{get checked(){return t().createFileIfItDoesntExist.enabled},set checked(he){t(t().createFileIfItDoesntExist.enabled=he,!0)}})},$$slots:{control:!0}});var Y=S(H,2);{var ie=oe=>{Co(oe,{name:"Create file with a template",desc:"Path to the template QuickAdd applies to the new file.",get bodyVisible(){return t().createFileIfItDoesntExist.createWithTemplate},control:Ie=>{Ot(Ie,{get checked(){return t().createFileIfItDoesntExist.createWithTemplate},set checked(we){t(t().createFileIfItDoesntExist.createWithTemplate=we,!0)}})},children:(Ie,we=At)=>{jn(Ie,{get id(){return we()},get value(){return t().createFileIfItDoesntExist.template},placeholder:"Template path",get app(){return e.app},get suggestions(){return h(n)},maxSuggestions:50,validator:o,onChange:Ge=>t(t().createFileIfItDoesntExist.template=Ge.trim(),!0)})},$$slots:{control:!0,default:!0}})};X(Y,oe=>{t().createFileIfItDoesntExist.enabled&&oe(ie)})}O(G,U)};X(m,G=>{t().captureToActiveFile||G(v)})}var g=S(m,2);Se(g,{name:"Position",heading:!0});var y=S(g,2);LD(y,{get app(){return e.app},get plugin(){return e.plugin},get choice(){return t()},set choice(G){t(G)}});var w=S(y,2);Se(w,{name:"Linking",heading:!0});var T=S(w,2);Gv(T,{fileLabel:"captured",get app(){return e.app},get appendLink(){return t().appendLink},set appendLink(G){t(t().appendLink=G,!0)}});var b=S(T,2);Se(b,{name:"Copy link to clipboard",desc:"Copy a link to the captured file after the Capture choice runs.",control:U=>{{let H=M(()=>t().copyLinkToClipboard??!1);Ot(U,{get checked(){return h(H)},onchange:Y=>t(t().copyLinkToClipboard=Y,!0)})}},$$slots:{control:!0}});var E=S(b,2);Se(E,{name:"Content",heading:!0});var C=S(E,2);Se(C,{name:"Task",desc:"Formats the value as a task.",control:U=>{Ot(U,{get checked(){return t().task},set checked(H){t(t().task=H,!0)}})},$$slots:{control:!0}});var _=S(C,2);Co(_,{name:"Capture format",desc:"Set the format of the capture. When off, QuickAdd captures {{VALUE}} on its own - what you type at the prompt, or the current selection.",get bodyVisible(){return t().format.enabled},control:H=>{Ot(H,{get checked(){return t().format.enabled},set checked(Y){t(t().format.enabled=Y,!0)}})},children:(H,Y=At)=>{var ie=jK(),oe=Te(ie);jn(oe,{get id(){return Y()},inputKind:"textarea",placeholder:"Format",required:!0,requiredMessage:"Capture format is required when enabled",get makeSuggesters(){return i},get value(){return t().format.format},set value(Ie){t(t().format.format=Ie,!0)}});var ce=S(oe,2);Fd(ce,{get value(){return t().format.format}});var he=S(ce,2);xo(he,{get value(){return t().format.format},get app(){return e.app},get plugin(){return e.plugin}}),O(H,ie)},$$slots:{control:!0,default:!0}});var I=S(_,2);Se(I,{name:"Behavior",heading:!0});var q=S(I,2);{var B=G=>{var U=h2(),H=Te(U);Yv(H,{description:"Open the captured file.",get openFile(){return t().openFile},set openFile(oe){t(t().openFile=oe,!0)}});var Y=S(H,2);{var ie=oe=>{Kv(oe,{contextLabel:"captured",get fileOpening(){return t().fileOpening},set fileOpening(ce){t(t().fileOpening=ce,!0)}})};X(Y,oe=>{t().openFile&&oe(ie)})}O(G,U)};X(q,G=>{t().captureToActiveFile||G(B)})}var J=S(q,2);Se(J,{name:"Use editor selection as default value",desc:"Controls whether this Capture uses the current editor selection as {{VALUE}}. Does not affect {{SELECTED}}.",control:U=>{wt(U,{get value(){return h(a)},get options(){return s},onchange:l})},$$slots:{control:!0}});var re=S(J,2);Se(re,{name:"Run Templater on entire destination file after capture",desc:"Advanced / legacy: this executes any <% %> anywhere in the destination file (including inside code blocks).",control:U=>{{let H=M(()=>t().templater?.afterCapture==="wholeFile");Ot(U,{get checked(){return h(H)},onchange:c})}},$$slots:{control:!0}});var L=S(re,2);ry(L,{get dateOrigin(){return t().dateOrigin},set dateOrigin(G){t(t().dateOrigin=G,!0)}});var W=S(L,2);Qv(W,{get onePageInput(){return t().onePageInput},set onePageInput(G){t(t().onePageInput=G,!0)}});var j=S(W,2);sy(j,{get name(){return t().name},get dateOrigin(){return t().dateOrigin},get command(){return t().command},set command(G){t(t().command=G,!0)},get pickDayCommand(){return t().pickDayCommand},set pickDayCommand(G){t(t().pickDayCommand=G,!0)}});var $=S(j,2);uy($,{get type(){return t().type},get app(){return e.app},get icon(){return t().icon},set icon(G){t(t().icon=G,!0)}}),O(r,u),me()}function g2(r){return st({...r,choice:ys(r.choice)})}var v2=require("obsidian");function Rf(r){return ys(r)}function HE(r,e){if(r.containerEl.addClass("qa-choice-builder"),r.modalEl.querySelector(".qa-builder-footer"))return;let t=r.modalEl.ownerDocument,n=t.createElement("div");n.className="qa-builder-footer";let i=t.createElement("span");i.className="qa-builder-footer-note",i.textContent=`Changes to this ${e} are saved automatically`,n.appendChild(i);let o=t.createElement("button");o.type="button",o.className="mod-cta",o.textContent="Done",o.addEventListener("click",()=>r.close()),n.appendChild(o),r.modalEl.appendChild(n)}var Lf=class extends v2.Modal{constructor(t){super(t);this.svelteElements=[];this.waitForClose=new Promise(n=>{this.resolvePromise=n}),this.containerEl.addClass("quickAddModal"),HE(this,"choice"),this.open()}destroySvelteElements(){this.svelteElements.forEach(t=>t.destroy()),this.svelteElements=[]}getResultChoice(){return this.choice}onClose(){super.onClose(),this.destroySvelteElements(),this.resolvePromise(Rf(this.getResultChoice()))}};var Nf=class extends Lf{constructor(t,n,i){super(t);this.plugin=i;this.choice=n,this.normalizeChoice(),this.display()}normalizeChoice(){this.choice.insertBefore||(this.choice.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:$i}),this.choice.activeFileWritePosition||(this.choice.activeFileWritePosition="cursor"),this.choice.createFileIfItDoesntExist||(this.choice.createFileIfItDoesntExist={enabled:!1,createWithTemplate:!1,template:""}),!this.choice.captureToActiveFile&&!Cc(this.choice.captureTo)&&(this.choice.captureToCanvasNodeId=""),this.choice.openFile&&(this.choice.fileOpening=qr(this.choice.fileOpening))}display(){this.containerEl.addClass("captureChoiceBuilder"),this.formProps=g2({choice:this.choice,app:this.app,plugin:this.plugin});let t=ci(this.contentEl,ND,this.formProps,{what:"this capture choice's settings"});t.ok||(this.formProps=void 0),this.svelteElements.push(t)}getResultChoice(){return this.formProps?.choice??this.choice}};Je();var b2=[{id:"prompt",label:"Ask every time"},{id:"update",label:"Update existing file"},{id:"create",label:"Create another file"},{id:"keep",label:"Keep existing file"}],BD=[{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"}],YK=new Map(BD.map(r=>[r.id,r])),KK={update:"appendBottom",create:"duplicateSuffix",keep:"doNothing"},y2={"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"},QK={increment:XK,duplicateSuffix:ZK};function Bf(r){let e=YK.get(r);if(!e)throw new Error(`Unknown file exists mode: ${r}`);return e}function w2(r){return BD.filter(e=>e.category===r)}function C2(r){return Bf(r).category}function E2(){return[...BD]}function x2(r){return r.kind==="prompt"?"prompt":C2(r.mode)}function T2(r,e){return r==="prompt"?{kind:"prompt"}:e?.kind==="apply"&&C2(e.mode)===r?e:{kind:"apply",mode:KK[r]}}function S2(r){return typeof r!="string"||!Object.prototype.hasOwnProperty.call(y2,r)?null:y2[r]??null}async function _2(r,e,t){return await QK[e](r,t)}async function XK(r,e){let t=r;for(;await e(t);){let{basename:n,extension:i}=k2(t),o=n.match(/^(.*?)(\d+)$/);t=`${o?`${o[1]}${String(BigInt(o[2])+1n).padStart(o[2].length,"0")}`:`${n}1`}${i}`}return t}async function ZK(r,e){let t=r;for(;await e(t);){let{basename:n,extension:i}=k2(t),o=n.match(/^(.*) \((\d+)\)$/);t=`${o?`${o[1]} (${String(BigInt(o[2])+1n)})`:`${n} (1)`}${i}`}return t}function k2(r){return Cr.test(r)?{basename:r.replace(Cr,""),extension:".canvas"}:li.test(r)?{basename:r.replace(li,""),extension:".base"}:{basename:r.replace(Ht,""),extension:".md"}}De();Dt();Ca();var WE=class extends Hr{constructor(t,n,i,o){super(t,n);this.app=t;this.inputEl=n;this.suggestItems=i;this.currentItems=o}updateCurrentItems(t){this.currentItems=t}getSuggestions(t){return this.suggestItems.filter(n=>n.contains(t))}selectSuggestion(t){this.inputEl.value=t,this.inputEl.trigger("input"),this.close()}renderSuggestion(t,n){t&&n.setText(t)}};function jE(r){let e=t=>t.stopPropagation();return r.addEventListener("mousedown",e),r.addEventListener("touchstart",e,{passive:!0}),{destroy(){r.removeEventListener("mousedown",e),r.removeEventListener("touchstart",e)}}}var JK=V('<button type="button"><!></button>');function Vt(r,e){let t=le(e,"size",3,16),n=le(e,"extraClass",3,""),i=le(e,"disabled",3,!1);var o=JK();let s;var a=F(o);bt(a,{get iconId(){return e.iconId},get size(){return t()}}),D(o),dr(o,l=>jE?.(l)),ae(()=>{s=at(o,1,`qa-icon-button ${n()}`,null,s,{"is-pressed":e.ariaPressed===!0}),Ce(o,"aria-label",e.label),Ce(o,"aria-pressed",e.ariaPressed),Ce(o,"aria-haspopup",e.ariaHasPopup),Ce(o,"title",e.title),o.disabled=i()}),_e("click",o,function(...l){e.onclick?.apply(this,l)}),O(r,o)}nt(["click"]);var eQ=V('<div class="quickAddCommandListItem svelte-ee11ws"><span> </span> <!></div>'),tQ=V('<div class="quickAddFolderListGrid quickAddCommandList svelte-ee11ws"></div>'),rQ={hash:"svelte-ee11ws",code:`.quickAddCommandListItem.svelte-ee11ws {display:flex;align-items:center;justify-content:space-between;}
@media (min-width: 768px) {.quickAddFolderListGrid.svelte-ee11ws {display:grid;grid-template-columns:repeat(2, 1fr);column-gap:20px;}
}.quickAddCommandList.svelte-ee11ws {max-width:50%;margin:12px auto;}`};function VD(r,e){fe(e,!0),Ke(r,rQ);var t=tQ();jt(t,20,()=>e.folders,n=>n,(n,i)=>{var o=eQ(),s=F(o),a=F(s,!0);D(s);var l=S(s,2);{let c=M(()=>`Remove folder ${i}`);Vt(l,{iconId:"trash-2",get label(){return h(c)},onclick:()=>e.deleteFolder(i)})}D(o),ae(()=>ue(a,i)),O(n,o)}),D(t),O(r,t),me()}function A2(r){return r.enabled?r.chooseWhenCreatingNote?"prompt":r.createInSameFolderAsActiveFile?"active-file":"specified":"obsidian-default"}function D2(r,e){switch(e){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 I2=[{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"}],F2={"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."};Je();Je();function GE(r,e){if(!r.fileNameFormat?.enabled)return!0;let t=e.trim().toLowerCase();return t===zo.toLowerCase()||t===WM.toLowerCase()}function qD(r,e){return r.discoverExistingNotesBeforeCreate===!0&&GE(r,e)}function UD(r,e,t){return!(!qD(r,e)||t!=null)}Je();function YE(r){if(!r?.enabled||r.chooseWhenCreatingNote||r.chooseFromSubfolders||r.createInSameFolderAsActiveFile)return;let e=r.folders??[];if(e.length!==1)return;let t=e[0]?.trim();if(t&&!t.includes("{{")&&!fl.test(t))return t}var nQ=V("<!> <!> <!>",1),iQ=V(`<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>`),oQ=V('<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),sQ=V("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);function zD(r,e){fe(e,!0);let t=le(e,"choice",15),n=M(()=>e.plugin.getTemplateFiles().map(ye=>ye.path)),i=M(()=>Rl(Go(e.app)));function o(ye){let $e=ye.trim();return $e?_c($e)?{valid:!0,message:"Contains format syntax \u2014 resolved at run time."}:Mi(e.app,$e)!==null||"Template not found":!0}let s=[ye=>new pi(e.app,ye,e.plugin,"fileName")],a=M(()=>GE(t(),t().fileNameFormat.enabled?t().fileNameFormat.format:zo)),l=M(()=>h(a)?"For the default note-title prompt, show matching notes first. Choosing one opens it unchanged; choosing the create row continues with this template.":"Only available when the file name prompt is the default note title: no custom format, {{VALUE}}, or {{NAME}}."),c=M(()=>A2(t().folder)),u=M(()=>F2[h(c)]),d=M(()=>h(c)==="specified"&&t().folder.folders.length===0);function f(ye){t(t().folder=D2(t().folder,ye),!0)}let p=Ee(""),m;function v(ye){return m=new WE(e.app,ye,h(i),t().folder.folders),m}Xt(()=>{m?.updateCurrentItems(t().folder.folders)});function g(){let ye=h(p).trim();if(ye){if(t().folder.folders.some($e=>$e===ye)){P.logWarning("cannot add same folder twice.");return}t().folder.folders.push(ye),Q(p,"")}}function y(ye){t(t().folder.folders=t().folder.folders.filter($e=>$e!==ye),!0)}function w(ye){ye.key==="Enter"&&g()}let T=M(()=>x2(t().fileExistsBehavior)),b=M(()=>h(T)!=="prompt"&&h(T)!=="keep"),E=M(()=>w2(h(T)==="update"?"update":"create")),C=M(()=>t().fileExistsBehavior.kind==="apply"?t().fileExistsBehavior.mode:h(E)[0].id);function _(ye){t(t().fileExistsBehavior=T2(ye,t().fileExistsBehavior),!0)}function I(ye){t(t().fileExistsBehavior={kind:"apply",mode:ye},!0)}var q=sQ(),B=Te(q);Zg(B,{get app(){return e.app},get name(){return t().name},set name(ye){t(t().name=ye,!0)}});var J=S(B,2);Se(J,{name:"Template",heading:!0});var re=S(J,2);Co(re,{name:"Template path",desc:"Path to the template this choice creates notes from.",children:($e,ge=At)=>{jn($e,{get id(){return ge()},get value(){return t().templatePath},placeholder:"Template path",get app(){return e.app},get suggestions(){return h(n)},maxSuggestions:50,validator:o,onChange:xe=>t(t().templatePath=xe.trim(),!0)})},$$slots:{default:!0}});var L=S(re,2);Co(L,{name:"File name format",desc:"Set the file name format. When off, QuickAdd asks for the note title.",get bodyVisible(){return t().fileNameFormat.enabled},control:ge=>{Ot(ge,{get checked(){return t().fileNameFormat.enabled},set checked(xe){t(t().fileNameFormat.enabled=xe,!0)}})},children:(ge,xe=At)=>{var tt=nQ(),kt=Te(tt);jn(kt,{get id(){return xe()},placeholder:"File name format",get makeSuggesters(){return s},get value(){return t().fileNameFormat.format},set value(Lt){t(t().fileNameFormat.format=Lt,!0)}});var Pt=S(kt,2);Fd(Pt,{get value(){return t().fileNameFormat.format}});var gt=S(Pt,2);{let Lt=M(()=>YE(t().folder));xo(gt,{get value(){return t().fileNameFormat.format},formatterKind:"fileName",get targetFolderPath(){return h(Lt)},get app(){return e.app},get plugin(){return e.plugin}})}O(ge,tt)},$$slots:{control:!0,default:!0}});var W=S(L,2);Se(W,{name:"Location",heading:!0});var j=S(W,2);Se(j,{name:"New note location",get desc(){return h(u)},control:$e=>{wt($e,{get value(){return h(c)},get options(){return I2},ariaLabel:"New note location",onchange:f})},$$slots:{control:!0}});var $=S(j,2);{var G=ye=>{var $e=oQ(),ge=Te($e),xe=F(ge),tt=F(xe);VD(tt,{get folders(){return t().folder.folders},deleteFolder:y}),D(xe);var kt=S(xe,2),Pt=F(kt);Bt(Pt),Br(()=>Pi(Pt,()=>h(p),rt=>Q(p,rt))),dr(Pt,(rt,cr)=>Td?.(rt,cr),()=>v);var gt=S(Pt,2);D(kt),D(ge);var Lt=S(ge,2);{var Lr=rt=>{var cr=iQ();O(rt,cr)};X(Lt,rt=>{h(d)&&rt(Lr)})}var lt=S(Lt,2);Se(lt,{name:"Include subfolders",desc:"Get prompted to choose from both the selected folders and their subfolders when creating the note.",control:cr=>{Ot(cr,{get checked(){return t().folder.chooseFromSubfolders},set checked(ti){t(t().folder.chooseFromSubfolders=ti,!0)}})},$$slots:{control:!0}}),al("keypress",Pt,w),_e("click",gt,g),O(ye,$e)};X($,ye=>{h(c)==="specified"&&ye(G)})}var U=S($,2);Se(U,{name:"Linking",heading:!0});var H=S(U,2);Gv(H,{fileLabel:"created",get app(){return e.app},get appendLink(){return t().appendLink},set appendLink(ye){t(t().appendLink=ye,!0)}});var Y=S(H,2);Se(Y,{name:"Copy link to clipboard",desc:"Copy a link to the created file after the Template choice runs.",control:$e=>{{let ge=M(()=>t().copyLinkToClipboard??!1);Ot($e,{get checked(){return h(ge)},onchange:xe=>t(t().copyLinkToClipboard=xe,!0)})}},$$slots:{control:!0}});var ie=S(Y,2);Se(ie,{name:"Behavior",heading:!0});var oe=S(ie,2);Se(oe,{name:"Search existing notes before creating",get desc(){return h(l)},control:$e=>{{let ge=M(()=>h(a)?t().discoverExistingNotesBeforeCreate??!1:!1),xe=M(()=>!h(a));Ot($e,{get checked(){return h(ge)},get disabled(){return h(xe)},onchange:tt=>t(t().discoverExistingNotesBeforeCreate=tt,!0)})}},$$slots:{control:!0}});var ce=S(oe,2);Se(ce,{name:"If the target file already exists",desc:"Choose whether QuickAdd should ask what to do, update the existing file, create another file, or keep the existing file.",control:$e=>{{let ge=M(()=>b2.map(xe=>({value:xe.id,label:xe.label})));wt($e,{get value(){return h(T)},get options(){return h(ge)},onchange:_})}},$$slots:{control:!0}});var he=S(ce,2);{var Ie=ye=>{{let $e=tt=>{{let kt=M(()=>h(E).map(Pt=>({value:Pt.id,label:Pt.label})));wt(tt,{get value(){return h(C)},get options(){return h(kt)},onchange:I})}},ge=M(()=>h(T)==="update"?"Update action":"New file naming"),xe=M(()=>Bf(h(C)).description);Se(ye,{get name(){return h(ge)},get desc(){return h(xe)},control:$e,$$slots:{control:!0}})}};X(he,ye=>{h(b)&&ye(Ie)})}var we=S(he,2);Yv(we,{description:"Open the created file.",get openFile(){return t().openFile},set openFile(ye){t(t().openFile=ye,!0)}});var Ge=S(we,2);{var Pe=ye=>{Kv(ye,{contextLabel:"created",get fileOpening(){return t().fileOpening},set fileOpening($e){t(t().fileOpening=$e,!0)}})};X(Ge,ye=>{t().openFile&&ye(Pe)})}var Ve=S(Ge,2);ry(Ve,{get dateOrigin(){return t().dateOrigin},set dateOrigin(ye){t(t().dateOrigin=ye,!0)}});var qe=S(Ve,2);Qv(qe,{get onePageInput(){return t().onePageInput},set onePageInput(ye){t(t().onePageInput=ye,!0)}});var et=S(qe,2);sy(et,{get name(){return t().name},get dateOrigin(){return t().dateOrigin},get command(){return t().command},set command(ye){t(t().command=ye,!0)},get pickDayCommand(){return t().pickDayCommand},set pickDayCommand(ye){t(t().pickDayCommand=ye,!0)}});var _t=S(et,2);uy(_t,{get type(){return t().type},get app(){return e.app},get icon(){return t().icon},set icon(ye){t(t().icon=ye,!0)}}),O(r,q),me()}nt(["click"]);function P2(r){return st({...r,choice:ys(r.choice)})}var Vf=class extends Lf{constructor(t,n,i){super(t);this.plugin=i;this.choice=n,this.normalizeChoice(),this.display()}normalizeChoice(){var t,n,i,o,s,a,l,c,u,d,f;(t=this.choice).fileExistsBehavior??(t.fileExistsBehavior={kind:"prompt"}),this.choice.fileOpening=qr(this.choice.fileOpening),(n=this.choice).templatePath??(n.templatePath=""),(i=this.choice).fileNameFormat??(i.fileNameFormat={enabled:!1,format:""}),(o=this.choice.fileNameFormat).enabled??(o.enabled=!1),(s=this.choice.fileNameFormat).format??(s.format=""),(a=this.choice).folder??(a.folder={enabled:!1,folders:[],chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1,chooseFromSubfolders:!1}),(l=this.choice.folder).enabled??(l.enabled=!1),(c=this.choice.folder).folders??(c.folders=[]),(u=this.choice.folder).chooseWhenCreatingNote??(u.chooseWhenCreatingNote=!1),(d=this.choice.folder).createInSameFolderAsActiveFile??(d.createInSameFolderAsActiveFile=!1),(f=this.choice.folder).chooseFromSubfolders??(f.chooseFromSubfolders=!1)}display(){this.containerEl.addClass("templateChoiceBuilder"),this.formProps=P2({choice:this.choice,app:this.app,plugin:this.plugin});let t=ci(this.contentEl,zD,this.formProps,{what:"this template choice's settings"});t.ok||(this.formProps=void 0),this.svelteElements.push(t)}getResultChoice(){return this.formProps?.choice??this.choice}};Pd();var Ba=require("obsidian");Ns();var Zn=require("obsidian");var LB=require("obsidian");function M2(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function vy(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?M2(Object(t),!0).forEach(function(n){jf(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):M2(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function qf(r){"@babel/helpers - typeof";return qf=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},qf(r)}function jf(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function lQ(r,e){if(r==null)return{};var t={},n=Object.keys(r),i,o;for(o=0;o<n.length;o++)i=n[o],!(e.indexOf(i)>=0)&&(t[i]=r[i]);return t}function cQ(r,e){if(r==null)return{};var t=lQ(r,e),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(r);for(i=0;i<o.length;i++)n=o[i],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(r,n)&&(t[n]=r[n])}return t}function uQ(r,e){return pQ(r)||mQ(r,e)||tI(r,e)||gQ()}function is(r){return dQ(r)||fQ(r)||tI(r)||hQ()}function dQ(r){if(Array.isArray(r))return jD(r)}function pQ(r){if(Array.isArray(r))return r}function fQ(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function mQ(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n=[],i=!0,o=!1,s,a;try{for(t=t.call(r);!(i=(s=t.next()).done)&&(n.push(s.value),!(e&&n.length===e));i=!0);}catch(l){o=!0,a=l}finally{try{!i&&t.return!=null&&t.return()}finally{if(o)throw a}}return n}}function tI(r,e){if(r){if(typeof r=="string")return jD(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return jD(r,e)}}function jD(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function hQ(){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 gQ(){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 Od(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=tI(r))||e&&r&&typeof r.length=="number"){t&&(r=t);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(){t=t.call(r)},n:function(){var l=t.next();return o=l.done,l},e:function(l){s=!0,a=l},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}var vQ="finalize",yQ="consider";function Gf(r,e,t){r.dispatchEvent(new CustomEvent(vQ,{detail:{items:e,info:t}}))}function iu(r,e,t){r.dispatchEvent(new CustomEvent(yQ,{detail:{items:e,info:t}}))}var ox="draggedEntered",by="draggedLeft",sx="draggedOverIndex",rI="draggedLeftDocument",ZE={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function bQ(r,e,t){r.dispatchEvent(new CustomEvent(ox,{detail:{indexObj:e,draggedEl:t}}))}function wQ(r,e,t){r.dispatchEvent(new CustomEvent(by,{detail:{draggedEl:e,type:ZE.LEFT_FOR_ANOTHER,theOtherDz:t}}))}function CQ(r,e){r.dispatchEvent(new CustomEvent(by,{detail:{draggedEl:e,type:ZE.OUTSIDE_OF_ANY}}))}function EQ(r,e,t){r.dispatchEvent(new CustomEvent(sx,{detail:{indexObj:e,draggedEl:t}}))}function xQ(r){window.dispatchEvent(new CustomEvent(rI,{detail:{draggedEl:r}}))}var Gn={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:ox,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:sx,DRAGGED_LEFT:by,DRAGGED_LEFT_ALL:"draggedLeftAll",DROPPED_INTO_ZONE:"droppedIntoZone",DROPPED_INTO_ANOTHER:"droppedIntoAnother",DROPPED_OUTSIDE_OF_ANY:"droppedOutsideOfAny",DRAG_STOPPED:"dragStopped"},bi={POINTER:"pointer",KEYBOARD:"keyboard"},TQ={space:[" "],enter:["Enter"],space_or_enter:[" ","Enter"]},j2="space_or_enter",SQ={space:"space-bar",enter:"enter",space_or_enter:"space-bar or enter"},Qf="isDndShadowItem",ax="data-is-dnd-shadow-item-internal",_Q="data-is-dnd-shadow-item-hint",wy="id:dnd-shadow-placeholder-0000",kQ="dnd-action-dragged-el",gr="id",GD=0;function G2(){GD++}function Y2(){if(GD===0)throw new Error("Bug! trying to decrement when there are no dropzones");GD--}var nI=typeof window>"u",Xe=function(){};function YD(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,t,n=e?FQ(r):r.getBoundingClientRect(),i=getComputedStyle(r),o=i.transform;if(o){var s,a,l,c;if(o.startsWith("matrix3d("))t=o.slice(9,-1).split(/, /),s=+t[0],a=+t[5],l=+t[12],c=+t[13];else if(o.startsWith("matrix("))t=o.slice(7,-1).split(/, /),s=+t[0],a=+t[3],l=+t[4],c=+t[5];else return n;var u=i.transformOrigin,d=n.left-l-(1-s)*parseFloat(u),f=n.top-c-(1-a)*parseFloat(u.slice(u.indexOf(" ")+1)),p=s?n.width/s:r.offsetWidth,m=a?n.height/a:r.offsetHeight;return{x:d,y:f,width:p,height:m,top:f,right:d+p,bottom:f+m,left:d}}else return n}function KD(r){var e=YD(r);return{top:e.top+window.scrollY,bottom:e.bottom+window.scrollY,left:e.left+window.scrollX,right:e.right+window.scrollX}}function AQ(r){var e=r.getBoundingClientRect();return{top:e.top+window.scrollY,bottom:e.bottom+window.scrollY,left:e.left+window.scrollX,right:e.right+window.scrollX}}function K2(r){return{x:(r.left+r.right)/2,y:(r.top+r.bottom)/2}}function DQ(r,e){return Math.sqrt(Math.pow(r.x-e.x,2)+Math.pow(r.y-e.y,2))}function hy(r,e){return r.y<=e.bottom&&r.y>=e.top&&r.x>=e.left&&r.x<=e.right}function Q2(r){return K2(AQ(r))}function O2(r,e){var t=Q2(e);return DQ(r,t)}function IQ(r){var e=r.ownerDocument,t=e.defaultView||window,n=r.getBoundingClientRect(),i=n.top+t.scrollY,o=n.left+t.scrollX;return n.right+t.scrollX<0||o>e.documentElement.scrollWidth||n.bottom+t.scrollY<0||i>e.documentElement.scrollHeight}function FQ(r){for(var e=r.getBoundingClientRect(),t={top:e.top,bottom:e.bottom,left:e.left,right:e.right},n=!1,i=!1,o=r.parentElement;o&&o!==document.body;){var s=window.getComputedStyle(o),a=s.overflowY,l=s.overflowX,c=a==="scroll"||a==="auto",u=l==="scroll"||l==="auto";if(c||u){var d=o.getBoundingClientRect();if(c){var f=Math.max(t.top,d.top),p=Math.min(t.bottom,d.bottom);(f!==t.top||p!==t.bottom)&&(n=!0),t.top=f,t.bottom=p}if(u){var m=Math.max(t.left,d.left),v=Math.min(t.right,d.right);(m!==t.left||v!==t.right)&&(i=!0),t.left=m,t.right=v}}o=o.parentElement}return n||i?{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)}:{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)}}var zf;function iI(){Xe(function(){return"resetting indexes cache"}),zf=new Map}iI();function PQ(r){var e=Array.from(r.children).findIndex(function(t){return t.getAttribute(ax)});if(e>=0)return zf.has(r)||zf.set(r,new Map),zf.get(r).set(e,KD(r.children[e])),e}function $Q(r,e){var t=KD(e);if(!hy(r,t))return null;var n=e.children;if(n.length===0)return{index:0,isProximityBased:!0};for(var i=PQ(e),o=0;o<n.length;o++){var s=KD(n[o]);if(hy(r,s)){var a=zf.has(e)&&zf.get(e).get(o);return a&&!hy(r,a)?{index:i,isProximityBased:!1}:{index:o,isProximityBased:!1}}}for(var l=Number.MAX_VALUE,c=void 0,u=0;u<n.length;u++){var d=O2(r,n[u]);d<l&&(l=d,c=u)}if(n.length>0){var f=n.length,p=n[f-1],m=p.cloneNode(!1);m.style.visibility="hidden",m.style.pointerEvents="none",e.appendChild(m);var v=O2(r,m);v<l&&(c=f),e.removeChild(m)}return{index:c,isProximityBased:!0}}function zs(r){return JSON.stringify(r,null,2)}function JE(r){if(!r)throw new Error("cannot get depth of a falsy node");return X2(r,0)}function X2(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return r.parentElement?X2(r.parentElement,e+1):e-1}function MQ(r,e){if(Object.keys(r).length!==Object.keys(e).length)return!1;for(var t in r)if(!{}.hasOwnProperty.call(e,t)||e[t]!==r[t])return!1;return!0}function OQ(r,e){if(r.length!==e.length)return!1;for(var t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}var RQ=200,R2=10,QD;function LQ(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:RQ,n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0,o,s,a=!1,l,c=Array.from(e).sort(function(d,f){return JE(f)-JE(d)});function u(){var d=i(),f=n.multiScrollIfNeeded();if(!f&&l&&Math.abs(l.x-d.x)<R2&&Math.abs(l.y-d.y)<R2){QD=window.setTimeout(u,t);return}if(IQ(r)){Xe(function(){return"off document"}),xQ(r);return}l=d;var p=!1,m=Od(c),v;try{for(m.s();!(v=m.n()).done;){var g=v.value;f&&iI();var y=$Q(d,g);if(y!==null){var w=y.index;p=!0,g!==o?(o&&wQ(o,r,g),bQ(g,y,r),o=g):w!==s&&(EQ(g,y,r),s=w);break}}}catch(T){m.e(T)}finally{m.f()}!p&&a&&o?(CQ(o,r),o=void 0,s=void 0,a=!1):a=!0,QD=window.setTimeout(u,t)}u()}function NQ(){Xe(function(){return"unobserving"}),clearTimeout(QD),iI()}var py=30;function BQ(){var r;function e(){r={directionObj:void 0,stepPx:0}}e();function t(o){var s=r,a=s.directionObj,l=s.stepPx;if(a){o.scrollBy(a.x*l,a.y*l);var c=o.ownerDocument.defaultView||window;c.requestAnimationFrame(function(){return t(o)})}}function n(o){return py-o}function i(o,s){if(!s)return!1;var a=VQ(o,s),l=!!r.directionObj;if(a===null)return l&&e(),!1;var c=!1,u=!1;return s.scrollHeight>s.clientHeight&&(a.bottom<py?(c=!0,r.directionObj={x:0,y:1},r.stepPx=n(a.bottom)):a.top<py&&(c=!0,r.directionObj={x:0,y:-1},r.stepPx=n(a.top)),!l&&c)||s.scrollWidth>s.clientWidth&&(a.right<py?(u=!0,r.directionObj={x:1,y:0},r.stepPx=n(a.right)):a.left<py&&(u=!0,r.directionObj={x:-1,y:0},r.stepPx=n(a.left)),!l&&u)?(t(s),!0):(e(),!1)}return{scrollIfNeeded:i,resetScrolling:e}}function VQ(r,e){var t=e===document.scrollingElement?{top:0,bottom:window.innerHeight,left:0,right:window.innerWidth}:e.getBoundingClientRect();return hy(r,t)?{top:r.y-t.top,bottom:t.bottom-r.y,left:r.x-t.left,right:t.right-r.x}:null}function qQ(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1?arguments[1]:void 0;Xe(function(){return"creating multi-scroller"});var t=zQ(r),n=Array.from(t).sort(function(l,c){return JE(c)-JE(l)}),i=BQ(),o=i.scrollIfNeeded,s=i.resetScrolling;function a(){var l=e();if(!l||!n)return!1;for(var c=n.filter(function(f){return hy(l,f.getBoundingClientRect())||f===document.scrollingElement}),u=0;u<c.length;u++){var d=o(l,c[u]);if(d)return!0}return!1}return{multiScrollIfNeeded:t.size>0?a:function(){return!1},destroy:function(){return s()}}}function UQ(r){if(!r)return[];for(var e=[],t=r;t;){var n=window.getComputedStyle(t),i=n.overflow;i.split(" ").some(function(o){return o.includes("auto")||o.includes("scroll")})&&e.push(t),t=t.parentElement}return e}function zQ(r){var e=new Set,t=Od(r),n;try{for(t.s();!(n=t.n()).done;){var i=n.value;UQ(i).forEach(function(o){return e.add(o)})}}catch(o){t.e(o)}finally{t.f()}return(document.scrollingElement.scrollHeight>document.scrollingElement.clientHeight||document.scrollingElement.scrollWidth>document.scrollingElement.clientHeight)&&e.add(document.scrollingElement),e}function HQ(r){var e=r.cloneNode(!0),t=[],n=r.tagName==="SELECT",i=n?[r]:is(r.querySelectorAll("select")),o=Od(i),s;try{for(o.s();!(s=o.n()).done;){var a=s.value;t.push(a.value)}}catch(T){o.e(T)}finally{o.f()}if(i.length>0)for(var l=n?[e]:is(e.querySelectorAll("select")),c=0;c<l.length;c++){var u=l[c],d=t[c],f=u.querySelector('option[value="'.concat(d,'"'));f&&f.setAttribute("selected",!0)}var p=r.tagName==="CANVAS",m=p?[r]:is(r.querySelectorAll("canvas"));if(m.length>0)for(var v=p?[e]:is(e.querySelectorAll("canvas")),g=0;g<v.length;g++){var y=m[g],w=v[g];w.width=y.width,w.height=y.height,y.width>0&&y.height>0&&w.getContext("2d").drawImage(y,0,0)}return e}var yy=Object.freeze({USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT:"USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT"}),WQ=jf({},yy.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT,!1);function Z2(r){if(!yy[r])throw new Error("Can't get non existing feature flag ".concat(r,"! Supported flags: ").concat(Object.keys(yy)));return WQ[r]}var jQ=.2;function $d(r){return"".concat(r," ").concat(jQ,"s ease")}function J2(r){var e=r.style.transitionProperty.split(",").map(function(t){return t.trim()});e.includes("all")||(e.includes("width")||(r.style.transition+=", ".concat($d("width"))),e.includes("height")||(r.style.transition+=", ".concat($d("height"))))}function GQ(r,e){var t=r.getBoundingClientRect(),n=HQ(r);eB(r,n),n.id=kQ,n.style.position="fixed";var i=t.top,o=t.left;if(n.style.top="".concat(i,"px"),n.style.left="".concat(o,"px"),e){var s=K2(t);i-=s.y-e.y,o-=s.x-e.x,window.setTimeout(function(){n.style.top="".concat(i,"px"),n.style.left="".concat(o,"px")},0)}return n.style.margin="0",n.style.boxSizing="border-box",n.style.height="".concat(t.height,"px"),n.style.width="".concat(t.width,"px"),n.style.transition="".concat($d("top"),", ").concat($d("left"),", ").concat($d("background-color"),", ").concat($d("opacity"),", ").concat($d("color")," "),window.setTimeout(function(){return J2(n)},0),n.style.zIndex="9999",n.style.cursor="grabbing",n}function YQ(r){r.style.cursor="grab"}function KQ(r,e,t,n){J2(r),eB(e,r);var i=e.getBoundingClientRect(),o=r.getBoundingClientRect(),s=window.getComputedStyle(r),a=parseFloat(s.left),l=parseFloat(s.top),c=i.width-o.width,u=i.height-o.height;if(c||u){var d={left:o.width?(t-o.left)/o.width:0,top:o.height?(n-o.top)/o.height:0};Z2(yy.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-d.left*c,"px"),r.style.top="".concat(l-d.top*u,"px")}}function eB(r,e){var t=window.getComputedStyle(r);Array.from(t).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"||Z2(yy.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT)&&(n==="width"||n==="height")}).forEach(function(n){return e.style.setProperty(n,t.getPropertyValue(n),t.getPropertyPriority(n))})}function QQ(r,e){r.draggable=!1,r.ondragstart=function(){return!1},e?(r.style.userSelect="",r.style.WebkitUserSelect="",r.style.cursor=""):(r.style.userSelect="none",r.style.WebkitUserSelect="none",r.style.cursor="grab")}function tB(r){r.style.display="none",r.style.position="fixed",r.style.zIndex="-5"}function XQ(r){r.style.visibility="hidden",r.setAttribute(ax,"true")}function ZQ(r){r.style.visibility="",r.removeAttribute(ax)}function XE(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){},t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:function(){return[]};r.forEach(function(n){var i=e(n);Object.keys(i).forEach(function(o){n.style[o]=i[o]}),t(n).forEach(function(o){return n.classList.add(o)})})}function ex(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){},t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:function(){return[]};r.forEach(function(n){var i=e(n);Object.keys(i).forEach(function(o){n.style[o]=""}),t(n).forEach(function(o){return n.classList.contains(o)&&n.classList.remove(o)})})}function JQ(r){var e=r.style.minHeight;r.style.minHeight=window.getComputedStyle(r).getPropertyValue("height");var t=r.style.minWidth;return r.style.minWidth=window.getComputedStyle(r).getPropertyValue("width"),function(){r.style.minHeight=e,r.style.minWidth=t}}var e7="--any--",t7=100,r7=20,KE=3,n7=80,L2={outline:"rgba(255, 255, 102, 0.7) solid 2px"},N2="data-is-dnd-original-dragged-item",Fn,Gr,Zi,oI,mr,lx,nu,$n,Pa,Pn,Ll=!1,tx=!1,sI,Cy=!1,Uf=[],gy,$a,my=!1,aI=!1,Fa,tu=new Set,Nl=new Map,Mr=new Map,fy=new WeakMap;function i7(r,e){Xe(function(){return"registering drop-zone if absent"}),Nl.has(e)||Nl.set(e,new Set),Nl.get(e).has(r)||(Nl.get(e).add(r),G2())}function B2(r,e){var t=Nl.get(e);!t||!t.delete(r)||(Y2(),t.size===0&&Nl.delete(e))}function o7(){Xe(function(){return"watching dragged element"});var r=Nl.get(oI);if(!(!r||r.size===0)){tu.size>0&&XD(),tu=new Set(r);var e=Od(tu),t;try{for(e.s();!(t=e.n()).done;){var n=t.value;n.addEventListener(ox,rB),n.addEventListener(by,nB),n.addEventListener(sx,iB)}}catch(a){e.e(a)}finally{e.f()}window.addEventListener(rI,Yf);var i=Math.max.apply(Math,is(Array.from(tu).map(function(a){return Mr.get(a).dropAnimationDurationMs}))),o=i===0?r7:Math.max(i,t7);gy=qQ(tu,function(){return Pn});var s=aI?function(){return{x:Pn.x+window.scrollX,y:Pn.y+window.scrollY}}:function(){return Q2(Gr)};LQ(Gr,tu,o*1.07,gy,s)}}function XD(){Xe(function(){return"unwatching dragged element"});var r=Od(tu),e;try{for(r.s();!(e=r.n()).done;){var t=e.value;t.removeEventListener(ox,rB),t.removeEventListener(by,nB),t.removeEventListener(sx,iB)}}catch(n){r.e(n)}finally{r.f()}tu=new Set,window.removeEventListener(rI,Yf),gy&&(gy.destroy(),gy=void 0),NQ()}function cx(r){return r.findIndex(function(e){return!!e[Qf]})}function s7(r){var e;return vy(vy({},r),{},(e={},jf(e,Qf,!0),jf(e,gr,wy),e))}function rB(r){Xe(function(){return["dragged entered",r.currentTarget,r.detail]});var e=Mr.get(r.currentTarget),t=e.items,n=e.dropFromOthersDisabled;if(n&&r.currentTarget!==mr){Xe(function(){return"ignoring dragged entered because drop is currently disabled"});return}if(Cy=!1,t=t.filter(function(a){return a[gr]!==nu[gr]&&a[gr]!==wy}),Xe(function(){return"dragged entered items ".concat(zs(t))}),mr!==r.currentTarget){var i=Mr.get(mr).items,o=i.filter(function(a){return!a[Qf]});iu(mr,o,{trigger:Gn.DRAGGED_ENTERED_ANOTHER,id:Zi[gr],source:bi.POINTER})}var s=r.detail.indexObj.index;$n=r.currentTarget,t.splice(s,0,nu),iu(r.currentTarget,t,{trigger:Gn.DRAGGED_ENTERED,id:Zi[gr],source:bi.POINTER})}function nB(r){if(Ll){Xe(function(){return["dragged left",r.currentTarget,r.detail]});var e=Mr.get(r.currentTarget),t=e.items,n=e.dropFromOthersDisabled;if(n&&r.currentTarget!==mr&&r.currentTarget!==$n){Xe(function(){return"drop is currently disabled"});return}var i=is(t),o=cx(i);o!==-1&&i.splice(o,1);var s=$n;$n=void 0;var a=r.detail,l=a.type,c=a.theOtherDz;if(l===ZE.OUTSIDE_OF_ANY||l===ZE.LEFT_FOR_ANOTHER&&c!==mr&&Mr.get(c).dropFromOthersDisabled){Xe(function(){return"dragged left all, putting shadow element back in the origin dz"}),Cy=!0,$n=mr;var u=s===mr?i:is(Mr.get(mr).items);u.splice(lx,0,nu),iu(mr,u,{trigger:Gn.DRAGGED_LEFT_ALL,id:Zi[gr],source:bi.POINTER})}iu(r.currentTarget,i,{trigger:Gn.DRAGGED_LEFT,id:Zi[gr],source:bi.POINTER})}}function iB(r){Xe(function(){return["dragged is over index",r.currentTarget,r.detail]});var e=Mr.get(r.currentTarget),t=e.items,n=e.dropFromOthersDisabled;if(n&&r.currentTarget!==mr){Xe(function(){return"drop is currently disabled"});return}var i=is(t);Cy=!1;var o=r.detail.indexObj.index,s=cx(i);s!==-1&&i.splice(s,1),i.splice(o,0,nu),iu(r.currentTarget,i,{trigger:Gn.DRAGGED_OVER_INDEX,id:Zi[gr],source:bi.POINTER})}function rx(r){r.preventDefault();var e=r.touches?r.touches[0]:r;Pn={x:e.clientX,y:e.clientY},Gr.style.transform="translate3d(".concat(Pn.x-Pa.x,"px, ").concat(Pn.y-Pa.y,"px, 0)")}function Yf(){Xe(function(){return"dropped"}),tx=!0,window.removeEventListener("mousemove",rx),window.removeEventListener("touchmove",rx),window.removeEventListener("mouseup",Yf),window.removeEventListener("touchend",Yf),XD(),YQ(Gr),$n||(Xe(function(){return"element was dropped right after it left origin but before entering somewhere else"}),$n=mr),Xe(function(){return["dropped in dz",$n]});var r=Mr.get($n),e=r.items,t=r.type;ex(Nl.get(t),function(o){return Mr.get(o).dropTargetStyle},function(o){return Mr.get(o).dropTargetClasses});var n=cx(e);n===-1&&$n===mr&&(n=lx),e=e.map(function(o){return o[Qf]?Zi:o});function i(){XD(),sI(),Gf($n,e,{trigger:Cy?Gn.DROPPED_OUTSIDE_OF_ANY:Gn.DROPPED_INTO_ZONE,id:Zi[gr],source:bi.POINTER}),$n!==mr&&Gf(mr,Mr.get(mr).items,{trigger:Gn.DROPPED_INTO_ANOTHER,id:Zi[gr],source:bi.POINTER});var o=Array.from($n.children).find(function(s){return s.getAttribute(ax)});o&&ZQ(o),c7()}Mr.get($n).dropAnimationDisabled?i():a7(n,i)}function a7(r,e){var t=r>-1?YD($n.children[r],!1):YD($n,!1),n={x:t.left-parseFloat(Gr.style.left),y:t.top-parseFloat(Gr.style.top)},i=Mr.get($n),o=i.dropAnimationDurationMs,s="transform ".concat(o,"ms ease");Gr.style.transition=Gr.style.transition?Gr.style.transition+","+s:s,Gr.style.transform="translate3d(".concat(n.x,"px, ").concat(n.y,"px, 0)"),window.setTimeout(e,o)}function l7(r,e){var t={dz:r,destroy:e};Uf.push(t),window.requestAnimationFrame(function(){Uf.includes(t)&&(tB(r),document.body.appendChild(r))})}function c7(){Gr&&Gr.remove&&Gr.remove(),Fn&&Fn.remove&&Fn.remove(),Gr=void 0,Fn=void 0,Zi=void 0,oI=void 0,mr=void 0,lx=void 0,nu=void 0,$n=void 0,Pa=void 0,Pn=void 0,Ll=!1,tx=!1,sI=void 0,Cy=!1,$a&&clearTimeout($a),$a=void 0,my=!1,aI=!1,Fa=void 0,Uf.length&&(Xe(function(){return["will destroy zones that were removed during drag",Uf]}),Uf.forEach(function(r){var e=r.dz,t=r.destroy;t(),e.remove()}),Uf=[])}function u7(r,e){var t=!1,n=!1,i={items:void 0,type:void 0,flipDurationMs:0,dragDisabled:!1,morphDisabled:!1,dropFromOthersDisabled:!1,dropTargetStyle:L2,dropTargetClasses:[],transformDraggedElement:function(){},centreDraggedOnCursor:!1,useCursorForDetection:!1,dropAnimationDisabled:!1,delayTouchStartMs:0};Xe(function(){return["dndzone good to go options: ".concat(zs(e),", config: ").concat(zs(i)),{node:r}]});var o=new Map;function s(){window.addEventListener("mousemove",u,{passive:!1}),window.addEventListener("touchmove",u,{passive:!1,capture:!1}),window.addEventListener("mouseup",c,{passive:!1}),window.addEventListener("touchend",c,{passive:!1})}function a(){window.removeEventListener("mousemove",u),window.removeEventListener("touchmove",u),window.removeEventListener("mouseup",c),window.removeEventListener("touchend",c),$a&&(clearTimeout($a),$a=void 0,my=!1)}function l(){Fa===r&&(a(),Fa=void 0,Fn=void 0,Pa=void 0,Pn=void 0)}function c(m){if(Fa===r&&(l(),m.type==="touchend")){var v=new Event("click",{bubbles:!0,cancelable:!0});m.target.dispatchEvent(v)}}function u(m){if(!(n||Fa!==r)){var v=!!m.touches,g=v?m.touches[0]:m;if(v&&i.delayTouchStartMs>0&&!my){Pn={x:g.clientX,y:g.clientY},(Math.abs(Pn.x-Pa.x)>=KE||Math.abs(Pn.y-Pa.y)>=KE)&&($a&&(clearTimeout($a),$a=void 0),c(m));return}m.preventDefault(),Pn={x:g.clientX,y:g.clientY},(Math.abs(Pn.x-Pa.x)>=KE||Math.abs(Pn.y-Pa.y)>=KE)&&f()}}function d(m){if(m.target!==m.currentTarget&&(m.target.value!==void 0||m.target.isContentEditable)){Xe(function(){return"won't initiate drag on a nested input element"});return}if(m.button){Xe(function(){return"ignoring none left click button: ".concat(m.button)});return}if(n||Ll||Fa){Xe(function(){return"cannot start a new drag before finalizing the current drag or pending gesture"});return}var v=!!m.touches,g=v&&i.delayTouchStartMs>0;g||m.preventDefault(),m.stopPropagation(),Fa=r;var y=v?m.touches[0]:m;if(Pa={x:y.clientX,y:y.clientY},Pn=vy({},Pa),Fn=m.currentTarget,g){var w=Fn;my=!1,$a=window.setTimeout(function(){n||Fa!==r||Fn!==w||(my=!0,f())},i.delayTouchStartMs)}s()}function f(){var m;if(n||Fa!==r||Ll||!((m=Fn)!==null&&m!==void 0&&m.parentElement)){l();return}a(),Fa=void 0,Xe(function(){return["drag start config: ".concat(zs(i)),Fn]}),Ll=!0;var v=o.get(Fn);lx=v,mr=Fn.parentElement;var g=mr.closest("dialog")||mr.closest("[popover]")||mr.getRootNode(),y=g.body||g,w=i.items,T=i.type,b=i.centreDraggedOnCursor,E=i.useCursorForDetection,C=is(w);Zi=C[v],oI=T,nu=s7(Zi),aI=E,Gr=GQ(Fn,b&&Pn),y.appendChild(Gr);var _=Fn.ownerDocument.defaultView||window;function I(){!Gr||tx||(Fn.parentElement?_.requestAnimationFrame(I):(Fn.setAttribute(N2,!0),y.appendChild(Fn),o7(),tB(Fn),nu[gr]=Zi[gr],Gr.focus()))}_.requestAnimationFrame(I),XE(Array.from(Nl.get(i.type)).filter(function(q){return q===mr||!Mr.get(q).dropFromOthersDisabled}),function(q){return Mr.get(q).dropTargetStyle},function(q){return Mr.get(q).dropTargetClasses}),C.splice(v,1,nu),sI=JQ(mr),iu(mr,C,{trigger:Gn.DRAG_STARTED,id:Zi[gr],source:bi.POINTER}),window.addEventListener("mousemove",rx,{passive:!1}),window.addEventListener("touchmove",rx,{passive:!1,capture:!1}),window.addEventListener("mouseup",Yf,{passive:!1}),window.addEventListener("touchend",Yf,{passive:!1})}function p(m){var v=m.items,g=v===void 0?void 0:v,y=m.flipDurationMs,w=y===void 0?0:y,T=m.type,b=T===void 0?e7:T,E=m.dragDisabled,C=E===void 0?!1:E,_=m.morphDisabled,I=_===void 0?!1:_,q=m.dropFromOthersDisabled,B=q===void 0?!1:q,J=m.dropTargetStyle,re=J===void 0?L2:J,L=m.dropTargetClasses,W=L===void 0?[]:L,j=m.transformDraggedElement,$=j===void 0?function(){}:j,G=m.centreDraggedOnCursor,U=G===void 0?!1:G,H=m.useCursorForDetection,Y=H===void 0?!1:H,ie=m.dropAnimationDisabled,oe=ie===void 0?!1:ie,ce=m.delayTouchStart,he=ce===void 0?!1:ce;i.dropAnimationDurationMs=w;var Ie=0;he===!0?Ie=n7:typeof he=="number"&&isFinite(he)&&he>=0&&(Ie=he),i.delayTouchStartMs=Ie,i.type&&b!==i.type&&B2(r,i.type),i.type=b,i.items=is(g),i.dragDisabled=C,i.morphDisabled=I,i.transformDraggedElement=$,i.centreDraggedOnCursor=U,i.useCursorForDetection=Y,i.dropAnimationDisabled=oe,t&&Ll&&!tx&&(!MQ(re,i.dropTargetStyle)||!OQ(W,i.dropTargetClasses))&&(ex([r],function(){return i.dropTargetStyle},function(){return W}),XE([r],function(){return re},function(){return W})),i.dropTargetStyle=re,i.dropTargetClasses=is(W);function we(qe,et){return Mr.get(qe)?Mr.get(qe)[et]:i[et]}t&&Ll&&i.dropFromOthersDisabled!==B&&(B?ex([r],function(qe){return we(qe,"dropTargetStyle")},function(qe){return we(qe,"dropTargetClasses")}):XE([r],function(qe){return we(qe,"dropTargetStyle")},function(qe){return we(qe,"dropTargetClasses")})),i.dropFromOthersDisabled=B,Mr.set(r,i),i7(r,b);for(var Ge=Ll?cx(i.items):-1,Pe=0;Pe<r.children.length;Pe++){var Ve=r.children[Pe];if(QQ(Ve,C),Pe===Ge){I||KQ(Gr,Ve,Pn.x,Pn.y),i.transformDraggedElement(Gr,Zi,Pe),XQ(Ve);continue}Ve.removeEventListener("mousedown",fy.get(Ve)),Ve.removeEventListener("touchstart",fy.get(Ve)),C||(Ve.addEventListener("mousedown",d),Ve.addEventListener("touchstart",d),fy.set(Ve,d)),o.set(Ve,Pe),t||(t=!0)}}return p(e),{update:function(v){Xe(function(){return"pointer dndzone will update newOptions: ".concat(zs(v))}),p(v)},destroy:function(){if(n)return;n=!0,l();var v=Od(r.children),g;try{for(v.s();!(g=v.n()).done;){var y=g.value;y.removeEventListener("mousedown",fy.get(y)),y.removeEventListener("touchstart",fy.get(y))}}catch(T){v.e(T)}finally{v.f()}function w(){Xe(function(){return"pointer dndzone will destroy"});var T=Mr.get(r);T&&(B2(r,T.type),Mr.delete(r))}Ll&&!r.closest("[".concat(N2,"]"))?(Xe(function(){return"pointer dndzone will be scheduled for destruction"}),l7(r,w)):w()}}}var QE,ZD={DND_ZONE_ACTIVE:"dnd-zone-active",DND_ZONE_DRAG_DISABLED:"dnd-zone-drag-disabled"},oB=(QE={},jf(QE,ZD.DND_ZONE_ACTIVE,"zoneActiveInstruction"),jf(QE,ZD.DND_ZONE_DRAG_DISABLED,"zoneDragDisabledInstruction"),QE),sB={dragStarted:function(e){var t=e.itemLabel,n=e.zoneLabel,i=e.canMoveBetweenZones;return"Started dragging item ".concat(t,". 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(e){var t=e.itemLabel,n=e.zoneLabel,i=e.position;return"Moved item ".concat(t," to position ").concat(i," in the list ").concat(n)},movedToZoneEnd:function(e){var t=e.itemLabel,n=e.zoneLabel;return"Moved item ".concat(t," to the end of the list ").concat(n)},movedToZoneStart:function(e){var t=e.itemLabel,n=e.zoneLabel;return"Moved item ".concat(t," to the beginning of the list ").concat(n)},dropped:function(e){var t=e.itemLabel;return"Stopped dragging item ".concat(t)},zoneActiveInstruction:function(e){var t=e.keyboardDragTrigger;return"Tab to one the items and press ".concat(SQ[t]," to start dragging it")},zoneDragDisabledInstruction:"This is a disabled drag and drop list"};var d7=vy({},sB),p7={keyboardDragTrigger:j2},f7="dnd-action-aria-alert",jr;function JD(){jr||(jr=document.createElement("div"),(function(){jr.id=f7,jr.style.position="fixed",jr.style.bottom="0",jr.style.left="0",jr.style.zIndex="-5",jr.style.opacity="0",jr.style.height="0",jr.style.width="0",jr.setAttribute("role","alert")})(),document.body.prepend(jr),Object.entries(oB).forEach(function(r){var e=uQ(r,2),t=e[0],n=e[1];return document.body.prepend(g7(t,aB(n,p7)))}))}function m7(){return nI?null:(document.readyState==="complete"?JD():window.addEventListener("DOMContentLoaded",JD),vy({},ZD))}function h7(){nI||!jr||(Object.keys(oB).forEach(function(r){var e;return(e=document.getElementById(r))===null||e===void 0?void 0:e.remove()}),jr.remove(),jr=void 0)}function g7(r,e){var t=document.createElement("div");return t.id=r,v7(t,e),t.style.display="none",t.style.position="fixed",t.style.zIndex="-5",t}function v7(r,e){r.replaceChildren();var t=document.createElement("p");t.textContent=e,r.appendChild(t)}function Ey(r){if(!nI){jr||JD(),jr.innerHTML="";var e=document.createTextNode(r);jr.appendChild(e),jr.style.display="none",jr.style.display="inline"}}function V2(r,e,t){var n=r[e];return typeof n=="function"?n(t):n}function aB(r,e){try{return V2(d7,r,e)}catch(t){Xe(function(){return['aria string formatter for "'.concat(r,'" threw, falling back to the default'),t]});try{return V2(sB,r,e)}catch(n){return Xe(function(){return['default aria string formatter for "'.concat(r,'" also threw'),n]}),""}}}function Hf(r,e){Ey(aB(r,e))}var y7=j2;function b7(r){return TQ[y7].includes(r)}var w7="--any--",q2={outline:"rgba(255, 255, 102, 0.7) solid 2px"},Xi=!1,Wf,yi,Ma="",Md,To,ru="",nx=new WeakSet,HD=new WeakMap,WD=new WeakMap,eI=new Map,fn=new Map,Oa=new Map,ix;function C7(r,e){Xe(function(){return"registering drop-zone if absent"}),Oa.size===0&&(Xe(function(){return"adding global keydown and click handlers"}),ix=m7(),window.addEventListener("keydown",lB),window.addEventListener("click",cB)),Oa.has(e)||Oa.set(e,new Set),Oa.get(e).has(r)||(Oa.get(e).add(r),G2())}function U2(r,e){Xe(function(){return"unregistering drop-zone"}),Xi&&yi===r&&Kf();var t=Oa.get(e);!t||!t.delete(r)||(Y2(),t.size===0&&Oa.delete(e),Oa.size===0&&(Xe(function(){return"removing global keydown and click handlers"}),window.removeEventListener("keydown",lB),window.removeEventListener("click",cB),ix=void 0,h7()))}function lB(r){Xi&&r.key==="Escape"&&Kf()}function cB(){Xi&&(nx.has(document.activeElement)||(Xe(function(){return"clicked outside of any draggable"}),Kf()))}function uB(r,e){return r===yi||Md.contains(r)||e.dropFromOthersDisabled||e.type!==Wf?-1:0}function E7(){fn.forEach(function(r,e){e.tabIndex=uB(e,r)})}function x7(){var r=fn.get(yi);return r!=null&&r.items.some(function(e){return e[gr]===To})?!0:(Xe(function(){return"dragged item is gone, dropping"}),Kf(),!1)}function z2(r){if(Xe(function(){return"zone focus"}),!!Xi){var e=r.currentTarget;if(e!==yi&&x7()){Ma=e.getAttribute("aria-label")||"";var t=fn.get(yi),n=t.items,i=n.find(function(f){return f[gr]===To}),o=n.indexOf(i),s=n.splice(o,1)[0],a=fn.get(e),l=a.items,c=a.autoAriaDisabled;e.getBoundingClientRect().top<yi.getBoundingClientRect().top||e.getBoundingClientRect().left<yi.getBoundingClientRect().left?(l.push(s),c||Hf("movedToZoneEnd",{itemLabel:ru,zoneLabel:Ma,position:l.length,count:l.length})):(l.unshift(s),c||Hf("movedToZoneStart",{itemLabel:ru,zoneLabel:Ma,position:1,count:l.length}));var u=yi,d=To;yi=e,Gf(u,n,{trigger:Gn.DROPPED_INTO_ANOTHER,id:d,source:bi.KEYBOARD}),fn.has(e)&&Gf(e,l,{trigger:Gn.DROPPED_INTO_ZONE,id:d,source:bi.KEYBOARD})}}}function dB(){eI.forEach(function(r,e){var t=r.update;return t(fn.get(e))})}function Kf(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;if(!(!Xi||!yi)){Xe(function(){return"drop"});var e=yi,t=fn.get(e),n=To,i=Wf;if(t){if(!t.autoAriaDisabled){var o=t.items,s=o.findIndex(function(l){return l[gr]===n});Hf("dropped",{itemLabel:ru,zoneLabel:Ma,position:(s<0?0:s)+1,count:o.length})}nx.has(document.activeElement)&&document.activeElement.blur(),Md=null,To=null,ru="",Wf=null,yi=null,Ma="",Xi=!1,r&&iu(e,t.items,{trigger:Gn.DRAG_STOPPED,id:n,source:bi.KEYBOARD});var a=Oa.get(i);a&&ex(a,function(l){return fn.get(l).dropTargetStyle},function(l){return fn.get(l).dropTargetClasses}),dB()}}}function T7(r,e){var t=!1,n={items:void 0,type:void 0,dragDisabled:!1,zoneTabIndex:0,zoneItemTabIndex:0,dropFromOthersDisabled:!1,dropTargetStyle:q2,dropTargetClasses:[],autoAriaDisabled:!1};function i(d,f,p){d.length<=1||d.splice(p,1,d.splice(f,1,d[p])[0])}function o(d){switch(Xe(function(){return["handling key down",d.key]}),d.key){case"Enter":case" ":{if(!b7(d.key)||(d.target.disabled!==void 0||d.target.href||d.target.isContentEditable)&&!nx.has(d.target))return;d.preventDefault(),d.stopPropagation(),Xi?Kf():s(d);break}case"ArrowDown":case"ArrowRight":{if(!Xi)return;d.preventDefault(),d.stopPropagation();var f=fn.get(r),p=f.items,m=Array.from(r.children),v=m.indexOf(d.currentTarget);Xe(function(){return["arrow down",v]}),v<m.length-1&&(n.autoAriaDisabled||Hf("movedToPosition",{itemLabel:ru,zoneLabel:Ma,position:v+2,count:p.length}),i(p,v,v+1),Gf(r,p,{trigger:Gn.DROPPED_INTO_ZONE,id:To,source:bi.KEYBOARD}));break}case"ArrowUp":case"ArrowLeft":{if(!Xi)return;d.preventDefault(),d.stopPropagation();var g=fn.get(r),y=g.items,w=Array.from(r.children),T=w.indexOf(d.currentTarget);Xe(function(){return["arrow up",T]}),T>0&&(n.autoAriaDisabled||Hf("movedToPosition",{itemLabel:ru,zoneLabel:Ma,position:T,count:y.length}),i(y,T,T-1),Gf(r,y,{trigger:Gn.DROPPED_INTO_ZONE,id:To,source:bi.KEYBOARD}));break}}}function s(d){Xe(function(){return"drag start"}),l(d.currentTarget),yi=r,Ma=r.getAttribute("aria-label")||"",Wf=n.type,Xi=!0;var f=Array.from(Oa.get(n.type)).filter(function(v){return v===yi||!fn.get(v).dropFromOthersDisabled});if(XE(f,function(v){return fn.get(v).dropTargetStyle},function(v){return fn.get(v).dropTargetClasses}),!n.autoAriaDisabled){var p=fn.get(r).items,m=p.findIndex(function(v){return v[gr]===To});Hf("dragStarted",{itemLabel:ru,zoneLabel:Ma,position:(m<0?0:m)+1,count:p.length,canMoveBetweenZones:f.length>1})}iu(r,fn.get(r).items,{trigger:Gn.DRAG_STARTED,id:To,source:bi.KEYBOARD}),dB()}function a(d){Xi&&d.currentTarget!==Md&&(d.stopPropagation(),Kf(!1),s(d))}function l(d){var f=fn.get(r),p=f.items,m=Array.from(r.children),v=m.indexOf(d);Md=d,Md.tabIndex=n.zoneItemTabIndex,To=p[v][gr],ru=m[v].getAttribute("aria-label")||""}function c(d){var f=d.items,p=f===void 0?[]:f,m=d.type,v=m===void 0?w7:m,g=d.dragDisabled,y=g===void 0?!1:g,w=d.zoneTabIndex,T=w===void 0?0:w,b=d.zoneItemTabIndex,E=b===void 0?0:b,C=d.dropFromOthersDisabled,_=C===void 0?!1:C,I=d.dropTargetStyle,q=I===void 0?q2:I,B=d.dropTargetClasses,J=B===void 0?[]:B,re=d.autoAriaDisabled,L=re===void 0?!1:re;n.items=is(p),n.dragDisabled=y,n.dropFromOthersDisabled=_,n.zoneTabIndex=T,n.zoneItemTabIndex=E,n.dropTargetStyle=q,n.dropTargetClasses=J,n.autoAriaDisabled=L,n.type&&v!==n.type&&U2(r,n.type),n.type=v,C7(r,v),L||(r.setAttribute("role","list"),r.setAttribute("aria-describedby",y?ix.DND_ZONE_DRAG_DISABLED:ix.DND_ZONE_ACTIVE)),fn.set(r,n);var W=!1;Xi?(W=n.type===Wf&&n.items.some(function(G){return G[gr]===To})&&r!==yi,W&&(yi=r,Ma=r.getAttribute("aria-label")||""),r.tabIndex=uB(r,n)):r.tabIndex=n.zoneTabIndex,r.addEventListener("focus",z2);for(var j=function(U){var H,Y=r.children[U];nx.add(Y),Y.tabIndex=Xi?-1:n.zoneItemTabIndex,L||Y.setAttribute("role","listitem"),Y.removeEventListener("keydown",HD.get(Y)),Y.removeEventListener("click",WD.get(Y)),y||(Y.addEventListener("keydown",o),HD.set(Y,o),Y.addEventListener("click",a),WD.set(Y,a)),Xi&&n.type===Wf&&((H=n.items[U])===null||H===void 0?void 0:H[gr])===To&&(Xe(function(){return["focusing on",{i:U,focusedItemId:To}]}),Md=Y,Md.tabIndex=n.zoneItemTabIndex,Y.focus())},$=0;$<r.children.length;$++)j($);W&&E7()}c(e);var u={update:function(f){Xe(function(){return"keyboard dndzone will update newOptions: ".concat(zs(f))}),c(f)},destroy:function(){if(!t){t=!0,Xe(function(){return"keyboard dndzone will destroy"}),r.removeEventListener("focus",z2);var f=Od(r.children),p;try{for(f.s();!(p=f.n()).done;){var m=p.value;m.removeEventListener("keydown",HD.get(m)),m.removeEventListener("click",WD.get(m))}}catch(v){f.e(v)}finally{f.f()}U2(r,n.type),fn.delete(r),eI.delete(r)}}};return eI.set(r,u),u}var S7=["items","flipDurationMs","type","dragDisabled","morphDisabled","dropFromOthersDisabled","zoneTabIndex","zoneItemTabIndex","dropTargetStyle","dropTargetClasses","transformDraggedElement","autoAriaDisabled","centreDraggedOnCursor","useCursorForDetection","delayTouchStart","dropAnimationDisabled"];function ux(r,e){if(_7(r))return{update:function(){},destroy:function(){}};H2(e);var t=u7(r,e),n=T7(r,e);return{update:function(o){H2(o),t.update(o),n.update(o)},destroy:function(){t.destroy(),n.destroy()}}}function _7(r){return!!r.closest("[".concat(_Q,'="true"]'))}function H2(r){var e=r.items;r.flipDurationMs,r.type,r.dragDisabled,r.morphDisabled,r.dropFromOthersDisabled;var t=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=cQ(r,S7);if(Object.keys(s).length>0&&console.warn("dndzone will ignore unknown options",s),!e)throw new Error("no 'items' key provided to dndzone");var a=e.find(function(u){return!{}.hasOwnProperty.call(u,gr)});if(a)throw new Error("missing '".concat(gr,"' property for item ").concat(zs(a)));if(i&&!Array.isArray(i))throw new Error("dropTargetClasses should be an array but instead it is a ".concat(qf(i),", ").concat(zs(i)));if(t&&!W2(t))throw new Error("zoneTabIndex should be a number but instead it is a ".concat(qf(t),", ").concat(zs(t)));if(n&&!W2(n))throw new Error("zoneItemTabIndex should be a number but instead it is a ".concat(qf(n),", ").concat(zs(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(qf(o),", ").concat(zs(o)))}}function W2(r){return!isNaN(r)&&(function(e){return(e|0)===e})(parseFloat(r))}function pB(r){var e=r,t=new Set;return{get:function(){return e},set:function(i){e=i,Array.from(t).forEach(function(o){return o(e)})},subscribe:function(i){t.add(i),i(e)},unsubscribe:function(i){t.delete(i)}}}var DLe=pB(!0),ILe=pB(!1);var k7=[[9,5],[9,12],[9,19],[15,5],[15,12],[15,19]];function fB(r,e,t=!1){if(!r)return;r.classList.add("qa-drag-clone"),r.dataset.qaMulti=t?"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 k7)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!==e&&(i.textContent=e)}function Ra(r){return r.filter(e=>e.id!==wy)}function dx(r,e){let t=r.findIndex(i=>i.id===wy);if(t===-1)return null;let n={...r[t]};return delete n[Qf],{item:{...n,id:e},index:t}}function mB(r,e){return r.map(t=>t.id===e.id?e:t)}function px(r){let e=r.resolveLabel??(t=>t.name??"");return{items:r.items,dragDisabled:r.dragDisabled,flipDurationMs:r.flipDurationMs??0,morphDisabled:!0,useCursorForDetection:!0,centreDraggedOnCursor:!1,transformDraggedElement:(t,n)=>fB(t,n?e(n):"",n?.type==="Multi"),dropTargetStyle:{},dropTargetClasses:r.dropTargetClasses??[],dropAnimationDisabled:!0,autoAriaDisabled:!0,zoneItemTabIndex:-1,delayTouchStart:200,...r.type?{type:r.type}:{}}}function fx(){let r=Ee(!1),e=!1;function t(){Q(r,!0),e=!1;let n=()=>{window.removeEventListener("pointerup",n,!0),window.removeEventListener("pointercancel",n,!0),e||Q(r,!1)};window.addEventListener("pointerup",n,!0),window.addEventListener("pointercancel",n,!0)}return{get armed(){return h(r)},markStarted(){e=!0},reset(){Q(r,!1),e=!1},startDrag:t}}xa();Tr();yf();function Rd(r){if(r.type==="Choice")try{return kn().getChoiceById(r.choiceId).name}catch{return"(missing choice)"}if(r.type==="Conditional"){let e=r.condition;return`If ${vf(e)}`}return r.name}var A7=V('<button type="button"><!></button>');function Yn(r,e){fe(e,!0);let t=le(e,"size",3,16),n=M(()=>!!(e.onMoveUp||e.onMoveDown));function i(l){l.key==="ArrowUp"&&e.onMoveUp?(l.preventDefault(),l.stopPropagation(),e.onMoveUp()):l.key==="ArrowDown"&&e.onMoveDown&&(l.preventDefault(),l.stopPropagation(),e.onMoveDown())}var o=A7();let s;var a=F(o);bt(a,{iconId:"grip-vertical",get size(){return t()}}),D(o),ae(()=>{s=at(o,1,"qa-icon-button qa-drag-handle",null,s,{"qa-drag-handle-ready":e.dragDisabled,"qa-drag-handle-active":!e.dragDisabled}),Ce(o,"aria-label",e.label),Ce(o,"aria-keyshortcuts",h(n)?"ArrowUp ArrowDown":void 0),Ce(o,"tabindex",e.dragDisabled?0:-1)}),_e("pointerdown",o,()=>e.onDragStart()),_e("keydown",o,i),O(r,o),me()}nt(["pointerdown","keydown"]);var D7=V('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!></div></li>');function lI(r,e){fe(e,!0);var t=D7(),n=F(t),i=F(n,!0);D(n);var o=S(n,2),s=F(o);{let l=M(()=>`Delete ${Rd(e.command)}`);Vt(s,{iconId:"trash-2",get label(){return h(l)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var a=S(s,2);{let l=M(()=>`Reorder ${Rd(e.command)}`);Yn(a,{get label(){return h(l)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}D(o),D(t),ae(l=>ue(i,l),[()=>Rd(e.command)]),O(r,t),me()}Tr();var I7=V('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> <input type="number" min="0" placeholder=" " class="dotInput svelte-1h5tx3b" aria-label="Wait duration in milliseconds"/>ms</span> <div class="quickAddCommandControls"><!> <!></div></li>'),F7={hash:"svelte-1h5tx3b",code:".dotInput.svelte-1h5tx3b {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-1h5tx3b:hover {background-color:transparent;}"};function cI(r,e){fe(e,!0),Ke(r,F7);let t=Ee(void 0),n=Ee(st(xt(()=>e.command.time)));function i(){if(!h(t))return;let p=String(h(t).value).length;h(t).style.setProperty("--qa-wait-input-width",`${p===0?2:p}ch`)}function o(p){let m=p.currentTarget.valueAsNumber;Q(n,Number.isNaN(m)||m<0?0:m,!0),i(),e.onUpdateCommand({...e.command,time:h(n)})}Sw(i);var s=I7(),a=F(s),l=F(a),c=S(l);Bt(c),ll(c,p=>Q(t,p),()=>h(t)),tn(),D(a);var u=S(a,2),d=F(u);{let p=M(()=>`Delete ${e.command.name}`);Vt(d,{iconId:"trash-2",get label(){return h(p)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var f=S(d,2);{let p=M(()=>`Reorder ${e.command.name}`);Yn(f,{get label(){return h(p)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}D(u),D(s),ae(()=>{ue(l,`${e.command.name??""} for `),Fi(c,h(n))}),_e("input",c,o),O(r,s),me()}nt(["input"]);var P7=V('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function uI(r,e){fe(e,!0);var t=P7(),n=F(t),i=F(n,!0);D(n);var o=S(n,2),s=F(o);{let c=M(()=>`Configure ${e.command.name}`);Vt(s,{iconId:"settings",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onConfigureChoice(e.command)})}var a=S(s,2);{let c=M(()=>`Delete ${e.command.name}`);Vt(a,{iconId:"trash-2",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var l=S(a,2);{let c=M(()=>`Reorder ${e.command.name}`);Yn(l,{get label(){return h(c)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}D(o),D(t),ae(()=>ue(i,e.command.name)),O(r,t),me()}var $7=V('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function dI(r,e){fe(e,!0);var t=$7(),n=F(t),i=F(n,!0);D(n);var o=S(n,2),s=F(o);{let c=M(()=>`Configure ${e.command.name}`);Vt(s,{iconId:"settings",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onConfigureScript(e.command)})}var a=S(s,2);{let c=M(()=>`Delete ${e.command.name}`);Vt(a,{iconId:"trash-2",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var l=S(a,2);{let c=M(()=>`Reorder ${e.command.name}`);Yn(l,{get label(){return h(c)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}D(o),D(t),ae(()=>ue(i,e.command.name)),O(r,t),me()}var Xn=require("obsidian");xa();function hB(r,e){let t=r.ownerDocument.createElement("div");t.className="qa-format-preview-host",r.appendChild(t);let n=st({value:e.value,app:e.app,plugin:e.plugin,targetFolderPath:null}),i=ci(t,xo,n,{what:"the preview for this field"}),o=!1;return{setValue(s){o||(n.value=s)},destroy(){o||(o=!0,i.destroy(),t.remove())}}}function gB(r){r.addEventListener("focus",()=>{r.type="text"}),r.addEventListener("blur",()=>{r.type="password"}),r.type="password"}xx();Bl();function Q7(r){return typeof r=="string"?r:r==null?"":String(r)}function kB(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 Xn.Modal{constructor(t,n,i,o){super(t);this.command=n;this.settings=i;this.onCommandChange=o;this.previewHandles=[];this.command.settings||(this.command.settings={}),nm(this.command.settings,this.settings),this.display(),this.migrateSecretSettings()}display(){this.containerEl.addClass("quickAddModal","userScriptSettingsModal"),this.destroyPreviews(),this.contentEl.empty();let t=kB(this.settings?.name??this.command.name),n=kB(this.settings?.author);this.titleEl.innerText=`${t}${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(em(s)){let u=this.addSecretInput(o,"placeholder"in s?s.placeholder:void 0);s.description&&u.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(t,n,i,o){return new Xn.Setting(this.contentEl).setName(t).addText(s=>{s.setValue(n).onChange(a=>{this.command.settings[t]=a,this.onCommandChange?.()}).setPlaceholder(i??""),o&&gB(s.inputEl)})}addSecretInput(t,n){let i=new Xn.Setting(this.contentEl).setName(t),o="",s,a=()=>{let c=this.command.settings?.[t];return Ex(this.command,t)!==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(u=>{o=u}),c.inputEl.type="password",c.inputEl.addClass("qa-user-script-secret-input"),c.inputEl.setAttribute("aria-label",t),s=c.inputEl,l()}),i.addButton(c=>{c.setIcon("save").setTooltip("Save secret").onClick(async()=>{if(o.length===0){new Xn.Notice("Paste a secret before saving.");return}let u=await vI(this.app,this.command,t,o,Ex(this.command,t),this.settings.options?.[t]);if(!u){new Xn.Notice("SecretStorage is unavailable. Secret was not saved.");return}this.command.settings[t]=vx(u),o="",s&&(s.value=""),l(),this.onCommandChange?.(),new Xn.Notice("Secret saved.")}),c.buttonEl.setAttribute("aria-label",`Save ${t}`)}),i.addButton(c=>{c.setIcon("trash-2").setTooltip("Clear secret").onClick(async()=>{let u=Ex(this.command,t);if(u&&!await yI(this.app,u)){new Xn.Notice("SecretStorage is unavailable. Secret was not cleared.");return}delete this.command.settings[t],o="",s&&(s.value=""),l(),this.onCommandChange?.(),new Xn.Notice("Secret cleared.")}),c.buttonEl.setAttribute("aria-label",`Clear ${t}`)}),i}addTextArea(t,n,i){return new Xn.Setting(this.contentEl).setName(t).addTextArea(o=>{o.setValue(n).onChange(s=>{this.command.settings[t]=s,this.onCommandChange?.()}).setPlaceholder(i??""),o.inputEl.addClass("qa-user-script-argument-textarea")})}addToggle(t,n){return new Xn.Setting(this.contentEl).setName(t).addToggle(i=>i.setValue(n).onChange(o=>{this.command.settings[t]=o,this.onCommandChange?.()}))}addDropdown(t,n,i){return new Xn.Setting(this.contentEl).setName(t).addDropdown(o=>{n.forEach(s=>{o.addOption(s,s)}),o.setValue(i),o.onChange(s=>{this.command.settings[t]=s,this.onCommandChange?.()})})}addFormatInput(t,n,i){let o=new Xn.Setting(this.contentEl).setName(t),s=Q7(n),a=new Xn.TextAreaComponent(this.contentEl);new pi(this.app,a.inputEl,kn()),a.inputEl.addClass("qa-user-script-format-textarea"),a.inputEl.setAttribute("aria-label",t);let l=hB(this.contentEl,{app:this.app,plugin:kn(),value:s});return this.previewHandles.push(l),a.setValue(s).onChange(c=>{this.command.settings[t]=c,l.setValue(c),this.onCommandChange?.()}).setPlaceholder(i??""),o}destroyPreviews(){for(let t of this.previewHandles)t.destroy();this.previewHandles=[]}onClose(){this.destroyPreviews(),super.onClose()}async migrateSecretSettings(){await tm(this.app,this.command,this.settings)&&(this.onCommandChange?.(),this.display())}};De();Dt();var X7=V('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function wI(r,e){fe(e,!0);var t=X7(),n=F(t),i=F(n,!0);D(n);var o=S(n,2),s=F(o);{let c=M(()=>`Configure ${e.command.name}`);Vt(s,{iconId:"settings",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onConfigureAssistant(e.command)})}var a=S(s,2);{let c=M(()=>`Delete ${e.command.name}`);Vt(a,{iconId:"trash-2",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var l=S(a,2);{let c=M(()=>`Reorder ${e.command.name}`);Yn(l,{get label(){return h(c)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}D(o),D(t),ae(()=>ue(i,e.command.name)),O(r,t),me()}var Ni=require("obsidian");var Z7="QuickAdd sends the system prompt to the model as written - format syntax like {{DATE}} is not resolved here. Only the prompt template is formatted.",J7=0;function Sx(r,e,t){let n=r.createEl("div",{text:Z7,cls:"qa-literal-format-note"}),i=`qa-literal-format-note-${++J7}`;n.id=i;let o=s=>{let a=s.includes("{{");n.classList.toggle("qa-literal-format-note--shown",a),a?e.setAttribute("aria-describedby",i):e.removeAttribute("aria-describedby")};return o(t),o}Dt();ht();Ns();ky();var MB=require("obsidian");om();var i9=[{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 OB(r,e,t,n){let i=Ld(t,{silent:!0})?.model;i?.supportsTemperature===!1&&r.createEl("div",{text:`${i.name} uses fixed sampling, so these settings are not sent to it.`,cls:"setting-item-description"});for(let o of i9){let s=typeof e[o.key]=="number";new MB.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.setDynamicTooltip(),a.setValue(e[o.key]??o.fallback),a.onChange(l=>{e[o.key]=l})}).addExtraButton(a=>{a.setIcon("rotate-ccw"),a.setTooltip("Reset to provider default"),a.setDisabled(!s),a.onClick(()=>{delete e[o.key],n()})})}}om();fo();ht();var sm="Ask me",_x="__qa-missing-model__";function kx(r,e,t){let n=ne.getState().ai.providers,i=r.selectEl,o=i.ownerDocument;e={model:e.model,modelRef:gc(e.model,e.modelRef)},r.addOption(sm,sm);let s=new Map,a=0;for(let c of n){if(c.models.length===0)continue;let u=o.createElement("optgroup");u.label=c.name,i.appendChild(u);for(let d of c.models){let f=`${c.id??c.name}/${d.name}:${a++}`;s.set(f,{providerId:c.id,modelName:d.name});let p=o.createElement("option");p.value=f,p.text=d.name,u.appendChild(p)}}let l=o9(e,s);if(l)r.setValue(l);else{let c=e.modelRef?`${e.modelRef.providerId}/${e.modelRef.name}`:e.model;r.addOption(_x,`(missing) ${c}`);let u=Array.from(i.options).find(d=>d.value===_x);u&&(u.disabled=!0),r.setValue(_x)}r.onChange(c=>{if(c===_x)return;if(c===sm){t({model:sm,modelRef:void 0});return}let u=s.get(c);u&&t({model:u.modelName,modelRef:u.providerId?{providerId:u.providerId,name:u.modelName}:void 0})})}function o9(r,e){if(!r.model||r.model===sm)return sm;if(r.modelRef){for(let[n,i]of e)if(i.providerId===r.modelRef.providerId&&i.modelName===r.modelRef.name)return n;return}let t=Ld(r.model,{silent:!0});if(t){for(let[n,i]of e)if(i.providerId===t.provider.id&&i.modelName===t.model.name)return n}}fo();var Ax=class extends Ni.Modal{constructor(t,n){super(t);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 Ji(this.settings.systemPrompt)}resolve(t){this.isResolved||(this.isResolved=!0,this.resolvePromise(t))}cloneSettings(t){return{...t,promptTemplate:{...t.promptTemplate},modelParameters:{...t.modelParameters}}}restoreOriginal(){let t=this.cloneSettings(this.originalSettings);Object.assign(this.settings,t),this.settings.promptTemplate=t.promptTemplate,this.settings.modelParameters=t.modelParameters}display(){let t=this.contentEl.createEl("h2");t.addClass("qa-clickable-modal-title"),t.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 sr.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={}),OB(this.contentEl,this.settings.modelParameters,gc(this.settings.model,this.settings.modelRef)??this.settings.model,()=>this.reload())),this.addSystemPromptSetting(this.contentEl),this.addButtonBar(this.contentEl)}addButtonBar(t){let n=t.createDiv({cls:"qa-command-button-row"});new Ni.ButtonComponent(n).setButtonText("Cancel").onClick(()=>{this.restoreOriginal(),this.resolve(null),this.close()}),new Ni.ButtonComponent(n).setButtonText("Save").setCta().onClick(()=>{this.resolve(this.settings),this.close()})}reload(){this.contentEl.empty(),this.display()}addPromptTemplateSetting(t){let n=ne.getState().ai.promptTemplatesFolderPath,i=ho(this.app,n).map(o=>o.name);new Ni.Setting(t).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 An(this.app,o.inputEl,i)})}addModelSetting(t){new Ni.Setting(t).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(n=>{kx(n,this.settings,i=>{this.settings.model=i.model,this.settings.modelRef=i.modelRef,this.reload()})})}addOutputVariableNameSetting(t){new Ni.Setting(t).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(t){new Ni.Setting(t).setName("System prompt").setDesc("The system prompt for the AI Assistant");let n=this.contentEl.createEl("div"),i=n.createEl("span",{cls:"qa-ai-token-count"}),o=n.createEl("div",{text:"Estimated locally. Providers enforce exact context limits.",cls:"qa-ai-token-note"});n.appendChild(i),n.appendChild(o);let s=new Ni.TextAreaComponent(t);s.inputEl.addClass("qa-ai-prompt-textarea"),s.inputEl.setAttribute("aria-label","System prompt");let a=Sx(t,s.inputEl,this.settings.systemPrompt??""),l=(0,Ni.debounce)(()=>{i.innerText=`Estimated tokens: ${this.systemPromptTokenLength}`},50);s.setValue(this.settings.systemPrompt).onChange(c=>{this.settings.systemPrompt=c,a(c),l()}),l()}addShowAdvancedSettingsToggle(t){new Ni.Setting(t).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 s9=V('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function xI(r,e){fe(e,!0);var t=s9(),n=F(t),i=F(n,!0);D(n);var o=S(n,2),s=F(o);{let c=M(()=>`Configure ${e.command.name}`);Vt(s,{iconId:"settings",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onConfigureOpenFile(e.command)})}var a=S(s,2);{let c=M(()=>`Delete ${e.command.name}`);Vt(a,{iconId:"trash-2",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var l=S(a,2);{let c=M(()=>`Reorder ${e.command.name}`);Yn(l,{get label(){return h(c)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}D(o),D(t),ae(()=>ue(i,e.command.name)),O(r,t),me()}var La=require("obsidian");Dx();Tr();var Ix=class extends La.Modal{constructor(t,n){super(t);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(t){this.isResolved||(this.resolvePromise(t),this.isResolved=!0)}display(){this.containerEl.addClass("quickAddModal","openFileCommandSettingsModal"),this.contentEl.empty();let t=this.contentEl.createEl("h2");t.textContent="Open file command settings",t.addClass("qa-modal-title"),this.addFilePathSetting(),this.addOpenLocationSetting(),this.addFocusSetting(),this.addButtonBar()}addFilePathSetting(){new La.Setting(this.contentEl).setName("File path").setDesc("Path to the file. Supports formatting like {{DATE}}, {{VALUE}}, etc.").addText(t=>t.setPlaceholder("{{DATE}}todo.md").setValue(this.command.filePath).onChange(n=>{this.command.filePath=n,this.command.name=`Open file: ${n}`}))}addOpenLocationSetting(){let t=[{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 La.Setting(this.contentEl).setName("Where to open").setDesc("Choose tab, split, window, or sidebar").addDropdown(n=>{for(let{value:i,label:o}of t)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(t){switch(t){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 La.Setting(this.contentEl).setName("Split direction").setDesc("How to arrange the new pane relative to the current one").addDropdown(t=>{t.addOption("vertical","Split right").addOption("horizontal","Split down").setValue(this.command.direction??"vertical").onChange(n=>{this.command.direction=n})})}addFocusSetting(){new La.Setting(this.contentEl).setName("Focus opened file").setDesc("Bring the opened file to the foreground").addToggle(t=>t.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 t=this.contentEl.createDiv({cls:"qa-command-button-row qa-command-button-row-compact"});new La.ButtonComponent(t).setButtonText("Cancel").onClick(()=>{this.resolveWithGuard(null),this.close()}),new La.ButtonComponent(t).setButtonText("Save").setCta().onClick(()=>{this.resolveWithGuard(this.command),this.close()})}reload(){this.display()}};yf();Qn();var a9=V('<li class="quickAddCommandListItem conditionalCommand svelte-p3uofi"><div class="quickAddCommandLabel"><div class="conditionalSummary svelte-p3uofi"> </div> <div class="conditionalBranches svelte-p3uofi"><span> </span> <span> </span></div></div> <div class="quickAddCommandControls"><!> <!> <!> <!> <!></div></li>'),l9={hash:"svelte-p3uofi",code:".conditionalCommand.svelte-p3uofi {flex-wrap:wrap;}.conditionalSummary.svelte-p3uofi {font-weight:600;margin-bottom:4px;}.conditionalBranches.svelte-p3uofi {display:flex;gap:12px;font-size:0.9em;opacity:0.8;}"};function TI(r,e){fe(e,!0),Ke(r,l9);let t=M(()=>vf(e.command.condition)),n=M(()=>ar(e.command.thenCommands).length),i=M(()=>ar(e.command.elseCommands).length);var o=a9(),s=F(o),a=F(s),l=F(a,!0);D(a);var c=S(a,2),u=F(c),d=F(u);D(u);var f=S(u,2),p=F(f);D(f),D(c),D(s);var m=S(s,2),v=F(m);{let b=M(()=>`Edit condition for ${h(t)}`);Vt(v,{iconId:"settings",get label(){return h(b)},extraClass:"clickable",onclick:()=>e.onConfigureCondition(e.command)})}var g=S(v,2);{let b=M(()=>`Edit then branch for ${h(t)}`);Vt(g,{iconId:"corner-down-right",get label(){return h(b)},extraClass:"clickable",onclick:()=>e.onEditThenBranch(e.command)})}var y=S(g,2);{let b=M(()=>`Edit else branch for ${h(t)}`);Vt(y,{iconId:"corner-down-left",get label(){return h(b)},extraClass:"clickable",onclick:()=>e.onEditElseBranch(e.command)})}var w=S(y,2);{let b=M(()=>`Delete ${e.command.name}`);Vt(w,{iconId:"trash-2",get label(){return h(b)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var T=S(w,2);{let b=M(()=>`Reorder ${e.command.name}`);Yn(T,{get label(){return h(b)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}D(m),D(o),ae(()=>{ue(l,h(t)),ue(d,`Then: ${h(n)??""}`),ue(p,`Else: ${h(i)??""}`)}),O(r,o),me()}var c9=V('<ol class="quickAddCommandList svelte-16btmqx"></ol>'),u9={hash:"svelte-16btmqx",code:".quickAddCommandList.svelte-16btmqx {display:grid;grid-template-columns:auto;width:auto;border:0 solid black;overflow-y:auto;height:auto;margin-bottom:8px;padding:20px;}"};function SI(r,e){let t=Zh();fe(e,!0),Ke(r,u9);let n=le(e,"commands",31,()=>st([])),i=M(()=>{let j=new Set;return Array.isArray(n())?n().filter($=>{if(typeof $!="object"||$===null)return!1;let G=$.id;return typeof G!="string"||G===""||j.has(G)?!1:(j.add(G),!0)}):[]}),o=`command:${t}`,s=LB.Platform.isMobile,a=fx(),l=M(()=>!s&&!a.armed),c=j=>j,u=j=>j,d=j=>j,f=j=>j,p=j=>j,m=j=>j;function v(){e.saveCommands(Rf(n()))}let g=null;function y(j){a.markStarted();let $=j.detail.items;g=dx($,j.detail.info.id)??g,n(Ra($))}function w(j){let $=Ra(j.detail.items),G=j.detail.info.id;g?.item.id===G&&!$.some(U=>U.id===G)&&($=[...$],$.splice(Math.min(g.index,$.length),0,g.item)),g=null,n($),j.detail.info.source===bi.POINTER&&a.reset(),v()}let T=()=>{a.startDrag()};function b(j,$){let G=Ra(h(i)),U=G.findIndex(oe=>oe.id===j);if(U===-1)return;let H=U+$;if(H<0||H>=G.length)return;let Y=[...G],[ie]=Y.splice(U,1);Y.splice(H,0,ie),n(Y),v(),Ey(`Moved ${Rd(ie)} to position ${H+1} of ${G.length}`)}function E(j){n(mB(h(i),j)),v()}async function C(j){await e.onConfigureCondition?.(j)&&E(j)}async function _(j){await e.onEditThenBranch?.(j)&&E(j)}async function I(j){await e.onEditElseBranch?.(j)&&E(j)}async function q(j){let $=await B(j.choice)?.waitForClose;if(!$)return;let G={...j,choice:$,name:$.name};E(G)}function B(j){switch(j.type){case"Template":return new Vf(e.app,j,e.plugin);case"Capture":return new Nf(e.app,j,e.plugin);default:break}}async function J(j){let $=await Fs(j,e.app);if(!$){P.logWarning(`${j.name} could not be loaded.`);return}let G=$.settings??{};new Tx(e.app,j,G,()=>v()).open()}async function re(j){await new Ax(e.app,j).waitForClose&&E(j)}async function L(j){let $=await new Ix(e.app,j).waitForClose;$&&E($)}var W=c9();jt(W,21,()=>Ra(h(i)),j=>j.id,(j,$)=>{var G=Vr(),U=Te(G);{var H=we=>{{let Ge=M(()=>c(h($)));cI(we,{get command(){return h(Ge)},get dragDisabled(){return h(l)},startDrag:T,get onDeleteCommand(){return e.deleteCommand},onUpdateCommand:E,onMoveUp:()=>b(h($).id,-1),onMoveDown:()=>b(h($).id,1)})}},Y=we=>{{let Ge=M(()=>u(h($)));uI(we,{get command(){return h(Ge)},get dragDisabled(){return h(l)},startDrag:T,get onDeleteCommand(){return e.deleteCommand},onConfigureChoice:q,onMoveUp:()=>b(h($).id,-1),onMoveDown:()=>b(h($).id,1)})}},ie=we=>{{let Ge=M(()=>d(h($)));dI(we,{get command(){return h(Ge)},get dragDisabled(){return h(l)},startDrag:T,get onDeleteCommand(){return e.deleteCommand},onConfigureScript:J,onMoveUp:()=>b(h($).id,-1),onMoveDown:()=>b(h($).id,1)})}},oe=we=>{{let Ge=M(()=>f(h($)));wI(we,{get command(){return h(Ge)},get dragDisabled(){return h(l)},startDrag:T,get onDeleteCommand(){return e.deleteCommand},onConfigureAssistant:re,onMoveUp:()=>b(h($).id,-1),onMoveDown:()=>b(h($).id,1)})}},ce=we=>{{let Ge=M(()=>p(h($)));xI(we,{get command(){return h(Ge)},get dragDisabled(){return h(l)},startDrag:T,get onDeleteCommand(){return e.deleteCommand},onConfigureOpenFile:L,onMoveUp:()=>b(h($).id,-1),onMoveDown:()=>b(h($).id,1)})}},he=we=>{{let Ge=M(()=>m(h($)));TI(we,{get command(){return h(Ge)},get dragDisabled(){return h(l)},startDrag:T,get onDeleteCommand(){return e.deleteCommand},onConfigureCondition:C,onEditThenBranch:_,onEditElseBranch:I,onMoveUp:()=>b(h($).id,-1),onMoveDown:()=>b(h($).id,1)})}},Ie=we=>{lI(we,{get command(){return h($)},get dragDisabled(){return h(l)},startDrag:T,get onDeleteCommand(){return e.deleteCommand},onMoveUp:()=>b(h($).id,-1),onMoveDown:()=>b(h($).id,1)})};X(U,we=>{h($).type==="Wait"?we(H):h($).type==="NestedChoice"?we(Y,1):h($).type==="UserScript"?we(ie,2):h($).type==="AIAssistant"?we(oe,3):h($).type==="OpenFile"?we(ce,4):h($).type==="Conditional"?we(he,5):we(Ie,-1)})}O(j,G)}),D(W),dr(W,(j,$)=>ux?.(j,$),()=>px({items:h(i),dragDisabled:h(l),type:o,resolveLabel:Rd})),al("consider",W,y),al("finalize",W,w),O(r,W),me()}function NB(r){return st(r)}Vl();Tr();Ea();var Ay=class extends Mn{constructor(t,n){super(t,"Obsidian");this.generateId=()=>this.id=ir();this.commandId=n}};Vl();Tr();var Fx=class extends Mn{constructor(e,t){super(e,"Choice"),this.choiceId=t}};Vl();Tr();var Px=class extends Mn{constructor(e){super("Wait","Wait"),this.time=e}};Tr();Vl();var $x=class extends Mn{constructor(e){super(e.name,"NestedChoice"),this.choice=e}};Ea();var Na=class{constructor(e,t){this.id=ir(),this.name=e,this.type=t,this.command=!1,this.onePageInput=void 0}};Je();var am=class extends Na{constructor(e){super(e,"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:!1,considerSubsections:!1,createIfNotFound:!1,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=qr(),this.templater={afterCapture:"none"}}static Load(e){let t=e;return t.activeFileWritePosition!=="cursor"&&t.activeFileWritePosition!=="top"&&t.activeFileWritePosition!=="bottom"&&(t.activeFileWritePosition="cursor"),typeof t.captureToCanvasNodeId!="string"&&(t.captureToCanvasNodeId=""),t.insertBefore||(t.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"}),t.captureToActiveFile&&t.prepend&&!t.insertAfter?.enabled&&!t.insertBefore.enabled&&!t.newLineCapture?.enabled&&(t.activeFileWritePosition!=="top"&&(t.activeFileWritePosition="bottom"),t.prepend=!1),t.templater||(t.templater={afterCapture:"none"}),t.templater.afterCapture!=="wholeFile"&&(t.templater.afterCapture="none"),t.insertAfter&&!t.insertAfter.blankLineAfterMatchMode&&(t.insertAfter.blankLineAfterMatchMode="auto"),t.insertAfter&&t.insertAfter.inline===void 0&&(t.insertAfter.inline=!1),t.insertAfter&&t.insertAfter.replaceExisting===void 0&&(t.insertAfter.replaceExisting=!1),t.insertAfter&&t.insertAfter.promptHeading===void 0&&(t.insertAfter.promptHeading=!1),t.insertAfter?.createIfNotFoundLocation===Ds&&(t.insertAfter.createIfNotFound&&!t.insertAfter.orderBy&&(t.insertAfter.orderBy={by:"insertion",direction:"desc",unparseable:"bottom"}),t.insertAfter.inline=!1),t}};var au=class extends Na{constructor(e){super(e,"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=qr(),this.fileExistsBehavior={kind:"prompt"}}static Load(e){return e}};var BB=require("obsidian");Je();Eg();function Mx(r){let e=[];for(let t of r.vault.getFiles())Ck.test(t.path)?e.push({file:t,isMarkdown:!1}):Ht.test(t.path)&&d9(r,t)&&e.push({file:t,isMarkdown:!0});return e}function d9(r,e){return r.metadataCache.getFileCache(e)?.sections?.some(n=>n.type==="code")??!1}function VB(r,e,t){let n=e.find(s=>s.file.path===t);if(n)return n;let i=e.find(s=>!s.isMarkdown&&s.file.basename===t);if(i)return i;let o=r.vault.getAbstractFileByPath(t);if(o instanceof BB.TFile){if(Ck.test(o.path))return{file:o,isMarkdown:!1};if(Ht.test(o.path))return{file:o,isMarkdown:!0}}return null}async function Dy(r,e){let t=await r.vault.read(e),{code:n,error:i}=vl(t);return n!==null&&n.length>0?null:i??"No ```js code block found in the note."}function _I(r){return r.isMarkdown?r.file.path:r.file.basename}Vl();Tr();var Iy=class extends Mn{constructor(e,t){super(e,"UserScript"),this.path=t,this.settings={}}};Pd();var qB=require("obsidian");function Ox(r){let t=new qB.Notice("",1e4).messageEl;t.replaceChildren(),lm(t,"No scripts found","quickadd-notice-title");let n=t.ownerDocument,i=n.createElement("div");t.append(i),lm(i,"QuickAdd cannot find any .js files or notes with a ```js code block in your vault."),i.append(n.createElement("br")),lm(i,"Please make sure your scripts are:"),lm(i,`\u2713 In your vault (not in ${r.vault.configDir} folder)`),lm(i,"\u2713 Not in hidden folders (starting with a dot)"),lm(i,"\u2713 A .js file, or a note containing a ```js code block"),i.append(n.createElement("br")),_E(i,Ia.userScripts,"View documentation")}function lm(r,e,t){let n=r.ownerDocument.createElement("div");return n.textContent=e,t&&n.classList.add(t),r.append(n),n}lu();De();So();kI();AI();DI();II();FI();PI();$I();MI();OI();RI();Vl();Tr();ht();fo();var Lx=class extends Mn{constructor(){super("AI Assistant","AIAssistant");let e=ne.getState().ai;this.model=e.defaultModel;let t=gc(e.defaultModel,e.defaultModelRef);this.modelRef=t?{...t}:void 0,this.systemPrompt=e.defaultSystemPrompt,this.outputVariableName="output",this.promptTemplate={enable:!1,name:""},this.modelParameters={}}};ht();Tr();Ea();Dx();var Nx=class{constructor(e="{{DATE}}.md",t=!1,n,i,o=!0){this.filePath=e;this.type="OpenFile";this.id=ir();this.openInNewTab=t,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}}};Dt();Vl();Tr();function p9(){return{mode:"variable",variableName:"",operator:"isTruthy",valueType:"string"}}function f9(r){return r.mode==="variable"?{...r}:{...r}}var Bx=class extends Mn{constructor(e){super(e?.name??"If condition","Conditional"),this.condition=e?.condition?f9(e.condition):p9(),this.thenCommands=e?.thenCommands?[...e.thenCommands]:[],this.elseCommands=e?.elseCommands?[...e.elseCommands]:[]}};Bl();Qn();var m9=V(`<div class="qaDataUnreadable svelte-ktqmtm"><div class="qaDataUnreadableHead svelte-ktqmtm"><!> <span class="qaDataUnreadableTitle svelte-ktqmtm"> </span></div> <p class="qaDataUnreadableBody svelte-ktqmtm">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-ktqmtm">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>`),h9={hash:"svelte-ktqmtm",code:".qaDataUnreadable.svelte-ktqmtm {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-ktqmtm {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaDataUnreadableTitle.svelte-ktqmtm {font-weight:var(--font-semibold);color:var(--text-normal);}.qaDataUnreadableBody.svelte-ktqmtm {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}"};function LI(r,e){Ke(r,h9);var t=m9(),n=F(t),i=F(n);bt(i,{iconId:"alert-triangle",size:16});var o=S(i,2),s=F(o);D(o),D(n),tn(4),D(t),ae(()=>ue(s,`QuickAdd couldn't read ${e.what??""}`)),O(r,t)}var bm=class{constructor(e){this.obsidianCommands=[];this.scriptCandidates=[];this.commandListHandle=null;this.commandListProps=null;this.containerEl=null;this.unreadableCardHandle=null;this.app=e.app,this.plugin=e.plugin,this.unreadable=Kn(e.commands),this.commandsRef=pI(e.commands).commands,this.choices=e.choices,this.onCommandsChange=e.onCommandsChange,this.conditionalHandlers=e.conditionalHandlers,this.loadObsidianCommands(),this.loadScriptCandidates()}render(e){return this.destroy(),this.containerEl=e,e.empty(),e.addClass("quickAddCommandEditor"),this.unreadable?(this.renderUnreadableCard(e),!1):this.renderCommandList(e)?(this.renderCommandBar(e),this.renderAddObsidianCommandSetting(e),this.renderAddEditorCommandSetting(e),this.renderAddUserScriptSetting(e),this.renderAddChoiceSetting(e),!0):!1}renderUnreadableCard(e){let t=e.createDiv("commandList");this.unreadableCardHandle=ci(t,LI,{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(e=>{let t=this.app.commands.commands[e];this.obsidianCommands.push(new Ay(t.name,t.id))})}loadScriptCandidates(){this.scriptCandidates=Mx(this.app)}renderCommandList(e){let t=e.createDiv("commandList");return this.commandListProps=NB({app:this.app,plugin:this.plugin,commands:this.commandsRef,deleteCommand:async n=>{let i=this.commandsRef.find(a=>a.id===n);if(!i)throw P.logError("command not found"),new Error("command not found");if(!await vi.Prompt(this.app,"Are you sure you wish to delete this command?",`If you click yes, you will delete '${i.name}'.`))return;if(!await _y(this.app,i)){new Zn.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=ci(t,SI,this.commandListProps,{what:"this macro's commands"}),this.commandListHandle.ok}renderCommandBar(e){let t=e.createDiv("quickCommandContainer");this.addChoiceButton(t,"Capture",am),this.addChoiceButton(t,"Template",au),this.addOpenFileCommandButton(t),this.addWaitCommandButton(t),this.addConditionalCommandButton(t),ne.getState().disableOnlineFeatures||this.addAIAssistantCommandButton(t)}renderAddObsidianCommandSetting(e){let t,n=()=>{let i=t.getValue(),o=this.obsidianCommands.find(a=>a.name===i);if(!o){P.logError(`Could not find Obsidian command with name "${i}"`);return}let s=new Ay(o.name,o.commandId);s.generateId(),this.addCommand(s),t.setValue("")};new Zn.Setting(e).setName("Obsidian command").setDesc("Add an Obsidian command").addText(i=>{t=i,i.inputEl.addClass("qa-command-sequence-input"),i.setPlaceholder("Obsidian command"),new An(this.app,i.inputEl,this.obsidianCommands.map(o=>o.name)),i.inputEl.addEventListener("keypress",o=>{o.key==="Enter"&&n()})}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}renderAddEditorCommandSetting(e){let t,n=()=>{let i=t.getValue(),o;switch(i){case"Copy":o=new cm;break;case"Cut":o=new um;break;case"Paste":o=new dm;break;case"Paste with format":o=new pm;break;case"Select active line":o=new fm;break;case"Select link on active line":o=new mm;break;case"Move cursor to file start":o=new hm;break;case"Move cursor to file end":o=new gm;break;case"Move cursor to line start":o=new vm;break;case"Move cursor to line end":o=new ym;break;default:throw P.logError("invalid editor command type"),new Error("invalid editor command type")}this.addCommand(o),t.setValue("")};new Zn.Setting(e).setName("Editor commands").setDesc("Add editor command").addDropdown(i=>{t=i,i.selectEl.addClass("qa-command-sequence-input"),i.addOption("","Select command").addOption("Copy","Copy").addOption("Cut","Cut").addOption("Paste","Paste").addOption("Paste with format","Paste with format").addOption("Select active line","Select active line").addOption("Select link on active line","Select link on active line").addOption("Move cursor to file start","Move cursor to file start").addOption("Move cursor to file end","Move cursor to file end").addOption("Move cursor to line start","Move cursor to line start").addOption("Move cursor to line end","Move cursor to line end")}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}renderAddUserScriptSetting(e){let t,n=null,i=async()=>{this.loadScriptCandidates();let o=t.getValue().trim();if(!o)return;let s=cd(o).basename??o,a=VB(this.app,this.scriptCandidates,s);if(!a){new Zn.Notice(`QuickAdd: No script or js-block note named "${o}" found.`);return}if(a.isMarkdown){let l=await Dy(this.app,a.file);if(l){new Zn.Notice(`QuickAdd: "${a.file.path}" \u2014 ${l}`);return}}this.addCommand(new Iy(o,a.file.path)),t.setValue(""),n&&n.buttonEl.addClass("qa-hidden")};new Zn.Setting(e).setName("User scripts").setDesc("Add a .js file or a note with a ```js code block - type the name or click Browse").addText(o=>{t=o,o.inputEl.addClass("qa-command-sequence-input"),o.setPlaceholder("Start typing script name..."),new An(this.app,o.inputEl,this.scriptCandidates.map(s=>_I(s))),o.inputEl.addEventListener("keypress",s=>{s.key==="Enter"&&i()})}).addButton(o=>o.setButtonText("Browse").setTooltip("Browse and select a script (.js file or note)").onClick(async()=>{let s=await this.showScriptPicker();if(s){let a=s.isMarkdown?s.file.path:s.file.basename;this.addCommand(new Iy(a,s.file.path))}})).addButton(o=>{n=o,o.setButtonText("Add").setCta().onClick(()=>{i()}),o.buttonEl.addClass("qa-hidden")}),t.onChange(o=>{n&&n.buttonEl.toggleClass("qa-hidden",o.trim().length===0)})}renderAddChoiceSetting(e){let t,n=()=>{let i=t.getValue(),o=this.choices.find(s=>s.name===i);if(!o){new Zn.Notice(`QuickAdd: No choice named "${i}".`);return}this.addCommand(new Fx(o.name,o.id)),t.setValue("")};new Zn.Setting(e).setName("Choices").setDesc("Add existing choice").addText(i=>{t=i,i.inputEl.addClass("qa-command-sequence-input"),i.setPlaceholder("Choice"),new An(this.app,i.inputEl,this.choices.map(o=>o.name)),i.inputEl.addEventListener("keypress",o=>{o.key==="Enter"&&n()})}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}addChoiceButton(e,t,n){new Zn.ButtonComponent(e).setButtonText(t).setTooltip(`Add ${t} choice`).onClick(()=>{let o=new n(`Untitled ${t} Choice`);this.addCommand(new $x(o))})}addOpenFileCommandButton(e){new Zn.ButtonComponent(e).setIcon("file-search").setTooltip("Add open file command").onClick(()=>{this.addCommand(new Nx)})}addAIAssistantCommandButton(e){new Zn.ButtonComponent(e).setIcon("bot").setTooltip("Add AI Assistant command").onClick(()=>{this.addCommand(new Lx)})}addWaitCommandButton(e){new Zn.ButtonComponent(e).setIcon("clock").setTooltip("Add wait command").onClick(()=>{this.addCommand(new Px(100))})}addConditionalCommandButton(e){new Zn.ButtonComponent(e).setIcon("git-branch").setTooltip("Add conditional command").onClick(()=>{this.addCommand(new Bx)})}async showScriptPicker(){if(this.loadScriptCandidates(),this.scriptCandidates.length===0)return Ox(this.app),null;let e=this.scriptCandidates.map(o=>o.file.path),t=this.scriptCandidates.map(o=>_I(o)),n=await Or.Suggest(this.app,t,e,{placeholder:"Select a script (.js file or note with a ```js block)",emptyStateText:"No scripts found in your vault"});if(!n)return null;let i=this.scriptCandidates.find(o=>o.file.path===n);if(!i)return null;if(i.isMarkdown){let o=await Dy(this.app,i.file);if(o)return new Zn.Notice(`QuickAdd: "${i.file.path}" \u2014 ${o}`),null}return i}addCommand(e){this.commandsRef=[...this.commandsRef,e],this.emitCommandsChanged()}emitCommandsChanged(){this.commandListProps&&(this.commandListProps.commands=[...this.commandsRef]),this.onCommandsChange?.(this.commandsRef)}};var On=require("obsidian");yf();lu();function zB(r){return r.mode==="variable"?{...r}:{...r}}function g9(){return{mode:"variable",variableName:"",operator:"isTruthy",valueType:"boolean"}}function v9(){return{mode:"script",scriptPath:""}}var Vx=class extends On.Modal{constructor(t,n){super(t);this.isResolved=!1;this.scriptCandidates=[];this.originalCommand=n,this.workingCommand={...n,condition:zB(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(t){this.isResolved||(this.isResolved=!0,this.resolvePromise(t))}loadScriptCandidates(){this.scriptCandidates=Mx(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 On.Setting(this.contentEl).setName("Condition type").setDesc("Choose how this condition should be evaluated.").addDropdown(t=>{t.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"?g9():v9(),this.reload())})})}renderVariableConfiguration(t){this.renderVariableNameSetting(t),this.renderOperatorSetting(t),this.renderValueTypeSetting(t),zc(t.operator)&&this.renderExpectedValueSetting(t)}renderVariableNameSetting(t){new On.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(t.variableName).onChange(i=>{t.variableName=i.trim()}))}renderOperatorSetting(t){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 On.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(t.operator),i.onChange(o=>{t.operator=o,t.valueType=bN(t.operator),zc(t.operator)||delete t.expectedValue,this.reload()})})}renderValueTypeSetting(t){new On.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(t.valueType).onChange(i=>{t.valueType=i,this.reload()})})}renderExpectedValueSetting(t){if(t.valueType==="boolean"){new On.Setting(this.contentEl).setName("Expected value").setDesc("Choose true or false.").addDropdown(n=>{n.addOption("true","True").addOption("false","False").setValue(t.expectedValue??"true").onChange(i=>{t.expectedValue=i})});return}new On.Setting(this.contentEl).setName("Expected value").setDesc("Value to compare against.").addText(n=>{n.setPlaceholder("Enter comparison value").setValue(t.expectedValue??"").onChange(i=>{t.expectedValue=i})})}renderScriptConfiguration(t){this.renderScriptPathSetting(t),this.renderScriptExportSetting(t)}renderScriptPathSetting(t){let n;new On.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(t.scriptPath).onChange(o=>{t.scriptPath=o.trim()})}).addButton(i=>i.setButtonText("Browse").setTooltip("Select a script (.js file or note)").onClick(async()=>{if(this.loadScriptCandidates(),this.scriptCandidates.length===0){Ox(this.app);return}let o=this.scriptCandidates.map(l=>l.file.path),s=await Or.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 Dy(this.app,a.file);if(l){new On.Notice(`QuickAdd: "${a.file.path}" \u2014 ${l}`);return}}t.scriptPath=s,n.setValue(s)}))}renderScriptExportSetting(t){new On.Setting(this.contentEl).setName("Export name").setDesc("Optional export or member to call (use :: to access nested members).").addText(n=>n.setPlaceholder("default").setValue(t.exportName??"").onChange(i=>{t.exportName=i.trim()||void 0}))}renderButtonBar(){let t=this.contentEl.createDiv({cls:"qa-command-button-row"});new On.ButtonComponent(t).setButtonText("Cancel").onClick(()=>{this.resolve(null),this.close()}),new On.ButtonComponent(t).setCta().setButtonText("Save").onClick(()=>{this.validateCondition()&&(this.applyChanges(),this.resolve(this.originalCommand),this.close())})}validateCondition(){let t=this.workingCommand.condition;return t.mode==="variable"?t.variableName.trim()?!0:(new On.Notice("QuickAdd: Enter a variable name before saving."),!1):t.scriptPath.trim()?!0:(new On.Notice("QuickAdd: Enter a script path before saving."),!1)}applyChanges(){this.originalCommand.condition=zB(this.workingCommand.condition);let t=vf(this.originalCommand.condition);this.originalCommand.name=`If ${t}`}};var wm=require("obsidian");qn();Qn();var qx=class extends wm.Modal{constructor(t){super(t.app);this.commandEditor=null;this.isResolved=!1;this.plugin=t.plugin,this.choices=t.choices,this.conditionalHandlers=t.conditionalHandlers,this.workingCommands=Ze(t.commands),this.waitForClose=new Promise(n=>{this.resolvePromise=n}),this.display(t.title),this.open()}onClose(){super.onClose(),this.commandEditor?.destroy(),this.isResolved||this.resolve(null)}resolve(t){this.isResolved||(this.isResolved=!0,this.resolvePromise(t))}display(t){this.containerEl.addClass("quickAddModal","conditionalBranchModal"),this.contentEl.empty(),this.contentEl.createEl("h2",{text:t}).addClass("qa-modal-title");let i=this.contentEl.createDiv("branchCommandEditor");this.commandEditor=new bm({app:this.app,plugin:this.plugin,commands:this.workingCommands,choices:this.choices,onCommandsChange:s=>{this.workingCommands=s},conditionalHandlers:this.conditionalHandlers});let o=this.commandEditor.render(i);this.renderButtonBar(o)}renderButtonBar(t){let n=this.contentEl.createDiv({cls:"qa-command-button-row"});if(!t){new wm.ButtonComponent(n).setCta().setButtonText("Close").onClick(()=>{this.resolve(null),this.close()});return}new wm.ButtonComponent(n).setButtonText("Cancel").onClick(()=>{this.resolve(null),this.close()}),new wm.ButtonComponent(n).setCta().setButtonText("Save").onClick(()=>{this.resolve(ar(this.workingCommands)),this.close()})}};var Ux=require("obsidian");It();Is();function y9(r){let e=r.trim();return e||void 0}function b9(r){return(typeof r.icon=="string"?r.icon.trim():"")||nf(r.type)}function zx(r,e,t,n){let i=nf(t.type),o=new Ux.Setting(e).setName("Icon").setDesc(`Lucide/Obsidian icon id. Leave empty to use ${i}.`);o.settingEl.addClass("qa-choice-icon-setting");let s=nr(e,"span");s.classList.add("qa-choice-icon-setting-preview"),s.setAttribute("aria-hidden","true"),o.controlEl.appendChild(s);function a(){s.replaceChildren(),(0,Ux.setIcon)(s,b9(t))}o.addText(l=>{l.setPlaceholder(i),l.setValue(typeof t.icon=="string"?t.icon:""),l.inputEl.addClass("qa-choice-icon-input"),l.inputEl.setAttribute("aria-label","Choice icon"),new An(r,l.inputEl,zE,50),l.onChange(c=>{let u=y9(c);t.icon=u,n(u),a()})}),a()}It();Qn();Ea();Jc();function w9(r){let e=[],t=n=>{n.forEach(i=>{Ne(i)&&(i.type==="Multi"?t(Qe(i)):e.push(i))})};return t(Wr(r)),e}var Hx=class extends Ba.Modal{constructor(t,n,i,o){super(t);this.choices=[];this.commandEditor=null;this.choice=i,this.macro=i.macro,this.choices=w9(o),this.plugin=n,this.waitForClose=new Promise(s=>{this.resolvePromise=s}),this.display(),HE(this,"macro"),this.open()}onClose(){super.onClose(),this.resolvePromise(this.choice),this.commandEditor?.destroy(),this.commandEditor=null}display(){this.containerEl.addClass("quickAddModal","macroBuilder"),this.contentEl.empty(),this.addCenteredHeader(this.choice.name),this.addCommandEditor(),this.addDateOriginSetting(),this.addRunOnStartupSetting(),this.addCommandPaletteSettings(),this.addIconSetting()}addCenteredHeader(t){let n=this.contentEl.createEl("h2");n.addClass("qa-clickable-modal-title"),n.createEl("button",{cls:"qa-rename-title-button",text:t,attr:{type:"button","aria-label":`Rename ${t}`}}).addEventListener("click",()=>{(async()=>{try{let o=await sr.Prompt(this.app,`Update name for ${this.choice.name}`,this.choice.name,this.choice.name);if(!o)return;this.choice.name=o,ou(this.macro)&&(this.macro.name=o),this.reload()}catch{}})()})}addDateOriginSetting(){let t=this.choice.dateOrigin,n=Ol(t);if(new Ba.Setting(this.contentEl).setName(kE).setDesc(AE).addDropdown(i=>{for(let o of $E)i.addOption(o.value,o.label);i.setValue(n),i.onChange(o=>{OE(o)&&(this.choice.dateOrigin=RE({preset:o,previous:this.choice.dateOrigin}),this.reload())})}),n==="ask"){let i=t?.kind==="ask"?t.defaultValue:void 0;new Ba.Setting(this.contentEl).setName(DE).setDesc(IE).addDropdown(o=>{for(let s of LE(i))o.addOption(s.value,s.label);o.setValue(ty(i)),o.onChange(s=>{let a=NE(s,i);this.choice.dateOrigin=a?{kind:"ask",defaultValue:a}:{kind:"ask"}})})}if(n==="custom"&&t?.kind==="relative"&&new Ba.Setting(this.contentEl).setName(Jv).setDesc(FE).addText(i=>{i.setValue(String(t.offset)),i.setPlaceholder("-2"),i.onChange(o=>{let s=this.choice.dateOrigin;if(s?.kind!=="relative")return;let a=o.trim();/^[+-]?\d+$/.test(a)&&(this.choice.dateOrigin={...s,offset:Number(a)})})}).addDropdown(i=>{for(let o of Xv)i.addOption(o,o);i.setValue(t.unit),i.onChange(o=>{let s=this.choice.dateOrigin;s?.kind==="relative"&&Zv(o)&&(this.choice.dateOrigin={...s,unit:o})})}),n==="variable"){let i=t?.kind==="variable"?t.name:"";new Ba.Setting(this.contentEl).setName(ey).setDesc(PE).addText(o=>{o.setValue(i),o.setPlaceholder("day"),o.onChange(s=>{this.choice.dateOrigin={kind:"variable",name:s}})})}}addCommandPaletteSettings(){new Ba.Setting(this.contentEl).setName(ny).setDesc(BE).addToggle(t=>{t.setValue(this.choice.command).onChange(n=>{this.choice.command=n,this.reload()})}),this.choice.command&&oy(this.choice.dateOrigin)&&new Ba.Setting(this.contentEl).setName(iy(this.choice.name)).setDesc(VE).addToggle(t=>{t.setValue(this.choice.pickDayCommand??!1).onChange(n=>{this.choice.pickDayCommand=n})})}addRunOnStartupSetting(){new Ba.Setting(this.contentEl).setName("Run on startup").setDesc("Execute this macro when Obsidian starts").addToggle(t=>t.setValue(this.choice.runOnStartup).onChange(n=>{this.choice.runOnStartup=n}))}addIconSetting(){zx(this.app,this.contentEl,this.choice,t=>{this.choice.icon=t})}reload(){this.commandEditor?.destroy(),this.commandEditor=null,this.display()}macroCommandsValue(){return hn(this.macro)}setMacroCommands(t){if(!ou(this.macro)){this.macro={id:ir(),name:this.choice.name,commands:t},this.choice.macro=this.macro;return}this.macro.commands=t}addCommandEditor(){let t=this.contentEl.createDiv("macroBuilder__editor");this.commandEditor=new bm({app:this.app,plugin:this.plugin,commands:this.macroCommandsValue(),choices:this.choices,onCommandsChange:n=>{this.setMacroCommands(n)},conditionalHandlers:this.buildConditionalHandlers()}),this.commandEditor.render(t)}buildConditionalHandlers(){return{configureCondition:t=>this.configureConditionalCondition(t),editThenBranch:t=>this.configureConditionalBranch(t,"then"),editElseBranch:t=>this.configureConditionalBranch(t,"else")}}async configureConditionalCondition(t){return await new Vx(this.app,t).waitForClose!==null}async configureConditionalBranch(t,n){let i=n==="then"?"Then branch":"Else branch",s=await new qx({app:this.app,plugin:this.plugin,choices:this.choices,title:`Edit ${i} commands`,commands:n==="then"?t.thenCommands:t.elseCommands,conditionalHandlers:this.buildConditionalHandlers()}).waitForClose;return s?(n==="then"?t.thenCommands=s:t.elseCommands=s,!0):!1}};var cu=require("obsidian");Er();var Wx=class extends cu.Modal{constructor(t,n){super(t);this.choice=n;this.didSubmit=!1;this.name=n.name,this.placeholder=n.placeholder??"",this.icon=typeof n.icon=="string"?n.icon:void 0,this.waitForClose=new Promise((i,o)=>{this.resolvePromise=i,this.rejectPromise=o}),this.containerEl.addClass("quickAddModal","qaMultiChoiceSettingsModal"),this.display(),this.open()}display(){this.contentEl.empty(),this.titleEl.setText("Edit folder"),new cu.Setting(this.contentEl).setName("Name").addText(n=>{n.setValue(this.name).onChange(i=>{this.name=i})}),new cu.Setting(this.contentEl).setName("Placeholder").setDesc("Shown in the choice picker search box when this folder opens. Leave blank to use the folder name.").addText(n=>{n.setPlaceholder("Defaults to the folder name"),n.setValue(this.placeholder).onChange(i=>{this.placeholder=i})}),zx(this.app,this.contentEl,{type:this.choice.type,icon:this.icon},n=>{this.icon=n});let t=this.contentEl.createDiv();new cu.ButtonComponent(t).setButtonText("Save").setCta().onClick(()=>this.submit()),new cu.ButtonComponent(t).setButtonText("Cancel").onClick(()=>this.cancel()),t.addClass("qa-modal-button-row")}submit(){this.didSubmit||(this.didSubmit=!0,this.close())}cancel(){this.close()}onClose(){if(super.onClose(),!this.didSubmit){this.rejectPromise(Ir());return}let t=this.placeholder.trim(),n={...this.choice,name:this.name.trim()||this.choice.name,placeholder:t||void 0,icon:this.icon};this.resolvePromise(n)}};ht();Ea();var jx=class{constructor(e){this.name=e,this.id=ir(),this.commands=[]}};var Cm=class extends Na{constructor(t){super(t,"Macro");this.runOnStartup=!1;this.macro=new jx(t)}};var Em=class extends Na{constructor(t){super(t,"Multi");this.choices=[];this.collapsed=!1}addChoice(t){return this.choices.push(t),this}addChoices(t){return this.choices.push(...t),this}};Qn();It();qn();function NI(r,e){let t=Ze(r);for(let n of e)delete t[n];return t}qn();Bl();De();Sa();var C9={Template:au,Capture:am,Macro:Cm,Multi:Em};function VI(r,e){let t=C9[r];if(!t)throw new Error(`Unknown choice type: ${r}`);return new t(e)}function WB(r,e){let t=VI(r.type,`${r.name} (copy)`);if(r.type==="Multi"){let n=t,i=r;return Object.assign(n,NI(i,["id","name","choices"])),Tl(i)?n.choices=Qe(i).filter(Ne).map(o=>WB(o,e)):n.choices=i.choices,n}return Object.assign(t,NI(r,["id","name"])),r.type==="Macro"&&(t.macro=Ze(r.macro),vB(t.macro),rm(t,e)),t}async function jB(r,e){let t=await E9(e,r);return WB(r,{secretOptionNamesByPath:t,stripUnknownStringSettings:!0})}function GB(r){return r!==null&&typeof r=="object"}function BI(r,e){if(GB(r)){if(r.type==="UserScript"&&typeof r.path=="string"&&e.add(r.path),Array.isArray(r.thenCommands))for(let t of r.thenCommands)BI(t,e);if(Array.isArray(r.elseCommands))for(let t of r.elseCommands)BI(t,e);qI(r.choice,e)}}function qI(r,e){if(GB(r)){if(r.type==="Macro"){let t=hn(r.macro);if(Array.isArray(t))for(let n of t)BI(n,e)}if(r.type==="Multi"&&Array.isArray(r.choices))for(let t of r.choices)qI(t,e)}}async function E9(r,e){let t=new Set;qI(e,t);let n=new Map;for(let i of t)try{if(Pr(i)||!await r.vault.adapter.exists(i))continue;let s=Jf(await r.vault.adapter.read(i),i);n.set(i,s.foundSecretOptions&&s.names.size===0?null:s.names)}catch(o){P.logWarning(`QuickAdd could not inspect user-script settings '${i}' while duplicating choice: ${o?.message??o}`)}return n}function x9(r,e,t){let i={Template:()=>new Vf(e,r,t),Capture:()=>new Nf(e,r,t),Macro:()=>new Hx(e,t,r,ne.getState().choices),Multi:()=>{}}[r.type];return typeof i=="function"?i():void 0}async function YB(r,e){let t=r.type==="Multi",n=r.type==="Macro",i=l=>{if(Jo(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=dn(Qe(l));if(c.length===0)return"";let u=c.filter(p=>p.type==="Multi").length,d=c.length-u,f=[];return d>0&&f.push(`${d} ${d===1?"choice":"choices"}`),u>0&&f.push(`${u} ${u===1?"folder":"folders"}`),`Deleting this folder will also delete everything inside it: ${f.join(" and ")}.`},o=l=>Kn(hn(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}'?`,t?i(r):"",n?o(r):""].filter(Boolean).join(" ");return await vi.Prompt(e,`Delete ${hf(r.type)}`,s)?(n||t)&&!await _y(e,{type:"NestedChoice",choice:r})?(new HB.Notice(`Could not clear user script secrets. The ${hf(r.type)} was not deleted.`),!1):!0:!1}async function KB(r,e,t){if(r.type==="Multi")try{return await new Wx(e,r).waitForClose}catch{return}let n=x9(r,e,t);if(!n)throw new Error("Invalid choice type");return await n.waitForClose}function QB(r){return{...r,command:!r.command}}var Gx=class{constructor(e){this.plugin=e}enableCommand(e){this.plugin.addCommandForChoice(e)}disableCommand(e,t){t?this.plugin.removeCommandForChoice(e,t):this.plugin.removeCommandForChoice(e)}updateCommand(e,t){this.plugin.removeCommandForChoice(e),this.plugin.addCommandForChoice(t)}};function XB(r,e,t){if(!e||!t)return r;let n=Fy(r,e),i=Fy(r,t);if(!n||!i||i.type!=="Multi"||n.type==="Multi"&&(n.id===i.id||T9(n).has(i.id)))return r;let{updated:o,removed:s}=Py(r,e);return s?UI(o,t,s)??r:r}function ZB(r,e){if(!e||r.some(i=>Ne(i)&&i.id===e))return r;let{updated:t,removed:n}=Py(r,e);return n?[...t,n]:r}function Fy(r,e){for(let t of r){if(!Ne(t))continue;if(t.id===e)return t;let n=Fy(Qe(t),e);if(n)return n}}function T9(r){let e=new Set,t=n=>{Ne(n)&&(e.add(n.id),Qe(n).forEach(t))};return Qe(r).forEach(t),e}function Py(r,e){let t;return{updated:r.map(i=>{if(!Ne(i))return i;if(i.id===e){t=i;return}if(!Tl(i))return i;let o=Py(Qe(i),e);return o.removed&&(t=o.removed),o.removed?{...i,choices:o.updated}:i}).filter(Boolean),removed:t}}function UI(r,e,t){let n=!1,i=r.map(o=>{if(!Ne(o))return o;if(o.id===e&&o.type==="Multi"){if(Jo(o))return o;n=!0;let a=o;return{...a,choices:[...Qe(a),t]}}if(!Tl(o))return o;let s=UI(Qe(o),e,t);return s?(n=!0,{...o,choices:s}):o});return n?i:void 0}function zI(r,e,t){let n=r.findIndex(s=>Ne(s)&&s.id===e);if(n!==-1){let s=[...r];return s.splice(n+1,0,t),s}let i=!1,o=r.map(s=>{if(!Ne(s)||!Tl(s))return s;let a=zI(Qe(s),e,t);return a?(i=!0,{...s,choices:a}):s});return i?o:void 0}function JB(r,e,t){if(!t)return[...r,e];let n=UI(r,t,e)??[...r,e];return S9(n,t)}function HI(r,e,t){return r.map(n=>{if(!Ne(n)||n.type!=="Multi")return n;let i=n;return i.id===e?t(i):Tl(i)?{...i,choices:HI(Qe(i),e,t)}:n})}function WI(r,e,t){return HI(r,e,n=>({...n,collapsed:t}))}function S9(r,e){return WI(r,e,!1)}function eV(r,e,t){return HI(r,e,n=>({...n,choices:t}))}var tV=require("obsidian");It();var jI="quickadd:move-to-root";function _9(r,e){let t=Wr(e);if(t.some(i=>Ne(i)&&i.id===r.id))return!1;let n=i=>{for(let o of i){if(!Ne(o))continue;let s=Qe(o);if(s.some(a=>a?.id===r.id)||n(s))return!0}return!1};return n(t)}function k9(r,e){let t=[],n=Array.isArray(e)?e:[],i=(o,s=[])=>{for(let a of o){if(!Ne(a))continue;let l=a.name??"";if(a.type==="Multi"){let c=[...s,l];A9(r,a)||t.push({id:a.id,path:c.join(" / ")}),i(Qe(a),[...s,l])}}};return i(n,[]),t}function A9(r,e){if(e.type!=="Multi"||r.id===e.id||Jo(e))return!0;if(r.type==="Multi"){let t=new Set,n=i=>{Ne(i)&&(t.add(i.id),Qe(i).forEach(n))};if(Qe(r).forEach(n),t.has(e.id))return!0}return!1}function rV(r,e,t,n){let i=new tV.Menu;i.addItem(s=>s.setTitle(e.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(),_9(e,t)&&i.addItem(s=>s.setTitle("Move to: (root)").setIcon("folder-up").onClick(()=>n.onMove(jI)));let o=k9(e,t);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 Yx(r,e,t,n,i){e.preventDefault(),rV(r,t,n,i).showAtMouseEvent(e)}function Kx(r,e,t,n,i){let o=e.getBoundingClientRect();rV(r,t,n,i).showAtPosition({x:o.left,y:o.bottom})}var Ys=require("obsidian");var lr=require("obsidian");fo();var nV=require("obsidian");ht();var Qx=null,D9=1440*60*1e3;async function GI(){if(Qx&&Date.now()-Qx.fetchedAt<D9)return Qx.data;if(ne.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let e=await(await(0,nV.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;return Qx={data:e,fetchedAt:Date.now()},e}function I9(r){for(let e of[r,`https://${r}`])try{let t=new URL(e).hostname.toLowerCase();if(t)return t}catch{}return""}function $y(r){let e=r.toLowerCase(),t=I9(r),n=i=>t===i||t.endsWith(`.${i}`);return n("openai.com")?"openai":n("openrouter.ai")?"openrouter":n("generativelanguage.googleapis.com")?"google":e.includes("anthropic")?"anthropic":n("groq.com")?"groq":n("together.ai")||n("together.xyz")?"togetherai":e.includes("huggingface")?"huggingface":e.includes("github")&&e.includes("models")?"github-models":e.includes("bedrock")||e.includes("aws")?"amazon-bedrock":e.includes("modelscope")?"modelscope":e.includes("dashscope")?"alibaba":n("fireworks.ai")?"fireworks-ai":e.includes("vercel")?"vercel":n("inference.net")?"inference":n("z.ai")||e.includes("zhipu")?"zhipuai":n("deepseek.com")?"deepseek":n("mistral.ai")?"mistral":e.includes("cerebras")?"cerebras":n("venice.ai")?"venice":n("upstage.ai")?"upstage":n("llama.com")?"llama":e.includes("morphllm")?"morph":n("inceptionlabs.ai")?"inception":e.includes("deepinfra")?"deepinfra":n("opencode.ai")?"opencode":n("inference.wandb.ai")?"wandb":n("githubcopilot.com")?"github-copilot":null}function F9(r){let e=r.modalities?.output;if(Array.isArray(e)&&!e.includes("text"))return!1;let t=r.limit??{};if(typeof t.context=="number"&&t.context<=0||typeof t.output=="number"&&t.output<=1)return!1;let n=(r.family??"").toLowerCase(),i=r.id.toLowerCase();return!(n.includes("embedding")||i.includes("embedding"))}function iV(r){return r.filter(F9).map(e=>{let t={name:e.id,maxTokens:Math.max(1,Math.floor(e.limit?.context??128e3))};return typeof e.limit?.output=="number"&&e.limit.output>0&&(t.maxOutputTokens=Math.floor(e.limit.output)),typeof e.temperature=="boolean"&&(t.supportsTemperature=e.temperature),t})}async function oV(r,e){let t=$y(r);if(!t)return e;let n;try{n=await GI()}catch{return e}let i=n[t]?.models;return i?e.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),a}):e}function My(r,e){let t=new Map(e.map(s=>[s.name,s])),n=r.map(s=>{let a=t.get(s.name);return a?{...s,maxTokens:a.maxTokens,maxOutputTokens:a.maxOutputTokens??s.maxOutputTokens,supportsTemperature:a.supportsTemperature??s.supportsTemperature}:s}),i=new Set(r.map(s=>s.name)),o=e.filter(s=>!i.has(s.name));return n.concat(o)}De();ht();var uV=require("obsidian");fo();Ry();ht();var Jx=128e3;async function eT(r,e){let t=r.modelSource??"providerApi";if(t==="modelsDev")return lV(r);if(t==="providerApi")return cV(r,e);try{return await cV(r,e)}catch(n){if(!$y(r.endpoint))throw n;return lV(r,n)}}async function lV(r,e){try{let t=await GI(),n=$y(r.endpoint);if(!n||!(n in t))throw new Error(`models.dev does not list a provider that matches ${r.endpoint}.`);let i=Object.values(t[n].models);return iV(i)}catch(t){throw e?new Error(`Provider API failed (${e.message}). Fallback to models.dev also failed: ${t.message}`):t}}async function cV(r,e){let{disableOnlineFeatures:t}=ne.getState();if(t)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=e??r.apiKey??"",i=sg(r),o=i==="anthropic"?await V9(r,n):i==="gemini"?await q9(r,n):await B9(r,n);if(!o.length)throw new Error("The provider's models endpoint did not include any usable models.");let s=await oV(r.endpoint,o);return L9(r.endpoint,s)}function L9(r,e){let t=$y(r);if(t!=="openai"&&t!=="google"&&t!=="anthropic")return e;let n=new Map(ag[t].map(i=>[i.name,i]));return e.map(i=>{let o=n.get(i.name);return o?{...i,maxTokens:i.maxTokens===Jx?o.maxTokens:i.maxTokens,maxOutputTokens:i.maxOutputTokens??o.maxOutputTokens,supportsTemperature:i.supportsTemperature??o.supportsTemperature}:i})}async function YI(r,e,t){try{let n=await(0,uV.requestUrl)({url:e,headers:t,throw:!1});if(n.status>=400)throw Zx(r.name,n);return await n.json}catch(n){throw new Error(`Provider rejected the models request: ${n.message}`)}}var N9=/(whisper|-tts|tts-|embed|dall-e|image|moderation|transcribe|realtime|rerank)/i;async function B9(r,e){let t=r.endpoint.replace(/\/+$/,""),n=t.endsWith("/v1")?`${t}/models`:`${t}/v1/models`,i={};e&&(i.Authorization=`Bearer ${e}`);let o=await YI(r,n,i),s=U9(o),a=[];for(let l of s){let c=z9(l);c&&!N9.test(c.name)&&a.push(c)}return a}async function V9(r,e){let t=r.endpoint.replace(/\/+$/,""),n={"anthropic-version":"2023-06-01"};e&&(n["x-api-key"]=e);let i=[],o=null;for(let s=0;s<10;s++){let a=`${t}/v1/models?limit=1000`+(o?`&after_id=${encodeURIComponent(o)}`:""),l=await YI(r,a,n);for(let c of l.data??[])c.id&&i.push({name:c.id,maxTokens:Jx});if(!l.has_more||!l.last_id)break;o=l.last_id}return i}async function q9(r,e){let t=r.endpoint.replace(/\/+$/,""),n={};e&&(n["x-goog-api-key"]=e);let i=[],o=null;for(let s=0;s<10;s++){let a=`${t}/v1beta/models?pageSize=1000`+(o?`&pageToken=${encodeURIComponent(o)}`:""),l=await YI(r,a,n);for(let c of l.models??[]){if(!c.name)continue;let u=c.supportedGenerationMethods;if(Array.isArray(u)&&!u.includes("generateContent"))continue;let d={name:c.name.replace(/^models\//,""),maxTokens:typeof c.inputTokenLimit=="number"&&c.inputTokenLimit>0?c.inputTokenLimit:Jx};typeof c.outputTokenLimit=="number"&&c.outputTokenLimit>0&&(d.maxOutputTokens=c.outputTokenLimit),i.push(d)}if(!l.nextPageToken)break;o=l.nextPageToken}return i}function U9(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 z9(r){let e=r.id??r.name;return e?{name:e,maxTokens:H9(r)}:null}function H9(r){let e=[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 t of e){let n=W9(t);if(n&&n>0)return Math.floor(n)}return Jx}function W9(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let e=Number(r);if(Number.isFinite(e))return e}return null}Nd();var K9=1440*60*1e3;function Q9(r,e){let t=new Map(r.map(i=>[i.name,JSON.stringify(i)])),n=0;for(let i of e){let o=t.get(i.name);o!==void 0&&o!==JSON.stringify(i)&&(n+=1)}return n}async function xm(r,e){let t=await Gs(r,e),n=await eT(e,t),i=e.models;return e.models=My(e.models,n),{added:e.models.length-i.length,updated:Q9(i,e.models)}}function fV(r){return`${(r.name??"").trim().toLowerCase()}\0${(r.endpoint??"").trim().toLowerCase().replace(/\/+$/,"")}`}async function mV(r,e={}){let t=ne.getState();if(t.disableOnlineFeatures)return[];let n=t.ai.providers.filter(l=>l.autoSyncModels);if(n.length===0)return[];let i=t.ai.lastModelAutoSyncAt??0;if(!e.ignoreThrottle&&Date.now()-i<K9)return[];let o=[],s=new Map;for(let l of n){let c={...l,models:l.models.map(u=>({...u}))};try{let{added:u,updated:d}=await xm(r,c);o.push({provider:c.name,added:u,updated:d}),s.set(fV(c),c)}catch(u){o.push({provider:c.name,added:0,updated:0,error:u.message??String(u)})}}let a=o.some(l=>!l.error);ne.setState(l=>({...l,ai:{...l.ai,providers:l.ai.providers.map(c=>{let u=s.get(fV(c));return u?{...c,models:My(c.models,u.models)}:c}),lastModelAutoSyncAt:a?Date.now():l.ai.lastModelAutoSyncAt}}));for(let l of o)l.error?P.logMessage(`[Model auto-sync] ${l.provider}: failed (${l.error})`):(l.added>0||l.updated>0)&&P.logMessage(`[Model auto-sync] ${l.provider}: ${l.added} new model(s), ${l.updated} updated.`);return o}ht();var Va=require("obsidian");Nd();var tT=class extends Va.Modal{constructor(t,n){super(t);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 t=await Gs(this.app,this.provider);this.allModels=await eT(this.provider,t),this.filtered=this.allModels.slice(),this.loadError=null}catch(t){this.loadError=`${t.message??t}`,new Va.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 Va.Setting(this.contentEl).setName("Search").addText(t=>{t.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(t=>{t.setIcon("check"),t.setTooltip("Select all"),t.onClick(()=>{this.filtered.forEach(n=>this.selectedIds.add(n.name)),this.renderList()})}).addExtraButton(t=>{t.setIcon("x"),t.setTooltip("Clear selection"),t.onClick(()=>{this.selectedIds.clear(),this.renderList()})}),new Va.Setting(this.contentEl).setName("Import mode").setDesc("Add will append new models. Replace will overwrite existing models with the selected list.").addDropdown(t=>{t.addOption("add","Add only"),t.addOption("replace","Replace existing"),t.setValue(this.mode),t.onChange(n=>this.mode=n)}).addButton(t=>{t.setButtonText("Import selected").setCta().onClick(()=>this.importSelected())}),this.contentEl.createDiv({cls:"qa-model-directory"}),this.renderList()}renderList(){let t=this.contentEl.querySelector(".qa-model-directory");if(t){if(t.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.";t.createDiv({text:n,cls:"qa-model-directory-empty"});return}for(let n of this.filtered){let i=t.createEl("label",{cls:"qa-model-row"}),o=this.contentEl.ownerDocument.createElement("input");o.type="checkbox",o.checked=this.selectedIds.has(n.name),o.onchange=()=>{o.checked?this.selectedIds.add(n.name):this.selectedIds.delete(n.name)},i.appendChild(o),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 Va.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 Va.Notice("No models selected to import.");return}this.resolved=!0,this.resolvePromise({imported:n,mode:this.mode}),this.close()}catch(t){new Va.Notice(`Import failed: ${t.message??t}`)}}onClose(){this.resolved||this.resolvePromise(null),super.onClose()}};qn();Ns();var wi=require("obsidian");fo();var hV=[{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 rT=class extends wi.Modal{constructor(e,t){super(e),this.providers=t,this.waitForClose=new Promise((n,i)=>{this.resolvePromise=n,this.rejectPromise=i}),this.open(),this.display()}addHeader(e){e.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 e=this.contentEl.createDiv({cls:"qa-provider-grid"});for(let t of hV){let n=e.createDiv({cls:"qa-provider-card"});if(n.createEl("div",{text:t.name,cls:"qa-provider-card-title"}),n.createEl("div",{text:t.endpoint,cls:"qa-provider-card-endpoint"}),t.doc){let s=n.createEl("a",{text:"Docs",href:t.doc});s.target="_blank",s.rel="noopener noreferrer"}let i="",o=new wi.Setting(n).setName("API key").setDesc("Select a secret from SecretStorage").addComponent(s=>new wi.SecretComponent(this.app,s).setValue(i).onChange(a=>{i=a}));o.settingEl.addClass("qa-provider-api-setting"),o.addButton(s=>{s.setButtonText("Connect").setCta().onClick(async()=>{try{let a=i.trim();try{new URL(t.endpoint)}catch{new wi.Notice(`Invalid endpoint URL for ${t.name}.`);return}let l=t.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(m=>l.includes(m))&&!a){new wi.Notice(`${t.name} requires an API key.`);return}let u=m=>m.trim().toLowerCase(),d=m=>m.trim().toLowerCase().replace(/\/+$/,"");if(this.providers.some(m=>u(m.name)===u(t.name)&&d(m.endpoint)===d(t.endpoint))){new wi.Notice(`${t.name} is already configured.`);return}let p={name:t.name,endpoint:t.endpoint,id:Aw(t.id,this.providers),kind:t.kind,apiKey:"",apiKeyRef:a,models:[],modelSource:t.modelSource??"auto",autoSyncModels:!0};s.setButtonText("Connecting..."),s.setDisabled(!0),await this.importInitialModels(p,t),this.providers.push(p),this.close()}catch(a){s.setButtonText("Connect"),s.setDisabled(!1),new wi.Notice(`Failed to add provider: ${a.message??a}`)}})})}new wi.Setting(this.contentEl).setName("Custom provider").setDesc("Create any custom endpoint (OpenAI-compatible or otherwise)").addButton(t=>{t.setButtonText("Add custom...").onClick(()=>{let n={id:Aw("custom",this.providers),name:"Custom",endpoint:"",apiKey:"",apiKeyRef:"",models:[],modelSource:"providerApi"};this.providers.push(n),new wi.Notice("Custom provider added. Click Edit to configure."),this.close()})})}async importInitialModels(e,t){try{await xm(this.app,e),new wi.Notice(`${t.name} connected with ${e.models.length} models.`)}catch(n){let i=n.message??String(n);t.seedKey?(e.models=Iw(t.seedKey),new wi.Notice(`${t.name} added with its built-in model list. Live model loading failed: ${i}`)):new wi.Notice(`${t.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()}};Pd();var nT=class extends lr.Modal{constructor(e,t){super(t),this.providers=e,Dw(this.providers),this.waitForClose=new Promise((n,i)=>{this.rejectPromise=i,this.resolvePromise=n}),this.open(),this.display(),this.autoSyncOnOpen()}async autoSyncOnOpen(){if(ne.getState().disableOnlineFeatures)return;let e=!1;for(let t of this.providers)if(t.autoSyncModels)try{let{added:n}=await xm(this.app,t);e=e||n>0}catch{}e&&!this.selectedProvider&&this.reload()}display(){let e=this.selectedProvider?`${this.selectedProvider.name}`:"Providers";if(this.contentEl.createEl("h2",{text:e,cls:"qa-modal-title"}),this.selectedProvider){this.addProviderSetting(this.contentEl);return}this.addProvidersSetting(this.contentEl)}reload(){this.contentEl.empty(),this.display()}addProvidersSetting(e){new lr.Setting(e).setName("Providers").setDesc("Providers for the AI Assistant").addButton(n=>{n.setButtonText("Add provider").onClick(async()=>{await new rT(this.app,this.providers).waitForClose,this.reload()}),n.setCta()});let t=e.createDiv({cls:"providers-container qa-ai-list-container"});this.providers.forEach((n,i)=>{new lr.Setting(t).setName(n.name).setDesc(n.endpoint).addButton(o=>{o.onClick(async()=>{await vi.Prompt(this.app,`Are you sure you want to delete ${n.name}?`)&&(this.providers.splice(i,1),this.reload())}),o.setDestructive(),o.setIcon("trash")}).addButton(o=>{o.setButtonText("Edit").onClick(()=>{this.selectedProvider=n,this._selectedProviderClone=Ze(n),this.reload()})})})}addProviderSetting(e){this.addNameSetting(e),this.addEndpointSetting(e),this.addApiKeySetting(e),this.addKindSetting(e),this.addModelSourceSetting(e),this.addProviderModelsSetting(e),this.addImportModelsFromDirectorySetting(e),this.addAutoSyncSetting(e),this.addProviderSettingButtonRow(this.contentEl)}addNameSetting(e){let t=this.selectedProvider.id;new lr.Setting(e).setName("Name").setDesc(t?`The display name of the provider. Its stable ID is "${t}" \u2014 use that to qualify models in scripts, e.g. ai.prompt with "${t}/model-name".`:"The display name of the provider").addText(n=>{n.setValue(this.selectedProvider.name).onChange(i=>{this.selectedProvider.name=i})})}addEndpointSetting(e){new lr.Setting(e).setName("Endpoint").setDesc("The endpoint for the AI Assistant").addText(t=>{t.setValue(this.selectedProvider.endpoint).onChange(n=>{this.selectedProvider.endpoint=n})})}addApiKeySetting(e){let n=!!this.selectedProvider?.apiKey&&!this.selectedProvider?.apiKeyRef?"Legacy API key detected. Select a SecretStorage entry to migrate.":"Select a secret from SecretStorage";new lr.Setting(e).setName("API key").setDesc(n).addComponent(i=>new lr.SecretComponent(this.app,i).setValue(this.selectedProvider?.apiKeyRef??"").onChange(o=>{this.selectedProvider&&(this.selectedProvider.apiKeyRef=o,this.selectedProvider.apiKey="")}))}addKindSetting(e){new lr.Setting(e).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(t=>{t.addOption("","Auto-detect"),t.addOption("openai","OpenAI-compatible"),t.addOption("anthropic","Anthropic"),t.addOption("gemini","Gemini"),t.setValue(this.selectedProvider?.kind??""),t.onChange(n=>{this.selectedProvider&&(this.selectedProvider.kind=n||void 0)})})}addModelSourceSetting(e){let t=this.selectedProvider;new lr.Setting(e).setName("Model source").setDesc("Choose where QuickAdd looks when browsing or syncing models for this provider.").addDropdown(n=>{n.addOption("providerApi","Provider models endpoint (requires API key)"),n.addOption("modelsDev","models.dev directory"),n.addOption("auto","Automatic (try provider, fallback to models.dev)");let i=t?.modelSource??"providerApi";n.setValue(i),n.onChange(o=>{this.selectedProvider&&(this.selectedProvider.modelSource=o,this.reload())})})}addProviderModelsSetting(e){let t=e.createDiv({cls:"models-container qa-ai-list-container"});this.selectedProvider.models.forEach((n,i)=>{let o=[`Context: ${n.maxTokens.toLocaleString()} tokens`];n.maxOutputTokens&&o.push(`Output: ${n.maxOutputTokens.toLocaleString()} tokens`),n.supportsTemperature===!1&&o.push("Fixed sampling (no temperature)"),new lr.Setting(t).setName(n.name).setDesc(o.join(" \xB7 ")).addButton(s=>{s.onClick(async()=>{await vi.Prompt(this.app,`Are you sure you want to delete ${n.name}?`)&&(this.selectedProvider.models.splice(i,1),this.reload())}),s.setDestructive(),s.setIcon("trash")})}),new lr.Setting(t).setName("Add model").addButton(n=>{n.setButtonText("Add model").onClick(async()=>{let i,o;try{i=await sr.Prompt(this.app,"Model name"),o=await sr.Prompt(this.app,"Max tokens")}catch{return}let s=i.trim();if(!s){new lr.Notice("Model name cannot be empty.");return}let a=o.trim();if(!/^[1-9]\d*$/.test(a)){new lr.Notice("Max tokens must be a positive number.");return}let l=Number(a);this.selectedProvider.models.push({name:s,maxTokens:l}),this.reload()}),n.setCta()})}addImportModelsFromDirectorySetting(e){let t=this.describeModelSource(this.selectedProvider);new lr.Setting(e).setName("Import models").setDesc(`Browse and import models from ${t}.`).addButton(n=>{n.setButtonText("Browse models").onClick(async()=>{let i=await new tT(this.app,this.selectedProvider).waitForClose;if(!i)return;let{imported:o,mode:s}=i;s==="replace"?this.selectedProvider.models=o:this.selectedProvider.models=My(this.selectedProvider.models,o),new lr.Notice(`Imported ${o.length} models${s==="replace"?" (replaced)":" (added)"}.`),this.reload()}),n.setCta()})}addAutoSyncSetting(e){let t=this.describeModelSource(this.selectedProvider);new lr.Setting(e).setName("Auto-sync models").setDesc(`Keep this provider's models current automatically: QuickAdd imports new models and refreshed context limits from ${t} once a day and when these settings open.`).addToggle(n=>{let i=!!this.selectedProvider?.autoSyncModels;n.setValue(i).onChange(o=>{this.selectedProvider&&(this.selectedProvider.autoSyncModels=o)})}).addButton(n=>{n.setButtonText("Sync now").onClick(async()=>{try{let{added:i,updated:o}=await xm(this.app,this.selectedProvider);new lr.Notice(i>0||o>0?`Synced from ${t}: ${i} new model(s), ${o} updated.`:`Synced from ${t}: already up to date.`),this.reload()}catch(i){new lr.Notice(`Sync failed: ${i.message??i}`)}}),n.setCta()})}restoreSelectedProviderFromClone(){if(!this.selectedProvider||!this._selectedProviderClone)return;let e=this.providers.indexOf(this.selectedProvider);e!==-1&&(this.providers[e]=this._selectedProviderClone),this.selectedProvider=null,this._selectedProviderClone=null}addProviderSettingButtonRow(e){let t=e.createDiv({cls:"button-row qa-ai-provider-button-row"}),n=new lr.ButtonComponent(t);n.setButtonText("Cancel"),n.setDestructive(),n.onClick(()=>{this.restoreSelectedProviderFromClone(),this.reload()});let i=new lr.ButtonComponent(t);i.setButtonText("Save"),i.setCta(),i.onClick(()=>{this.selectedProvider=null,this.reload()})}describeModelSource(e){switch(e?.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"}}onClose(){this.restoreSelectedProviderFromClone(),this.resolvePromise(this.providers),super.onClose()}};Dt();var iT=class extends Ys.Modal{constructor(e,t){super(e),this.settings=t,this.waitForClose=new Promise((n,i)=>{this.rejectPromise=i,this.resolvePromise=n}),this.open(),this.display()}display(){this.modalEl.addClass("qa-ai-wide-modal"),this.contentEl.addClass("qa-ai-scroll-content"),this.contentEl.createEl("h2",{text:"AI Assistant settings",cls:"qa-modal-title"}),this.addProvidersSetting(this.contentEl),this.addDefaultModelSetting(this.contentEl),this.addPromptTemplateFolderPathSetting(this.contentEl),this.addShowAssistantSetting(this.contentEl),this.addConfirmToolCallsSetting(this.contentEl),this.addDefaultSystemPromptSetting(this.contentEl)}reload(){this.contentEl.empty(),this.display()}addProvidersSetting(e){new Ys.Setting(e).setName("Providers").setDesc("The providers for the AI Assistant").addButton(t=>{t.setButtonText("Edit providers").onClick(()=>{new nT(this.settings.providers,this.app).waitForClose.then(()=>{this.reload()})})})}addDefaultModelSetting(e){new Ys.Setting(e).setName("Default model").setDesc("The default model for the AI Assistant").addDropdown(t=>{kx(t,{model:this.settings.defaultModel,modelRef:this.settings.defaultModelRef},n=>{this.settings.defaultModel=n.model,this.settings.defaultModelRef=n.modelRef})})}addPromptTemplateFolderPathSetting(e){new Ys.Setting(e).setName("Prompt template folder path").setDesc("Path to your folder with prompt templates").addText(t=>{t.setValue(this.settings.promptTemplatesFolderPath).onChange(n=>{this.settings.promptTemplatesFolderPath=n}),new An(this.app,t.inputEl,Go(this.app))})}addShowAssistantSetting(e){new Ys.Setting(e).setName("Show assistant").setDesc("Show status messages from the AI Assistant").addToggle(t=>{t.setValue(this.settings.showAssistant),t.onChange(n=>{this.settings.showAssistant=n})})}addConfirmToolCallsSetting(e){new Ys.Setting(e).setName("Confirm AI tool calls").setDesc("When an AI agent runs script-defined or built-in tools, ask before executing. 'Destructive only' confirms tools not marked read-only; 'Always' confirms every tool; 'Never' defers to each tool's own setting. A tool that requires approval is always confirmed regardless.").addDropdown(t=>{t.addOption("destructive","Destructive tools only (recommended)"),t.addOption("always","Always confirm every tool"),t.addOption("never","Never (use each tool's own setting)"),t.setValue(this.settings.confirmToolCalls??"destructive"),t.onChange(n=>{this.settings.confirmToolCalls=n})})}addDefaultSystemPromptSetting(e){new Ys.Setting(e).setName("Default system prompt").setDesc("The default system prompt for the AI Assistant");let t=new Ys.TextAreaComponent(e);t.inputEl.addClass("qa-ai-prompt-textarea"),t.inputEl.setAttribute("aria-label","Default system prompt");let n=Sx(e,t.inputEl,this.settings.defaultSystemPrompt??"");t.setValue(this.settings.defaultSystemPrompt).onChange(i=>{this.settings.defaultSystemPrompt=i,n(i)})}onClose(){this.resolvePromise(this.settings),super.onClose()}};var yV=require("obsidian");It();var gV=[{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 oT(r){switch(r){case"Template":return"New template";case"Capture":return"New capture";case"Macro":return"New macro";case"Multi":return"New folder"}}function vV(r,e){let t=oT(r),n=new Set(dn(e).map(o=>o.name));if(!n.has(t))return t;let i=2;for(;n.has(`${t} ${i}`);)i++;return`${t} ${i}`}var X9=V('<div><button type="button" class="qaNewFolderBtn svelte-a7rp4h"><!> <span> </span></button> <button type="button" aria-haspopup="menu"><!> <span> </span> <!></button></div>'),Z9={hash:"svelte-a7rp4h",code:`.qaAddChoiceControls.svelte-a7rp4h {display:flex;flex-direction:row;align-items:center;gap:0.5rem;}.qaAddChoiceControls.svelte-a7rp4h button:where(.svelte-a7rp4h) {display:inline-flex;align-items:center;gap:0.35em;}
/* The chevron sits tighter to the label than the leading plus. */.qaNewChoiceBtn.svelte-a7rp4h 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-a7rp4h {gap:1rem;}.qaAddChoiceControls.compact.svelte-a7rp4h button:where(.svelte-a7rp4h) {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-a7rp4h button:where(.svelte-a7rp4h):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-a7rp4h {flex:1;}.qaAddChoiceControls.fill.svelte-a7rp4h button:where(.svelte-a7rp4h) {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-a7rp4h:not(.compact):not(.fill) {flex-direction:column;align-items:stretch;}
}`};function Tm(r,e){fe(e,!0),Ke(r,Z9);let t=le(e,"targetFolderId",3,void 0),n=le(e,"targetFolderName",3,void 0),i=le(e,"compact",3,!1),o=le(e,"fill",3,!1),s=Ee(!1);function a(B){let J=new yV.Menu;for(let L of gV)J.addItem(W=>W.setTitle(`${L.label} \u2014 ${L.description}`).setIcon(L.iconId).onClick(j=>{let $=j.altKey===!0;e.onAddChoice(oT(L.type),L.type,t(),$)}));Q(s,!0),J.onHide(()=>{Q(s,!1)});let re=B.target?.closest("button");if(re){let L=re.getBoundingClientRect();J.showAtPosition({x:L.left,y:L.bottom+4})}else J.showAtMouseEvent(B)}function l(){e.onAddChoice(oT("Multi"),"Multi",t(),!0)}let c=M(()=>i()?"Add choice":"New choice"),u=M(()=>i()?"Add folder":"New folder"),d=M(()=>n()?`Add choice to ${n()}`:h(c)),f=M(()=>n()?`Add folder to ${n()}`:h(u));var p=X9();let m;var v=F(p),g=F(v);bt(g,{iconId:"folder-plus",size:14});var y=S(g,2),w=F(y,!0);D(y),D(v);var T=S(v,2);let b;var E=F(T);bt(E,{iconId:"plus",size:14});var C=S(E,2),_=F(C,!0);D(C);var I=S(C,2);{var q=B=>{bt(B,{iconId:"chevron-down",size:12})};X(I,B=>{i()||B(q)})}D(T),D(p),ae(()=>{m=at(p,1,"qaAddChoiceControls svelte-a7rp4h",null,m,{compact:i(),fill:o()&&!i()}),Ce(v,"aria-label",h(f)),Ce(v,"title",i()?h(f):void 0),ue(w,h(u)),b=at(T,1,"qaNewChoiceBtn svelte-a7rp4h",null,b,{"mod-cta":!i()}),Ce(T,"aria-expanded",h(s)),Ce(T,"aria-label",h(d)),Ce(T,"title",i()?h(d):void 0),ue(_,h(c))}),_e("click",v,l),_e("click",T,a),O(r,p),me()}nt(["click"]);var J9=V('<div class="rightButtonsContainer svelte-1es4f02"><!> <!> <!> <!> <!> <!></div>'),eX={hash:"svelte-1es4f02",code:`.rightButtonsContainer.svelte-1es4f02 {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 Ly(r,e){fe(e,!0),Ke(r,eX);let t=le(e,"showConfigureButton",3,!0),n=le(e,"showDuplicateButton",3,!0),i=le(e,"commandEnabled",3,!1),o=le(e,"choiceName",3,"");var s=J9(),a=F(s);{var l=g=>{{let y=M(()=>`Configure${o()?" "+o():""}`);Vt(g,{iconId:"settings",get label(){return h(y)},extraClass:"qa-row-secondary-action",get onclick(){return e.onConfigureChoice}})}};X(a,g=>{t()&&g(l)})}var c=S(a,2);{var u=g=>{{let y=M(()=>`Duplicate${o()?" "+o():""}`);Vt(g,{iconId:"copy",get label(){return h(y)},extraClass:"qa-row-secondary-action",get onclick(){return e.onDuplicateChoice}})}};X(c,g=>{n()&&g(u)})}var d=S(c,2);{let g=M(()=>`Delete${o()?" "+o():""}`);Vt(d,{iconId:"trash-2",get label(){return h(g)},extraClass:"qa-row-secondary-action",get onclick(){return e.onDeleteChoice}})}var f=S(d,2);{var p=g=>{{let y=M(()=>`More options${o()?" for "+o():""}`);Vt(g,{iconId:"more-vertical",ariaHasPopup:"menu",get label(){return h(y)},onclick:w=>e.onOpenMenu?.(w.currentTarget)})}};X(f,g=>{e.onOpenMenu&&g(p)})}var m=S(f,2);{let g=M(()=>`Command palette${o()?": "+o():""}`);Vt(m,{iconId:"zap",get ariaPressed(){return i()},get label(){return h(g)},extraClass:"qa-row-secondary-action",get onclick(){return e.onToggleCommand}})}var v=S(m,2);{let g=M(()=>`Reorder${o()?" "+o():""}`);Yn(v,{get label(){return h(g)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.onDragHandleDown},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}D(s),O(r,s),me()}var aT=require("obsidian");var bV=require("obsidian");function sT(r,e,t,n){e.replaceChildren(),bV.MarkdownRenderer.render(n,r,e,"/",t)}It();var tX=V('<div class="choiceListItem"><span class="qaChoiceRowIcon" aria-hidden="true"><!></span> <span class="choiceListItemName"></span> <!></div>'),rX={hash:"svelte-1aljzaf",code:""};function KI(r,e){fe(e,!0),Ke(r,rX);let t=!0,n=Ee(void 0),i=new aT.Component;Xt(()=>{h(n)&&sT(e.choice.name,h(n),i,e.app)}),Xt(()=>()=>i.unload());let o=()=>({onRename:()=>e.actions.onRenameChoice(e.choice),onToggle:()=>e.actions.onToggleCommand(e.choice),onConfigure:()=>e.actions.onConfigureChoice(e.choice),onDuplicate:()=>e.actions.onDuplicateChoice(e.choice),onDelete:()=>e.actions.onDeleteChoice(e.choice),onMove:p=>e.actions.onMoveChoice(e.choice,p)});function s(p){Yx(e.app,p,e.choice,e.roots,o())}function a(p){Kx(e.app,p,e.choice,e.roots,o())}var l=tX(),c=F(l),u=F(c);{let p=M(()=>Cd(e.choice));bt(u,{get iconId(){return h(p)},size:15})}D(c);var d=S(c,2);ll(d,p=>Q(n,p),()=>h(n));var f=S(d,2);Ly(f,{get onDragHandleDown(){return e.startDrag},onDeleteChoice:()=>e.actions.onDeleteChoice(e.choice),onConfigureChoice:()=>e.actions.onConfigureChoice(e.choice),onToggleCommand:()=>e.actions.onToggleCommand(e.choice),onDuplicateChoice:()=>e.actions.onDuplicateChoice(e.choice),onOpenMenu:a,get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown},get choiceName(){return e.choice.name},get commandEnabled(){return e.choice.command},showConfigureButton:t,get dragDisabled(){return e.dragDisabled},showDuplicateButton:!0}),D(l),ae(()=>Ce(l,"data-choice-id",e.choice.id)),_e("contextmenu",l,s),_e("dblclick",l,p=>{aT.Platform.isMobile||p.target.closest("button, a")||e.actions.onConfigureChoice(e.choice)}),O(r,l),me()}nt(["contextmenu","dblclick"]);var lT=require("obsidian");It();var nX=V('<span class="qaFolderCount svelte-1jxjn06" aria-hidden="true"> </span>'),iX=V(`<p class="qaUnreadableFolder svelte-1jxjn06">QuickAdd couldn't read this folder's contents. They're still
in <code class="svelte-1jxjn06">data.json</code>.</p>`),oX=V('<div class="nestedAddRow svelte-1jxjn06"><!></div>'),sX=V("<!> <!>",1),aX=V('<div class="nestedChoiceList svelte-1jxjn06"><!></div>'),lX=V('<div><div class="multiChoiceListItem"><button type="button" class="multiChoiceListItemName svelte-1jxjn06"><span aria-hidden="true"><!></span> <span class="choiceListItemName"></span> <!></button> <!></div> <!></div>'),cX={hash:"svelte-1jxjn06",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-1jxjn06 {transition:transform 150ms ease;}.multiChoiceCollapseIcon.is-collapsed.svelte-1jxjn06 {transform:rotate(-90deg);}
@media (prefers-reduced-motion: reduce) {.multiChoiceCollapseIcon.svelte-1jxjn06 {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-1jxjn06 {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-1jxjn06 .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-1jxjn06 {margin:0;padding:6px 8px 8px;color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);line-height:1.4;}.qaUnreadableFolder.svelte-1jxjn06 code:where(.svelte-1jxjn06) {font-size:inherit;}.qaFolderCount.svelte-1jxjn06 {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-1jxjn06: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-1jxjn06 {position:relative;padding-left:26px;}.nestedChoiceList.svelte-1jxjn06::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-1jxjn06 {margin:2px 0 4px 0;padding:0 8px;}`};function QI(r,e){fe(e,!0),Ke(r,cX);let t=le(e,"choice",7),n=le(e,"forceDragDisabled",3,!1),i=M(()=>Qe(t())),o=M(()=>Jo(t())),s=!0,a=Ee(void 0),l=new lT.Component;Xt(()=>{h(a)&&sT(t().name,h(a),l,e.app)}),Xt(()=>()=>l.unload());let c=()=>({onRename:()=>e.actions.onRenameChoice(t()),onToggle:()=>e.actions.onToggleCommand(t()),onConfigure:()=>e.actions.onConfigureChoice(t()),onDuplicate:()=>e.actions.onDuplicateChoice(t()),onDelete:()=>e.actions.onDeleteChoice(t()),onMove:B=>e.actions.onMoveChoice(t(),B)});function u(B){Yx(e.app,B,t(),e.roots,c())}function d(B){Kx(e.app,B,t(),e.roots,c())}let f={...xt(()=>e.actions),onReorderChoices:B=>{t().choices=B,e.actions.onCommitFolder(t().id,B)}};function p(){n()||e.actions.onToggleCollapsed(t())}var m=lX(),v=F(m),g=F(v),y=F(g);let w;var T=F(y);bt(T,{iconId:"chevron-down",size:16}),D(y);var b=S(y,2);ll(b,B=>Q(a,B),()=>h(a));var E=S(b,2);{var C=B=>{var J=nX(),re=F(J,!0);D(J),ae(()=>ue(re,h(i).length)),O(B,J)};X(E,B=>{t().collapsed&&h(i).length>0&&B(C)})}D(g),dr(g,B=>jE?.(B));var _=S(g,2);Ly(_,{get onDragHandleDown(){return e.startDrag},onDeleteChoice:()=>e.actions.onDeleteChoice(t()),onConfigureChoice:()=>e.actions.onConfigureChoice(t()),onToggleCommand:()=>e.actions.onToggleCommand(t()),onDuplicateChoice:()=>e.actions.onDuplicateChoice(t()),onOpenMenu:d,get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown},showConfigureButton:s,get dragDisabled(){return e.dragDisabled},get choiceName(){return t().name},get commandEnabled(){return t().command},showDuplicateButton:!0}),D(v);var I=S(v,2);{var q=B=>{var J=Vr(),re=Te(J);{var L=W=>{var j=aX(),$=F(j);{var G=H=>{var Y=iX();O(H,Y)},U=H=>{var Y=sX(),ie=Te(Y);{let he=M(()=>h(i).length===0),Ie=M(()=>e.rootReorder??e.actions.onReorderChoices);Sm(ie,{get app(){return e.app},get roots(){return e.roots},get choices(){return h(i)},nested:!0,get isEmptyFolder(){return h(he)},get forceDragDisabled(){return n()},get rootReorder(){return h(Ie)},get actions(){return f}})}var oe=S(ie,2);{var ce=he=>{var Ie=oX(),we=F(Ie);Tm(we,{compact:!0,get targetFolderId(){return t().id},get targetFolderName(){return t().name},get onAddChoice(){return e.actions.onAddChoice}}),D(Ie),O(he,Ie)};X(oe,he=>{n()||he(ce)})}O(H,Y)};X($,H=>{h(o)?H(G):H(U,-1)})}D(j),O(W,j)};X(re,W=>{t().collapsed||W(L)})}O(B,J)};X(I,B=>{(!e.collapseId||e.collapseId&&t().id!==e.collapseId)&&B(q)})}D(m),ae(()=>{Ce(v,"data-choice-id",t().id),Ce(g,"aria-expanded",!t().collapsed),Ce(g,"aria-label",`Toggle ${t().name}`),w=at(y,1,"qaChoiceRowIcon multiChoiceCollapseIcon svelte-1jxjn06",null,w,{"is-collapsed":t().collapsed})}),_e("contextmenu",v,u),_e("click",v,B=>{lT.Platform.isMobile||B.target.closest("button, a")||p()}),_e("click",g,p),O(r,m),me()}nt(["contextmenu","click"]);function wV(r){let e=r-1;return e*e*e+1}function CV(r,{from:e,to:t},n={}){var{delay:i=0,duration:o=C=>Math.sqrt(C)*120,easing:s=wV}=n,a=getComputedStyle(r),l=a.transform==="none"?"":a.transform,[c,u]=a.transformOrigin.split(" ").map(parseFloat);c/=r.clientWidth,u/=r.clientHeight;var d=uX(r),f=r.clientWidth/t.width/d,p=r.clientHeight/t.height/d,m=e.left+e.width*c,v=e.top+e.height*u,g=t.left+t.width*c,y=t.top+t.height*u,w=(m-g)*f,T=(v-y)*p,b=e.width/t.width,E=e.height/t.height;return{delay:i,duration:typeof o=="function"?o(Math.sqrt(w*w+T*T)):o,easing:s,css:(C,_)=>{var I=_*w,q=_*T,B=C+_*b,J=C+_*E;return`transform: ${l} translate(${I}px, ${q}px) scale(${B}, ${J});`}}}function uX(r){if("currentCSSZoom"in r)return r.currentCSSZoom;for(var e=r,t=1;e!==null;)t*=+getComputedStyle(e).zoom,e=e.parentElement;return t}var EV=require("obsidian");It();var dX=V("<div><!></div>"),pX=V("<div></div>"),fX={hash:"svelte-2ry05y",code:`.choiceList.svelte-2ry05y {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-2ry05y:not(.qa-nested) {padding-bottom:0.5rem;}.choiceList.qa-nested.svelte-2ry05y {
/* 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-2ry05y::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-2ry05y.qa-folder-droptarget {background-color:var(--background-modifier-hover);}.choiceList.qa-nested.svelte-2ry05y.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-2ry05y {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-2ry05y::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-2ry05y,
.choiceList.qa-nested.svelte-2ry05y::before {transition:none;}
}`};function Sm(r,e){fe(e,!0),Ke(r,fX);let t=le(e,"choices",31,()=>st([])),n=le(e,"forceDragDisabled",3,!1),i=le(e,"isEmptyFolder",3,!1),o=le(e,"nested",3,!1),s=M(()=>{let b=new Set;return Wr(t()).filter(E=>{if(!Ne(E))return!1;let C=E.id;return typeof C!="string"||C===""||b.has(C)?!1:(b.add(C),!0)})}),a=M(()=>e.rootReorder??e.actions.onReorderChoices),l=0,c=EV.Platform.isMobile,u=Ee(""),d=fx(),f=M(()=>n()||!c&&!d.armed),p=null;function m(b){if(n())return;d.markStarted();let E=b.detail.items;p=dx(E,b.detail.info.id)??p,Q(u,b.detail.info.id,!0),t(Ra(E))}function v(b){if(n())return;Q(u,"");let E=Ra(b.detail.items),C=b.detail.info.id;b.detail.info.trigger===Gn.DROPPED_INTO_ANOTHER?E=E.filter(_=>_.id!==C):p?.item.id===C&&!E.some(_=>_.id===C)&&(E=[...E],E.splice(Math.min(p.index,E.length),0,p.item)),p=null,t(E),d.reset(),e.actions.onReorderChoices(t())}let g=()=>{n()||d.startDrag()};function y(b,E){if(n())return;let C=Ra(h(s)),_=C.findIndex(J=>J.id===b.id);if(_===-1)return;let I=_+E;if(I<0||I>=C.length)return;let q=[...C],[B]=q.splice(_,1);q.splice(I,0,B),t(q),e.actions.onReorderChoices(t()),Ey(`Moved ${b.name} to position ${I+1} of ${C.length}`)}var w=pX();let T;jt(w,29,()=>Ra(h(s)),b=>b.id,(b,E)=>{var C=dX(),_=F(C);{var I=B=>{{let J=M(()=>e.roots??t()),re=M(()=>n()?void 0:()=>y(h(E),-1)),L=M(()=>n()?void 0:()=>y(h(E),1));KI(B,{get app(){return e.app},get roots(){return h(J)},get dragDisabled(){return h(f)},startDrag:g,get actions(){return e.actions},get choice(){return h(E)},get onMoveUp(){return h(re)},get onMoveDown(){return h(L)}})}},q=B=>{{let J=M(()=>e.roots??t()),re=M(()=>n()?void 0:()=>y(h(E),-1)),L=M(()=>n()?void 0:()=>y(h(E),1));QI(B,{get app(){return e.app},get roots(){return h(J)},get dragDisabled(){return h(f)},startDrag:g,get actions(){return e.actions},get collapseId(){return h(u)},get forceDragDisabled(){return n()},get rootReorder(){return h(a)},get choice(){return h(E)},get onMoveUp(){return h(re)},get onMoveDown(){return h(L)}})}};X(_,B=>{h(E).type!=="Multi"?B(I):B(q,-1)})}D(C),ik(C,()=>CV,()=>({duration:l})),O(b,C)}),D(w),dr(w,(b,E)=>ux?.(b,E),()=>px({items:h(s),dragDisabled:h(f),flipDurationMs:l,dropTargetClasses:o()?["qa-folder-droptarget"]:[]})),ae(()=>T=at(w,1,"choiceList svelte-2ry05y",null,T,{"qa-nested":o(),"qa-folder-empty":i(),"qa-empty":h(s).length===0})),al("consider",w,m),al("finalize",w,v),O(r,w),me()}var mX=V('<pre class="qaChoicesUnavailableDetail svelte-1fs8ikt"> </pre>'),hX=V(`<div class="qaChoicesUnavailable svelte-1fs8ikt"><div class="qaChoicesUnavailableHead svelte-1fs8ikt"><!> <span class="qaChoicesUnavailableTitle svelte-1fs8ikt"> </span></div> <p class="qaChoicesUnavailableBody svelte-1fs8ikt">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-1fs8ikt">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>`),gX={hash:"svelte-1fs8ikt",code:".qaChoicesUnavailable.svelte-1fs8ikt {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-1fs8ikt {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaChoicesUnavailableTitle.svelte-1fs8ikt {font-weight:var(--font-semibold);color:var(--text-normal);}.qaChoicesUnavailableBody.svelte-1fs8ikt {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}.qaChoicesUnavailableDetail.svelte-1fs8ikt {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 _m(r,e){Ke(r,gX);let t=le(e,"what",3,"your choices"),n=le(e,"detail",3,"");var i=hX(),o=F(i),s=F(o);bt(s,{iconId:"alert-triangle",size:16});var a=S(s,2),l=F(a);D(a),D(o);var c=S(o,6);{var u=d=>{var f=mX(),p=F(f,!0);D(f),ae(()=>ue(p,n())),O(d,f)};X(c,d=>{n()&&d(u)})}D(i),ae(()=>ue(l,`QuickAdd couldn't display ${t()??""}`)),O(r,i)}It();It();var XI=new WeakMap;function xV(r){let e=XI.get(r);if(e)return e;let t=JR(r);return XI.set(r,t),t}function TV(r){return XI.has(r)}rr();var vX=V(`<div class="choiceEmptyState svelte-1r4uuo1"><!> <div class="choiceEmptyTitle svelte-1r4uuo1">No choices yet</div> <p class="choiceEmptyBody svelte-1r4uuo1">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-1r4uuo1"><!></div></div>`),yX=V('<button class="search-input-clear-button qaFilterClearButton svelte-1r4uuo1" aria-label="Clear filter"></button>'),bX=V('<div class="choiceFilterEmpty svelte-1r4uuo1">No choices match your filter.</div>'),wX=V('<button type="button" class="qaAIAssistantBtn clickable-icon svelte-1r4uuo1" aria-label="Configure AI Assistant" title="Configure AI Assistant"><!></button>'),CX=V('<div class="choiceFilterBar svelte-1r4uuo1"><div class="search-input-container choiceFilterInput svelte-1r4uuo1"><input type="search" placeholder="Filter choices..." autocapitalize="off" autocorrect="off" enterkeyhint="search"/> <!></div></div> <!> <div class="choiceViewBottomBar svelte-1r4uuo1"><!> <!></div>',1),EX=V("<div><!></div>"),xX={hash:"svelte-1r4uuo1",code:`.choiceViewBottomBar.svelte-1r4uuo1 {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-1r4uuo1 {flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;color:var(--text-muted);}.qaAIAssistantBtn.svelte-1r4uuo1:hover {color:var(--text-normal);}.choiceEmptyState.svelte-1r4uuo1 {display:flex;flex-direction:column;align-items:center;text-align:center;gap:0.5rem;padding:2.5rem 1rem;color:var(--text-muted);}.choiceEmptyTitle.svelte-1r4uuo1 {font-weight:var(--font-semibold);color:var(--text-normal);}.choiceEmptyBody.svelte-1r4uuo1 {margin:0;max-width:42ch;}.choiceEmptyActions.svelte-1r4uuo1 {margin-top:0.5rem;}.choiceFilterBar.svelte-1r4uuo1 {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-1r4uuo1 {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-1r4uuo1 {background:transparent;border:none;box-shadow:none;padding:0;margin:0;cursor:var(--cursor, pointer);}.choiceFilterEmpty.svelte-1r4uuo1 {color:var(--text-faint);font-size:var(--font-ui-small, 13px);padding:12px 8px 16px;}`};function ZI(r,e){fe(e,!0),Ke(r,xX);let t=le(e,"choices",31,()=>st([])),n=Ee(""),i=M(()=>!Array.isArray(t())),o=M(()=>`The "choices" value in data.json is ${t()===null?"null":`of type "${typeof t()}"`}, but QuickAdd expects a list.`),s=km.Platform.isMobile,a=Ee(st(ne.getState().disableOnlineFeatures)),l=new Gx(xt(()=>e.plugin));function c(U){if(!Array.isArray(U))return U;let H=TV(U),{choices:Y,repaired:ie}=xV(U);if(H)return Y;for(let{choice:oe}of ie)if(oe.command)try{l.enableCommand(oe)}catch(ce){P.logError(`Could not register a command for the repaired choice "${oe.name}": ${ce instanceof Error?ce.message:String(ce)}`)}return Y}t(c(t())),Xt(()=>{let U=ne.subscribe(H=>{t(c(H.choices)),Q(a,H.disableOnlineFeatures,!0)});return()=>U()});function u(){e.saveChoices(Rf(t()))}let d=U=>U.type==="Multi";function f(U,H){let Y=H.trim();if(!Y)return U;let ie=(0,km.prepareFuzzySearch)(Y),oe=ce=>{if(!Ne(ce))return null;let he=!!ie(ce.name??"");if(!d(ce))return he?ce:null;let Ie=Qe(ce).map(we=>oe(we)).filter(Boolean);return he||Ie.length>0?{...ce,collapsed:!1,choices:Ie}:null};return U.map(ce=>oe(ce)).filter(Boolean)}async function p(U,H,Y,ie=!1){let oe=vV(H,t()),ce=VI(H,oe);if(t(JB(t(),ce,Y)),!Y&&h(n).trim().length>0&&Q(n,""),H==="Multi")u(),await b(ce),await m(ce.id);else if(ie)u(),await m(ce.id);else{u();try{await w(ce)}catch(he){P.logError(`Failed to configure the new choice: ${he instanceof Error?he.message:String(he)}`),u()}await m(ce.id)}}async function m(U){await Ip();try{document.querySelector(`[data-choice-id="${U}"]`)?.scrollIntoView({block:"nearest"})}catch{}}function v(U){return Fy(t(),U.id)??U}function g(U){return Ne(U)?U.command?!0:Qe(U).some(g):!1}async function y(U){let H=v(U);await YB(H,e.app)&&(t(Py(t(),U.id).updated),l.disableCommand(H,{recursive:!0}),u())}async function w(U){let H=v(U),Y=await KB(H,e.app,e.plugin);Y&&(t(t().map(ie=>T(ie,Y))),l.updateCommand(H,Y),u())}function T(U,H){if(!Ne(U))return U;if(U.id===H.id)return{...U,...H};if(Tl(U)){let Y=Qe(U).map(oe=>T(oe,H));return{...U,choices:Y}}return U}async function b(U){if(!U)return;let H=await KC(e.app,U.name,U.type);if(!H)return;let Y=v(U),ie={...Y,name:H};t(t().map(oe=>T(oe,ie))),l.updateCommand(Y,ie),u()}function E(U){let H=QB(v(U));t(t().map(Y=>T(Y,H))),H.command?l.enableCommand(H):l.disableCommand(H),u()}async function C(U){let H=await jB(v(U),e.app);t(zI(t(),U.id,H)??[...t(),H]),g(H)&&l.enableCommand(H),u(),new km.Notice(`Duplicated "${U.name}".`),await m(H.id)}function _(U,H){t(H===jI?ZB(t(),U.id):XB(t(),U.id,H)),u()}function I(U){t(U),u()}function q(U,H){t(eV(t(),U,H)),u()}function B(U){t(WI(t(),U.id,!U.collapsed)),u()}function J(U,H){return(Y,...ie)=>{let oe=hf(Y?.type),ce=Y?.name?`the ${oe} \u201C${Y.name}\u201D`:`that ${oe}`;Np(`Couldn't ${U} ${ce}`,H)(Y,...ie)}}let re={onDeleteChoice:J("delete",y),onConfigureChoice:J("open the settings for",w),onToggleCommand:J("update the command palette entry for",E),onDuplicateChoice:J("duplicate",C),onRenameChoice:J("rename",b),onMoveChoice:J("move",_),onToggleCollapsed:J("open or close",B),onReorderChoices:Np("Couldn't save the new order",I),onCommitFolder:Np("Couldn't save that folder's contents",q),onAddChoice:(U,H,Y,ie)=>Np(`Couldn't add that ${hf(H)}`,p)(U,H,Y,ie)},L=Np("Couldn't open the AI assistant settings",async()=>{let U=await new iT(e.app,ne.getState().ai).waitForClose;U&&ne.setState(H=>({...H,ai:U}))});var W=EX(),j=F(W);{var $=U=>{_m(U,{get detail(){return h(o)}})},G=U=>{var H=Vr(),Y=Te(H);qh(Y,{onerror:oe=>P.logError(`QuickAdd could not render the choice list: ${oe instanceof Error?oe.message:String(oe)}`),failed:(oe,ce=At)=>{{let he=M(()=>ce()instanceof Error?ce().message:String(ce()));_m(oe,{get detail(){return h(he)}})}}},oe=>{var ce=Vr(),he=Te(ce);{var Ie=Pe=>{var Ve=vX(),qe=F(Ve);bt(qe,{iconId:"folder-plus",size:28});var et=S(qe,4),_t=S(F(et));D(et);var ye=S(et,2),$e=F(ye);Tm($e,{get onAddChoice(){return re.onAddChoice}}),D(ye),D(Ve),ae(()=>Ce(_t,"href",Ia.gettingStarted)),O(Pe,Ve)},we=M(()=>t().length===0&&h(n).trim().length===0),Ge=Pe=>{var Ve=CX(),qe=Te(Ve),et=F(qe),_t=F(et);Bt(_t),Ce(_t,"spellcheck",!1);var ye=S(_t,2);{var $e=lt=>{var rt=yX();_e("click",rt,()=>Q(n,"")),O(lt,rt)};X(ye,lt=>{h(n)&&lt($e)})}D(et),D(qe);var ge=S(qe,2);{var xe=lt=>{Sm(lt,{get app(){return e.app},get roots(){return t()},get actions(){return re},get choices(){return t()},set choices(rt){t(rt)}})},tt=M(()=>h(n).trim().length===0),kt=lt=>{let rt=M(()=>f(t(),h(n)));var cr=Vr(),ti=Te(cr);{var Fo=te=>{var Ae=bX();O(te,Ae)},vn=te=>{Sm(te,{get app(){return e.app},get roots(){return t()},get choices(){return h(rt)},forceDragDisabled:!0,get actions(){return re}})};X(ti,te=>{h(rt).length===0?te(Fo):te(vn,-1)})}O(lt,cr)};X(ge,lt=>{h(tt)?lt(xe):lt(kt,-1)})}var Pt=S(ge,2),gt=F(Pt);{var Lt=lt=>{var rt=wX(),cr=F(rt);bt(cr,{iconId:"sparkles",size:16}),D(rt),_e("click",rt,L),O(lt,rt)};X(gt,lt=>{h(a)||lt(Lt)})}var Lr=S(gt,2);Tm(Lr,{get onAddChoice(){return re.onAddChoice},get fill(){return s}}),D(Pt),_e("keydown",_t,lt=>{lt.key==="Escape"&&h(n)&&(Q(n,""),lt.stopPropagation())}),Pi(_t,()=>h(n),lt=>Q(n,lt)),O(Pe,Ve)};X(he,Pe=>{h(we)?Pe(Ie):Pe(Ge,-1)})}O(oe,ce)}),O(U,H)};X(j,U=>{h(i)?U($):U(G,-1)})}D(W),O(r,W),me()}nt(["keydown","click"]);ht();var TX=V('<div class="qa-gv__empty svelte-hx6w4t">No global variables yet.</div>'),SX=V('<div class="qa-gv__row qa-gv__row--head svelte-hx6w4t"><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-hx6w4t">Actions</div></div>'),_X=V('<div class="qa-gv__row svelte-hx6w4t"><div class="qa-gv__cell qa-gv__name svelte-hx6w4t"><input type="text" placeholder="Name" class="svelte-hx6w4t"/></div> <div class="qa-gv__cell qa-gv__value svelte-hx6w4t"><textarea rows="2" placeholder="Snippet value (supports QuickAdd tokens)" class="svelte-hx6w4t"></textarea></div> <div class="qa-gv__cell qa-gv__ops svelte-hx6w4t"><button class="qa-gv__btn danger svelte-hx6w4t" title="Delete">Delete</button></div></div>'),kX=V('<div class="qa-gv svelte-hx6w4t"><div class="qa-gv__desc svelte-hx6w4t">Define reusable snippets referenced as <code>&#123;&#123;GLOBAL_VAR:&lt;name&gt;&#125;&#125;</code>. Snippets support other QuickAdd tokens and expand before VALUE/VDATE/etc.</div> <div class="qa-gv__table svelte-hx6w4t"><!> <!></div> <div class="qa-gv__actions svelte-hx6w4t"><button class="mod-cta">Add variable</button></div></div>'),AX={hash:"svelte-hx6w4t",code:`.qa-gv.svelte-hx6w4t {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-hx6w4t {display:flex;justify-content:flex-end;}.qa-gv__desc.svelte-hx6w4t {color:var(--text-muted);font-size:12px;}
/* Mirrors .qa-template-folder-empty, the sibling list's empty state. */.qa-gv__empty.svelte-hx6w4t {color:var(--text-muted);font-size:var(--font-ui-smaller);padding:6px 0;}.qa-gv__table.svelte-hx6w4t {display:grid;gap:8px;}.qa-gv__row.svelte-hx6w4t {display:grid;grid-template-columns:180px 1fr 140px;gap:8px;align-items:start;}.qa-gv__row--head.svelte-hx6w4t {font-weight:600;color:var(--text-muted);}.qa-gv__cell.svelte-hx6w4t input[type="text"]:where(.svelte-hx6w4t) {width:100%;}.qa-gv__cell.svelte-hx6w4t textarea:where(.svelte-hx6w4t) {width:100%;resize:vertical;}.qa-gv__ops.svelte-hx6w4t {display:flex;gap:6px;align-items:center;}.qa-gv__btn.svelte-hx6w4t {padding:4px 8px;}.qa-gv__btn.danger.svelte-hx6w4t {color:var(--text-error);}
@media (max-width: 900px) {.qa-gv__row.svelte-hx6w4t {grid-template-columns:1fr;}.qa-gv__row--head.svelte-hx6w4t {display:none;}
}`};function JI(r,e){fe(e,!0),Ke(r,AX);let t=Ee(st([]));function n(b,E){if(!E.has(b))return b;let C=1;for(;E.has(`${b}${C}`);)C++;return`${b}${C}`}function i(){let E=ne.getState().globalVariables||{};Q(t,Object.keys(E).map(C=>({name:C,value:E[C]??""})),!0)}let o=!1;function s(){let b=h(t).map(I=>I.name.trim()),E=b.some(I=>!I),C=new Set(b).size!==b.length;if(E||C)return;let _={};for(let I of h(t))_[I.name.trim()]=I.value??"";o=!0;try{ne.setState({globalVariables:_})}finally{o=!1}}function a(){let b=new Set(h(t).map(C=>C.name)),E=n("NewVar",b);Q(t,[...h(t),{name:E,value:""}],!0),s()}function l(b){Q(t,h(t).filter((E,C)=>C!==b),!0),s()}function c(b){return new pi(e.app,b,e.plugin),{destroy(){}}}let u;function d(b){u!==void 0&&window.clearTimeout(u),u=window.setTimeout(()=>{s()},200)}Xt(()=>{let b=ne.subscribe(()=>{o||i()});return i(),()=>{u!==void 0&&window.clearTimeout(u),b()}});var f=kX(),p=S(F(f),2),m=F(p);{var v=b=>{var E=TX();O(b,E)},g=b=>{var E=SX();O(b,E)};X(m,b=>{h(t).length===0?b(v):b(g,-1)})}var y=S(m,2);jt(y,17,()=>h(t),ig,(b,E,C)=>{var _=_X(),I=F(_),q=F(I);Bt(q),dr(q,W=>c?.(W)),Br(()=>Pi(q,()=>h(E).name,W=>h(E).name=W)),D(I);var B=S(I,2),J=F(B);Pu(J),dr(J,W=>c?.(W)),Br(()=>Pi(J,()=>h(E).value,W=>h(E).value=W)),D(B);var re=S(B,2),L=F(re);D(re),D(_),_e("input",q,()=>{d(h(E))}),_e("input",J,()=>d(h(E))),_e("click",L,()=>l(h(t).indexOf(h(E)))),O(b,_)}),D(p);var w=S(p,2),T=F(w);D(w),D(f),_e("click",T,a),O(r,f),me()}nt(["input","click"]);ht();Dt();var BV=require("obsidian");var Ks=require("obsidian");It();Qn();Tr();var DX=new Set;function tF(r){return r.type==="Multi"}function rF(r){return r.type==="Macro"}function IX(r){return r.type==="Template"}function FX(r){return r.type==="Capture"}function cT(r,e,t){return r?e.has(r.id)?t.has(r.id):!0:!1}function SV(r,e,t,n){switch(r.type){case"Choice":{let i=r;if(!t.has(i.choiceId))return!0;let o=e.get(i.choiceId);return o&&cT(o.choice,e,t)&&n(o.choice),!0}case"NestedChoice":{let i=r;return i.choice&&cT(i.choice,e,t)&&n(i.choice),!0}default:return!1}}function PX(r){let e=new Map,t=(n,i,o)=>{for(let s of n){if(!Ne(s))continue;let a=[...o,s.name];e.set(s.id,{choice:s,parentId:i,path:a}),tF(s)&&Array.isArray(s.choices)&&t(s.choices,s.id,a)}};return t(Wr(r),null,[]),e}function _V(r){let e=new Set;for(let t of Qe(r))Ne(t)&&e.add(t.id);return rF(r)&&eF(r.macro?.commands,e),e}function eF(r,e){for(let t of ar(r))if(mn(t))switch(t.type){case"Choice":{let n=t;n.choiceId&&e.add(n.choiceId);break}case"Conditional":{let n=t;eF(n.thenCommands,e),eF(n.elseCommands,e);break}case"NestedChoice":{let i=t.choice;if(!i)break;let o=_V(i);for(let s of o)e.add(s);break}default:break}}function uT(r,e,t){let n=PX(r),i=new Set,o=new Set,s=t?.excludedChoiceIds??DX,a=e.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 u=n.get(c);if(!u){o.add(c);continue}i.add(c),l.push(c);let d=_V(u.choice);for(let f of d){if(!n.has(f)){o.add(f);continue}s.has(f)||a.push(f)}}return{catalog:n,choiceIds:l,missingChoiceIds:Array.from(o)}}function dT(r,e){let t=new Set(e),n=new Set,i=new Set,o=new Set,s=l=>{if(l&&cT(l,r,t)&&!n.has(l.id)){if(n.add(l.id),tF(l)&&Array.isArray(l.choices))for(let c of l.choices)s(c);rF(l)&&a(l.macro?.commands)}},a=l=>{for(let c of ar(l))if(mn(c)&&!SV(c,r,t,s))switch(c.type){case"UserScript":{let u=c;u.path&&i.add(u.path);break}case"Conditional":{let u=c,d=u.condition;d.mode==="script"&&d.scriptPath&&o.add(d.scriptPath),a(u.thenCommands),a(u.elseCommands);break}default:break}};for(let l of e){let c=r.get(l);c&&s(c.choice)}return{userScriptPaths:i,conditionalScriptPaths:o}}function pT(r,e){let t=new Set(e),n=new Set,i=new Set,o=new Set,s=l=>{if(l&&cT(l,r,t)&&!n.has(l.id)){if(n.add(l.id),IX(l)&&l.templatePath&&i.add(l.templatePath),FX(l)&&l.createFileIfItDoesntExist?.enabled&&l.createFileIfItDoesntExist.createWithTemplate&&l.createFileIfItDoesntExist.template&&o.add(l.createFileIfItDoesntExist.template),tF(l)&&Array.isArray(l.choices))for(let c of l.choices)s(c);rF(l)&&a(l.macro?.commands)}},a=l=>{for(let c of ar(l))if(mn(c)&&!SV(c,r,t,s)&&c.type==="Conditional"){let u=c;a(u.thenCommands),a(u.elseCommands)}};for(let l of e){let c=r.get(l);c&&s(c.choice)}return{templatePaths:i,captureTemplatePaths:o}}It();var MV=require("obsidian");function fT(r){return!!r&&typeof r=="object"}function kV(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}function $X(r){return fT(r)?typeof r.id=="string"&&typeof r.name=="string"&&typeof r.type=="string":!1}function MX(r){return fT(r)?$X(r.choice)&&kV(r.pathHint)&&(r.parentChoiceId===null||typeof r.parentChoiceId=="string"):!1}function OX(r){if(!fT(r))return!1;let{kind:e,originalPath:t,contentEncoding:n,content:i}=r;return(e==="user-script"||e==="conditional-script"||e==="template"||e==="capture-template")&&typeof t=="string"&&n==="base64"&&typeof i=="string"}function AV(r){if(!fT(r))return!1;let{schemaVersion:e,quickAddVersion:t,createdAt:n,rootChoiceIds:i,choices:o,assets:s}=r;return typeof e=="number"&&Number.isInteger(e)&&e>=1&&typeof t=="string"&&typeof n=="string"&&kV(i)&&Array.isArray(o)&&o.every(MX)&&Array.isArray(s)&&s.every(OX)}De();Pd();var DV=typeof TextEncoder<"u"?new TextEncoder:void 0,IV=typeof TextDecoder<"u"?new TextDecoder:void 0;function FV(r){return typeof window>"u"?!1:typeof window[r]=="function"}function PV(){if(!(typeof Buffer>"u"))return Buffer}function $V(r){if(DV&&FV("btoa")){let t=DV.encode(r),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return window.btoa(n)}let e=PV();if(e)return e.from(r,"utf8").toString("base64");throw new Error("Base64 encoding is not supported in this environment.")}function ql(r){if(IV&&FV("atob")){let t=window.atob(r),n=Uint8Array.from(t,i=>i.charCodeAt(0));return IV.decode(n)}let e=PV();if(e)return e.from(r,"base64").toString("utf8");throw new Error("Base64 decoding is not supported in this environment.")}qn();It();async function mT(r,e){let t=e.lastIndexOf("/");if(t<0)return;let n=e.slice(0,t);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)}Bl();function OV(){return`QuickAdd Packages/quickadd-package-${new Date().toISOString().replace(/[:.]/g,"-")}.quickadd.json`}async function RV(r,e){let{choices:t,rootChoiceIds:n,quickAddVersion:i}=e,o=new Set(e.excludedChoiceIds??[]),s=e.createdAt??new Date().toISOString(),a=uT(t,n,{excludedChoiceIds:o}),l=new Set(a.choiceIds),c=dT(a.catalog,a.choiceIds),u=pT(a.catalog,a.choiceIds),d=RX(c,u),f=await LX(r,d),p=NX(f.encodedAssets),m=a.choiceIds.map(y=>{let w=a.catalog.get(y);if(!w)throw new Error(`Choice '${y}' missing from catalog.`);let T=Ze(w.choice);return LV(T,l),rm(T,{secretOptionNamesByPath:p,stripUnknownStringSettings:!0}),{choice:T,pathHint:[...w.path],parentChoiceId:w.parentId}}),v=n.filter(y=>l.has(y));return{pkg:{schemaVersion:1,quickAddVersion:i,createdAt:s,rootChoiceIds:[...v],choices:m,assets:f.encodedAssets},missingChoiceIds:a.missingChoiceIds,missingAssets:f.missingAssets}}function RX(r,e){let t=new Map;for(let n of r.userScriptPaths)n&&t.set(n,"user-script");for(let n of r.conditionalScriptPaths)n&&t.set(n,"conditional-script");for(let n of e.templatePaths)n&&(t.has(n)||t.set(n,"template"));for(let n of e.captureTemplatePaths)n&&(t.has(n)||t.set(n,"capture-template"));return Array.from(t.entries()).map(([n,i])=>({path:n,kind:i}))}async function LX(r,e){let t=[],n=[];for(let{path:i,kind:o}of e)try{if(!await r.vault.adapter.exists(i)){n.push({path:i,kind:o}),P.logWarning(`QuickAdd export skipped missing ${o}: ${i}`);continue}let a=await r.vault.adapter.read(i);t.push({kind:o,originalPath:i,contentEncoding:"base64",content:$V(a)})}catch(s){n.push({path:i,kind:o}),P.logWarning(`QuickAdd export failed to read ${o} '${i}': ${s?.message??s}`)}return{encodedAssets:t,missingAssets:n}}function NX(r){let e=new Map;for(let t of r)if(t.kind==="user-script")try{let n=Jf(ql(t.content),t.originalPath);e.set(t.originalPath,n.foundSecretOptions&&n.names.size===0?null:n.names)}catch(n){P.logWarning(`QuickAdd export could not inspect user-script settings '${t.originalPath}': ${n?.message??n}`)}return e}function LV(r,e){if(r.type!=="Multi")return;let t=r;if(!Array.isArray(t.choices)||t.choices.length===0){t.choices=[];return}t.choices=t.choices.filter(n=>Ne(n)&&e.has(n.id)).map(n=>(LV(n,e),n))}async function BX(r,e){return vi.Prompt(r,"Overwrite existing file?",`A file already exists at '${e}'. Saving the package will overwrite it. Continue?`)}async function NV(r,e,t,n={}){let i=(0,MV.normalizePath)(t.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=>BX(r,c)))(i))throw new Error(`Save cancelled: '${i}' already exists.`);await mT(r,i);let s=JSON.stringify(e,null,2);return await r.vault.adapter.write(i,s),{overwritten:o}}var VX=V('<p class="emptyState svelte-llmxn2">No choices match the current filter.</p>'),qX=V('<span class="choicePath svelte-llmxn2"> </span>'),UX=V('<li><label class="svelte-llmxn2"><input type="checkbox"/> <span class="choiceName svelte-llmxn2"> </span> <!> <span class="choiceType svelte-llmxn2"> </span></label></li>'),zX=V('<ul class="svelte-llmxn2"></ul>'),HX=V('<div class="warning svelte-llmxn2"><strong>Missing dependencies detected</strong> <p> </p></div>'),WX=V("<p> </p>"),jX=V('<li> <span class="assetKind svelte-llmxn2"> </span></li>'),GX=V('<div><p>Missing assets:</p> <ul class="svelte-llmxn2"></ul></div>'),YX=V('<section class="warning svelte-llmxn2"><h4>Warnings</h4> <!> <!></section>'),KX=V('<div class="exportPackageModal svelte-llmxn2"><header class="svelte-llmxn2"><h2>Export QuickAdd package</h2> <p class="svelte-llmxn2">Select choices to bundle. Dependencies are added automatically.</p></header> <section class="controls svelte-llmxn2"><input type="text" placeholder="Filter choices" autocapitalize="off" autocorrect="off" class="svelte-llmxn2"/> <div class="controlButtons svelte-llmxn2"><button type="button" class="svelte-llmxn2">Select visible</button> <button type="button" class="svelte-llmxn2">Clear selection</button></div></section> <section class="choiceList svelte-llmxn2"><!></section> <section class="summary svelte-llmxn2"><h3 class="svelte-llmxn2">Package summary</h3> <div class="summaryGrid svelte-llmxn2"><div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Selected choices</span></div> <div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Total packaged</span></div> <div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Auto-included</span></div> <div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Scripts embedded</span></div> <div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Templates embedded</span></div></div> <!></section> <!> <section class="actions svelte-llmxn2"><div class="actionGroup svelte-llmxn2"><button type="button" class="secondary svelte-llmxn2"><!></button></div> <div class="actionGroup svelte-llmxn2"><label><span>Save to file</span> <div class="saveRow svelte-llmxn2"><input type="text" placeholder="QuickAdd Packages/quickadd-package-YYYY-MM-DD.quickadd.json" class="svelte-llmxn2"/> <button type="button" class="svelte-llmxn2"><!></button></div></label></div></section> <section class="footer svelte-llmxn2"><button type="button" class="secondary svelte-llmxn2">Cancel</button></section></div>'),QX={hash:"svelte-llmxn2",code:`.exportPackageModal.svelte-llmxn2 {display:flex;flex-direction:column;gap:1rem;width:min(640px, 100%);min-width:0;max-height:75vh;}header.svelte-llmxn2 p:where(.svelte-llmxn2) {margin:0;color:var(--text-muted);}.controls.svelte-llmxn2 {display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;}.controls.svelte-llmxn2 input:where(.svelte-llmxn2) {flex:1;}.controlButtons.svelte-llmxn2 {display:flex;gap:0.5rem;flex-wrap:wrap;justify-content:flex-end;}.choiceList.svelte-llmxn2 {flex:1;min-height:180px;max-height:260px;overflow:auto;border:1px solid var(--background-modifier-border);border-radius:6px;padding:0.5rem;}.choiceList.svelte-llmxn2 ul:where(.svelte-llmxn2) {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0.25rem;}.choiceList.svelte-llmxn2 label:where(.svelte-llmxn2) {display:flex;align-items:center;gap:0.5rem;padding:0.25rem 0.5rem;border-radius:4px;}.choiceList.svelte-llmxn2 label:where(.svelte-llmxn2):hover {background:var(--background-modifier-hover);}.choiceName.svelte-llmxn2 {font-weight:600;}.choicePath.svelte-llmxn2 {color:var(--text-muted);font-size:0.8rem;}.choiceType.svelte-llmxn2 {margin-left:auto;font-size:0.75rem;text-transform:uppercase;color:var(--text-faint);}.emptyState.svelte-llmxn2 {margin:0;color:var(--text-muted);text-align:center;}.summary.svelte-llmxn2 {border:1px solid var(--background-modifier-border);border-radius:6px;padding:0.75rem;display:flex;flex-direction:column;gap:0.5rem;}.summary.svelte-llmxn2 h3:where(.svelte-llmxn2) {margin:0 0 0.5rem 0;font-size:1rem;}.summaryGrid.svelte-llmxn2 {display:grid;grid-template-columns:repeat(auto-fit, minmax(140px, 1fr));gap:0.75rem;}.summaryGrid.svelte-llmxn2 div:where(.svelte-llmxn2) {display:flex;flex-direction:column;}.summaryGrid.svelte-llmxn2 strong:where(.svelte-llmxn2) {font-size:1.1rem;}
/* Neutral surface with an amber-tinted border (these are warnings, not
critical danger): ranked, not a blanket-red fill \u2014 matches the import
modal's CapabilityBanner treatment. */.warning.svelte-llmxn2 {border:1px solid var(--qa-sev-warning-border);background:var(--background-secondary);border-radius:var(--radius-m, 8px);padding:0.6rem 0.75rem;color:var(--text-normal);}.warning.svelte-llmxn2 ul:where(.svelte-llmxn2) {margin:0.25rem 0 0 1rem;padding:0;}.assetKind.svelte-llmxn2 {color:var(--text-muted);}.actions.svelte-llmxn2 {display:flex;flex-direction:column;gap:1rem;}.actionGroup.svelte-llmxn2 {display:flex;flex-direction:column;gap:0.5rem;}.saveRow.svelte-llmxn2 {display:flex;gap:0.5rem;}.saveRow.svelte-llmxn2 input:where(.svelte-llmxn2) {flex:1;}.footer.svelte-llmxn2 {display:flex;justify-content:flex-end;gap:0.5rem;margin-top:0.5rem;}.footer.svelte-llmxn2 button.secondary:where(.svelte-llmxn2) {background:transparent;}
@media (max-width: 600px) {.exportPackageModal.svelte-llmxn2 {max-height:90vh;padding-bottom:0.5rem;}.controls.svelte-llmxn2 {flex-direction:column;align-items:stretch;gap:0.5rem;}.controlButtons.svelte-llmxn2 {width:100%;flex-direction:column;gap:0.5rem;align-items:stretch;}.controlButtons.svelte-llmxn2 button:where(.svelte-llmxn2) {width:100%;}.choiceList.svelte-llmxn2 {min-height:160px;max-height:40vh;}.summaryGrid.svelte-llmxn2 {grid-template-columns:1fr;}.actions.svelte-llmxn2 {gap:0.75rem;}.actionGroup.svelte-llmxn2 {align-items:stretch;}.actionGroup.svelte-llmxn2 button:where(.svelte-llmxn2) {width:100%;}.saveRow.svelte-llmxn2 {flex-direction:column;}.saveRow.svelte-llmxn2 button:where(.svelte-llmxn2) {width:100%;}.footer.svelte-llmxn2 {flex-direction:column-reverse;align-items:stretch;}.footer.svelte-llmxn2 button:where(.svelte-llmxn2) {width:100%;}
}`};function nF(r,e){fe(e,!0),Ke(r,QX);let t={"user-script":"User script","conditional-script":"Conditional script",template:"Template file","capture-template":"Capture template"},n=Ee(""),i=Ee(st(new Set)),o=Ee(st(new Set)),s=Ee(st(OV())),a=Ee(null),l=Ee(null),c=M(()=>Og(e.allChoices)),u=M(()=>v(h(c),h(n))),d=M(()=>E(h(c),h(i))),f=M(()=>C(e.allChoices,h(d),h(o))),p=M(()=>new Map(h(c).map(A=>[A.id,A.path.join(" / ")])));function m(A){return A.type==="Multi"}function v(A,N){let K=N.trim().toLowerCase();return K?A.filter(Z=>`${Z.path.join(" ")} ${Z.choice.type}`.toLowerCase().includes(K)):A}function g(A){let N=[];for(let K of Qe(A))Ne(K)&&N.push(K.id,...g(K));return N}function y(A,N){let K=[A.id,...g(A)];if(N){let Z=new Set(h(i));for(let se of K)Z.add(se);if(Q(i,Z,!0),h(o).size>0){let se=new Set(h(o));for(let de of K)se.delete(de);Q(o,se,!0)}}else{let Z=new Set(h(i));for(let de of K)Z.delete(de);Q(i,Z,!0);let se=new Set(h(o));for(let de of K)se.add(de);Q(o,se,!0)}}function w(A){let N=h(c).find(Z=>Z.id===A);if(!N)return;let K=h(i).has(A);y(N.choice,!K),Q(a,null)}function T(){for(let A of h(u))y(A.choice,!0);Q(a,null)}function b(){Q(i,new Set,!0),Q(o,new Set,!0),Q(a,null)}function E(A,N){let K=[];for(let Z of A)N.has(Z.id)&&(!Z.parentId||!N.has(Z.parentId))&&K.push(Z.id);return K}function C(A,N,K){if(N.length===0)return{rootCount:0,totalChoices:0,dependencyCount:0,missingChoiceIds:[],userScripts:0,conditionalScripts:0,templateFiles:0,captureTemplates:0};let Z=uT(A,N,{excludedChoiceIds:K}),se=dT(Z.catalog,Z.choiceIds),de=pT(Z.catalog,Z.choiceIds);return{rootCount:N.length,totalChoices:Z.choiceIds.length,dependencyCount:Math.max(Z.choiceIds.length-N.length,0),missingChoiceIds:Z.missingChoiceIds,userScripts:se.userScriptPaths.size,conditionalScripts:se.conditionalScriptPaths.size,templateFiles:de.templatePaths.size,captureTemplates:de.captureTemplatePaths.size}}function _(A){let{missingChoiceIds:N,missingAssets:K}=A;return N.length===0&&K.length===0?null:{missingChoices:N,missingAssets:K}}async function I(){if(h(d).length===0)return new Ks.Notice("Select at least one choice to export."),null;try{let A=await RV(e.app,{choices:e.allChoices,rootChoiceIds:h(d),excludedChoiceIds:Array.from(h(o)),quickAddVersion:e.plugin.manifest.version});return Q(a,_(A),!0),A}catch(A){return console.error(A),Q(a,null),new Ks.Notice(`Export failed: ${A?.message??String(A)}`),null}}async function q(){if(!h(l)){Q(l,"copy");try{let A=await I();if(!A)return;let N=JSON.stringify(A.pkg,null,2);await J(N),new Ks.Notice(`Copied package (${A.pkg.choices.length} choice${A.pkg.choices.length===1?"":"s"}) to clipboard.`),h(a)?new Ks.Notice("Package copied with warnings. Review details below."):e.close()}catch(A){console.error(A),new Ks.Notice(`Copy failed: ${A?.message??String(A)}`)}finally{Q(l,null)}}}async function B(){if(h(l))return;let A=h(s).trim();if(!A){new Ks.Notice("Enter a file path before saving.");return}Q(l,"save");try{let N=await I();if(!N)return;let{overwritten:K}=await NV(e.app,N.pkg,A),Z=N.pkg.choices.length,se=`${Z} choice${Z===1?"":"s"}`;new Ks.Notice(K?`Overwrote package (${se}) at '${A}'.`:`Saved package (${se}) to '${A}'.`),h(a)?new Ks.Notice("Package saved with warnings. Review details below."):e.close()}catch(N){let K=N?.message??String(N);if(K.startsWith("Save cancelled:")){new Ks.Notice("Save cancelled.");return}console.error(N),new Ks.Notice(`Save failed: ${K}`)}finally{Q(l,null)}}async function J(A){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(A);return}let N=document.createElement("textarea");N.value=A,N.setAttribute("readonly","true"),N.style.position="fixed",N.style.opacity="0",document.body.appendChild(N),N.focus(),N.select();let K=document.execCommand("copy");if(document.body.removeChild(N),!K)throw new Error("Clipboard copy is not supported in this environment.")}var re=KX(),L=S(F(re),2),W=F(L);Bt(W),Ce(W,"spellcheck",!1);var j=S(W,2),$=F(j),G=S($,2);D(j),D(L);var U=S(L,2),H=F(U);{var Y=A=>{var N=VX();O(A,N)},ie=A=>{var N=zX();jt(N,21,()=>h(u),K=>K.id,(K,Z)=>{var se=UX(),de=F(se),Me=F(de);Bt(Me);var it=S(Me,2),ur=F(it,!0);D(it);var $t=S(it,2);{var ri=or=>{var yn=qX(),mt=F(yn,!0);D(yn),ae(qi=>ue(mt,qi),[()=>h(Z).path.slice(0,-1).join(" \u203A ")]),O(or,yn)};X($t,or=>{h(Z).path.length>1&&or(ri)})}var ot=S($t,2),Yt=F(ot,!0);D(ot),D(de),D(se),ae((or,yn)=>{Pp(se,`padding-left: ${h(Z).depth*16}px`),Yu(Me,or),ue(ur,yn),ue(Yt,h(Z).choice.type)},[()=>h(i).has(h(Z).id),()=>h(Z).path.at(-1)]),_e("change",Me,()=>w(h(Z).id)),O(K,se)}),D(N),O(A,N)};X(H,A=>{h(u).length===0?A(Y):A(ie,-1)})}D(U);var oe=S(U,2),ce=S(F(oe),2),he=F(ce),Ie=F(he),we=F(Ie,!0);D(Ie),tn(2),D(he);var Ge=S(he,2),Pe=F(Ge),Ve=F(Pe,!0);D(Pe),tn(2),D(Ge);var qe=S(Ge,2),et=F(qe),_t=F(et,!0);D(et),tn(2),D(qe);var ye=S(qe,2),$e=F(ye),ge=F($e,!0);D($e),tn(2),D(ye);var xe=S(ye,2),tt=F(xe),kt=F(tt,!0);D(tt),tn(2),D(xe),D(ce);var Pt=S(ce,2);{var gt=A=>{var N=HX(),K=S(F(N),2),Z=F(K);D(K),D(N),ae(se=>ue(Z,`The following choice IDs were referenced but not found:
${se??""}`),[()=>h(f).missingChoiceIds.join(", ")]),O(A,N)};X(Pt,A=>{h(f).missingChoiceIds.length>0&&A(gt)})}D(oe);var Lt=S(oe,2);{var Lr=A=>{var N=YX(),K=S(F(N),2);{var Z=Me=>{var it=WX(),ur=F(it);D(it),ae($t=>ue(ur,`Missing choices:
${$t??""}`),[()=>h(a).missingChoices.map($t=>h(p).get($t)??$t).join(", ")]),O(Me,it)};X(K,Me=>{h(a).missingChoices.length>0&&Me(Z)})}var se=S(K,2);{var de=Me=>{var it=GX(),ur=S(F(it),2);jt(ur,21,()=>h(a).missingAssets,$t=>$t.path,($t,ri)=>{var ot=jX(),Yt=F(ot),or=S(Yt),yn=F(or);D(or),D(ot),ae(()=>{ue(Yt,`${h(ri).path??""} `),ue(yn,`(${t[h(ri).kind]??""})`)}),O($t,ot)}),D(ur),D(it),O(Me,it)};X(se,Me=>{h(a).missingAssets.length>0&&Me(de)})}D(N),O(A,N)};X(Lt,A=>{h(a)&&A(Lr)})}var lt=S(Lt,2),rt=F(lt),cr=F(rt),ti=F(cr);{var Fo=A=>{var N=ga("Copying\u2026");O(A,N)},vn=A=>{var N=ga("Copy JSON");O(A,N)};X(ti,A=>{h(l)==="copy"?A(Fo):A(vn,-1)})}D(cr),D(rt);var te=S(rt,2),Ae=F(te),Gt=S(F(Ae),2),er=F(Gt);Bt(er);var Kr=S(er,2),no=F(Kr);{var ra=A=>{var N=ga("Saving\u2026");O(A,N)},na=A=>{var N=ga("Save to file");O(A,N)};X(no,A=>{h(l)==="save"?A(ra):A(na,-1)})}D(Kr),D(Gt),D(Ae),D(te),D(lt);var tc=S(lt,2),x=F(tc);D(tc),D(re),ae(()=>{ue(we,h(f).rootCount),ue(Ve,h(f).totalChoices),ue(_t,h(f).dependencyCount),ue(ge,h(f).userScripts+h(f).conditionalScripts),ue(kt,h(f).templateFiles+h(f).captureTemplates),cr.disabled=h(l)!==null,Kr.disabled=h(l)!==null,x.disabled=h(l)!==null}),Pi(W,()=>h(n),A=>Q(n,A)),_e("click",$,T),_e("click",G,b),_e("click",cr,q),Pi(er,()=>h(s),A=>Q(s,A)),_e("click",Kr,B),_e("click",x,function(...A){e.close?.apply(this,A)}),O(r,re),me()}nt(["click","change"]);var gT=class extends BV.Modal{constructor(t,n,i){super(t);this.plugin=n;this.choices=i;this.handle=null}onOpen(){this.modalEl.addClass("quickAddModal","packageExportModal"),this.handle=ci(this.contentEl,nF,{app:this.app,plugin:this.plugin,allChoices:this.choices,close:()=>this.close()},{what:"the package exporter"})}onClose(){this.handle?.destroy(),this.handle=null}};var hq=require("obsidian");var qy=require("obsidian");ht();Dt();var xT=require("obsidian");Ea();It();Qn();Tr();Tr();Tr();It();Qn();function XX(r){return r.type==="Multi"}function ZX(r){return r.type==="Macro"}function iF(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){e.onUnreadable?.();return}if(!t.has(r)){if(t.add(r),e.onChoice?.(r),XX(r))if(Array.isArray(r.choices))for(let n of r.choices)iF(n,e,t);else wC(r.choices)&&e.onUnreadable?.();ZX(r)&&vT(hn(r.macro),e,t)}}}function vT(r,e,t){if(!Array.isArray(r)){Kn(r)&&e.onUnreadable?.();return}for(let n of r){if(!n||typeof n!="object")continue;if(Array.isArray(n)){e.onUnreadable?.();continue}e.onCommand?.(n);let i=n;(n.type==="Conditional"||Array.isArray(i.thenCommands)||Array.isArray(i.elseCommands))&&(vT(i.thenCommands,e,t),vT(i.elseCommands,e,t));let s=n,a=n.type==="NestedChoice"||s.choice&&typeof s.choice=="object"?s.choice:void 0;a&&iF(a,e,t)}}function oF(r,e){let t=new Set;if(Array.isArray(r.choices))for(let i of r.choices)iF(i,e,t);else e.onUnreadable?.();let n=r.macros;if(Array.isArray(n))for(let i of n)vT(hn(i),e,t);else Kn(n)&&e.onUnreadable?.()}function Am(r){let e=!1;return oF(r,{onUnreadable:()=>{e=!0}}),e}function Dm(r,e){oF(r.settings,{onChoice:e})}function yT(r,e){oF(r,{onCommand:e})}function JX(r){return r.type==="AIAssistant"}function bT(r,e,t){let n=0;return yT({choices:r},i=>{if(!JX(i)||i.modelRef&&i.modelRef.name===i.model&&e.find(l=>l.id===i.modelRef?.providerId)?.models.some(l=>l.name===i.model)||!i.model||i.model==="Ask me")return;let o=e.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++,t?.(i,s)}),n}De();qn();aF();Sa();Bl();Tr();It();Qn();Eg();Je();var cF={"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 wT(r){return cF[r].severity}function UV(r){return cF[r].label}function zV(r){return cF[r].description}function HV(r){return r==="user-script"||r==="conditional-script"}function tZ(r,e){return HV(r)||!Ht.test(e)}function rZ(r,e){if(!Ht.test(r))return!1;let t;try{t=ql(e)}catch{return!1}let{code:n}=vl(t);return n!==null&&n.length>0}function nZ(r,e){let t;try{t=ql(e)}catch{return null}if(Ht.test(r)){let{code:n}=vl(t);return n!==null&&n.length>0?n:null}return t}var iZ=/\bai\s*\.\s*(?:tools|agent|tool)\b|\btools\s*\.\s*(?:vault|workspace|system)\s*\(/;function oZ(r){return iZ.test(r)}var CT={critical:0,warning:1,info:2},sZ=new Set(Object.values(vr));function Qs(r){return r.filter(e=>!!e).join(" \u203A ")}function aZ(r){let e=r.name?.trim();return e&&e.length>0?e:String(r.type)}function lZ(r){if(r.mode==="script")return`script: ${r.scriptPath}${r.exportName?` (${r.exportName})`:""}`;let e=r.expectedValue!==void 0?` ${r.expectedValue}`:"";return`${r.variableName} ${r.operator}${e}`}function cZ(r){return r.type==="Macro"}function uZ(r){return r.type==="Multi"}function dZ(r){return r.type==="Template"}function pZ(r){return r.type==="Capture"}function fZ(r){let e=r.fileExistsBehavior;return!e||e.kind!=="apply"?!1:e.mode==="overwrite"||e.mode==="appendTop"||e.mode==="appendBottom"}function WV(r){let e=[],t=new Set(r.choices.map(n=>n.choice.id));for(let n of r.choices){let i=n.choice,o=Qs(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:[]};uF(i,s,[i.name],t,0),e.push(s)}return{choiceWalks:e}}function uF(r,e,t,n,i){if(r.command&&(e.registersCommand=!0,e.flags.add("registers-command")),cZ(r)&&(r.runOnStartup&&(e.flags.add("run-on-startup"),e.rows.push({flag:"run-on-startup",severity:"critical",title:"Runs automatically every time Obsidian starts",detail:Qs(t)})),lF(r.macro?.commands,e,t,n,i)),dZ(r)&&(r.templatePath&&e.usages.push({choiceId:e.choiceId,path:r.templatePath,asScript:!1,impliedKind:"template",breadcrumb:Qs([...t,"template"])}),fZ(r)&&e.flags.add("template-write")),pZ(r)){e.flags.add("capture-writes");let o=r.createFileIfItDoesntExist;o?.enabled&&o.createWithTemplate&&o.template&&e.usages.push({choiceId:e.choiceId,path:o.template,asScript:!1,impliedKind:"capture-template",breadcrumb:Qs([...t,"new-file template"])})}if(uZ(r)&&Array.isArray(r.choices))for(let o of r.choices)Ne(o)&&(n.has(o.id)||uF(o,e,[...t,o.name],n,i))}function lF(r,e,t,n,i){for(let o of ar(r)){if(!mn(o))continue;let s=aZ(o),a=[...t,s];switch(o.type){case"UserScript":{let l=o;e.flags.add("user-script"),e.commands.push({name:s,type:o.type,depth:i,flag:"user-script",scriptPath:l.path}),l.path&&(e.usages.push({choiceId:e.choiceId,path:l.path,asScript:!0,impliedKind:"user-script",breadcrumb:Qs(a)}),e.rows.push({flag:"user-script",severity:"critical",title:"Runs custom JavaScript with full access to your vault and the network",detail:`${Qs(a)} (${l.path})`,scriptPath:l.path}));break}case"Conditional":{let l=o,c=l.condition,u=c?lZ(c):void 0,d=c?.mode==="script"&&!!c.scriptPath;if(e.commands.push({name:s,type:o.type,depth:i,flag:d?"conditional-script":void 0,scriptPath:d?c.scriptPath:void 0,summary:u}),d){let f=c.scriptPath;e.flags.add("conditional-script"),e.usages.push({choiceId:e.choiceId,path:f,asScript:!0,impliedKind:"conditional-script",breadcrumb:Qs(a)}),e.rows.push({flag:"conditional-script",severity:"critical",title:"Runs custom JavaScript chosen by a condition",detail:`${Qs(a)} (${f})`,scriptPath:f})}lF(l.thenCommands??[],e,[...a,"then"],n,i+1),lF(l.elseCommands??[],e,[...a,"else"],n,i+1);break}case"NestedChoice":{let l=o;e.commands.push({name:s,type:o.type,depth:i}),l.choice&&uF(l.choice,e,[...a,l.choice.name],n,i+1);break}case"Obsidian":{let l=o;e.flags.add("obsidian-command"),e.commands.push({name:s,type:o.type,depth:i}),e.rows.push({flag:"obsidian-command",severity:"warning",title:"Triggers another Obsidian command",detail:`${Qs(a)}${l.commandId?` (${l.commandId})`:""}`});break}case"AIAssistant":{e.flags.add("ai"),e.commands.push({name:s,type:o.type,depth:i}),e.rows.push({flag:"ai",severity:"warning",title:"Sends note content to your AI provider over the network",detail:Qs(a)});break}case"EditorCommand":{e.flags.add("editor-command"),e.commands.push({name:s,type:o.type,depth:i});break}case"OpenFile":{e.flags.add("open-file"),e.commands.push({name:s,type:o.type,depth:i});break}case"Choice":case"Wait":{e.commands.push({name:s,type:o.type,depth:i});break}default:{sZ.has(String(o.type))?e.commands.push({name:s,type:String(o.type),depth:i}):(e.flags.add("unknown-command"),e.commands.push({name:s,type:String(o.type),depth:i,flag:"unknown-command"}),e.rows.push({flag:"unknown-command",severity:"warning",title:"Unknown capability. Review it manually.",detail:`${Qs(a)} (${String(o.type)})`}));break}}}}function jV(r){let{choiceWalks:e}=WV(r),t=new Set;for(let n of e)for(let i of n.usages)i.path&&t.add(i.path);return Array.from(t)}function mZ(r){let e=r.length;if(e===0)return 0;let t=0;return r.endsWith("==")?t=2:r.endsWith("=")&&(t=1),Math.max(0,Math.floor(e*3/4)-t)}function hZ(r,e){return CT[wT(r)]-CT[wT(e)]}function GV(r,e,t){let{choiceWalks:n}=WV(e),i=new Set(dn(r).map(C=>C.id)),o=new Map;for(let C of n)for(let _ of C.usages){let I=o.get(_.path)??[];I.push(_),o.set(_.path,I)}let s=new Set;for(let[C,_]of o)_.some(I=>I.asScript)&&s.add(C);let a=new Set(e.assets.map(C=>C.originalPath)),l=e.assets.map(C=>{let _=o.get(C.originalPath)??[],I=s.has(C.originalPath),q=I||tZ(C.kind,C.originalPath)||rZ(C.originalPath,C.content);return{originalPath:C.originalPath,kind:C.kind,bundled:!0,executable:I,requiresReview:q,exists:t.has(C.originalPath),sizeBytes:mZ(C.content),orphan:_.length===0,referencedBy:_}}),c=n.map(C=>{let _=i.has(C.choiceId),I=Array.from(C.flags);return _&&I.push("overwrites-existing-choice"),I.sort(hZ),{choiceId:C.choiceId,name:C.name,type:C.type,location:C.location,exists:_,registersCommand:C.registersCommand,flags:I,commands:C.commands}}),u=[];for(let[C,_]of o){if(a.has(C)||t.has(C))continue;let I=_.some(q=>q.asScript);u.push({path:C,asScript:I,breadcrumb:_[0]?.breadcrumb??C})}let d=l.filter(C=>C.orphan).map(C=>C.originalPath),f=[];for(let C of n)for(let _ of C.rows)f.push(_);for(let C of l)C.executable&&(HV(C.kind)||f.push({flag:"mislabeled-executable",severity:"critical",title:"Runs a file as code even though it is labeled a template",detail:C.originalPath,scriptPath:C.originalPath}));for(let C of l)C.requiresReview&&(C.executable||f.push({flag:"bundled-script",severity:"critical",title:"Bundles a file that will be written to your vault and can be run as code",detail:C.originalPath,scriptPath:C.originalPath}));for(let C of l){if(!C.requiresReview)continue;let _=e.assets.find(q=>q.originalPath===C.originalPath);if(!_)continue;let I=nZ(_.originalPath,_.content);!I||!oZ(I)||f.push({flag:"ai-tools",severity:"critical",title:"Lets an AI model read and write your vault",detail:C.originalPath,scriptPath:C.originalPath})}let p=c.filter(C=>C.registersCommand).length;p>0&&f.push({flag:"registers-command",severity:"warning",title:"Adds commands to the command palette",detail:`${p} choice${p===1?"":"s"}`});let m=c.filter(C=>C.exists).length;m>0&&f.push({flag:"overwrites-existing-choice",severity:"warning",title:"Replaces choices that already exist in your vault",detail:`${m} choice${m===1?"":"s"}`});let v=l.filter(C=>C.exists).length;if(v>0&&f.push({flag:"overwrites-existing-file",severity:"warning",title:"Overwrites existing files in your vault",detail:`${v} file${v===1?"":"s"}`}),u.length>0){let C=u.filter(_=>_.asScript).length;f.push({flag:"missing-reference",severity:C>0?"critical":"warning",title:C>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"}`})}f.sort((C,_)=>CT[C.severity]-CT[_.severity]);let g=l.filter(C=>C.requiresReview).map(C=>C.originalPath),y=s.size,w=n.some(C=>C.flags.has("run-on-startup")),T=f.filter(C=>C.severity==="critical").length,b=f.filter(C=>C.severity==="warning").length,E={hasCritical:T>0,hasWarning:b>0,criticalCount:T,warningCount:b,runsOnStartup:w,scriptCount:y,registersCommandCount:p,overwritesChoices:m,overwritesFiles:v,missingCount:u.length};return{quickAddVersion:e.quickAddVersion,createdAt:e.createdAt,choiceCount:e.choices.length,fileCount:e.assets.length,choices:c,files:l,capabilityRows:f,missingReferences:u,orphanAssets:d,criticalScriptPaths:g,summary:E}}var qV=1e5;function gZ(r){return typeof TextEncoder<"u"?new TextEncoder().encode(r).length:r.length}function vZ(r){if(r.length<1e3)return!1;let e=0,t=1,n=0;for(let o=0;o<r.length;o++)r[o]===`
`?(n>e&&(e=n),n=0,t++):n++;n>e&&(e=n);let i=r.length/t;return e>1e3||i>250}function ET(r,e){let t=r.assets.find(n=>n.originalPath===e);if(!t)return{found:!1,text:"",truncated:!1,sizeBytes:0,looksMinified:!1,error:"File is not bundled in this package."};try{let n=ql(t.content),i=n.length>qV,o=i?n.slice(0,qV):n;return{found:!0,text:o,truncated:i,sizeBytes:gZ(n),looksMinified:vZ(o)}}catch(n){return{found:!0,text:"",truncated:!1,sizeBytes:0,looksMinified:!1,error:n instanceof Error?n.message:String(n)}}}function YV(r){return r.summary.hasCritical}function KV(r,e){return r.criticalScriptPaths.every(t=>e.has(t))}async function QV(r,e){if(Pr(e))throw new Error(`Refusing to read a package outside the vault: "${e}".`);let t=(0,xT.normalizePath)(e.trim());if(!t)throw new Error("Package path cannot be empty.");if(!await r.vault.adapter.exists(t))throw new Error(`Package file not found: ${t}`);let i=await r.vault.adapter.read(t);return{pkg:hF(i),path:t}}function hF(r){let e;try{e=JSON.parse(r)}catch(o){throw new Error(`Package content is not valid JSON: ${o?.message??o}`)}if(!AV(e))throw new Error("Content is not a valid QuickAdd package.");if(e.schemaVersion>1)throw new Error(`Package schema version ${e.schemaVersion} is newer than this plugin supports (${1}).`);let t=yZ(e.assets);if(t!==null)throw new Error(`Package contains duplicate asset path "${t}". Each asset must have a unique path.`);let n=bZ(e.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=wZ(e.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 e}function yZ(r){let e=new Set;for(let t of r){let n=(0,xT.normalizePath)(t.originalPath??"");if(e.has(n))return t.originalPath;e.add(n)}return null}function bZ(r){let e=new Map,t=null,n=i=>{if(t!==null||!i||typeof i!="object")return;let o=i.id;if(typeof o=="string"){let s=pF(i),a=e.get(o);if(a===void 0)e.set(o,s);else if(a!==s){t=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"&&dF(i.macro?.commands,n)};for(let i of r){if(t!==null)break;n(i?.choice)}return t}function dF(r,e){if(Array.isArray(r)){for(let t of r)if(t){if(t.type==="NestedChoice")e(t.choice);else if(t.type==="Conditional"){let n=t;dF(n.thenCommands,e),dF(n.elseCommands,e)}}}}function pF(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(pF).join(",")}]`;let e=r;return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${pF(e[n])}`).join(",")}}`}function wZ(r){let e=new Map(r.map(t=>[t.choice.id,t]));for(let t of r){let n=t.parentChoiceId;if(n===null)continue;let i=e.get(n);if(!i)continue;let o=i.choice;if(!Qe(o).some(a=>a?.id===t.choice.id))return t.choice.id}return null}async function XV(r,e,t){let n=new Map(dn(e).map(s=>[s.id,s])),i=t.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 t.assets){let a=Pr(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 TT(r,e,t){let n=new Set([...t.assets.map(a=>a.originalPath),...jV(t)]),i=new Set;await Promise.all(Array.from(n,async a=>{a&&(Pr(a)||await JV(r,a)&&i.add(a))}));let o=GV(e,t,i),{summary:s}=o;return P.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 CZ(r){let t=(r??"").trim();if(!t)throw new Error("Package asset has an empty destination path.");let n=t.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,xT.normalizePath)(t);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 ZV(r){let{app:e,existingChoices:t,pkg:n}=r,i=new Map(r.choiceDecisions.map(L=>[L.choiceId,L.mode])),o=new Map(r.assetDecisions.map(L=>[L.originalPath,L])),s=new Map(n.choices.map(L=>[L.choice.id,L])),a=EZ(n),l=new Set,c=new Map,u=new Set,d=L=>{let W=Y=>(c.set(L,Y),u.delete(L),Y);if(c.has(L))return c.get(L);if(u.has(L))return!0;if(u.add(L),i.get(L)==="skip")return W(!1);let $=s.get(L);if(!$)return W(!1);let G=$.parentChoiceId;if(!G||!s.has(G)||i.get(G)==="skip")return W(!0);let H=d(G);return W(H)};for(let L of n.choices)d(L.choice.id)&&l.add(L.choice.id);let f=new Set,p=new Set,m=new Set,v=new Map,g=L=>{let W=()=>(f.add(L),p.delete(L),!0),j=()=>(p.add(L),!1);if(!l.has(L))return!1;if(f.has(L))return!0;if(p.has(L))return!1;if(m.has(L))return j();m.add(L);try{if(i.get(L)==="duplicate")return W();let U=s.get(L)?.parentChoiceId??null;return U&&(i.get(U)==="duplicate"||l.has(U)&&g(U))?W():j()}finally{m.delete(L)}};for(let L of n.choices){if(!l.has(L.choice.id))continue;let j=g(L.choice.id)?ir():L.choice.id;v.set(L.choice.id,j)}let y=Ze(t),w=[],T=[],b=[],E=new Map;for(let L of n.choices){if(!l.has(L.choice.id)){b.push(L.choice.id);continue}let W=Ze(L.choice),j=gF(W,v,l,{secretOptionNamesByPath:a,stripUnknownStringSettings:!0});E.set(L.choice.id,j)}r.aiProviders?.length&&bT(Array.from(E.values()),r.aiProviders);let C=new Set;for(let L of n.choices){let W=L.choice.id;if(!l.has(W)||C.has(W))continue;let j=E.get(W);if(!j)continue;let $=j.id,G=i.get(W)??"import",U=L.parentChoiceId;if(U&&l.has(U)?E.get(U):null){C.add(W);continue}if((G==="overwrite"||G==="import")&&eq(y,j)){T.push($),C.add(W);continue}if(U){let ie=v.get(U)??U;if(tq(y,ie,j)){w.push($),C.add(W);continue}let ce=TZ(y,L.pathHint.slice(0,-1));if(ce&&rq(ce,j)){w.push($),C.add(W);continue}P.logWarning(`QuickAdd import: could not locate parent for '${L.choice.name}'. Adding to root.`)}let Y=y.findIndex(ie=>Ne(ie)&&ie.id===$);Y!==-1?(y.splice(Y,1,j),T.push($)):(y.push(j),w.push($)),C.add(W)}let _=new Map,I=[],q=[],B=n.assets.map(L=>{let j=o.get(L.originalPath)?.destinationPath?.trim(),$=CZ(j||L.originalPath);return{asset:L,destinationPath:$}}),J=await xZ(e),re=new Map;for(let{asset:L,destinationPath:W}of B){if(o.get(L.originalPath)?.mode==="skip")continue;let j=J?W.toLowerCase():W,$=re.get(j);if($)throw new Error(`Refusing to import: assets "${$.originalPath}" and "${L.originalPath}" resolve to the same destination ("${W}"). Rename one so each imported file is unique.`);re.set(j,{originalPath:L.originalPath,destinationPath:W})}for(let{destinationPath:L}of B)await Im(e,L);for(let{asset:L,destinationPath:W}of B){let j=o.get(L.originalPath),$=await JV(e,W);if((j?.mode??($?"overwrite":"write"))==="skip"){q.push(W);continue}await mT(e,W);let U=ql(L.content);await e.vault.adapter.write(W,U),I.push(W),_.set(L.originalPath,W)}for(let L of E.values())vF(L,_);return{updatedChoices:y,addedChoiceIds:w,overwrittenChoiceIds:T,skippedChoiceIds:b,writtenAssets:I,skippedAssets:q}}function EZ(r){let e=new Map;for(let t of r.assets)if(t.kind==="user-script")try{let n=Jf(ql(t.content),t.originalPath);e.set(t.originalPath,n.foundSecretOptions&&n.names.size===0?null:n.names)}catch(n){P.logWarning(`QuickAdd import could not inspect user-script settings '${t.originalPath}': ${n?.message??n}`)}return e}async function JV(r,e){try{return await r.vault.adapter.exists(e)}catch{return!1}}async function xZ(r){let e=r.vault.configDir;if(!e)return!1;let t=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();if(t===e)return!1;try{return await r.vault.adapter.exists(t)}catch{return!1}}function gF(r,e,t,n){let i=r.id,o=e.get(i)??i;r.id=o;let s=o!==i;if(r.type==="Macro"){let a=r;s&&ou(a.macro)&&(a.macro.id=ir()),fF(hn(a.macro),e,t,s,n)}if(r.type==="Multi"){let a=r;Array.isArray(a.choices)&&(a.choices=a.choices.filter(l=>Ne(l)&&t.has(l.id)).map(l=>gF(l,e,t,n)))}return r}function fF(r,e,t,n,i){for(let o of ar(r))if(mn(o))switch(bI(o,i),n&&(o.id=ir()),o.type){case"Choice":{let s=o,a=e.get(s.choiceId);a&&(s.choiceId=a);break}case"Conditional":{let s=o;fF(s.thenCommands,e,t,n,i),fF(s.elseCommands,e,t,n,i);break}case"NestedChoice":{let s=o;s.choice&&t.has(s.choice.id)&&(s.choice=gF(s.choice,e,t,i));break}default:break}}function eq(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(Ne(n)){if(n.id===e.id)return r.splice(t,1,e),!0;if(eq(Qe(n),e))return!0}}return!1}function tq(r,e,t){for(let n of r)if(Ne(n)){if(n.id===e&&n.type==="Multi")return rq(n,t);if(tq(Qe(n),e,t))return!0}return!1}function rq(r,e){if(!Array.isArray(r.choices)){if(Jo(r))return!1;r.choices=[]}let t=r.choices.findIndex(n=>Ne(n)&&n.id===e.id);return t!==-1?r.choices.splice(t,1,e):r.choices.push(e),!0}function TZ(r,e){if(e.length===0)return null;let t=r,n=null;for(let i of e){let o=t.find(s=>Ne(s)&&s.type==="Multi"&&s.name===i);if(!o)return null;n=o,t=Qe(o)}return n}function vF(r,e){switch(r.type){case"Macro":{mF(hn(r.macro),e);break}case"Template":{let t=r,n=e.get(t.templatePath);n&&(t.templatePath=n);break}case"Capture":{let t=r,n=t.createFileIfItDoesntExist?.template;if(n){let i=e.get(n);i&&(t.createFileIfItDoesntExist={...t.createFileIfItDoesntExist,template:i})}break}case"Multi":{r.choices?.forEach(n=>vF(n,e));break}default:break}}function mF(r,e){for(let t of ar(r))if(mn(t))switch(t.type){case"UserScript":{let n=t,i=e.get(n.path);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=t;if(n.condition.mode==="script"&&n.condition.scriptPath){let i=e.get(n.condition.scriptPath);i&&(n.condition={...n.condition,scriptPath:i})}mF(n.thenCommands,e),mF(n.elseCommands,e);break}case"NestedChoice":{let n=t;n.choice&&vF(n.choice,e);break}default:break}}var ST=require("obsidian");function By(r,e){return e&&(0,ST.setTooltip)(r,e),{update(t){(0,ST.setTooltip)(r,t??"")},destroy(){(0,ST.setTooltip)(r,"")}}}var SZ=V("<span> </span>"),_Z={hash:"svelte-5jkd35",code:`.qa-import-tag.svelte-5jkd35 {display:inline-flex;align-items:center;padding:0.05rem 0.4rem;border-radius:var(--radius-s, 4px);font-size:0.7rem;font-weight:600;letter-spacing:0.02em;text-transform:uppercase;line-height:1.45;white-space:nowrap;cursor:help;}
/* Critical: darkened red so white text clears WCAG AA (~5:1) at this size,
where Obsidian's stock --color-red (#e93147) lands at ~3.5:1. */.qa-import-tag.critical.svelte-5jkd35 {background:var(--qa-sev-critical-pill);color:#fff;}
/* Warning: amber is medium-luminance in both themes, so near-black text
(~8:1) beats white-on-amber (~2.9:1). Fallback #ff8c00 matches styles.css
and clears AA (~5.9:1) with #1a1a1a. */.qa-import-tag.warning.svelte-5jkd35 {background:var(--color-orange, #ff8c00);color:#1a1a1a;}.qa-import-tag.info.svelte-5jkd35 {background:var(--background-modifier-border);color:var(--text-normal);}`};function Vy(r,e){fe(e,!0),Ke(r,_Z);let t=M(()=>wT(e.flag)),n=M(()=>UV(e.flag)),i=M(()=>zV(e.flag));var o=SZ();let s;var a=F(o,!0);D(o),dr(o,(l,c)=>By?.(l,c),()=>h(i)),ae(()=>{s=at(o,1,"qa-import-tag svelte-5jkd35",null,s,{critical:h(t)==="critical",warning:h(t)==="warning",info:h(t)==="info"}),ue(a,h(n))}),O(r,o),me()}var kZ=V('<span class="qa-import-banner-detail svelte-tb9yz"> </span>'),AZ=V('<li><span class="qa-import-banner-tag svelte-tb9yz"><!></span><span class="qa-import-banner-title svelte-tb9yz"> </span> <!></li>'),DZ=V('<p class="qa-import-banner-note svelte-tb9yz">Takes effect after you reload the plugin or restart Obsidian.</p>'),IZ=V('<section aria-label="What this package can do"><div class="qa-import-banner-head svelte-tb9yz"><span class="qa-import-banner-icon svelte-tb9yz"><!></span> <h3 class="svelte-tb9yz">What this package can do</h3></div> <ul class="qa-import-banner-rows svelte-tb9yz"></ul> <!></section>'),FZ={hash:"svelte-tb9yz",code:`.qa-import-banner.svelte-tb9yz {background:var(--background-secondary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);padding:0.85rem;display:flex;flex-direction:column;gap:0.5rem;}
/* Critical packages get a red-tinted hairline + red icon, not a blanket-red
fill: severity stays ranked and all text keeps its contrast on the neutral
surface. (A solid colored side-stripe would be the banned pattern.) */.qa-import-banner.critical.svelte-tb9yz {border-color:var(--qa-sev-critical-border);}.qa-import-banner-head.svelte-tb9yz {display:flex;align-items:center;gap:0.5rem;}.qa-import-banner-icon.svelte-tb9yz {display:inline-flex;color:var(--text-warning, var(--text-muted));}.qa-import-banner.critical.svelte-tb9yz .qa-import-banner-icon:where(.svelte-tb9yz) {color:var(--text-error);}.qa-import-banner-head.svelte-tb9yz h3:where(.svelte-tb9yz) {margin:0;font-size:1rem;}.qa-import-banner-rows.svelte-tb9yz {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0.25rem;}
/* The pill is an inline lead-in to the sentence (not a fixed left column),
so long titles wrap full-width under it instead of leaving a dead column
of whitespace beside a one-line pill. */.qa-import-banner-rows.svelte-tb9yz li:where(.svelte-tb9yz) {display:block;padding:0.4rem 0.5rem;border-radius:var(--radius-s, 4px);}.qa-import-banner-tag.svelte-tb9yz {display:inline-block;vertical-align:middle;margin:0 0.4rem 0.15rem 0;}
/* Faint per-row severity wash so critical rows read hottest while warnings
recede, without saturating the whole banner. Composited over the banner
surface (not transparent) so the tint is a solid, predictable colour. */.qa-import-banner-rows.svelte-tb9yz li.sev-critical:where(.svelte-tb9yz) {background:var(--qa-sev-critical-wash);}.qa-import-banner-rows.svelte-tb9yz li.sev-warning:where(.svelte-tb9yz) {background:var(--qa-sev-warning-wash);}.qa-import-banner-rows.svelte-tb9yz li.sev-info:where(.svelte-tb9yz) {background:var(--qa-sev-info-wash);}.qa-import-banner-title.svelte-tb9yz {line-height:1.4;}.qa-import-banner-detail.svelte-tb9yz {display:block;margin-top:0.15rem;font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);overflow-wrap:anywhere;}.qa-import-banner-note.svelte-tb9yz {margin:0;font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);}`};function yF(r,e){fe(e,!0),Ke(r,FZ);let t=M(()=>e.preview.summary.runsOnStartup||e.preview.summary.registersCommandCount>0);var n=IZ();let i;var o=F(n),s=F(o),a=F(s);bt(a,{iconId:"alert-triangle",size:17}),D(s),tn(2),D(o);var l=S(o,2);jt(l,21,()=>e.preview.capabilityRows,d=>d.flag+d.detail,(d,f)=>{var p=AZ();let m;var v=F(p),g=F(v);Vy(g,{get flag(){return h(f).flag}}),D(v);var y=S(v),w=F(y,!0);D(y);var T=S(y,2);{var b=E=>{var C=kZ(),_=F(C,!0);D(C),ae(()=>ue(_,h(f).detail)),O(E,C)};X(T,E=>{h(f).detail&&E(b)})}D(p),ae(()=>{m=at(p,1,"svelte-tb9yz",null,m,{"sev-critical":h(f).severity==="critical","sev-warning":h(f).severity==="warning","sev-info":h(f).severity==="info"}),ue(w,h(f).title)}),O(d,p)}),D(l);var c=S(l,2);{var u=d=>{var f=DZ();O(d,f)};X(c,d=>{h(t)&&d(u)})}D(n),ae(()=>i=at(n,1,"qa-import-banner svelte-tb9yz",null,i,{critical:e.preview.summary.hasCritical})),O(r,n),me()}var PZ=V('<span class="qa-import-file-exec svelte-lmqem5">Executable</span>'),$Z=V('<span class="qa-import-file-reviewed svelte-lmqem5"><!> Reviewed</span>'),MZ=V('<span class="qa-import-file-orphan svelte-lmqem5">Unused</span>'),OZ=V("<option>Overwrite</option>"),RZ=V(`<p class="qa-import-file-skip-warn svelte-lmqem5" 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.</p>`),LZ=V('<p class="qa-import-file-error svelte-lmqem5"> </p>'),NZ=V(`<p class="qa-import-file-warn svelte-lmqem5">Minified: cannot be visually reviewed. Import
only if you trust the source.</p>`),BZ=V('<p class="qa-import-file-warn svelte-lmqem5"> </p>'),VZ=V('<!> <pre class="qa-import-file-code svelte-lmqem5" tabindex="0" role="region"> </pre> <!>',1),qZ=V('<div class="qa-import-file-preview svelte-lmqem5"><!></div>'),UZ=V('<div><div class="qa-import-file-head svelte-lmqem5"><!> <span> </span> <span class="qa-import-file-arrow svelte-lmqem5" aria-hidden="true">\u2192</span> <span class="qa-import-file-dest svelte-lmqem5"> </span></div> <div class="qa-import-file-badges svelte-lmqem5"><!> <!> <!> <span class="qa-import-file-size svelte-lmqem5"> </span></div> <div class="qa-import-file-fields svelte-lmqem5"><label class="qa-import-file-field svelte-lmqem5"><span class="qa-import-file-field-name svelte-lmqem5">Destination</span> <input type="text" placeholder="vault/path/to/file" class="svelte-lmqem5"/></label> <label class="qa-import-file-field svelte-lmqem5"><span class="qa-import-file-field-name svelte-lmqem5">Action</span> <select class="dropdown svelte-lmqem5"><option>Write</option><!><option>Skip</option></select></label></div> <!> <button type="button" class="qa-import-file-toggle svelte-lmqem5"><span><!></span> <span> </span></button> <div><div class="qa-import-file-preview-inner svelte-lmqem5"><!></div></div></div>'),zZ={hash:"svelte-lmqem5",code:`.qa-import-file.svelte-lmqem5 {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);padding:0.6rem 0.75rem;display:flex;flex-direction:column;gap:0.5rem;background:var(--background-secondary);}.qa-import-file.overwrite.svelte-lmqem5 {border-color:var(--qa-sev-critical-border);}.qa-import-file-head.svelte-lmqem5 {display:flex;align-items:center;gap:0.4rem;flex-wrap:wrap;}.qa-import-file-status.svelte-lmqem5 {font-size:0.78rem;font-weight:700;letter-spacing:0.01em;color:var(--text-muted);}.qa-import-file-status.overwrite.svelte-lmqem5 {color:var(--text-error);}.qa-import-file-arrow.svelte-lmqem5 {color:var(--text-muted);}.qa-import-file-dest.svelte-lmqem5 {font-family:var(--font-monospace);font-size:0.85rem;overflow-wrap:anywhere;}.qa-import-file-badges.svelte-lmqem5 {display:flex;flex-wrap:wrap;gap:0.35rem;align-items:center;}.qa-import-file-orphan.svelte-lmqem5 {display:inline-flex;padding:0.05rem 0.4rem;border-radius:var(--radius-s, 4px);font-size:0.7rem;background:var(--background-modifier-hover);
/* --text-normal (not --text-muted) so the badge clears AA on the hover
surface in dark themes too. */color:var(--text-normal);cursor:help;}.qa-import-file-exec.svelte-lmqem5 {display:inline-flex;padding:0.05rem 0.4rem;border-radius:var(--radius-s, 4px);font-size:0.7rem;font-weight:700;letter-spacing:0.02em;text-transform:uppercase;background:var(--qa-sev-critical-pill);color:#fff;cursor:help;}.qa-import-file-reviewed.svelte-lmqem5 {display:inline-flex;align-items:center;gap:0.15rem;font-size:0.72rem;color:var(--text-success, var(--color-green, #0aa344));}.qa-import-file-size.svelte-lmqem5 {font-size:0.72rem;color:var(--text-faint);margin-left:auto;}
/* Obsidian Setting-row geometry: field name on the left at --text-normal,
control docked right at its native height \u2014 not a stacked label-above
form field (which read as non-native). */.qa-import-file-fields.svelte-lmqem5 {display:flex;flex-direction:column;gap:0.4rem;}.qa-import-file-field.svelte-lmqem5 {display:flex;align-items:center;gap:1rem;}.qa-import-file-field-name.svelte-lmqem5 {flex:1 1 auto;min-width:0;color:var(--text-normal);}.qa-import-file-field.svelte-lmqem5 input:where(.svelte-lmqem5) {flex:0 1 300px;min-width:0;}.qa-import-file-field.svelte-lmqem5 select:where(.svelte-lmqem5) {flex:0 0 auto;}
/* The native Obsidian input/dropdown focus box-shadow handles focus; no
custom outline (which would read as non-native). */.qa-import-file-field.svelte-lmqem5 input:where(.svelte-lmqem5):disabled {opacity:0.5;cursor:not-allowed;}.qa-import-file-toggle.svelte-lmqem5 {display:inline-flex;align-items:center;gap:0.3rem;align-self:flex-start;background:transparent;border:none;box-shadow:none;padding:0.1rem 0.2rem;margin-left:-0.2rem;cursor:pointer;color:var(--text-accent);font-size:0.85rem;border-radius:var(--radius-s, 4px);}.qa-import-file-toggle.svelte-lmqem5:hover {color:var(--interactive-accent-hover, var(--text-accent));text-decoration:underline;}.qa-import-file-toggle.svelte-lmqem5:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:1px;}.qa-import-file-chevron.svelte-lmqem5 {display:inline-flex;transition:transform 180ms ease;}.qa-import-file-chevron.open.svelte-lmqem5 {transform:rotate(90deg);}.qa-import-file-preview-wrap.svelte-lmqem5 {display:grid;grid-template-rows:0fr;transition:grid-template-rows 200ms ease;}.qa-import-file-preview-wrap.open.svelte-lmqem5 {grid-template-rows:1fr;}.qa-import-file-preview-inner.svelte-lmqem5 {overflow:hidden;min-height:0;}.qa-import-file-preview.svelte-lmqem5 {display:flex;flex-direction:column;gap:0.4rem;padding-top:0.2rem;}.qa-import-file-warn.svelte-lmqem5 {margin:0;color:var(--text-warning, var(--text-muted));font-size:var(--font-ui-smaller, 0.85rem);}.qa-import-file-skip-warn.svelte-lmqem5 {margin:0;padding:0.4rem 0.5rem;border-radius:var(--radius-s, 4px);background:var(--qa-sev-warning-wash);color:var(--text-normal);font-size:var(--font-ui-smaller, 0.85rem);line-height:1.4;}.qa-import-file-error.svelte-lmqem5 {margin:0;color:var(--text-error);font-size:var(--font-ui-smaller, 0.85rem);}.qa-import-file-code.svelte-lmqem5 {margin:0;max-height:240px;overflow:auto;padding:0.5rem 0.6rem;border-radius:var(--radius-s, 4px);background:var(--background-modifier-form-field);border:1px solid var(--background-modifier-border);font-family:var(--font-monospace);font-size:0.8rem;line-height:1.5;white-space:pre;tab-size:4;}.qa-import-file-code.svelte-lmqem5:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:1px;}
@media (max-width: 600px) {
/* Stack control under its name and let it use the full width on narrow
screens, where a right-docked control would be cramped. */.qa-import-file-field.svelte-lmqem5 {flex-wrap:wrap;gap:0.25rem;}.qa-import-file-field.svelte-lmqem5 input:where(.svelte-lmqem5),
.qa-import-file-field.svelte-lmqem5 select:where(.svelte-lmqem5) {flex:1 1 100%;}.qa-import-file-size.svelte-lmqem5 {margin-left:0;}
}.is-mobile .qa-import-file-toggle.svelte-lmqem5 {min-height:36px;padding:0.4rem 0.3rem;}
@media (prefers-reduced-motion: reduce) {.qa-import-file-chevron.svelte-lmqem5,
.qa-import-file-preview-wrap.svelte-lmqem5 {transition:none;}
}`};function _T(r,e){fe(e,!0),Ke(r,zZ);let t=le(e,"reviewed",3,!1),n=Ee(!1),i=M(()=>h(n)?ET(e.pkg,e.file.originalPath):null),o=M(()=>`qa-file-preview-${e.file.originalPath.replace(/[^a-zA-Z0-9_-]/g,"-")}`);function s(ge){return ge<1024?`${ge} B`:ge<1024*1024?`${(ge/1024).toFixed(1)} KB`:`${(ge/(1024*1024)).toFixed(1)} MB`}function a(){Q(n,!h(n)),h(n)&&e.file.requiresReview&&e.onReviewed(e.file.originalPath)}function l(ge){e.onPathInput(ge.currentTarget.value)}function c(ge){e.onModeChange(ge.currentTarget.value)}var u=UZ();let d;var f=F(u),p=F(f);{let ge=M(()=>e.destinationExists?"file-warning":"file-plus");bt(p,{get iconId(){return h(ge)},size:16})}var m=S(p,2);let v;var g=F(m,!0);D(m);var y=S(m,4),w=F(y,!0);D(y),D(f);var T=S(f,2),b=F(T);{var E=ge=>{var xe=PZ();dr(xe,(tt,kt)=>By?.(tt,kt),()=>"Runs as code when its choice runs. It can read, change, or delete files in your vault and access the network."),O(ge,xe)};X(b,ge=>{e.file.executable&&ge(E)})}var C=S(b,2);{var _=ge=>{var xe=$Z(),tt=F(xe);bt(tt,{iconId:"check",size:12}),tn(),D(xe),O(ge,xe)};X(C,ge=>{t()&&e.mode!=="skip"&&e.file.requiresReview&&ge(_)})}var I=S(C,2);{var q=ge=>{var xe=MZ();dr(xe,(tt,kt)=>By?.(tt,kt),()=>"Bundled in this package but not referenced by any choice."),O(ge,xe)};X(I,ge=>{e.file.orphan&&ge(q)})}var B=S(I,2),J=F(B,!0);D(B),D(T);var re=S(T,2),L=F(re),W=S(F(L),2);Bt(W),D(L);var j=S(L,2),$=S(F(j),2),G=F($);G.value=G.__value="write";var U=S(G);{var H=ge=>{var xe=OZ();xe.value=xe.__value="overwrite",O(ge,xe)};X(U,ge=>{e.destinationExists&&ge(H)})}var Y=S(U);Y.value=Y.__value="skip",D($);var ie;Gu($),D(j),D(re);var oe=S(re,2);{var ce=ge=>{var xe=RZ();O(ge,xe)};X(oe,ge=>{e.file.requiresReview&&e.mode==="skip"&&ge(ce)})}var he=S(oe,2),Ie=F(he);let we;var Ge=F(Ie);bt(Ge,{iconId:"chevron-right",size:14}),D(Ie);var Pe=S(Ie,2),Ve=F(Pe,!0);D(Pe),D(he);var qe=S(he,2);let et;var _t=F(qe),ye=F(_t);{var $e=ge=>{var xe=qZ(),tt=F(xe);{var kt=gt=>{var Lt=LZ(),Lr=F(Lt);D(Lt),ae(()=>ue(Lr,`Preview unavailable: ${h(i).error??""}`)),O(gt,Lt)},Pt=gt=>{var Lt=VZ(),Lr=Te(Lt);{var lt=vn=>{var te=NZ();O(vn,te)};X(Lr,vn=>{h(i).looksMinified&&vn(lt)})}var rt=S(Lr,2),cr=F(rt,!0);D(rt);var ti=S(rt,2);{var Fo=vn=>{var te=BZ(),Ae=F(te);D(te),ae(()=>ue(Ae,`Preview truncated. The full ${e.file.executable?"script will run":"file will be imported"}.`)),O(vn,te)};X(ti,vn=>{h(i).truncated&&vn(Fo)})}ae(()=>{Ce(rt,"aria-label",`Contents of ${e.file.originalPath??""}`),ue(cr,h(i).text)}),O(gt,Lt)};X(tt,gt=>{h(i).error?gt(kt):gt(Pt,-1)})}D(xe),O(ge,xe)};X(ye,ge=>{h(i)&&ge($e)})}D(_t),D(qe),D(u),ae(ge=>{d=at(u,1,"qa-import-file svelte-lmqem5",null,d,{overwrite:e.destinationExists}),v=at(m,1,"qa-import-file-status svelte-lmqem5",null,v,{overwrite:e.destinationExists}),ue(g,e.destinationExists?"Will overwrite":"New file"),ue(w,e.destinationPath),ue(J,ge),Fi(W,e.destinationPath),W.disabled=e.mode==="skip",ie!==(ie=e.mode)&&($.value=($.__value=e.mode)??"",hc($,e.mode)),Ce(he,"aria-expanded",h(n)),Ce(he,"aria-controls",h(o)),we=at(Ie,1,"qa-import-file-chevron svelte-lmqem5",null,we,{open:h(n)}),ue(Ve,h(n)?"Hide contents":"View contents"),et=at(qe,1,"qa-import-file-preview-wrap svelte-lmqem5",null,et,{open:h(n)}),Ce(qe,"id",h(o))},[()=>s(e.file.sizeBytes)]),_e("input",W,l),_e("change",$,c),_e("click",he,a),O(r,u),me()}nt(["input","change","click"]);var HZ=V('<span class="macroCommandType svelte-1qj0pve"> </span>'),WZ=V("<code> </code>"),jZ=V('<span class="macroCommandSummary svelte-1qj0pve"> </span>'),GZ=V('<li class="svelte-1qj0pve"><span class="macroCommandName svelte-1qj0pve"> </span> <!> <!></li>'),YZ=V('<ul class="macroCommands svelte-1qj0pve"></ul>'),KZ={hash:"svelte-1qj0pve",code:".macroCommands.svelte-1qj0pve {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0.25rem;}.macroCommands.svelte-1qj0pve li:where(.svelte-1qj0pve) {display:flex;flex-wrap:wrap;align-items:center;gap:0.4rem;font-size:var(--font-ui-smaller, 0.85rem);}.macroCommandName.svelte-1qj0pve {font-weight:500;}.macroCommandType.svelte-1qj0pve {color:var(--text-muted);font-size:0.72rem;}.macroCommandSummary.svelte-1qj0pve {color:var(--text-muted);}"};function bF(r,e){Ke(r,KZ);let t={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 t[o]??o}var i=YZ();jt(i,21,()=>e.commands,ig,(o,s)=>{var a=GZ(),l=F(a),c=F(l,!0);D(l);var u=S(l,2);{var d=g=>{Vy(g,{get flag(){return h(s).flag}})},f=g=>{var y=HZ(),w=F(y,!0);D(y),ae(T=>ue(w,T),[()=>n(h(s).type)]),O(g,y)};X(u,g=>{h(s).flag?g(d):g(f,-1)})}var p=S(u,2);{var m=g=>{var y=WZ(),w=F(y,!0);D(y),ae(()=>ue(w,h(s).scriptPath)),O(g,y)},v=g=>{var y=jZ(),w=F(y,!0);D(y),ae(()=>ue(w,h(s).summary)),O(g,y)};X(p,g=>{h(s).scriptPath?g(m):h(s).summary&&g(v,1)})}D(a),ae(()=>{Pp(a,`padding-left:${h(s).depth*1}rem`),ue(c,h(s).name)}),O(o,a)}),D(i),O(r,i)}var wF=require("obsidian");Sa();function nq(r,e){return r==="skip"?r:e&&r==="write"?"overwrite":!e&&r==="overwrite"?"write":r}function CF(r,e){return!e&&r==="overwrite"?"import":r}function iq(r,e,t){let n=e(r),i=r.exists||t(n);return{mode:i?"overwrite":"write",destinationPath:n,destinationExists:i}}function oq(r,e){let t=e(r);return{mode:t?"overwrite":"write",destinationPath:r,destinationExists:t}}function sq(r,e,t){let n=new Map;for(let i of r)n.set(i.originalPath,iq(i,e,t));return n}function aq(r,e,t,n){return r.get(e.originalPath)??iq(e,t,n)}function lq(r){let e=new Map;for(let t of r)e.set(t.choiceId,t.exists?"overwrite":"import");return e}function cq(r,e,t){let n=new Map(r);return n.set(e,t),n}function uq(r,e,t,n){let i=r.get(e)??oq(e,n),o=new Map(r);return o.set(e,{...i,mode:t}),o}function dq(r,e,t,n){let i=r.get(e)??oq(e,n),o=t.trim(),s=o||e,a=o||t,l=n(s),c=new Map(r);return c.set(e,{...i,mode:nq(i.mode,l),destinationPath:a,destinationExists:l}),{decisions:c,effectivePath:s}}function pq(r,e,t){let n=r.get(e);if(!n||n.destinationExists===t)return r;let i=new Map(r);return i.set(e,{...n,destinationExists:t,mode:nq(n.mode,t)}),i}function fq(r,e){return r.map(t=>({choiceId:t.choiceId,mode:CF(e.get(t.choiceId)??"import",t.exists)}))}function mq(r,e,t){return r.map(n=>{let i=e.get(n.originalPath),o=i?.destinationPath?.trim()||n.originalPath,s=i?.destinationExists??(n.exists||t(o)),a=i?.mode??(s?"overwrite":"write");return{originalPath:n.originalPath,destinationPath:o,mode:a}})}var kT=class{constructor(e){this.app=e;this.tokens=new Map}optimistic(e){let t=e.trim();return!t||Pr(t)?!1:!!this.app.vault.getAbstractFileByPath((0,wF.normalizePath)(t))}async resolve(e){let t=e.trim();if(!t||Pr(t))return!1;try{return await this.app.vault.adapter.exists((0,wF.normalizePath)(t))}catch{return!1}}schedule(e,t,n){let i=(this.tokens.get(e)??0)+1;this.tokens.set(e,i),this.resolve(t).then(o=>{this.tokens.get(e)===i&&n(o)})}};var QZ=V('<div class="errorMessage svelte-1nd6fqb"> </div>'),XZ=V('<div class="info svelte-1nd6fqb">Analyzing package\u2026</div>'),ZZ=V('<p class="svelte-1nd6fqb">No choices found in this package.</p>'),JZ=V('<div class="choiceExists svelte-1nd6fqb">already in vault</div>'),eJ=V('<button type="button" class="macroToggle svelte-1nd6fqb"> </button>'),tJ=V('<option class="svelte-1nd6fqb">Overwrite</option>'),rJ=V('<tr class="macroRow svelte-1nd6fqb"><td colspan="3" class="svelte-1nd6fqb"><!></td></tr>'),nJ=V('<tr class="svelte-1nd6fqb"><td data-label="Name" class="svelte-1nd6fqb"><div class="choiceName svelte-1nd6fqb"> </div> <!> <!></td><td data-label="Location" class="svelte-1nd6fqb"> </td><td data-label="Action" class="svelte-1nd6fqb"><select class="dropdown svelte-1nd6fqb"><option class="svelte-1nd6fqb">Import</option><!><option class="svelte-1nd6fqb">Duplicate</option><option class="svelte-1nd6fqb">Skip</option></select></td></tr> <!>',1),iJ=V('<table class="svelte-1nd6fqb"><colgroup class="svelte-1nd6fqb"><col class="colName svelte-1nd6fqb"/><col class="colLocation svelte-1nd6fqb"/><col class="colAction svelte-1nd6fqb"/></colgroup><thead class="svelte-1nd6fqb"><tr class="svelte-1nd6fqb"><th class="svelte-1nd6fqb">Name</th><th class="svelte-1nd6fqb">Location</th><th class="svelte-1nd6fqb">Action</th></tr></thead><tbody class="svelte-1nd6fqb"></tbody></table>'),oJ=V('<p class="svelte-1nd6fqb">No files bundled with this package.</p>'),sJ=V('<h4 class="filesGroupHeading svelte-1nd6fqb"> </h4> <div class="fileRows svelte-1nd6fqb"></div>',1),aJ=V('<h4 class="filesGroupHeading overwrite svelte-1nd6fqb"> </h4> <div class="fileRows svelte-1nd6fqb"></div>',1),lJ=V("<!> <!>",1),cJ=V('<li><code class="svelte-1nd6fqb"> </code> <span class="warnLoc svelte-1nd6fqb"> </span></li>'),uJ=V('<div class="warnItem svelte-1nd6fqb"><h4 class="svelte-1nd6fqb">Missing files</h4> <ul class="svelte-1nd6fqb"></ul></div>'),dJ=V(`<li class="svelte-1nd6fqb"><code class="svelte-1nd6fqb"> </code>: bundled but not
used by any choice</li>`),pJ=V('<div class="warnItem svelte-1nd6fqb"><h4 class="svelte-1nd6fqb">Unreferenced files</h4> <ul class="svelte-1nd6fqb"></ul></div>'),fJ=V('<section class="warningsBand svelte-1nd6fqb"><!> <!></section>'),mJ=V('<section class="filesSection svelte-1nd6fqb"><h3 class="svelte-1nd6fqb">Files</h3> <!></section> <!>',1),hJ=V('<section class="summary svelte-1nd6fqb"><!> <span class="svelte-1nd6fqb"> </span></section>'),gJ=V('<section class="packageMeta svelte-1nd6fqb"><span class="svelte-1nd6fqb"><span class="metaLabel svelte-1nd6fqb">Version</span> </span> <span class="metaSep svelte-1nd6fqb" aria-hidden="true">\xB7</span> <span class="svelte-1nd6fqb"><span class="metaLabel svelte-1nd6fqb">Created</span> </span> <span class="metaSep svelte-1nd6fqb" aria-hidden="true">\xB7</span> <span class="svelte-1nd6fqb"> </span> <span class="metaSep svelte-1nd6fqb" aria-hidden="true">\xB7</span> <span class="svelte-1nd6fqb"> </span></section> <!> <section class="choicesSection svelte-1nd6fqb"><h3 class="svelte-1nd6fqb">Choices</h3> <!></section> <!> <!>',1),vJ=V('<p id="qa-import-ack-hint" class="ackGate-hint svelte-1nd6fqb"> </p>'),yJ=V('<section><label class="ackGate-label svelte-1nd6fqb"><input id="qa-import-ack-checkbox" type="checkbox" class="svelte-1nd6fqb"/> <span class="svelte-1nd6fqb"> </span></label> <!></section>'),bJ=V('<div class="importPackageModal svelte-1nd6fqb"><header class="svelte-1nd6fqb"><h2 class="svelte-1nd6fqb">Import QuickAdd package</h2> <p class="svelte-1nd6fqb">Review what this package adds and runs before importing.</p></header> <section class="pasteSection svelte-1nd6fqb"><label class="svelte-1nd6fqb"><span class="svelte-1nd6fqb">Paste package JSON</span> <textarea placeholder="Paste the contents of a .quickadd.json package here" rows="8" class="svelte-1nd6fqb"></textarea></label> <!></section> <!> <!> <section class="footer svelte-1nd6fqb"><button type="button" class="secondary svelte-1nd6fqb">Cancel</button> <button type="button" class="primary svelte-1nd6fqb"><!></button></section></div>'),wJ={hash:"svelte-1nd6fqb",code:`.importPackageModal.svelte-1nd6fqb {display:flex;flex-direction:column;gap:1rem;width:min(720px, 100%);max-height:80vh;overflow-y:auto;
/* overflow-x:hidden (paired with overflow-y:auto) clips child focus rings
at the flush left/right edges; the inline padding gives the ring room. */overflow-x:hidden;box-sizing:border-box;padding:2px 4px;}.importPackageModal.svelte-1nd6fqb :where(.svelte-1nd6fqb) {box-sizing:border-box;}.importPackageModal.svelte-1nd6fqb > section:where(.svelte-1nd6fqb) {max-width:100%;}.pasteSection.svelte-1nd6fqb label:where(.svelte-1nd6fqb) {display:flex;flex-direction:column;gap:0.5rem;}.pasteSection.svelte-1nd6fqb textarea:where(.svelte-1nd6fqb) {width:100%;font-family:var(--font-monospace);resize:vertical;}.errorMessage.svelte-1nd6fqb {color:var(--text-error);}.info.svelte-1nd6fqb {color:var(--text-muted);}
/* A single compact line that sizes to content and wraps naturally, instead
of a 4-equal-column grid where the date wraps to 3 lines and the rest
leave dead space. */.packageMeta.svelte-1nd6fqb {display:flex;flex-wrap:wrap;align-items:baseline;gap:0.3rem 0.6rem;padding:0.55rem 0.75rem;border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);width:100%;font-size:var(--font-ui-small, 0.9rem);overflow-wrap:anywhere;}.metaLabel.svelte-1nd6fqb {color:var(--text-muted);}.metaSep.svelte-1nd6fqb {color:var(--text-faint);}.choicesSection.svelte-1nd6fqb,
.filesSection.svelte-1nd6fqb {display:flex;flex-direction:column;gap:0.75rem;}.filesGroupHeading.svelte-1nd6fqb {margin:0;font-size:var(--font-ui-small, 0.9rem);font-weight:600;color:var(--text-muted);}.filesGroupHeading.overwrite.svelte-1nd6fqb {color:var(--text-error);}.fileRows.svelte-1nd6fqb {display:flex;flex-direction:column;gap:0.5rem;}.choiceName.svelte-1nd6fqb {font-weight:500;}
/* A plain inline text link, not a chrome button: neutralise Obsidian's
default button background/shadow on every state (!important to win over
the global button:hover / :focus rules that paint the grey box). */.macroToggle.svelte-1nd6fqb {display:inline-block;margin-top:0.35rem;padding:0;background:transparent !important;border:none;box-shadow:none !important;color:var(--text-accent);cursor:pointer;font-size:var(--font-ui-smaller, 0.8rem);border-radius:var(--radius-s, 4px);}.macroToggle.svelte-1nd6fqb:hover {color:var(--interactive-accent-hover, var(--text-accent));text-decoration:underline;}.macroToggle.svelte-1nd6fqb:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:2px;}.macroRow.svelte-1nd6fqb td:where(.svelte-1nd6fqb) {background:var(--background-primary-alt, var(--background-secondary));}.warningsBand.svelte-1nd6fqb {display:flex;flex-direction:column;border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);padding:0.6rem 0.75rem;gap:0.5rem;}.warnItem.svelte-1nd6fqb h4:where(.svelte-1nd6fqb) {margin:0;font-size:var(--font-ui-small, 0.9rem);}.warnItem.svelte-1nd6fqb ul:where(.svelte-1nd6fqb) {margin:0.25rem 0 0;padding-left:1rem;}.warnItem.svelte-1nd6fqb li:where(.svelte-1nd6fqb) {overflow-wrap:anywhere;}
/* A missing SCRIPT reference is an execution-hijack risk, not a broken
link: it runs from whatever exists at that path. Mark it as critical. */.warnItem.svelte-1nd6fqb li.script:where(.svelte-1nd6fqb) {padding:0.25rem 0.4rem;border-radius:var(--radius-s, 4px);background:var(--qa-sev-critical-wash);}.warnLoc.svelte-1nd6fqb {color:var(--text-muted);font-size:var(--font-ui-smaller, 0.8rem);}.choicesSection.svelte-1nd6fqb table:where(.svelte-1nd6fqb) {width:100%;border-collapse:collapse;table-layout:fixed;}.choicesSection.svelte-1nd6fqb col.colName:where(.svelte-1nd6fqb) {width:52%;}.choicesSection.svelte-1nd6fqb col.colLocation:where(.svelte-1nd6fqb) {width:26%;}.choicesSection.svelte-1nd6fqb col.colAction:where(.svelte-1nd6fqb) {width:22%;}.choicesSection.svelte-1nd6fqb th:where(.svelte-1nd6fqb),
.choicesSection.svelte-1nd6fqb td:where(.svelte-1nd6fqb) {padding:0.5rem;border-bottom:1px solid var(--background-modifier-border);text-align:left;word-break:break-word;overflow-wrap:anywhere;white-space:normal;vertical-align:top;}.choicesSection.svelte-1nd6fqb th:where(.svelte-1nd6fqb) {font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);font-weight:600;}.choiceExists.svelte-1nd6fqb {font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);margin-top:0.1rem;}.choicesSection.svelte-1nd6fqb tbody:where(.svelte-1nd6fqb) tr:where(.svelte-1nd6fqb):not(.macroRow):hover td:where(.svelte-1nd6fqb) {background:var(--background-modifier-hover);}.choicesSection.svelte-1nd6fqb select:where(.svelte-1nd6fqb) {max-width:100%;}
/* Narrow viewports (mobile): a 3-column table can't breathe, so each row
becomes a stacked card with the column name as an inline label. */
@media (max-width: 500px) {.choicesSection.svelte-1nd6fqb thead:where(.svelte-1nd6fqb) {display:none;}.choicesSection.svelte-1nd6fqb table:where(.svelte-1nd6fqb),
.choicesSection.svelte-1nd6fqb tbody:where(.svelte-1nd6fqb),
.choicesSection.svelte-1nd6fqb tr:where(.svelte-1nd6fqb),
.choicesSection.svelte-1nd6fqb td:where(.svelte-1nd6fqb) {display:block;width:100%;}.choicesSection.svelte-1nd6fqb tbody:where(.svelte-1nd6fqb) tr:where(.svelte-1nd6fqb):not(.macroRow) {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);padding:0.5rem 0.6rem;margin-bottom:0.5rem;}.choicesSection.svelte-1nd6fqb td:where(.svelte-1nd6fqb) {border-bottom:none;padding:0.15rem 0;}.choicesSection.svelte-1nd6fqb td[data-label="Location"]:where(.svelte-1nd6fqb)::before,
.choicesSection.svelte-1nd6fqb td[data-label="Action"]:where(.svelte-1nd6fqb)::before {content:attr(data-label) ": ";font-weight:600;color:var(--text-muted);}.choicesSection.svelte-1nd6fqb td[data-label="Action"]:where(.svelte-1nd6fqb) {display:flex;align-items:center;gap:0.4rem;margin-top:0.25rem;}.choicesSection.svelte-1nd6fqb td[data-label="Action"]:where(.svelte-1nd6fqb) select:where(.svelte-1nd6fqb) {flex:1;}.macroRow.svelte-1nd6fqb td:where(.svelte-1nd6fqb) {padding:0.25rem 0;}
}.summary.svelte-1nd6fqb {display:flex;align-items:center;gap:0.5rem;padding:0.55rem 0.7rem;border-radius:var(--radius-m, 8px);border:1px solid var(--qa-sev-success-border);background:var(--qa-sev-success-wash);color:var(--text-normal);}.summary.svelte-1nd6fqb .quickadd-icon {color:var(--text-success, var(--color-green, #0aa344));flex-shrink:0;}.ackGate.svelte-1nd6fqb {display:flex;flex-direction:column;gap:0.4rem;padding:0.75rem;border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);background:var(--background-secondary);}.ackGate.critical.svelte-1nd6fqb {border-color:var(--qa-sev-critical-border);}.ackGate-label.svelte-1nd6fqb {display:flex;align-items:flex-start;gap:0.5rem;font-weight:600;cursor:pointer;}.ackGate-label.svelte-1nd6fqb:has(input:where(.svelte-1nd6fqb):disabled) {cursor:not-allowed;opacity:0.6;}.ackGate-label.svelte-1nd6fqb input:where(.svelte-1nd6fqb) {margin-top:0.2rem;flex-shrink:0;}.ackGate-label.svelte-1nd6fqb input:where(.svelte-1nd6fqb):focus-visible {outline:2px solid var(--interactive-accent);outline-offset:2px;}.ackGate-hint.svelte-1nd6fqb {margin:0;font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);}.footer.svelte-1nd6fqb {display:flex;justify-content:flex-end;gap:0.5rem;margin-top:0.5rem;}.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb) {background:var(--interactive-accent);color:var(--text-on-accent);}.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb):hover:not(:disabled) {background:var(--interactive-accent-hover);}.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb):active:not(:disabled),
.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb):active:not(:disabled) {transform:translateY(1px);}.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb) {background:transparent;}.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb):hover:not(:disabled) {background:var(--background-modifier-hover);}.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb):focus-visible {outline:2px solid var(--interactive-accent);outline-offset:2px;}
/* Accent background needs a light outline to stay visible. */.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb):focus-visible {outline:2px solid var(--text-on-accent);outline-offset:-4px;}.is-mobile .macroToggle.svelte-1nd6fqb {min-height:36px;padding:0.4rem 0.3rem;}
@media (prefers-reduced-motion: reduce) {.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb),
.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb) {transition:none;}.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb):active:not(:disabled),
.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb):active:not(:disabled) {transform:none;}
}`};function EF(r,e){fe(e,!0),Ke(r,wJ);let t;function n(){return t??(t=new kT(e.app))}let i=Ee(null),o=Ee(null),s=Ee(null),a=Ee(!1),l=Ee(st(new Set)),c=Ee(st(new Set)),u=Ee(null),d=Ee(!1),f=Ee(null),p=Ee(st(new Map)),m=Ee(st(new Map)),v=Ee(""),g=Ee(!1),y=Ee(0),w=Ee(!1),T=M(()=>h(s)?YV(h(s)):!1),b=M(()=>h(s)?KV(h(s),h(l)):!0),E=M(()=>new Map((h(s)?.choices??[]).map(te=>[te.choiceId,te]))),C=M(()=>new Map((h(s)?.files??[]).map(te=>[te.originalPath,te]))),_=M(()=>!!(h(s)&&(h(s).summary.hasCritical||h(s).summary.hasWarning))),I=M(()=>!!(h(i)&&h(o))&&!h(g)&&(!h(T)||h(a)&&h(b))),q=M(()=>h(s)?.criticalScriptPaths.length??0),B=M(()=>h(s)?.missingReferences.some(te=>te.asScript)??!1),J=M(()=>{let te=h(f);if(!te)return"";let Ae=[];te.added&&Ae.push(`${te.added} choice${te.added===1?"":"s"} added`),te.overwritten&&Ae.push(`${te.overwritten} overwritten`),te.assetsWritten&&Ae.push(`${te.assetsWritten} file${te.assetsWritten===1?"":"s"} written`);let Gt=te.skipped+te.assetsSkipped;return Gt&&Ae.push(`${Gt} skipped`),Ae.length?`Imported: ${Ae.join(", ")}.`:"Nothing was imported."}),re=M(()=>h(q)>0?h(B)?"I have reviewed each bundled script 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.":h(B)?"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.");function L(te){if(h(l).has(te))return;let Ae=new Set(h(l));Ae.add(te),Q(l,Ae,!0)}function W(te){let Ae=new Set(h(c));Ae.has(te)?Ae.delete(te):Ae.add(te),Q(c,Ae,!0)}let j=te=>n().optimistic(te),$=M(()=>(h(o)?.assetConflicts??[]).map(te=>({conflict:te,state:aq(h(m),te,H,j),file:h(C).get(te.originalPath)}))),G=M(()=>h($).filter(te=>!te.state.destinationExists)),U=M(()=>h($).filter(te=>te.state.destinationExists));function H(te){let[Ae]=ui(ne.getState().templateFolderPaths),Gt=te.kind==="template"||te.kind==="capture-template";if(Ae&&Gt){let er=te.originalPath.split("/").pop()??te.originalPath;return`${Ae}/${er}`}return te.originalPath}function Y(te,Ae){n().schedule(te,Ae,Gt=>{Q(m,pq(h(m),te,Gt),!0)})}function ie(){if(!h(o)){Q(p,new Map,!0),Q(m,new Map,!0);return}Q(p,lq(h(o).choiceConflicts),!0),Q(m,sq(h(o).assetConflicts,H,j),!0);for(let te of h(o).assetConflicts){let Ae=h(m).get(te.originalPath);Ae&&Y(te.originalPath,Ae.destinationPath)}}function oe(te,Ae){Q(p,cq(h(p),te,Ae),!0)}function ce(te,Ae){Q(m,uq(h(m),te,Ae,j),!0)}function he(te,Ae){let{decisions:Gt,effectivePath:er}=dq(h(m),te.originalPath,Ae,j);Q(m,Gt,!0),Y(te.originalPath,er)}function Ie(te,Ae){let er=Ae.currentTarget.value;oe(te,er)}function we(){Q(s,null),Q(a,!1),Q(l,new Set,!0),Q(c,new Set,!0)}async function Ge(te){let Ae=te.trim(),Gt=q_(y);if(Q(f,null),Q(w,!1),!Ae){Q(i,null),Q(o,null),Q(p,new Map,!0),Q(m,new Map,!0),we(),Q(u,null);return}Q(g,!0);try{let er=hF(Ae),Kr=ne.getState().choices,no=await XV(e.app,Kr,er),ra=await TT(e.app,Kr,er);if(Gt!==h(y))return;Q(i,{pkg:er,path:"[pasted]"},!0),Q(o,no,!0),we(),Q(s,ra,!0),Q(u,null),ie()}catch(er){if(Gt!==h(y))return;Q(u,er?.message??String(er),!0),Q(i,null),Q(o,null),Q(p,new Map,!0),Q(m,new Map,!0),we()}finally{Gt===h(y)&&Q(g,!1)}}function Pe(te){let Ae=te.currentTarget.value;Q(v,Ae,!0),Ge(Ae)}function Ve(te){return!te||te.length===0?"Root":te.slice(0,-1).join(" \u203A ")||"Root"}async function qe(){if(h(w)){new qy.Notice("This package has already been imported.");return}if(!h(i)||!h(o)){new qy.Notice("Load a package before importing.");return}Q(d,!0),Q(f,null);try{let te=await ZV({app:e.app,existingChoices:ne.getState().choices,aiProviders:ne.getState().ai.providers,pkg:h(i).pkg,choiceDecisions:fq(h(o).choiceConflicts,h(p)),assetDecisions:mq(h(o).assetConflicts,h(m),j)});ne.setState(Ae=>({...Ae,choices:te.updatedChoices})),Q(f,{added:te.addedChoiceIds.length,overwritten:te.overwrittenChoiceIds.length,skipped:te.skippedChoiceIds.length,assetsWritten:te.writtenAssets.length,assetsSkipped:te.skippedAssets.length},!0),Q(w,!0),new qy.Notice(`Imported ${te.addedChoiceIds.length+te.overwrittenChoiceIds.length} choice${te.addedChoiceIds.length+te.overwrittenChoiceIds.length===1?"":"s"} successfully.`)}catch(te){console.error(te),new qy.Notice(`Import failed: ${te?.message??te}`)}finally{Q(d,!1)}}var et=bJ(),_t=S(F(et),2),ye=F(_t),$e=S(F(ye),2);Pu($e),D(ye);var ge=S(ye,2);{var xe=te=>{var Ae=QZ(),Gt=F(Ae,!0);D(Ae),ae(()=>ue(Gt,h(u))),O(te,Ae)},tt=te=>{var Ae=XZ();O(te,Ae)};X(ge,te=>{h(u)?te(xe):h(g)&&te(tt,1)})}D(_t);var kt=S(_t,2);{var Pt=te=>{var Ae=gJ(),Gt=Te(Ae),er=F(Gt),Kr=S(F(er));D(er);var no=S(er,4),ra=S(F(no));D(no);var na=S(no,4),tc=F(na);D(na);var x=S(na,4),A=F(x);D(x),D(Gt);var N=S(Gt,2);{var K=ot=>{yF(ot,{get preview(){return h(s)}})};X(N,ot=>{h(_)&&h(s)&&ot(K)})}var Z=S(N,2),se=S(F(Z),2);{var de=ot=>{var Yt=ZZ();O(ot,Yt)},Me=ot=>{var Yt=iJ(),or=S(F(Yt),2);jt(or,21,()=>h(o).choiceConflicts,yn=>yn.choiceId,(yn,mt)=>{let qi=M(()=>CF(h(p).get(h(mt).choiceId)??"import",h(mt).exists)),hs=M(()=>h(E).get(h(mt).choiceId)),Po=M(()=>(h(hs)?.commands?.length??0)>0);var Nr=nJ(),Qr=Te(Nr),Ka=F(Qr),Su=F(Ka),_h=F(Su,!0);D(Su);var sp=S(Su,2);{var Rn=Zr=>{var Si=JZ();O(Zr,Si)};X(sp,Zr=>{h(mt).exists&&Zr(Rn)})}var Ci=S(sp,2);{var Ei=Zr=>{var Si=eJ(),Lb=F(Si,!0);D(Si),ae((c_,u_)=>{Ce(Si,"aria-expanded",c_),ue(Lb,u_)},[()=>h(c).has(h(mt).choiceId),()=>h(c).has(h(mt).choiceId)?"Hide macro":"Show macro"]),_e("click",Si,()=>W(h(mt).choiceId)),O(Zr,Si)};X(Ci,Zr=>{h(Po)&&Zr(Ei)})}D(Ka);var xi=S(Ka),Ui=F(xi,!0);D(xi);var Xr=S(xi),Mt=F(Xr),Ti=F(Mt);Ti.value=Ti.__value="import";var rc=S(Ti);{var nc=Zr=>{var Si=tJ();Si.value=Si.__value="overwrite",O(Zr,Si)};X(rc,Zr=>{h(mt).exists&&Zr(nc)})}var zi=S(rc);zi.value=zi.__value="duplicate";var ic=S(zi);ic.value=ic.__value="skip",D(Mt);var ia;Gu(Mt),D(Xr),D(Qr);var I6=S(Qr,2);{var F6=Zr=>{var Si=rJ(),Lb=F(Si),c_=F(Lb);{let u_=M(()=>h(hs)?.commands??[]);bF(c_,{get commands(){return h(u_)}})}D(Lb),D(Si),O(Zr,Si)},P6=M(()=>h(Po)&&h(c).has(h(mt).choiceId));X(I6,Zr=>{h(P6)&&Zr(F6)})}ae(Zr=>{ue(_h,h(mt).name),ue(Ui,Zr),ia!==(ia=h(qi))&&(Mt.value=(Mt.__value=h(qi))??"",hc(Mt,h(qi)))},[()=>Ve(h(mt).pathHint)]),_e("change",Mt,Zr=>Ie(h(mt).choiceId,Zr)),O(yn,Nr)}),D(or),D(Yt),O(ot,Yt)};X(se,ot=>{h(o).choiceConflicts.length===0?ot(de):ot(Me,-1)})}D(Z);var it=S(Z,2);{var ur=ot=>{var Yt=mJ(),or=Te(Yt),yn=S(F(or),2);{var mt=Nr=>{var Qr=oJ();O(Nr,Qr)},qi=Nr=>{var Qr=lJ(),Ka=Te(Qr);{var Su=Rn=>{var Ci=sJ(),Ei=Te(Ci),xi=F(Ei);D(Ei);var Ui=S(Ei,2);jt(Ui,21,()=>h(G),Xr=>Xr.conflict.originalPath,(Xr,Mt)=>{var Ti=Vr(),rc=Te(Ti);{var nc=zi=>{{let ic=M(()=>h(l).has(h(Mt).file.originalPath));_T(zi,{get file(){return h(Mt).file},get pkg(){return h(i).pkg},get mode(){return h(Mt).state.mode},get destinationPath(){return h(Mt).state.destinationPath},get destinationExists(){return h(Mt).state.destinationExists},onPathInput:ia=>he(h(Mt).conflict,ia),onModeChange:ia=>ce(h(Mt).conflict.originalPath,ia),get reviewed(){return h(ic)},onReviewed:L})}};X(rc,zi=>{h(Mt).file&&zi(nc)})}O(Xr,Ti)}),D(Ui),ae(()=>ue(xi,`Added (${h(G).length??""})`)),O(Rn,Ci)};X(Ka,Rn=>{h(G).length>0&&Rn(Su)})}var _h=S(Ka,2);{var sp=Rn=>{var Ci=aJ(),Ei=Te(Ci),xi=F(Ei);D(Ei);var Ui=S(Ei,2);jt(Ui,21,()=>h(U),Xr=>Xr.conflict.originalPath,(Xr,Mt)=>{var Ti=Vr(),rc=Te(Ti);{var nc=zi=>{{let ic=M(()=>h(l).has(h(Mt).file.originalPath));_T(zi,{get file(){return h(Mt).file},get pkg(){return h(i).pkg},get mode(){return h(Mt).state.mode},get destinationPath(){return h(Mt).state.destinationPath},get destinationExists(){return h(Mt).state.destinationExists},onPathInput:ia=>he(h(Mt).conflict,ia),onModeChange:ia=>ce(h(Mt).conflict.originalPath,ia),get reviewed(){return h(ic)},onReviewed:L})}};X(rc,zi=>{h(Mt).file&&zi(nc)})}O(Xr,Ti)}),D(Ui),ae(()=>ue(xi,`Will overwrite (${h(U).length??""})`)),O(Rn,Ci)};X(_h,Rn=>{h(U).length>0&&Rn(sp)})}O(Nr,Qr)};X(yn,Nr=>{h($).length===0?Nr(mt):Nr(qi,-1)})}D(or);var hs=S(or,2);{var Po=Nr=>{var Qr=fJ(),Ka=F(Qr);{var Su=Rn=>{var Ci=uJ(),Ei=S(F(Ci),2);jt(Ei,21,()=>h(s).missingReferences,xi=>xi.path,(xi,Ui)=>{var Xr=cJ();let Mt;var Ti=F(Xr),rc=F(Ti,!0);D(Ti);var nc=S(Ti),zi=S(nc),ic=F(zi,!0);D(zi),D(Xr),ae(()=>{Mt=at(Xr,1,"svelte-1nd6fqb",null,Mt,{script:h(Ui).asScript}),ue(rc,h(Ui).path),ue(nc,`:
${h(Ui).asScript?"not bundled, so it runs from whatever file exists at that path after import":"not bundled and not in your vault"} `),ue(ic,h(Ui).breadcrumb)}),O(xi,Xr)}),D(Ei),D(Ci),O(Rn,Ci)};X(Ka,Rn=>{h(s).missingReferences.length>0&&Rn(Su)})}var _h=S(Ka,2);{var sp=Rn=>{var Ci=pJ(),Ei=S(F(Ci),2);jt(Ei,20,()=>h(s).orphanAssets,xi=>xi,(xi,Ui)=>{var Xr=dJ(),Mt=F(Xr),Ti=F(Mt,!0);D(Mt),tn(),D(Xr),ae(()=>ue(Ti,Ui)),O(xi,Xr)}),D(Ei),D(Ci),O(Rn,Ci)};X(_h,Rn=>{h(s).orphanAssets.length>0&&Rn(sp)})}D(Qr),O(Nr,Qr)};X(hs,Nr=>{h(s)&&(h(s).missingReferences.length>0||h(s).orphanAssets.length>0)&&Nr(Po)})}O(ot,Yt)};X(it,ot=>{h(i)&&ot(ur)})}var $t=S(it,2);{var ri=ot=>{var Yt=hJ(),or=F(Yt);bt(or,{iconId:"check-circle",size:16});var yn=S(or,2),mt=F(yn,!0);D(yn),D(Yt),ae(()=>ue(mt,h(J))),O(ot,Yt)};X($t,ot=>{h(f)&&ot(ri)})}ae(ot=>{ue(Kr,` ${h(i).pkg.quickAddVersion??""}`),ue(ra,` ${ot??""}`),ue(tc,`${h(o).choiceConflicts.length??""} choice${h(o).choiceConflicts.length===1?"":"s"}`),ue(A,`${h(i).pkg.assets.length??""} file${h(i).pkg.assets.length===1?"":"s"}`)},[()=>new Date(h(i).pkg.createdAt).toLocaleDateString()]),O(te,Ae)};X(kt,te=>{h(i)&&h(o)&&te(Pt)})}var gt=S(kt,2);{var Lt=te=>{var Ae=yJ();let Gt;var er=F(Ae),Kr=F(er);Bt(Kr);var no=S(Kr,2),ra=F(no,!0);D(no),D(er);var na=S(er,2);{var tc=x=>{var A=vJ(),N=F(A);D(A),ae(()=>ue(N,`Open \u201CView contents\u201D on each of the ${h(q)??""} executable
script${h(q)===1?"":"s"} above to enable this.`)),O(x,A)};X(na,x=>{h(q)>0&&!h(b)&&x(tc)})}D(Ae),ae(()=>{Gt=at(Ae,1,"ackGate svelte-1nd6fqb",null,Gt,{critical:h(s)?.summary.hasCritical}),Yu(Kr,h(a)),Kr.disabled=!h(b),Ce(Kr,"aria-describedby",h(q)>0&&!h(b)?"qa-import-ack-hint":void 0),ue(ra,h(re))}),_e("change",Kr,x=>Q(a,x.currentTarget.checked,!0)),O(te,Ae)};X(gt,te=>{h(i)&&h(T)&&!h(w)&&te(Lt)})}var Lr=S(gt,2),lt=F(Lr),rt=S(lt,2),cr=F(rt);{var ti=te=>{var Ae=ga("Importing\u2026");O(te,Ae)},Fo=te=>{var Ae=ga("Close");O(te,Ae)},vn=te=>{var Ae=ga("Import package");O(te,Ae)};X(cr,te=>{h(d)?te(ti):h(w)?te(Fo,1):te(vn,-1)})}D(rt),D(Lr),D(et),ae(()=>{lt.disabled=h(d),rt.disabled=h(d)||!h(w)&&!h(I),Ce(rt,"title",!h(w)&&h(T)&&h(b)&&!h(a)?"Confirm the acknowledgement above to continue":void 0)}),_e("input",$e,Pe),Pi($e,()=>h(v),te=>Q(v,te)),_e("click",lt,function(...te){e.close?.apply(this,te)}),_e("click",rt,function(...te){(h(w)?e.close:qe)?.apply(this,te)}),O(r,et),me()}nt(["input","click","change"]);var AT=class extends hq.Modal{constructor(t){super(t);this.handle=null}onOpen(){this.modalEl.addClass("quickAddModal","packageImportModal"),this.handle=ci(this.contentEl,EF,{app:this.app,close:()=>this.close()},{what:"the package importer"})}onClose(){this.handle?.destroy(),this.handle=null}};sf();Ku();Is();function xF(r,e,t,n){let i=nr(r,"div"),o=nr(r,"strong");return o.textContent=e,i.appendChild(o),i.appendChild(bg(r,` ${t}`)),n?.className&&i.classList.add(n.className),i.classList.add("qa-dev-info-row"),r.appendChild(i),i}function gq(r,e){if(e.branch!==null&&xF(r,"Branch:",e.branch),e.commit!==null&&xF(r,"Commit:",e.commit),e.dirty!==null){let t=e.dirty?"Yes (uncommitted changes)":"No",n=e.dirty?"qa-dev-dirty-status":"qa-dev-clean-status";xF(r,"Uncommitted changes:",t,{className:n})}}It();var TF="Bundle or import QuickAdd automations as reusable packages.",DT=class extends uu.PluginSettingTab{constructor(t,n){super(t,n);this.choiceViewHandle=null;this.globalVariablesViewHandle=null;this.packagesUnsubscribe=null;this.plugin=n,this.icon="zap"}getControlValue(t){let n=ne.getState();return t==="inputPrompt"?n.inputPrompt==="multi-line":n[t]}setControlValue(t,n){if(t==="inputPrompt"){ne.setState({inputPrompt:n?"multi-line":"single-line"});return}if(t==="persistInputPromptDrafts"){let i=!!n;ne.setState({persistInputPromptDrafts:i}),i||mi.getInstance().clearAll();return}ne.setState({[t]:n})}getSettingDefinitions(){return[this.choicesAndPackagesGroup(),this.choicePickerGroup(),this.inputGroup(),this.templatesGroup(),this.notificationsGroup(),this.globalVariablesGroup(),this.aiAndOnlineGroup(),this.appearanceGroup()]}hide(){super.hide(),this.destroySettingViews()}destroySettingViews(){this.choiceViewHandle?.destroy(),this.choiceViewHandle=null,this.globalVariablesViewHandle?.destroy(),this.globalVariablesViewHandle=null,this.packagesUnsubscribe?.(),this.packagesUnsubscribe=null}choicesAndPackagesGroup(){return{type:"group",heading:"Choices & packages",extraButtons:[t=>t.setIcon("help-circle").setTooltip("QuickAdd documentation").onClick(()=>t2(Ia.gettingStarted,t.extraSettingsEl))],items:[{name:"Choices",render:t=>this.renderChoicesView(t)},{name:"Packages",desc:TF,render:t=>this.renderPackages(t)}]}}choicePickerGroup(){return{type:"group",heading:"Choice picker",items:[{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"}},{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:"Show at the bottom (keeps your top choice first)",top:"Show at the top",off:"Hide"}}}]}}inputGroup(){return{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:"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:"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:"One-page input for choices",desc:this.descWithDocsLink("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. ",Ia.onePageInputs,"Learn more about one-page inputs"),control:{type:"toggle",key:"onePageInputEnabled"}},{name:"Date aliases",desc:"Shortcodes for natural language date parsing. One per line: alias = phrase. Example: tm = tomorrow.",render:t=>this.renderDateAliases(t)}]}}templatesGroup(){return{type:"group",heading:"Templates & properties",items:[{name:"Template folder paths",desc:"Folders where templates are stored. Used to suggest template files when configuring QuickAdd. Add as many as you like; leave empty to suggest every template file in the vault.",render:t=>this.renderTemplateFolderPaths(t)},{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"}}]}}notificationsGroup(){return{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:"Show updates on each new release",major:"Show updates only on major releases (new features, breaking changes)",none:"Don't show"}}},{name:"Show capture notifications",desc:"Display a notification when content is captured successfully to confirm the operation completed.",control:{type:"toggle",key:"showCaptureNotification"}},{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"}}]}}globalVariablesGroup(){return{type:"group",heading:"Global variables",items:[{name:"Global variables",render:t=>this.renderGlobalVariablesView(t)}]}}aiAndOnlineGroup(){return{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"}},{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"}}]}}appearanceGroup(){return{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"}}]}}developerGroup(){return{type:"group",heading:"Developer",items:[{name:"Development information",desc:"Git information for developers.",render:t=>this.renderDevInfo(t)}]}}descWithDocsLink(t,n,i="Learn more"){let o=document.createDocumentFragment();return o.append(document.createTextNode(t)),_E(o,n,i),o}prepareFullWidthSetting(t){t.infoEl.remove(),t.settingEl.addClass("qa-setting-full-width"),t.controlEl.addClass("qa-setting-full-width-control")}renderChoicesView(t){this.prepareFullWidthSetting(t),this.choiceViewHandle?.destroy();let n=ci(t.controlEl,ZI,{app:this.app,plugin:this.plugin,choices:ne.getState().choices,saveChoices:i=>{ne.setState({choices:i})}},{what:"your choices",fallbackComponent:_m});return this.choiceViewHandle=n,()=>{n.destroy(),this.choiceViewHandle===n&&(this.choiceViewHandle=null)}}renderGlobalVariablesView(t){this.prepareFullWidthSetting(t),this.globalVariablesViewHandle?.destroy();let n=ci(t.controlEl,JI,{app:this.app,plugin:this.plugin},{what:"your global variables"});return this.globalVariablesViewHandle=n,()=>{n.destroy(),this.globalVariablesViewHandle===n&&(this.globalVariablesViewHandle=null)}}packagesDesc(t){return this.descWithDocsLink(t?`${TF} Export becomes available once you have a choice. `:`${TF} `,Ia.packages,"Learn more about packages")}renderPackages(t){let n;t.addButton(a=>{n=a,a.setButtonText("Export package\u2026").onClick(()=>{let l=Wr(ne.getState().choices);new gT(this.app,this.plugin,l).open()})}),t.addButton(a=>a.setButtonText("Import package\u2026").onClick(()=>{new AT(this.app).open()}));let i=a=>{t.setDesc(this.packagesDesc(a)),n&&(n.setDisabled(a),a?n.setTooltip("Nothing to export yet"):n.buttonEl.removeAttribute("aria-label"))},o=Wr(ne.getState().choices).length===0;i(o),this.packagesUnsubscribe?.();let s=ne.subscribe(a=>{let l=Wr(a.choices).length===0;l!==o&&(o=l,i(l))});return this.packagesUnsubscribe=s,()=>{s(),this.packagesUnsubscribe===s&&(this.packagesUnsubscribe=null)}}renderDateAliases(t){t.settingEl.addClass("qa-date-alias-setting"),t.controlEl.addClass("qa-date-alias-control");let n=null;t.addTextArea(i=>{n=i,i.setPlaceholder(`t = today
tm = tomorrow
yd = yesterday`).setValue(gk(ne.getState().dateAliases)).onChange(o=>{ne.setState({dateAliases:HM(o)})}),i.inputEl.addClass("qa-date-alias-input")}),t.addButton(i=>{i.setButtonText("Reset to defaults").onClick(()=>{ne.setState({dateAliases:$p}),n?.setValue(gk($p))}),i.buttonEl.addClass("qa-date-alias-reset")})}renderTemplateFolderPaths(t){t.settingEl.addClass("qa-template-folders-setting");let n=t.controlEl.createDiv("qa-template-folders"),i=n.createDiv("qa-template-folder-list"),o=()=>ui(ne.getState().templateFolderPaths),s=p=>{ne.setState({templateFolderPaths:p})},a=()=>{i.empty();let p=o();if(p.length===0){i.createDiv({cls:"qa-template-folder-empty",text:"No folders added yet."});return}for(let m of p){let v=i.createDiv("qa-template-folder-row");v.createSpan({cls:"qa-template-folder-name",text:m,attr:{title:m}}),new uu.ExtraButtonComponent(v).setIcon("trash-2").setTooltip(`Remove ${m}`).onClick(()=>{s(o().filter(g=>g!==m)),a()})}},l=n.createDiv("qa-template-folder-input-row"),c=new uu.TextComponent(l);c.setPlaceholder("templates/"),c.inputEl.addClass("qa-template-folder-input");let u=new An(this.app,c.inputEl,Rl(Go(this.app)).filter(p=>p!=="/")),d=()=>{let[p]=ui([c.inputEl.value]);if(c.inputEl.value="",!p)return;let m=o();m.includes(p)||(s([...m,p]),a())},f=p=>{p.key==="Enter"&&(p.preventDefault(),d())};return c.inputEl.addEventListener("keydown",f),new uu.ButtonComponent(l).setCta().setButtonText("Add").onClick(()=>d()),a(),()=>{c.inputEl.removeEventListener("keydown",f),u.destroy()}}renderDevInfo(t){let n=t.settingEl.createDiv();n.addClass("qa-dev-info"),gq(n,{branch:null,commit:null,dirty:null})}};vk();De();Bw();var Fm=class{formatOutputString(e){return`QuickAdd: (${e.level}) ${e.message}`}getQuickAddError(e,t,n,i){return{message:e,level:t,time:Date.now(),stack:n,originalError:i}}};rr();var Uy=class extends Fm{constructor(){super(...arguments);this.ErrorLog=[]}logError(t,n,i){let o=this.getQuickAddError(t,"ERROR",n,i);this.addMessageToErrorLog(o);let s=i||new Error(t);console.error(this.formatOutputString(o),s)}logWarning(t,n,i){let o=this.getQuickAddError(t,"WARNING",n,i);this.addMessageToErrorLog(o);let s=i||new Error(t);console.warn(this.formatOutputString(o),s)}logMessage(t,n,i){let o=this.getQuickAddError(t,"LOG",n,i);this.addMessageToErrorLog(o),i?console.log(this.formatOutputString(o),i):console.log(this.formatOutputString(o))}addMessageToErrorLog(t){this.ErrorLog.push(t),this.ErrorLog.length>_k&&(this.ErrorLog=this.ErrorLog.slice(-_k))}clearErrorLog(){this.ErrorLog=[]}};var SF=require("obsidian");Bw();var IT=class extends Fm{constructor(t){super();this.plugin=t}logError(t,n,i){let o=this.getQuickAddError(t,"ERROR",n,i);new SF.Notice(this.formatOutputString(o),15e3)}logWarning(t,n,i){let o=this.getQuickAddError(t,"WARNING",n,i);new SF.Notice(this.formatOutputString(o))}logMessage(t,n,i){}};De();rr();rr();var vq=1e4,yq=50,CJ=/plugin:([^\s:)]+)/;function EJ(r){let e=r.stack??"",t=`${r.name}: ${r.message}`;return(e.startsWith(t)?e.slice(t.length):e).split(`
`)}function xJ(r){for(let e of EJ(r)){let t=CJ.exec(e);if(t)return{pluginId:t[1],frame:e.trim()}}return null}function TJ(r,e){return`${r.name}@${e}`}function bq(r,e=Date.now){let t=r.manifest.id,n=new Map;r.registerDomEvent(window,"unhandledrejection",i=>{let o=i.reason,s=o instanceof Error?xJ(o):null;if(s?.pluginId!==t)return;if(pt(o)){i.preventDefault();return}let a=o,l=TJ(a,s.frame),c=e(),u=n.get(l);if(n.set(l,c),!(u!==void 0&&c-u<vq)){if(n.size>=yq){for(let[d,f]of n)c-f>=vq&&n.delete(d);if(n.size>=yq){let d=n.keys().next();!d.done&&d.value!==l&&n.delete(d.value)}}We(a,"A QuickAdd action failed")&&i.preventDefault()}})}var wq=require("obsidian");De();function SJ(r,e){try{let t=r.setting;return!t?.open||!t?.openTabById?(P.logMessage("QuickAdd: Obsidian internal settings API is unavailable."),!1):(t.open(),t.openTabById(e),!0)}catch(t){return P.logMessage(`QuickAdd: Failed to open plugin settings automatically: ${t}`),!1}}function Pm(r,e,t){let n=SJ(r,e);return!n&&t?.notice!==!1&&new wq.Notice("QuickAdd: Unable to open settings automatically. Open Settings \u2192 QuickAdd manually."),n}pb();It();rr();var RS=class{constructor(e,t,n,i){this.app=e;this.plugin=t;this.choices=n;this.choiceExecutor=i}async run(){let e=dn(this.choices).filter(t=>t.type==="Macro"&&t.runOnStartup);for(let t of e)try{await new Wa(this.app,this.plugin,t,this.choiceExecutor,new Map).run()}catch(n){We(n,`Startup macro '${t.name}' failed`)}}};var KW=require("obsidian");var bh=require("obsidian");zy();Je();Ul();De();var nW=require("obsidian");lu();ih();oh();Bi();var rW=require("obsidian");wo();Qi();function _b(r,e,t){let n=e.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=$g(n>=0?e.slice(n+1):e),s=t?.vault.getAbstractFileByPath(e),a=t&&s instanceof rW.TFile?HA([s],d=>t.metadataCache.getFileCache(d))[0]:null,l=a?.primary??o,c=a?.secondary??i;r.addClass("mod-complex");let u=r.createDiv({cls:"suggestion-content"});u.createDiv({cls:"suggestion-title",text:l}),c&&u.createDiv({cls:"suggestion-note",text:c})}function ep(r,e={}){let{openedAtOf:t,recentRankOf:n,isExcluded:i}=e;return r.map(o=>({file:o,name:o.basename||o.path,excluded:i?.(o.path)??!1,openedAt:t?.(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,u=s.recentRank??Number.POSITIVE_INFINITY;return c!==u?c-u:o.name.localeCompare(s.name)}).map(o=>o.file)}MA();function tp(r){let e=r.workspace?.getLastOpenFiles?.(),t=Array.isArray(e)?e:[],n=new Map;t.forEach((s,a)=>{n.has(s)||n.set(s,a)});let i;try{i=of.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}}rr();Er();Aa();Sa();var cP="@quickadd-existing-note:",uP="@quickadd-unresolved-note:";function Dne(r){return`${cP}${r}`}function Ine(r){return`${uP}${r}`}function Fne(r){return r.startsWith(cP)}function Pne(r){return r.startsWith(uP)}function $ne(r){return r.slice(cP.length)}function Mne(r){return r.slice(uP.length)}function rp(r){return r.trim().replace(/\.md$/i,"").toLowerCase()}function iW(r){return r.trim().replace(/^\/+/,"")}function One(r){return r.trim().length>0&&!r.includes("{{")}function Rne(r){if(!One(r.templatePath))return new Set;let e=iW(r.templatePath),t=/\.md$/i.test(e)?e:`${e}.md`;return new Set([t.toLowerCase()])}function Lne(r,e,t){let n=e.replace(/\.md$/i,"");r.add(rp(e)),r.add(rp(n)),r.add(rp(t))}function Nne(r,e){let t=r.metadataCache.getFileCache(e)?.frontmatter;if(!t)return[];let n=[];for(let[i,o]of Object.entries(t)){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 Bne(r){let n=((r.split("|")[0]?.trim()??"").split("#")[0]?.trim()??"").replace(/\.md$/i,"").trim();return!n||n==="/"||Pr(n)?null:n}function Vne(r){let e=r.metadataCache.unresolvedLinks??{},t=new Map;for(let n of Object.values(e))for(let i of Object.keys(n)){let o=Bne(i);if(!o)continue;let s=rp(o);t.has(s)||t.set(s,o)}return[...t.values()].sort((n,i)=>n.localeCompare(i))}function qne(r,e){let t=new Set,n=Rne(e),i=ep(r.vault.getMarkdownFiles(),tp(r)),o=[];for(let s of i){if(n.has(iW(s.path).toLowerCase()))continue;Lne(t,s.path,s.basename);let a=Nne(r,s),l=[s.basename,s.path,...a].join(" ");o.push({item:Dne(s.path),display:l,title:a[0]?`${s.basename} (${s.path})`:s.path,renderPath:s.path,renderAlias:a[0]})}for(let s of Vne(r)){let a=rp(s);t.has(a)||o.push({item:Ine(s),display:s,title:`${s} (unresolved link)`,unresolvedTitle:s})}return{candidates:o,existingKeys:t}}function Une(r,e){r.addClass("mod-complex");let t=r.createDiv({cls:"suggestion-content"});t.createDiv({cls:"suggestion-title",text:e}),t.createDiv({cls:"suggestion-note",text:"Unresolved link"})}function zne(r,e,t){if(_b(r,e),!t)return;r.querySelector(".suggestion-content")?.createDiv({cls:"suggestion-note",text:`Alias: ${t}`})}async function oW(r,e,t){let{candidates:n,existingKeys:i}=qne(r,e),o=new Map(n.map(a=>[a.item,a])),s=`Search notes or create ${e.name}`;try{let a=String(await cs(t,{remote:c=>us(c,{items:n.map(u=>({value:u.item,title:u.title})),placeholder:s,allowCustomInput:!0,what:"the note-discovery picker"}),headless:()=>{throw new ve(`'${e.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:()=>Or.Suggest(r,n.map(c=>c.display),n.map(c=>c.item),{placeholder:s,allowCustomValue:!0,customValueLabel:c=>`Create new note: ${c}`,valueExists:c=>{let u=rp(c);return i.has(u)||n.some(d=>d.unresolvedTitle&&rp(d.unresolvedTitle)===u)},renderItem:(c,u)=>{let d=o.get(c);if(d){if(d.renderPath){zne(u,d.renderPath,d.renderAlias);return}d.unresolvedTitle&&Une(u,d.unresolvedTitle)}}})}));if(Fne(a)){let c=r.vault.getAbstractFileByPath($ne(a));if(c instanceof nW.TFile)return{kind:"openExisting",file:c};throw new Error("Selected note no longer exists. Please run QuickAdd again.")}if(Pne(a)){let c=In(Mne(a),"Note title");return{kind:"create",title:c,...c.includes("/")?{vaultRelativePath:c}:{}}}let l=In(a,"Note title");return{kind:"create",title:l,...l.includes("/")?{vaultRelativePath:l}:{}}}catch(a){throw pt(a)?new dt("Input cancelled by user"):a}}ih();oh();od();Dt();rr();var yh=class{constructor(e){this.executor=e;this.closed=!1}success(e,t){this.closed=!0,this.executor.recordExecutionResult?.({status:"success",file:e,effect:t})}failure(e){this.closed||this.executor.recordExecutionResult?.({status:"error",reason:e})}};function LS(r){return r instanceof Error?r.message||sW:String(r)||sW}var sW="Choice execution failed.";Aa();yg();qp();sf();gS();$S();jo();Bi();db();nh();var NS=class extends wu{constructor(t,n,i,o,s=null){super(t,n,o);this.originLeaf=s;this.choiceExecutor=o,this.outcome=new yh(o),this.choice=i,this.formatter.setPromptRunContext({draftScopeId:i.id,choiceName:i.name})}async run(){let t=null,n=null;try{Jn(this.choice.templatePath,()=>`Invalid template path for ${this.choice.name}. ${this.choice.templatePath.length===0?"Template path is empty.":`Template path is not valid: ${this.choice.templatePath}`}`);let i=xc(this.choice.appendLink);if(this.setLinkToCurrentFileBehavior(i.enabled&&!i.requireActiveFile?"optional":"required"),!this.validateAppendLinkDestination(i))return;let o=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:zo;if(UD(this.choice,o,this.choiceExecutor.variables.get("value"))){let w=await oW(this.app,this.choice,this.choiceExecutor);if(w.kind==="openExisting"){await this.openDiscoveredExistingNote(w.file),this.outcome.success(w.file,"unchanged");return}t=this.setTemporaryValueVariable(w.title),n=w.vaultRelativePath??null}let s=await this.resolveTemplateSourcePath(this.choice.templatePath),a="";if(n)a=ro(n);else if(this.choice.folder.enabled)a=await this.getFolderPath();else{let w=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");a=w===this.app.vault.getRoot()?"":w.path}this.formatter.setTargetFolderPath(a),this.choice.folder.enabled&&this.formatter.setPromptRunContext({destination:a,destinationKind:"folder"});let l=n||await this.formatter.formatFileName(o,"noteTitle"),c=In(l,"File name"),{fileName:u,strippedPrefix:d}=n?{fileName:c,strippedPrefix:!1}:this.stripDuplicateFolderPrefix(c,a),f=this.shouldTreatFormattedNameAsVaultRelativePath(c,d,this.choice.folder.enabled),p=this.normalizeTemplateFilePath(n||f?"":a,u,s),m,v=!1,g=!1,y="created";if(await this.app.vault.adapter.exists(p)){let w=await this.getSelectedFileExistsMode(),T=Bf(w);y=T.resolutionKind==="reuseExisting"?"unchanged":T.resolutionKind==="createNew"?"created":"changed";let b=T.requiresExistingFile?this.findExistingFile(p):null;if(T.requiresExistingFile&&(!(b instanceof bh.TFile)||b.extension!=="md"&&b.extension!=="canvas"&&b.extension!=="base")){this.failRun(`'${p}' already exists but could not be resolved as a markdown, canvas, or base file.`);return}if({createdFile:m,shouldAutoOpen:v}=await this.applyFileExistsMode(w,p,b,s,i),!m){this.lastTemplateFileFailure?this.failRun(this.lastTemplateFileFailure,"none"):this.failRun(`Could not resolve file exists behavior for '${p}'.`,"warning");return}}else{if(m=await this.createFileWithTemplate(p,s),!m){this.failRun(this.lastTemplateFileFailure??`Could not create file '${p}'.`,"none");return}g=!0}if(this.outcome.success(m,y),i.enabled&&m)try{i.destination.type==="specifiedFile"?await Ww(this.app,m,i):id(i.placement)?await ad(this.app,m,i):this.choiceExecutor.focusedProperty?await Yw(this.app,this.choiceExecutor.focusedProperty,m):await ad(this.app,m,i)}catch(w){if(w instanceof Tt)throw w;P.logWarning(`Created '${m.basename}' but could not insert the link: ${w instanceof Error?w.message:String(w)}`)}if(this.choice.copyLinkToClipboard&&m)try{await jw(m)}catch(w){P.logWarning(`Could not copy link to clipboard for '${m.path}': ${w instanceof Error?w.message:String(w)}`)}if((this.choice.openFile||v)&&m){let w=qr(this.choice.fileOpening),T=w.focus??!0;ld(this.app,m,T)||await gl(this.app,m,{...w,originLeaf:this.originLeaf}),await Ec(this.app,m)}else g&&!i.enabled&&!this.choice.copyLinkToClipboard&&new bh.Notice(`Created '${m.basename}'.`)}catch(i){if(bu(i,{logPrefix:"Template execution aborted",noticePrefix:"Template execution aborted",defaultReason:"Template execution aborted"})){this.choiceExecutor.signalAbort?.(i);return}mi.getInstance().markExecutionScopeFailed(),this.outcome.failure(LS(i)),We(i,`Error running template choice "${this.choice.name}"`)}finally{t?.()}}failRun(t,n="error"){mi.getInstance().markExecutionScopeFailed(),n==="warning"?P.logWarning(t):n==="error"&&P.logError(t),this.outcome.failure(t)}setTemporaryValueVariable(t){let n=this.choiceExecutor.variables,i=n.has("value"),o=n.get("value");return n.set("value",t),()=>{if(i){n.set("value",o);return}n.delete("value")}}validateAppendLinkDestination(t){return!t.enabled||t.destination.type!=="specifiedFile"||vg(this.app,t.destination)?!0:(this.failRun(`Append link target file not found or is not a Markdown file: ${t.destination.path}`),!1)}async getSelectedFileExistsMode(){var i;if((i=this.choice).fileExistsBehavior??(i.fileExistsBehavior={kind:"prompt"}),this.choice.fileExistsBehavior.kind==="apply")return this.choice.fileExistsBehavior.mode;let t=E2(),n="If the target file already exists";return await cs(this.choiceExecutor,{remote:o=>us(o,{items:t.map(s=>({value:s.id,title:s.label})),placeholder:n,what:'the "file already exists" chooser'}),headless:()=>{throw new ve(`'${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:()=>hr.Suggest(this.app,t.map(o=>o.label),t.map(o=>o.id),n)})}async applyFileExistsMode(t,n,i,o,s){let a=Bf(t);switch(a.resolutionKind){case"modifyExisting":return{createdFile:await this.applyExistingFileUpdate(a.id,i,o,s),shouldAutoOpen:!1};case"createNew":{let l=await _2(n,a.id,async u=>await this.app.vault.adapter.exists(u)),c=await this.createFileWithTemplate(l,o);return c&&l!==n&&!this.choice.openFile&&new bh.Notice(`Created '${c.basename}'.`),{createdFile:c,shouldAutoOpen:!1}}case"reuseExisting":return P.logMessage(`Opening existing file: ${i.path}`),{createdFile:i,shouldAutoOpen:!0}}}async openDiscoveredExistingNote(t){let n=qr(this.choice.fileOpening);ld(this.app,t,!0)||await gl(this.app,t,{...n,focus:!0,originLeaf:this.originLeaf})}async applyExistingFileUpdate(t,n,i,o){switch(t){case"appendTop":return await this.appendToExistingFileWithTemplate(n,i,"top",o);case"appendBottom":return await this.appendToExistingFileWithTemplate(n,i,"bottom",o);case"overwrite":return await this.overwriteFileWithTemplate(n,i)}}async appendToExistingFileWithTemplate(t,n,i,o){if(t.extension==="canvas"||t.extension==="base")return this.lastTemplateFileFailure=`Cannot append to '${t.path}': appending a template to a ${t.extension} file would corrupt it. Use the "Overwrite" file-exists option instead.`,mi.getInstance().markExecutionScopeFailed(),P.logError(this.lastTemplateFileFailure),null;if(t.extension!=="md")return await this.appendToFileWithTemplate(t,n,i);let s=new fh(this.app,this.plugin,t,n,i,this.choiceExecutor,n);return s.setPromptRunContext({draftScopeId:this.choice.id,choiceName:this.choice.name,destination:t.path,destinationKind:"file"}),s.setLinkToCurrentFileBehavior(o.enabled&&!o.requireActiveFile?"optional":"required"),await this.withAnonymousValueForInsertEngine(()=>s.apply())}async withAnonymousValueForInsertEngine(t){let n=this.formatter.getAnonymousValue(),i=this.choiceExecutor.variables;if(!(n!==void 0&&!i.has("value")))return await t();i.set("value",n);try{return await t()}finally{i.delete("value")}}findExistingFile(t){let n=this.app.vault.getAbstractFileByPath(t);if(n instanceof bh.TFile)return n;if(n)return null;let i=t.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(", ");P.logError(`Multiple files match '${t}' when ignoring case: ${s}`)}return null}async formatFolderPaths(t){let n=[];for(let i of t)n.push(await this.formatter.formatFolderPath(i));return n}async getFolderPath(){let t=await this.formatFolderPaths([...this.choice.folder.folders]),n=this.getCurrentFolderSuggestion(),i=n?[n]:[],o=this.choiceExecutor;if(this.choice.folder?.chooseFromSubfolders&&!(this.choice.folder?.chooseWhenCreatingNote||this.choice.folder?.createInSameFolderAsActiveFile)){let s=Rl(Go(this.app)),a=s2(s,t);return await this.getOrCreateFolder(a,{allowCreate:!0,allowedRoots:t,topItems:i,executor:o})}if(this.choice.folder?.chooseWhenCreatingNote){let s=Rl(Go(this.app));return await this.getOrCreateFolder(s,{allowCreate:!0,topItems:i,executor:o})}if(this.choice.folder?.createInSameFolderAsActiveFile){let s=this.app.workspace.getActiveFile();return!s||!s.parent?(P.logWarning("No active file or active file has no parent. Cannot create file in same folder as active file. Creating in root folder."),""):await this.getOrCreateFolder([s.parent.path],{allowCreate:!0,topItems:i,executor:o})}return await this.getOrCreateFolder(t,{allowCreate:!0,allowedRoots:t,topItems:i,executor:o})}getCurrentFolderSuggestion(){let t=this.app.workspace.getActiveFile(),n=t?.parent;return!t||!n?null:{path:n.path??"",label:"<current folder>"}}};var ec=require("obsidian");wa();lu();zy();var BS=class{isResolved(){return!this.hasConflicts}isConflicted(){return this.hasConflicts}},kb=class r extends BS{constructor(e,t,n){super(),this.left=e,this.base=t,this.right=n,this.hasConflicts=!0}static create(e){return new r(e.left,e.base,e.right)}apply(e){return r.create({left:e(this.left),base:e(this.base),right:e(this.right)})}},fs=class r extends BS{constructor(e){super(),this.hasConflicts=!1,this.result=e}combine(e){this.result=this.result.concat(e.result)}apply(e){return new r(e(this.result))}};var Xl=class r{constructor(e,t){this.left=e,this.right=t}static executeDiff(e,t){if(!e.push)throw new Error("Argument is not an array");let n=r.diff(e,t);return new pP(e,t,n).convertToTypedOutput()}static diff(e,t){return new r(e,t).performDiff()}performDiff(){let e=this.identifyUniquePositions();e.sort((o,s)=>s[0]-o[0]);let[t,n]=this.findNextChange(),i=new VS(t,n,[]);return e.forEach(o=>{i=this.getDifferences(i,o)}),i.changeRanges}getDifferences(e,t){let[n,i]=[e.leftChangePos,e.rightChangePos],[o,s]=t;if(o<n||s<i)return e;{let[a,l,c,u]=this.findPrevChange(n,i,o-1,s-1),[d,f]=this.findNextChange(o+1,s+1),p=this.appendChangeRange(e.changeRanges,a,l,c,u);return new VS(d,f,p)}}findNextChange(e=0,t=0){let n=this.left.slice(e)||[],i=this.right.slice(t)||[],o=this.mismatchOffset(n,i);return[e+o,t+o]}findPrevChange(e,t,n,i){if(e>n||t>i)return[e,n,t,i];{let o=this.left.slice(e,n+1).reverse()||[],s=this.right.slice(t,i+1).reverse()||[],a=this.mismatchOffset(o,s);return[e,n-a,t,i-a]}}mismatchOffset(e,t){let n=Math.max(e.length,t.length);for(let i=0;i<n;i++)if(e[i]!==t[i])return i;return Math.min(e.length,t.length)}identifyUniquePositions(){let e=this.findUnique(this.left),t=this.findUnique(this.right),n=new Set(...e.keys()),i=new Set(...t.keys()),s=[...new Set([...n].filter(a=>i.has(a)))].map(a=>[e.get(a),t.get(a)]);return s.unshift([this.left.length,this.right.length]),s}findUnique(e){let t=new Map;e.forEach((i,o)=>{t.set(i,new dP(o,!t.has(i)))});let n=new Map;for(let[i,o]of t.entries())o.unique&&n.set(i,o.pos);return n}appendChangeRange(e,t,n,i,o){return t<=n&&i<=o?e.push(new Ab(Ga.change,t+1,n+1,i+1,o+1)):t<=n?e.push(new Ab(Ga.remove,t+1,n+1,i+1,i)):i<=o&&e.push(new Ab(Ga.add,t+1,t,i+1,o+1)),e}},dP=class{constructor(e,t){this.pos=e,this.unique=t}},wh=class{constructor(e,t){this.text=e,this.low=t}},pP=class{constructor(e,t,n){this.oldTextArray=e,this.newTextArray=t,this.chunks=n,this.oldText=[],this.newText=[]}convertToTypedOutput(){let e=new fP(0,0);return this.chunks.forEach(t=>{let[n,i]=this.setTextNodeIndexes(t,e.oldIndex,e.newIndex),[o,s]=this.appendChanges(t,e.oldIndex+n,e.newIndex+i);e.oldIndex=o,e.newIndex=s}),this.setTheRemainingTextNodeIndexes(e.oldIndex,e.newIndex),{oldText:this.oldText,newText:this.newText}}setTextNodeIndexes(e,t,n){let i=0;for(;t+i<e.leftLo-1;)this.oldText.push(new wh(this.oldTextArray[t+i],n+i)),i+=1;let o=0;for(;n+o<e.rightLo-1;)this.newText.push(new wh(this.newTextArray[n+o],t+o)),o+=1;return[i,o]}appendChanges(e,t,n){for(;t<=e.leftHi-1;)this.oldText.push(this.oldTextArray[t]),t+=1;for(;n<=e.rightHi-1;)this.newText.push(this.newTextArray[n]),n+=1;return[t,n]}setTheRemainingTextNodeIndexes(e,t){let n=0;for(;e+n<this.oldTextArray.length;)this.oldText.push(new wh(this.oldTextArray[e+n],t+n)),n+=1;for(;t+n<this.newTextArray.length;)this.newText.push(new wh(this.newTextArray[t+n],e+n)),n+=1}},fP=class{constructor(e,t){this.oldIndex=e,this.newIndex=t}},Ga;(function(r){r.change="change",r.add="add",r.remove="remove"})(Ga||(Ga={}));var Ab=class{constructor(e,t,n,i,o){this.action=e,this.leftLo=t,this.leftHi=n,this.rightLo=i,this.rightHi=o}},VS=class{constructor(e,t,n){this.leftChangePos=e,this.rightChangePos=t,this.changeRanges=n}};var qS=class r{constructor(e,t,n,i,o){this.code=e,this.baseLo=t,this.baseHi=n,this.sideLo=i,this.sideHi=o}static fromChangeRange(e){return new r(e.action,e.leftLo,e.leftHi,e.rightLo,e.rightHi)}},Ch=class r{constructor(e,t,n){this.left=e,this.base=t,this.right=n}static executeDiff(e,t,n){return new r(e,t,n).getDifferences()}getDifferences(){let e=Xl.diff(this.base,this.left).map(n=>qS.fromChangeRange(n)),t=Xl.diff(this.base,this.right).map(n=>qS.fromChangeRange(n));return this.collapseDifferences(new US(e,t))}collapseDifferences(e,t=[]){if(e.isFinished())return t;{let n=new US,i=e.chooseSide(),o=e.dequeue();return n.enqueue(i,o),e.switchSides(),this.buildResultQueue(e,o.baseHi,n),t.push(this.determineDifference(n,i,e.switchSides())),this.collapseDifferences(e,t)}}buildResultQueue(e,t,n){if(this.queueIsFinished(e.peek(),t))return n;{let i=e.dequeue();return n.enqueue(e.currentSide,i),t<i.baseHi?(e.switchSides(),this.buildResultQueue(e,i.baseHi,n)):this.buildResultQueue(e,t,n)}}queueIsFinished(e,t){return e.length===0||e[0].baseLo>t+1}determineDifference(e,t,n){let i=e.get(t)[0].baseLo,o=e.get(n),s=o[o.length-1].baseHi,[a,l]=this.diffableEndpoints(e.get(gn.left),i,s),[c,u]=this.diffableEndpoints(e.get(gn.right),i,s),d=this.left.slice(a-1,l),f=this.right.slice(c-1,u),p=this.decideAction(e,d,f);return new mP(p,a,l,c,u,i,s)}diffableEndpoints(e,t,n){if(e.length){let i=e[0],o=e[e.length-1],s=i.sideLo-i.baseLo+t,a=o.sideHi-o.baseHi+n;return[s,a]}else return[t,n]}decideAction(e,t,n){return e.isEmpty(gn.left)?Zl.chooseRight:e.isEmpty(gn.right)?Zl.chooseLeft:t.every((i,o)=>n[o]===i)?Zl.noConflictFound:Zl.possibleConflict}},mP=class{constructor(e,t,n,i,o,s,a){this.changeType=e,this.leftLo=t,this.leftHi=n,this.rightLo=i,this.rightHi=o,this.baseLo=s,this.baseHi=a}},Zl;(function(r){r.chooseRight="choose_right",r.chooseLeft="choose_left",r.possibleConflict="possible_conflict",r.noConflictFound="no_conflict_found"})(Zl||(Zl={}));var gn;(function(r){r.left="left",r.right="right"})(gn||(gn={}));var US=class{constructor(e=[],t=[]){this.diffs={left:e,right:t}}dequeue(e=this.currentSide){return this.diffs[e].shift()}peek(e=this.currentSide){return this.diffs[e]}isFinished(){return this.isEmpty(gn.left)&&this.isEmpty(gn.right)}enqueue(e=this.currentSide,t){return this.diffs[e].push(t)}get(e=this.currentSide){return this.diffs[e]}isEmpty(e=this.currentSide){return this.diffs[e].length===0}switchSides(e=this.currentSide){return this.currentSide=e===gn.left?gn.right:gn.left}chooseSide(){return this.isEmpty(gn.left)?this.currentSide=gn.right:this.isEmpty(gn.right)?this.currentSide=gn.left:this.currentSide=this.get(gn.left)[0].baseLo<=this.get(gn.right)[0].baseLo?gn.left:gn.right,this.currentSide}};var Db=class r{static merge(e,t,n){let i=new r(e,t,n);return i.executeThreeWayMerge(),i.result}constructor(e,t,n){this.result=[],this.text3=new hP(e,n,t)}executeThreeWayMerge(){let e=Ch.executeDiff(this.text3.left,this.text3.base,this.text3.right),t=1;e.forEach(i=>{let o=[];for(let s=t;s<i.baseLo;s++)o.push(this.text3.base[s-1]);o.length&&this.result.push(new fs(o)),this.interpretChunk(i),t=i.baseHi+1});let n=this.accumulateLines(t,this.text3.base.length,this.text3.base);n.length&&this.result.push(new fs(n))}setConflict(e){let t=kb.create({left:this.accumulateLines(e.leftLo,e.leftHi,this.text3.left),base:this.accumulateLines(e.baseLo,e.baseHi,this.text3.base),right:this.accumulateLines(e.rightLo,e.rightHi,this.text3.right)});this.result.push(t)}determineConflict(e,t,n){let i=1;e.forEach(s=>{for(let l=i;l<=s.leftLo;l++)this.result.push(new fs(this.accumulateLines(i,l,n)));let a=this.determineOutcome(s,t,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 fs(o))}determineOutcome(e,t,n){return e.action===Ga.change?kb.create({left:this.accumulateLines(e.rightLo,e.rightHi,t),right:this.accumulateLines(e.leftLo,e.leftHi,n),base:[]}):e.action===Ga.add?new fs(this.accumulateLines(e.rightLo,e.rightHi,t)):null}setText(e,t,n){let i=[];for(let o=t;o<=n;o++)i.push(e[o-1]);return i}_conflictRange(e){let t=this.setText(this.text3.right,e.rightLo,e.rightHi),n=this.setText(this.text3.left,e.leftLo,e.leftHi),i=Xl.diff(t,n);(this._assocRange(i,Ga.change)||this._assocRange(i,Ga.remove))&&e.baseLo<=e.baseHi?this.setConflict(e):this.determineConflict(i,n,t)}interpretChunk(e){if(e.changeType==Zl.chooseLeft){let t=this.accumulateLines(e.leftLo,e.leftHi,this.text3.left);t.length&&this.result.push(new fs(t))}else if(e.changeType!==Zl.possibleConflict){let t=this.accumulateLines(e.rightLo,e.rightHi,this.text3.right);t.length&&this.result.push(new fs(t))}else this._conflictRange(e)}_assocRange(e,t){for(let n=0;n<e.length;n++){let i=e[n];if(i.action===t)return i}return null}accumulateLines(e,t,n){let i=[];for(let o=e;o<=t;o++)n[o-1]&&i.push(n[o-1]);return i}},hP=class{constructor(e,t,n){this.left=e,this.right=t,this.base=n}};var np=class{constructor(e,t,n={}){this.results=e,this.joinFunction=t,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[e,t]=[this.results[0],this.results.slice(1)],n=e;return t.forEach(i=>n.combine(i)),n.apply(this.joinFunction).result}}};var Ib=class r{static collateMerge(e,t,n){return e.length?(e=r.combineNonConflicts(e),e.length===1&&e[0].isResolved()?new np(e,t):new np(e,t,{conflict:!0,conflictHandler:n})):new np([new fs([])],t)}static combineNonConflicts(e){let t=[];return e.forEach(n=>{t.length&&t[t.length-1].isResolved()&&n.isResolved()?t[t.length-1].combine(n):t.push(n)}),t}};function aW(r,e,t,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,e,c,t].join(`
`)}}).join(`
`)}}var lW=r=>r.join(""),Hne=r=>r.split(/\b/),Wne=aW("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",lW),jne={splitFunction:Hne,joinFunction:lW,conflictFunction:Wne};function gP(r,e,t,n={}){n=Object.assign({},jne,n);let[i,o,s]=[r,e,t].map(c=>n.splitFunction.call(n,c)),a=Db.merge(i,o,s);return Ib.collateMerge(a,n.joinFunction,n.conflictFunction)}var cW=gP;Je();wa();MS();Je();Dt();Bi();ah();function uW(r,e){return r.line===e.line}function Jl(r){let e=[];return r.forEach((t,n)=>{let i=t.match(/^(#+)[\s]+(.*)$/);i&&e.push({level:i[1].length,text:i[2],line:n})}),e}function Eu(r,e,t=!1){let n=Jl(r),i=n.find(c=>c.line===e),o=!!i;if(!o&&t)throw new Error(`Target line ${e} is not a heading, but we are trying to find the end of its section.`);if(!o&&!t){let c=dW(r,e,u=>u.trim()==="");return c!==null&&c>e?c-1:e}let s=r.length-1,a=Gne(i,n,r,t),l=Qne(r,a,c=>c.trim()!=="");if(l!==null){if(l<e)return e;let c=r[l+1].trim()==="";return l+1===s&&!c?a:l===0?l+1:l}return a}function Gne(r,e,t,n){let i=e.findIndex(u=>uW(u,r)),o=i===e.length-1,s=t.length-1;if(o)return s;let[a,l]=Yne(r,e);if(l&&a===e.length)return s;if(l&&n)return e[a].line-1;if(l&&!n)return e[i+1].line;if(!n&&!l){let u=Kne(r.line,e);return u===null?s:u}return s}function Yne(r,e){let t=e.findIndex(i=>uW(i,r)),n=dW(e,t,i=>i.level<=r.level);return n===null?[-1,!1]:[n,!0]}function Kne(r,e){let t=e.find(n=>n.line>r);return t?t.line:null}function Qne(r,e,t){for(let n=e-1;n>=0;n--)if(t(r[n]))return n;return null}function dW(r,e,t){for(let n=e+1;n<r.length;n++)if(t(r[n]))return n;return null}var Xne="\u200B";function Fb(r){let e=r.slice(),t=!1,n="",i=0;for(let o=0;o<r.length;o++){let s=r[o].match(/^(\s*)(`{3,}|~{3,})/);if(!t){s&&(t=!0,n=s[2][0],i=s[2].length);continue}e[o]=r[o].replace(/^(\s*)#+(\s)/,`$1${Xne}$2`),s&&s[2][0]===n&&s[2].length>=i&&r[o].slice(s[1].length+s[2].length).trim()===""&&(t=!1,n="",i=0)}return e}function pW(r){return(r.match(/^#+\s+(.*)$/)?.[1]??"").trim()}function Zne(r){let e=r.match(/^\[?v?(\d+)\.(\d+)\.(\d+)(?:[-+\]].*)?$/i)??r.match(/^\[?v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/i);if(!e)return{value:0,parsed:!1};let t=n=>Math.min(Number(n??"0"),999999);return{value:t(e[1])*1e12+t(e[2])*1e6+t(e[3]),parsed:!0}}function fW(r,e,t){switch(e.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=t?t(r,e.dateFormat||void 0,!1):null;return n&&n.isValid()?{value:n.valueOf(),parsed:!0}:{value:0,parsed:!1}}case"semver":return Zne(r);default:return{value:0,parsed:!0}}}function Jne(r,e){if(typeof r.value=="string"&&typeof e.value=="string")return r.value<e.value?-1:r.value>e.value?1:0;let t=r.value,n=e.value;return t<n?-1:t>n?1:0}function mW(r,e,t,n,i,o=0){let s=Fb(r),a=Jl(s).filter(f=>f.line>=o),l=a.filter(f=>f.level===t),c=fW(pW(e),n,i);if(l.length===0){let f=a.filter(p=>p.level<t).pop();return f?{mode:"after",line:Eu(s,f.line,!0)}:{mode:"bodyStart"}}let u=()=>{let f=l[l.length-1];return{mode:"after",line:Eu(s,f.line,!0)}};if(n.by==="insertion")return n.direction==="desc"?{mode:"before",line:l[0].line}:u();if(!c.parsed)return u();let d=n.unparseable??"bottom";for(let f of l){let p=fW(pW(s[f.line]),n,i),m;if(!p.parsed)m=d==="bottom";else{let v=Jne(c,p);m=n.direction==="desc"?v>0:v<0}if(m)return{mode:"before",line:f.line}}return u()}bb();function vP(r){let e=r.split(`
`);for(;e.length>1&&e[e.length-1].trim()==="";)e.pop();return e}function yP(r){return r.length===0||r.length===1&&r[0].trim()===""}function bP(r,e){if(e.length<=1){let t=eie(r,e[0]??"");return{start:t,end:t}}return tie(r,e)}function eie(r,e){let t=e.trimEnd(),n=-1;for(let i=0;i<r.length;i++){let o=r[i].trimStart();if(o===t)return i;if(o.startsWith(t)){let a=o.slice(t.length);if(/^\s*$/.test(a))return i;n===-1&&(n=i);continue}let s=o.indexOf(t);if(s!==-1){let a=o.slice(s+t.length);if(/^\s*$/.test(a))return i;n===-1&&(n=i)}}return n}function tie(r,e){let t=e.length,n=e.map(i=>hW(i));for(let i=0;i+t<=r.length;i++){let o=!0;for(let s=0;s<t;s++)if(hW(r[i+s])!==n[s]){o=!1;break}if(o)return{start:i,end:i+t-1}}return{start:-1,end:-1}}function hW(r){return r.trimEnd()}function gW(r,e,t){return r?Jl([e[t]??""]).length>0:!1}function rie(r,e){return r==="skip"?!0:r==="none"?!1:nie(e)}function nie(r){return/^\s{0,3}#{1,6}\s+\S/.test(r)}function wP(r,e,t,n){if(e<0)return e;let i=r[e]??"";if(!rie(n,i))return e;let s=t.endsWith(`
`)?Math.max(r.length-1,0):r.length,a=e;for(let l=e+1;l<s;l++){if(r[l].trim().length===0){a=l;continue}break}return a}function zS(r,e,t,n){if(e<0)return e;let i=e,o=e+1;for(;o<r.length&&r[o].trim().length===0;)i=o,o++;return i===e||o!==r.length||!n.endsWith(`
`)?e:t.endsWith(`
`)?Math.max(e,i-1):i}function vW(r){return r.includes(`
`)||r.includes("\r")}function yW(r,e){let t=r.indexOf(`
`,e);return t===-1?r.length:t>0&&r[t-1]==="\r"?t-1:t}function CP(r){let e=Z0(r);return e>0?r.slice(0,e).split(`
`).length-1:0}function bW(r,e){let t=CP(e),n=r.map((i,o)=>o<t?"":i);return Fb(n).map(i=>i.replace(/\r$/,""))}function wW(r,e,t,n){let i=e.split(`
`),o=i.slice(0,t+1).join(`
`),s=i.slice(t+1).join(`
`),l=(i[t+1]??"").trim(),c=e.endsWith(`
`)&&t+1===i.length-1,u=t+1<i.length&&!c&&l==="",d=n&&r.endsWith(`
`)&&u?r.slice(0,-1):r,f=!d.endsWith(`
`)&&l!==""?`
`:"";return{content:`${o}
${d}${f}${s}`,insertedEndOffset:o.length+1+d.length}}function CW(r,e,t,n=r.length){let i=e.length>0&&!r.endsWith(`
`)?`
`:"",o=Math.max(0,Math.min(n,r.length));if(t<=0)return{content:`${r}${i}${e}`,insertedEndOffset:o};let s=e.split(`
`),a=s.slice(0,t).join(`
`),l=s.slice(t).join(`
`);return{content:`${a}
${r}${i}${l}`,insertedEndOffset:a.length+1+o}}function EW(r,e,t,n){let i=n,o=i.includes(`\r
`)?`\r
`:`
`,s=e.mode==="before"?e.line:e.line+1,a=0;for(let w=0;w<s&&w<r.length;w++)a+=r[w].length+1;a>i.length&&(a=i.length);let l=i.slice(0,a),c=i.slice(a),u=s>0?(r[s-1]??"").replace(/\r$/,""):"",d=s<r.length?(r[s]??"").replace(/\r$/,""):"",f=t.split(`
`).map(w=>w.replace(/\r$/,""));f.length>1&&f[f.length-1]===""&&f.pop();let p=[];s>0&&u.trim()!==""&&p.push(""),p.push(...f),s<r.length&&d.trim()!==""&&p.push("");let m=p.join(o),v=l.length>0&&!/\n$/.test(l)?o:"",g=c.length>0||/\n$/.test(i)?o:"",y=l.length+v.length;return{content:`${l}${v}${m}${g}${c}`,insertedEndOffset:y+m.length}}bb();nh();UC();var oie=/^[ \t\r\n\f\v]*$/;function xW(r){return oie.test(r)}var HS=class extends Do{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.captureInsertionEndOffset=null}setDestinationFile(t){this.file=t,this.sourcePath=t.path,this.clipboardAttachmentLink=void 0,this.setTargetFolderPath(ro(t.path)),this.setPromptRunContext({destination:t.path,destinationKind:"file"})}setDestinationSourcePath(t){this.sourcePath=t,this.file=null,this.clipboardAttachmentLink=void 0,this.setTargetFolderPath(ro(t)),this.setPromptRunContext({destination:t,destinationKind:"file"})}setUseSelectionAsCaptureValue(t){this.useSelectionAsCaptureValue=t}setInsertAfterTargetOverride(t){this.insertAfterTargetOverride=t}getResolvedInsertAfterHeading(){return this.lastResolvedInsertAfterHeading}consumeCreatedClipboardAttachmentPaths(){let t=this.createdClipboardAttachmentPaths;return this.createdClipboardAttachmentPaths=[],t}getCaptureInsertionEndOffset(){return this.captureInsertionEndOffset}setCaptureInsertionEndOffset(t){this.captureInsertionEndOffset=typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}shouldUseSelectionForValue(){return this.useSelectionAsCaptureValue}async getSelectedTextForValue(){let t=await this.getSelectedText();return t.trim().length>0?t:""}getLinkSourcePath(){return this.sourcePath??this.file?.path??null}async getClipboardContent(){let t=await super.getClipboardContent();return t.length>0||!this.clipboardImageFallbackEnabled?t:this.clipboardAttachmentLink!==void 0?this.clipboardAttachmentLink??"":(this.clipboardAttachmentLink=await this.saveClipboardImageAsAttachment(),this.clipboardAttachmentLink??"")}async withClipboardImageFallback(t){let n=this.clipboardImageFallbackEnabled;this.clipboardImageFallbackEnabled=!0;try{return await t()}finally{this.clipboardImageFallbackEnabled=n}}async saveClipboardImageAsAttachment(){let t=navigator.clipboard;if(typeof t?.read!="function")return null;let n,i;try{if(n=await this.getFirstClipboardImageItem(t),!n)return null;i=await(await n.clipboardItem.getType(n.mimeType)).arrayBuffer()}catch{return null}let o=this.getLinkSourcePath()??"",s=await VC(this.app,i,n.mimeType,o);return this.createdClipboardAttachmentPaths.push(s.path),qC(this.app,s,o)}async getFirstClipboardImageItem(t){let n=await t.read();for(let i of n){let o=i.types.find(s=>_l[s]!==void 0);if(o)return{clipboardItem:i,mimeType:o}}return null}getCurrentFileLink(){let t=this.app.workspace.getActiveFile();if(!t)return null;let n=this.sourcePath??this.file?.path??"";return this.app.fileManager.generateMarkdownLink(t,n)}async formatContentWithFile(t,n,i,o){if(this.setCaptureInsertionEndOffset(null),this.choice=n,this.file=o,this.fileContent=i,!n||!o||i===null)return t;this.setTargetFolderPath(ro(o.path));let s=n.insertAfter.enabled||!!n.insertBefore?.enabled||n.prepend||!n.captureToActiveFile||n.activeFileWritePosition==="top"||n.activeFileWritePosition==="bottom";return await this.formatFileContent(t,s)}async formatContent(t,n){return this.choice=n,n?await this.formatFileContent(t):t}async formatFileContent(t,n=!0){let i=await this.withClipboardImageFallback(async()=>this.withPromptScope("captureText",t,async()=>super.formatFileContent(await this.expandTemplateLinebreaksOnce(t))));if(n&&this.file&&!this.templaterProcessed){let a=await hl(this.app,i,this.file);a&&(i=a),this.templaterProcessed=!0}if(xW(i))return this.fileContent;if(this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom"){let a=!this.choice.task,l=this.fileContent.length>0&&!this.fileContent.endsWith(`
`)&&!i.startsWith(`
`),c=a||l?`
`:"";return this.setCaptureInsertionEndOffset(this.fileContent.length+c.length+i.length),`${this.fileContent}${c}${i}`}return this.choice.insertAfter.enabled?await this.insertAfterHandler(i):this.choice.insertBefore?.enabled?await this.insertBeforeHandler(i):this.insertAtNoteBodyStartTracking(i)}async formatContentOnly(t){let n=await this.withClipboardImageFallback(async()=>this.withPromptScope("captureText",t,async()=>super.formatFileContent(await this.expandTemplateLinebreaksOnce(t))));return xW(n)?this.fileContent:n}async expandTemplateLinebreaksOnce(t){return this.linebreaksProcessed?t:(this.linebreaksProcessed=!0,this.expandFormatTemplateEscapes(t))}async expandFormatTemplateEscapes(t){let n=await this.replaceGlobalVarInString(t);return this.expandLinebreakEscapesOutsideTokens(n)}async insertAfterHandler(t){let n=this.insertAfterTargetOverride;if(this.choice.insertAfter?.inline&&n===null){let f=await this.formatLocationString(await this.expandFormatTemplateEscapes(this.choice.insertAfter.after));return await this.insertAfterInlineHandler(t,f)}let i=n??await this.formatLocationString(await this.expandFormatTemplateEscapes(this.choice.insertAfter.after));if(n===null){let f=i.split(`
`,1)[0];this.lastResolvedInsertAfterHeading=/^#+\s+\S/.test(f)?f.trim():null}let o=vP(i);if(yP(o))throw new ve("Insert-after target is empty after formatting.");let s=Jd(this.fileContent),a=this.isOrderedCreate()?bW(s,this.fileContent):s,{start:l,end:c}=bP(a,o);if(l===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(t,i);throw new ve(`Insert-after target not found: '${i}'.`)}let d;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let f=Eu(s,l,this.considerSubsectionsForAnchor(s,l)),p=Math.max(f??s.length-1,c);d=zS(s,p,this.fileContent,t)}else{let f=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";d=wP(s,c,this.fileContent,f)}return this.insertTextAfterPositionInBody(t,this.fileContent,d)}async insertBeforeHandler(t){let n=this.choice.insertBefore;if(!n)throw new ve("Insert-before settings are missing.");let i=await this.formatLocationString(await this.expandFormatTemplateEscapes(n.before)),o=vP(i);if(yP(o))throw new ve("Insert-before target is empty after formatting.");let s=Jd(this.fileContent),{start:a}=bP(s,o);if(a===-1){if(n.createIfNotFound)return await this.createInsertBeforeIfNotFound(t,i);throw new ve(`Insert-before target not found: '${i}'.`)}return this.insertTextBeforePositionInBody(t,this.fileContent,a)}async insertAfterInlineHandler(t,n){if(vW(n))throw new ve("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(t,n);throw new ve(`Inline insert-after target not found: '${n}'.`)}let o=i+n.length;if(this.setCaptureInsertionEndOffset(o+t.length),this.choice.insertAfter?.replaceExisting){let s=yW(this.fileContent,o);return this.fileContent.slice(0,o)+t+this.fileContent.slice(s)}return this.fileContent.slice(0,o)+t+this.fileContent.slice(o)}async createInsertAfterIfNotFound(t,n){let i=`${n}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===$i)return this.insertAtNoteBodyStartTracking(i);if(this.choice.insertAfter?.createIfNotFoundLocation===ul)return this.setCaptureInsertionEndOffset(this.fileContent.length+1+i.length),`${this.fileContent}
${i}`;if(this.choice.insertAfter?.createIfNotFoundLocation===dl){let o=ln(this.app);if(!o)throw new ve(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position: no active markdown editor.`);try{let a=o.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let c=Jd(this.fileContent),u=Eu(c,a,this.considerSubsectionsForAnchor(c,a));a=zS(c,u??c.length-1,this.fileContent,i)}return this.insertTextAfterPositionInBody(i,this.fileContent,a)}catch{throw new ve(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position.`)}}if(this.choice.insertAfter?.createIfNotFoundLocation===Ds)return this.createInsertAfterOrdered(t,n);throw new ve(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`)}isOrderedCreate(){return!!this.choice.insertAfter?.createIfNotFound&&this.choice.insertAfter?.createIfNotFoundLocation===Ds}considerSubsectionsForAnchor(t,n){return gW(!!this.choice.insertAfter?.considerSubsections,t,n)}createInsertAfterOrdered(t,n){let i=this.choice.insertAfter?.orderBy??{by:"insertion",direction:"desc",unparseable:"bottom"},o=n.split(/\r?\n/,1)[0],s=Jl([o])[0]?.level??0,a=`${n}
${t}`;if(s===0)return this.insertAtNoteBodyStartTracking(a);let l=Jd(this.fileContent),c=l.map(g=>g.replace(/\r$/,"")),u=CP(this.fileContent),d=Fb(c),f=o.replace(/\r$/,"").trimEnd(),p=d.findIndex((g,y)=>y>=u&&g.trimEnd()===f);if(p!==-1){let g=this.choice.insertAfter?.insertAtEnd?zS(d,Eu(d,p,this.considerSubsectionsForAnchor(d,p))??d.length-1,this.fileContent,t):wP(d,p,this.fileContent,this.choice.insertAfter?.blankLineAfterMatchMode??"auto");return this.insertTextAfterPositionInBody(t,this.fileContent,g)}let m=typeof window<"u"?window.moment:void 0,v=mW(c,o,s,i,m,u);return v.mode==="bodyStart"?this.insertAtNoteBodyStartTracking(a):this.spliceOrderedSection(l,v,a)}spliceOrderedSection(t,n,i){let{content:o,insertedEndOffset:s}=EW(t,n,i,this.fileContent);return this.setCaptureInsertionEndOffset(s),o}async createInsertBeforeIfNotFound(t,n){let i=this.choice.insertBefore;if(!i)throw new ve("Insert-before settings are missing.");let o=t.endsWith(`
`)||t.length===0?`${t}${n}`:`${t}
${n}`;if(i.createIfNotFoundLocation===$i)return this.insertAtNoteBodyStartTracking(o,t.length);if(i.createIfNotFoundLocation===ul)return this.setCaptureInsertionEndOffset(this.fileContent.length+1+t.length),`${this.fileContent}
${o}`;if(i.createIfNotFoundLocation===dl){let s=ln(this.app);if(!s)throw new ve(`Unable to insert line '${i.before}' at cursor position: no active markdown editor.`);try{let a=s.editor.getCursor();return this.insertTextBeforePositionInBody(o,this.fileContent,a.line,t.length)}catch{throw new ve(`Unable to insert line '${i.before}' at cursor position.`)}}throw new ve(`Unknown createIfNotFoundLocation: ${i.createIfNotFoundLocation}`)}async createInlineInsertAfterIfNotFound(t,n){let i=`${n}${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===$i)return this.insertAtNoteBodyStartTracking(i);if(this.choice.insertAfter?.createIfNotFoundLocation===ul)return this.setCaptureInsertionEndOffset(this.fileContent.length+1+i.length),`${this.fileContent}
${i}`;if(this.choice.insertAfter?.createIfNotFoundLocation===dl){let o=ln(this.app);if(!o)throw new ve(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position: no active markdown editor.`);try{let a=o.editor.getCursor().line;return this.insertTextAfterPositionInBody(i,this.fileContent,a)}catch{throw new ve(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position.`)}}throw new ve(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`)}insertAtNoteBodyStartTracking(t,n=t.length){let i=J0(this.fileContent,t);if(i.insertedStartOffset===null)return this.setCaptureInsertionEndOffset(null),i.content;let o=Math.max(0,Math.min(n,t.length));return this.setCaptureInsertionEndOffset(i.insertedStartOffset+o),i.content}insertTextAfterPositionInBody(t,n,i){let{content:o,insertedEndOffset:s}=wW(t,n,i,!!this.choice.task);return this.setCaptureInsertionEndOffset(s),o}insertTextBeforePositionInBody(t,n,i,o=t.length){let{content:s,insertedEndOffset:a}=CW(t,n,i,o);return this.setCaptureInsertionEndOffset(a),s}};Je();es();var EP=`${dg}.`;function xP(r){return`${EP}${r}`}function Eh(r){return r.startsWith(EP)&&r.length>EP.length}function TP(r){return r===dg||Eh(r)}function TW(r,e){let t=qc(r,e);return t?r.get(t)==null?null:t:null}function sie(r){let e=0;for(let t of r.keys())Eh(t)&&e++;return e}function SW(r,e){if(!r)return;let t=r.get(xP(e));if(typeof t=="string"&&t.length>0)return t;if(sie(r)>1)return;let n=r.get(dg);if(typeof n=="string"&&n.length>0)return n}function _W(r,e){return TP(e)?TW(r,e):null}function kW(r,e,t){return t!==1||!Eh(e)?!1:TW(r,dg)!==null}MS();De();od();Dt();rr();ih();oh();var AW=require("obsidian");Je();Bi();Aa();function DW(r,e){let t=r.trim().replace(/^\/+/,"");if(t==="")return{kind:"vault"};let n=Of(t);if(n){if(!n.field)throw new ve("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=Mf(t);if(i){if(i.multiSelect)throw new ve("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=In(t,"Capture target file path");if(li.test(o))throw new ve(`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(Ht.test(o)||Cr.test(o))return{kind:"file",path:o};let l=e.normalizeMarkdownFilePath("",a),u=e.getAbstractFileByPath(l)instanceof AW.TFile;return e.isFolder(a)&&!u?{kind:"folder",folder:a}:{kind:"file",path:o}}Je();function WS(r){return`${r.replace(/^\/+/,"").replace(Ht,"")}.md`}function jS(r,e,t){if(t)return null;let n=(e??"").trim().replace(/^\/+/,"");if(_c(n))return null;let i=Of(n),o=!!i&&!!i.field,s=o?null:Mf(n),a=!!s&&!s.multiSelect,l=!o&&!s&&n.startsWith("#"),c=n.endsWith("/"),u=!l&&!o&&!a&&!c&&(Ht.test(n)||Cr.test(n)||li.test(n)),d=n.replace(/\/+$/,""),f=!l&&!o&&!a&&!u&&(n===""||r.isFolder(d)&&!r.markdownFileExists(d)),p=!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(f||p){let m=d;return{kind:"folder",folderPathSlash:m===""?"":`${m}/`}}return null}yg();Aa();Sa();sf();qp();nh();wo();lP();fS();Bi();mS();G0();function IW(r){let e=r.insertAfter.enabled||!!r.insertBefore?.enabled;return r.captureToActiveFile&&!e&&r.newLineCapture?.enabled?r.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":r.captureToActiveFile&&!e?r.activeFileWritePosition==="top"?"activeFileTop":r.activeFileWritePosition==="bottom"||r.prepend?"append":"currentLine":r.insertAfter.enabled?"insertAfter":r.insertBefore?.enabled?"insertBefore":r.prepend?"prepend":"append"}Je();Bi();function SP(r){return r?.type==="text"?"text":r?.type==="file"||r?.file?"file":typeof r?.text=="string"?"text":"unsupported"}function aie(r,e){let t=e.id;if(!t)return null;let n=r.getData?.();return n?.nodes?.length?n.nodes.find(i=>i.id===t)??null:null}function FW(r,e){if(r==="text"){if(e==="currentLine")return"Canvas capture does not support 'At cursor' for text cards. Use top, bottom, insert-after, or insert-before placement.";if(e==="newLineAbove"||e==="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"&&(e==="currentLine"||e==="newLineAbove"||e==="newLineBelow")?"Canvas file cards do not support cursor-based capture modes. Use top, bottom, insert-after, or insert-before modes.":null}function lie(r){let e=r.file;return e?typeof e=="string"?e:typeof e=="object"&&"path"in e&&typeof e.path=="string"?e.path:null:null}function _P(r){return!!r&&"path"in r&&"extension"in r}function cie(r){let t=(r.workspace.activeLeaf??r.workspace.getMostRecentLeaf?.()??null)?.view;return!t||t.getViewType?.()!=="canvas"?null:t}function uie(r,e){let t=e.file??r.workspace.getActiveFile?.();if(!t)throw new ve("Cannot capture to Canvas because no active Canvas file is available.");return t}function die(r){let e=r.selection?Array.from(r.selection):[];if(e.length!==1)throw new ve("Canvas capture requires exactly one selected node.");return e[0]}function PW(r){let e=lie(r);if(!e)throw new ve("Selected Canvas file card does not have a valid linked file path.");if(!Ht.test(e))throw new ve("Canvas file card targets markdown files only in this version.");return e}function pie(r,e){let t=PW(e),n=r.vault.getAbstractFileByPath(t);if(!_P(n))throw new ve(`Selected Canvas file card target not found: ${t}`);return n}function fie(r,e){let t=PW(e),n=r.vault.getAbstractFileByPath(t);if(!n)return{targetPath:t};if(!_P(n))throw new ve(`Selected Canvas file card target not found: ${t}`);return{targetPath:t,targetFile:n}}function mie(r,e){let t;try{t=JSON.parse(r)}catch{throw new ve(`Canvas file is not valid JSON: ${e}`)}if(!t||typeof t!="object")throw new ve(`Canvas file has invalid structure: ${e}`);if(!Array.isArray(t.nodes))throw new ve(`Canvas file has no nodes array: ${e}`);return t}function $W(r,e){let t=r,n=cie(t);if(!n)return null;let i=n.canvas;if(!i)throw new ve("Canvas capture is unavailable in this Obsidian version.");let o=uie(t,n),s=die(i),a=aie(i,s),l=SP(s);if(l==="unsupported"&&a&&(l=SP(a)),l==="unsupported")throw new ve("Canvas capture currently supports only text and file cards.");let c=FW(l,e);if(c)throw new ve(c);if(l==="text")return{kind:"text",source:"active",canvas:i,canvasFile:o,node:s,nodeData:a};let u=s.file||!a?.file?s:{...s,file:a.file};return{kind:"file",source:"active",canvasFile:o,node:u,targetFile:pie(t,u)}}async function MW(r,e,t,n){let i=t.trim();if(!i)throw new ve("Canvas node id is required for Canvas node capture.");let o=r.vault.getAbstractFileByPath(e);if(!_P(o))throw new ve(`Canvas target not found: ${e}`);if(!Cr.test(o.path))throw new ve("Canvas node capture requires the target path to be a .canvas file.");let s=await r.vault.read(o),a=mie(s,o.path),l=a.nodes.findIndex(v=>v.id===i);if(l===-1)throw new ve(`Canvas node id '${i}' was not found in ${o.path}.`);let c=a.nodes[l],u=SP(c);if(u==="unsupported")throw new ve("Canvas capture currently supports only text and file cards.");let d=FW(u,n);if(d)throw new ve(d);if(u==="text")return{kind:"text",source:"configured",canvasFile:o,rawCanvas:s,canvasData:a,nodeData:c,nodeIndex:l};let f=r,{targetPath:p,targetFile:m}=fie(f,c);return{kind:"file",source:"configured",canvasFile:o,nodeData:c,targetPath:p,targetFile:m}}function OW(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 RW(r,e,t){if(e.source==="active"){typeof e.node.setText=="function"?e.node.setText(t):e.node.text=t,e.canvas.requestSave?.();return}if(await r.vault.read(e.canvasFile)!==e.rawCanvas)throw new ve("Canvas target changed while capture was running. Re-run capture to avoid overwriting newer Canvas edits.");e.nodeData.text=t,e.canvasData.nodes[e.nodeIndex]=e.nodeData,await r.vault.modify(e.canvasFile,JSON.stringify(e.canvasData,null," "))}db();var GS=4e3,hie=/^[ \t\r\n\f\v]*$/;function gie(r){return hie.test(r)}var vie=/\{\{(?:VALUE|FILE|FIELD):[^}]*\|\s*multi\s*(?=[:}|]|$)[^}]*\}\}/gi,yie=/\|\s*format\s*:\s*(?:inline|spaced|yaml|markdown)\s*(?=\||}})/i;function bie(r){return Array.from(r.matchAll(vie)).some(e=>!yie.test(e[0]))}var YS=class extends vh{constructor(t,n,i,o,s=null){super(t);this.choiceExecutor=o;this.originLeaf=s;this.capturePropertyVars=new Map;this.suppressFrontmatterCollection=!1;this.resolvedInsertAfterHeading=null;this.choice=i,this.plugin=n,this.outcome=new yh(o),this.formatter=new HS(t,n,o),this.formatter.setPromptRunContext({draftScopeId:i.id,choiceName:i.name})}captureResolvedOrderedHeading(){if(this.choice.insertAfter?.enabled&&this.choice.insertAfter.createIfNotFoundLocation===Ds){let t=this.formatter.getResolvedInsertAfterHeading();t&&(this.resolvedInsertAfterHeading=t)}}showSuccessNotice(t,{wasNewFile:n,action:i}){let o=`'${t.basename}'`;if(n){new ec.Notice(`Created and captured to ${o}`,GS);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 ec.Notice(a,GS)}showNothingToCaptureNotice(t,{wasNewFile:n}){let i=`'${t.basename}'`;new ec.Notice(n?`Created ${i} \u2014 nothing to capture (no content)`:`Nothing to capture \u2014 ${i} unchanged`,GS)}hasActiveMarkdownCaptureContext(){let t=!!this.app.workspace.getActiveFile(),n=!!ln(this.app);return t&&n}shouldSkipRequiredCanvasLinkInsertion(t,n){return n&&t.destination?.type!=="specifiedFile"&&t.requireActiveFile&&!this.hasActiveMarkdownCaptureContext()}async insertCaptureLink(t,n,{isCanvasTriggered:i}){if(!n.enabled)return;if(n.destination?.type==="specifiedFile"){await Ww(this.app,t,n);return}if(id(n.placement)){await ad(this.app,t,n);return}if(this.shouldSkipRequiredCanvasLinkInsertion(n,i)){this.plugin.settings.showCaptureNotification&&new ec.Notice("Canvas capture skipped link insertion because no Markdown editor is focused.",GS);return}let o=this.choiceExecutor.focusedProperty;if(o){await Yw(this.app,o,t);return}await ad(this.app,t,n)}async copyCapturedFileLinkToClipboard(t){if(this.choice.copyLinkToClipboard)try{await jw(t)}catch(n){P.logWarning(`Could not copy link to clipboard for '${t.path}': ${n instanceof Error?n.message:String(n)}`)}}validateAppendLinkDestination(t){return!t.enabled||t.destination.type!=="specifiedFile"||vg(this.app,t.destination)?!0:(this.failRun(`Append link target file not found or is not a Markdown file: ${t.destination.path}`),!1)}async run(){let t=!1;try{this.capturePropertyVars.clear();let n=xc(this.choice.appendLink);if(this.formatter.setLinkToCurrentFileBehavior(n.enabled&&!n.requireActiveFile?"optional":"required"),!this.validateAppendLinkDestination(n))return;let i=this.choice.useSelectionAsCaptureValue,o=this.plugin.settings.useSelectionAsCaptureValue??!0,s=typeof i=="boolean"?i:o;this.formatter.setUseSelectionAsCaptureValue(s);let a=IW(this.choice),l=a==="currentLine"||a==="newLineAbove"||a==="newLineBelow",c=this.choice.captureToActiveFile?$W(this.app,a):null,u=await this.resolveConfiguredCanvasTarget(a),d=c??u;if(d?.kind==="text"){await this.handleCanvasTextCapture(d,a,n,()=>{t=!0});return}if(d?.kind==="file"&&(a==="insertAfter"&&this.choice.insertAfter?.createIfNotFound&&this.choice.insertAfter?.createIfNotFoundLocation==="cursor"||a==="insertBefore"&&this.choice.insertBefore?.createIfNotFound&&this.choice.insertBefore?.createIfNotFoundLocation==="cursor"))throw new ve("Canvas file cards do not support creating missing line targets at cursor. Use top or bottom.");let f=d?.kind==="file"?d.source==="configured"?d.targetFile?.path??d.targetPath:d.targetFile.path:await this.getFormattedPathToCaptureTo(this.choice.captureToActiveFile);if(!d&&!this.choice.captureToActiveFile&&Cr.test(f))throw new ve("Capture to a .canvas file requires a target canvas node id.");let p=this.getCaptureContent(),m,v=await this.fileExists(f);!v&&this.choice?.createFileIfItDoesntExist?.enabled&&mb(f),this.isInsertAfterHeadingMode()&&!Cr.test(f)&&await this.maybeResolveInsertAfterHeading(await this.readNoteBodyForHeadingPicker(f,v));let g=!v&&!!this.choice?.createFileIfItDoesntExist?.enabled&&!this.choice?.createFileIfItDoesntExist?.createWithTemplate;if(this.suppressFrontmatterCollection=!g,this.suppressFrontmatterCollection&&bie(this.choice?.format?.format??"")&&P.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."),v)m=this.onFileExists.bind(this);else if(this.choice?.createFileIfItDoesntExist?.enabled)m=((re,L,W)=>this.onCreateFileIfItDoesntExist(re,L,n));else throw new ve(`Target file missing: ${f}. Enable "Create file if it doesn't exist" or choose an existing file.`);let{file:y,newFileContent:w,captureContent:T,priorContent:b,cursorEndOffset:E,cursorPlacementSafe:C=!0}=await m(f,p),_=null,I=C,q=!1,B=gie(T);if(this.captureResolvedOrderedHeading(),l)if(B)t=!0;else{let re=await hl(this.app,T,y),L=!1;switch(a){case"currentLine":L=Rk(re,this.app);break;case"newLineAbove":L=Nk(re,this.app);break;case"newLineBelow":L=Bk(re,this.app);break}if(!L){await this.cleanupCreatedClipboardAttachments(),this.failRun(`Capture "${this.choice.name}": no active Markdown editor to insert into.`);return}t=!0}else{await this.app.vault.modify(y,w),t=!0,this.choice.templater?.afterCapture==="wholeFile"&&(await td(this.app,y),I=!1,q=!0);let re=await this.applyCapturePropertyVars(y);re&&(I=!1),re&&(q=!0),_=I?w:null}let J=l?B?"unchanged":"changed":v?w!==b||q?"changed":"unchanged":"created";if(this.outcome.success(y,J),this.plugin.settings.showCaptureNotification&&(B?this.showNothingToCaptureNotice(y,{wasNewFile:!v}):this.showSuccessNotice(y,{wasNewFile:!v,action:a})),await this.copyCapturedFileLinkToClipboard(y),await this.insertCaptureLink(y,n,{isCanvasTriggered:!!d}),this.choice.openFile&&y){let re=qr(this.choice.fileOpening),L=re.focus??!0;ld(this.app,y,L)||await gl(this.app,y,{...re,originLeaf:this.originLeaf}),!await Ec(this.app,y)&&I&&L&&_!==null&&typeof E=="number"&&Vk(this.app,y,E,_)}}catch(n){if(t||await this.cleanupCreatedClipboardAttachments(),bu(n,{logPrefix:"Capture execution aborted",noticePrefix:"Capture execution aborted",defaultReason:"Capture aborted"})){this.choiceExecutor.signalAbort?.(n);return}mi.getInstance().markExecutionScopeFailed(),this.outcome.failure(LS(n)),We(n,`Error running capture choice "${this.choice.name}"`)}finally{t&&this.formatter.consumeCreatedClipboardAttachmentPaths()}}failRun(t){mi.getInstance().markExecutionScopeFailed(),P.logError(t),this.outcome.failure(t)}async cleanupCreatedClipboardAttachments(){let t=this.formatter.consumeCreatedClipboardAttachmentPaths();for(let n of t)try{let i=this.app.vault.getAbstractFileByPath(n);i instanceof ec.TFile&&await this.app.fileManager.trashFile(i)}catch(i){P.logWarning(`QuickAdd: failed to clean up clipboard attachment '${n}': ${String(i)}`)}}async handleCanvasTextCapture(t,n,i,o){if(n==="currentLine"||n==="newLineAbove"||n==="newLineBelow")throw new ve("Canvas text cards support top, bottom, insert-after, and insert-before positions only.");if(n==="insertAfter"&&this.choice.insertAfter?.createIfNotFound&&this.choice.insertAfter?.createIfNotFoundLocation==="cursor"||n==="insertBefore"&&this.choice.insertBefore?.createIfNotFound&&this.choice.insertBefore?.createIfNotFoundLocation==="cursor")throw new ve("Canvas text cards do not support creating missing line targets at cursor. Use top or bottom.");let s=t.canvasFile;this.formatter.setTitle(rh(s.basename)),this.formatter.setDestinationFile(s);let a=this.getCaptureContent(),l=OW(t);this.isInsertAfterHeadingMode()&&await this.maybeResolveInsertAfterHeading(l);let c=await this.formatter.formatContentWithFile(a,this.choice,l,s);this.captureResolvedOrderedHeading();let u=c===l;if(u||await RW(this.app,t,c),o(),this.outcome.success(s,u?"unchanged":"changed"),this.plugin.settings.showCaptureNotification&&(u?this.showNothingToCaptureNotice(s,{wasNewFile:!1}):this.showSuccessNotice(s,{wasNewFile:!1,action:n})),await this.copyCapturedFileLinkToClipboard(s),await this.insertCaptureLink(s,i,{isCanvasTriggered:!0}),this.choice.openFile&&s){let d=qr(this.choice.fileOpening),f=d.focus??!0;ld(this.app,s,f)||await gl(this.app,s,{...d,originLeaf:this.originLeaf}),await Ec(this.app,s)}}async resolveConfiguredCanvasTarget(t){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 Cr.test(o)?await MW(this.app,o,i,t):null}assertInteractiveCaptureTarget(){if(this.choiceExecutor.interactive===!1)throw new ve(`'${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.`)}async maybeResolveInsertAfterHeading(t){let n=this.choice.insertAfter;if(!n?.enabled||!n.promptHeading)return;let i=!!n.createIfNotFound,o=Jd(t),s=Jl(o),a=s.map(p=>o[p.line]),l=s.map(p=>`${" ".repeat(Math.max(0,p.level-1))}${p.text}`),c=s.map(p=>p.text),u="Choose a heading to insert under",d=String(await cs(this.choiceExecutor,{remote:p=>us(p,{items:a.map((m,v)=>({value:m,title:l[v]??m})),placeholder:u,allowCustomInput:i,what:"the heading picker"}),headless:()=>{throw new ve(`'${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:()=>Or.Suggest(this.app,l,a,{allowCustomValue:i,placeholder:u,emptyStateText:i?"No headings found \u2014 type a heading to create":"No headings found in the target note",customValueLabel:p=>`Insert after new line: ${p}`})}));Jn(!!d&&d.length>0,"No heading selected for capture."),this.formatter.setInsertAfterTargetOverride(d);let f=a.indexOf(d);this.resolvedInsertAfterHeading=f>=0?c[f]:d}isInsertAfterHeadingMode(){return!!this.choice.insertAfter?.enabled&&!!this.choice.insertAfter.promptHeading}async readNoteBodyForHeadingPicker(t,n){if(!n)return"";let i=this.app.vault.getAbstractFileByPath(t);return i instanceof ec.TFile?await this.app.vault.read(i):""}getCaptureContent(){let t;return this.choice.format.enabled?t=this.choice.format.format:t=zo,this.choice.task&&(t=`- [ ] ${t}
`),t}async getFormattedPathToCaptureTo(t){if(t){let a=this.app.workspace.getActiveFile();return Jn(a,"Cannot capture to active file - no active file."),a.path}let n=this.getPreselectedCaptureTargetPath();if(n!==void 0){let a=jS({isFolder:l=>zp(this.app,l),markdownFileExists:l=>this.app.vault.getAbstractFileByPath(WS(l))instanceof ec.TFile},this.choice.captureTo??"",!1);if(a){let l=this.confinePreselectedToScope(a,n);if(l!==null)return this.normalizeCaptureFilePath(l)}}let i=this.choice.captureTo,o=await this.formatter.formatFileName(i,"captureTarget"),s=this.resolveCaptureTarget(o);switch(s.kind){case"vault":return this.selectFileInFolder("",!0);case"filter":return this.selectFileWithFilter(s.filter);case"property":return this.selectFileWithProperty(s.field,s.value,s.filter);case"folder":return this.selectFileInFolder(s.folder,!1);case"file":return this.normalizeCaptureFilePath(s.path)}}getPreselectedCaptureTargetPath(){return SW(this.choiceExecutor?.variables,this.choice.id)}confinePreselectedToScope(t,n){let i=this.stripLeadingSlash(n);if(t.kind==="folder")return t.folderPathSlash&&!i.startsWith(t.folderPathSlash)?`${t.folderPathSlash}${i}`:i;if(this.resolveScopeFiles(t).some(l=>l.path===i))return i;if(!(this.choice.createFileIfItDoesntExist?.enabled??!1))return null;let a=new Set(this.app.vault.getMarkdownFiles().map(l=>l.basename.toLowerCase()));return this.captureTargetAlreadyExists(i,a)?null:i}resolveScopeFiles(t){switch(t.kind){case"filter":return Hp(this.app,t.filter);case"property":return Wp(this.app,t.field,t.value,t.filter);case"tag":return xg(this.app,t.tag);case"folder":return ho(this.app,t.folderPathSlash)}}resolveCaptureTarget(t){return DW(t,{getAbstractFileByPath:n=>this.app.vault.getAbstractFileByPath(n),isFolder:n=>zp(this.app,n),normalizeMarkdownFilePath:(n,i)=>this.normalizeMarkdownFilePath(n,i)})}captureTargetExists(t,n){let i=n.startsWith(t)?n:`${t}${n}`,o;try{o=In(i,"Capture target file path")}catch{return!1}let s=[o];return/\.(md|canvas)$/i.test(o)||s.push(`${o}.md`,`${o}.canvas`),s.some(a=>!!this.app.vault.getAbstractFileByPath(a))}async selectFileInFolder(t,n){let i=t.endsWith("/")||n?t:`${t}/`,o=ho(this.app,i),s=this.choice.createFileIfItDoesntExist?.enabled??!1;Jn(s||o.length>0,`Folder ${i} is empty.`);let a=ep(o,tp(this.app)),l=a.map(v=>v.path),c=Sl(a,v=>this.app.metadataCache.getFileCache(v)),u=l.map((v,g)=>`${c[g]??v} ${v}`),d=new Set(c.map(v=>v.toLowerCase())),f=s?"Choose a note or type to create one":void 0,p=String(await cs(this.choiceExecutor,{remote:v=>us(v,{items:l.map((g,y)=>({value:g,title:c[y]??g})),placeholder:f,allowCustomInput:s,what:"the capture-target picker"}),headless:()=>{throw this.assertInteractiveCaptureTarget(),new Error("unreachable")},app:()=>Or.Suggest(this.app,c,l,{placeholder:f,emptyStateText:s?"Type a note name to create it":void 0,renderItem:(v,g)=>_b(g,v,this.app),searchItems:u,allowCustomValue:s,customValueLabel:v=>`Create new note: ${v}`,valueExists:v=>d.has(v.toLowerCase())||this.captureTargetExists(i,v)})}));Jn(!!p&&p.length>0,"No file selected for capture.");let m=p.startsWith(`${i}`)?p:`${i}${p}`;return await this.formatFilePath(m)}async selectFileWithFilter(t){let n=Hp(this.app,t);return this.selectFileFromSet(n,"No files matched the capture target filters.")}async selectFileWithProperty(t,n,i){let o=Wp(this.app,t,n,i),s=n!==void 0?`${t}=${n}`:t;return this.selectFileFromSet(o,`No notes with property ${s}.`)}captureTargetAlreadyExists(t,n){let i=t.trim();if(!i)return!1;let o;try{o=In(i,"Capture target file path")}catch{return!1}let s=o.replace(/\.(md|canvas)$/i,"");if([o,`${s}.md`,`${s}.canvas`].some(c=>!!this.app.vault.getAbstractFileByPath(c)))return!0;let l=s.slice(s.lastIndexOf("/")+1);return n.has(l.toLowerCase())}async selectFileFromSet(t,n){let i=this.choice.createFileIfItDoesntExist?.enabled??!1;Jn(i||t.length>0,n);let o=ep(t,tp(this.app)),s=o.map(m=>m.path),a=Sl(o,m=>this.app.metadataCache.getFileCache(m)),l=s.map((m,v)=>`${a[v]??m} ${m}`),c=new Set(this.app.vault.getMarkdownFiles().map(m=>m.basename.toLowerCase())),u=new Set(a.map(m=>m.toLowerCase())),d=m=>u.has(m.toLowerCase())||this.captureTargetAlreadyExists(m,c),f=i?"Choose a note or type to create one":void 0,p=String(await cs(this.choiceExecutor,{remote:async m=>{let v=await us(m,{items:s.map((g,y)=>({value:g,title:a[y]??g})),placeholder:f,allowCustomInput:i,what:"the capture-target picker"});if(!s.includes(v)&&d(v))throw new Error(`"${v}" 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 v},headless:()=>{throw this.assertInteractiveCaptureTarget(),new Error("unreachable")},app:()=>Or.Suggest(this.app,a,s,{placeholder:f,emptyStateText:i?"Type a note name to create it":void 0,renderItem:(m,v)=>_b(v,m,this.app),searchItems:l,allowCustomValue:i,customValueLabel:m=>`Create new note: ${m}`,valueExists:d})}));return Jn(!!p&&p.length>0,"No file selected for capture."),await this.formatFilePath(p)}async onFileExists(t,n){let i=this.getFileByPath(t);if(!i)throw new Error("File not found");this.formatter.setTitle(i.basename),this.formatter.setDestinationFile(i);let o=await this.collectIfFrontmatter(()=>this.formatter.formatContentOnly(n));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let s=await this.app.vault.read(i),a=await this.collectIfFrontmatter(()=>this.formatter.formatContentWithFile(o,this.choice,s,i));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let l=this.formatter.getCaptureInsertionEndOffset(),c=await this.app.vault.read(i),u=a,d=!0;if(c!==s){let f=cW(c,s,a);Jn(f.isSuccess(),()=>`The file ${t} has been modified since the last read.
QuickAdd could not merge the versions two without conflicts, and will not modify the file.
This is in order to prevent data loss.`),u=f.joinedResults(),d=!1}return{file:i,newFileContent:u,captureContent:o,priorContent:c,cursorEndOffset:l??void 0,cursorPlacementSafe:d}}async onCreateFileIfItDoesntExist(t,n,i){mb(t);let o=rh(t);this.formatter.setTitle(o),this.formatter.setDestinationSourcePath(t);let s=await this.collectIfFrontmatter(()=>this.formatter.formatContentOnly(n));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let a="";if(this.choice.createFileIfItDoesntExist.createWithTemplate){let f=new hb(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);i?.enabled&&!i.requireActiveFile&&f.setLinkToCurrentFileBehavior("optional"),f.setTargetFolderPath(ro(t)),f.setPromptRunContext({draftScopeId:`${this.choice.id}#${this.choice.createFileIfItDoesntExist.template}`,choiceName:this.choice.name,destination:t,destinationKind:"file"}),a=await f.run();let p=f.getAndClearTemplatePropertyVars();P.logMessage(`CaptureChoiceEngine: Collected ${p.size} template property variables`),p.size>0&&P.logMessage(`Variables: ${Array.from(p.keys()).join(", ")}`),this.templatePropertyVars=p}let l=await this.createFileWithInput(t,a,{suppressTemplaterOnCreate:this.choice.createFileIfItDoesntExist.createWithTemplate});this.choice.createFileIfItDoesntExist.createWithTemplate&&this.templatePropertyVars&&eh(l,this.templatePropertyVars)&&await th(this.app,l,this.templatePropertyVars),this.choice.createFileIfItDoesntExist.createWithTemplate&&a?await td(this.app,l):hg(this.app)&&await $k(this.app,l);let c=await this.app.vault.read(l),u=await this.collectIfFrontmatter(()=>this.formatter.formatContentWithFile(s,this.choice,c,l));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let d=this.formatter.getCaptureInsertionEndOffset();return{file:l,newFileContent:u,captureContent:s,priorContent:c,cursorEndOffset:d??void 0,cursorPlacementSafe:!0}}async formatFilePath(t){let n=await this.formatter.formatFileName(t,"captureTarget");return this.normalizeCaptureFilePath(n)}normalizeCaptureFilePath(t){let n=In(this.stripLeadingSlash(t),"Capture target file path");if(li.test(n))throw new ve(`Capture to '.base' files is not supported (${n}). Use a Template choice instead.`);let i=this.normalizeCaptureFilePathExtension(n);if(!rh(i).trim())throw new ve(`Capture target file name is empty after formatting ('${i}'). Make sure the tokens in 'Capture to' produce a value.`);if(Pr(i))throw new ve(`Refusing to capture to a file outside the vault: "${i}".`);return i}normalizeCaptureFilePathExtension(t){let n=t.match(Ht)?.[0];if(n)return`${In(t.replace(Ht,""),"Capture target file path")}${n}`;let i=t.match(Cr)?.[0];return i?`${In(t.replace(Cr,""),"Capture target file path")}${i}`:this.normalizeMarkdownFilePath("",t)}collectIfFrontmatter(t){return this.suppressFrontmatterCollection?t():this.formatter.withTemplatePropertyCollection(t)}mergeCapturePropertyVars(t){if(!(!t||t.size===0)){for(let[n,i]of t)this.capturePropertyVars.set(n,i);P.logMessage(`CaptureChoiceEngine: Accumulated ${this.capturePropertyVars.size} structured capture variables`)}}async applyCapturePropertyVars(t){return this.capturePropertyVars.size===0?!1:eh(t,this.capturePropertyVars)?(P.logMessage(`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`),await th(this.app,t,this.capturePropertyVars),this.capturePropertyVars.clear(),!0):(this.capturePropertyVars.clear(),!1)}};pb();var Io=require("obsidian");Qi();rr();Er();ht();It();qp();var kP=require("obsidian");Je();Ul();Dt();rr();function LW(r){let e=r.split("/").pop()??r,t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}function AP(r){let e=new au(LW(r));return e.id=`folder-template:${r}`,e.templatePath=r,e.openFile=!0,e.fileNameFormat={enabled:!0,format:zo},e.discoverExistingNotesBeforeCreate=!0,e}function DP(r){return ui(r.settings.templateFolderPaths).length>0}function wie(r,e){let t=r.lastIndexOf("/"),n=t===-1?"":r.slice(0,t),i=e.createDiv({cls:"suggestion-content"});i.createDiv({cls:"suggestion-title",text:LW(r)}),n&&(e.classList.add("mod-complex"),i.createDiv({cls:"suggestion-note",text:n}))}async function Cie(r,e){let n=[...e].sort((i,o)=>i.path.localeCompare(o.path)).map(i=>i.path);try{return await hr.Suggest(r,n,n,"New note from template",(i,o)=>wie(i,o))}catch(i){if(pt(i))return null;throw i}}async function KS(r,e,t){try{let n=t.templatePath?.trim()||void 0;if(!n){if(!DP(e)){new kP.Notice("QuickAdd: Set a template folder in Settings \u2192 QuickAdd \u2192 Templates & properties to use \u201CNew note from template\u201D.",8e3),Pm(r,e.manifest.id,{notice:!1});return}let i=e.getTemplateFiles();if(i.length===0){new kP.Notice("QuickAdd: No template files found in your configured template folder(s).");return}let o=await Cie(r,i);if(!o)return;n=o}await t.choiceExecutor.execute(AP(n))}catch(n){if(pt(n))return;We(n,"Error running template from folder")}}It();Is();var Eie="\u2190 Back",xie="Select a choice";function $b(r){return Jo(r)?`QuickAdd couldn't read the contents of "${r.name}". They're still in data.json.`:`Folder "${r.name}" is empty.`}var Tie="Empty",Sie="Unreadable";function _ie(r){return IP(r)?Jo(r)?Sie:Tie:""}var Pb="quickadd:run-template-from-folder",kie="New note from template\u2026",xh="quickadd:back";function IP(r){return r.type==="Multi"&&r.id!==xh&&Qe(r).length===0}var Aie=.5;function Die(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 FP(r){return(r.settings.templateFolderLauncherRow??"bottom")!=="off"&&DP(r)}function Iie(){return{id:Pb,name:kie,type:"Template",command:!1}}var ip=class r extends Io.FuzzySuggestModal{constructor(t,n,i){super(t.app);this.plugin=t;this.choices=n;this.focusedProperty=null;this.triggerContext=null;this.placeholderStack=[];this.selectionDispatched=!1;this.breadcrumbById=new Map;this.markdownComponent=new Io.Component;this.warnRenderFailure=wd("Could not render a choice name as Markdown; showing it as plain text");if(this.choiceExecutor=i?.choiceExecutor??new ei(this.app,this.plugin),this.focusedProperty=i&&"focusedProperty"in i?i.focusedProperty??null:Gw(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.currentPlaceholder=i?.placeholder?.trim()||xie,this.setPlaceholder(this.currentPlaceholder),this.markdownComponent.load(),i?.includeTemplateFolderRow){let o=this.plugin.settings.templateFolderLauncherRow??"bottom";if(FP(this.plugin)){let s=Iie();this.choices=o==="top"?[s,...this.choices]:[...this.choices,s]}}}static Open(t,n,i){new r(t,n,i).open()}onClose(){super.onClose(),this.markdownComponent.unload(),this.completion&&!this.selectionDispatched&&this.completion(Ir())}getSuggestions(t){let n=t.trim();if(!n||!ne.getState().searchNestedChoices)return super.getSuggestions(n);let i=(0,Io.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-=Aie),o.push({item:s.choice,match:a}))}return o.sort((s,a)=>a.match.score-s.match.score),o}getNestedSearchCandidates(){if(!this.nestedSearchCandidates){let t=this.choices.filter(n=>n.id!==xh&&n.id!==Pb);this.nestedSearchCandidates=Og(t).map(({choice:n,path:i})=>{let o=i.slice(0,-1);o.length>0&&this.breadcrumbById.set(n.id,o.map(Die).join(" / "));let s=i.join(" / ");return{choice:n,text:s,nameOffset:s.length-n.name.length}})}return this.nestedSearchCandidates}selectSuggestion(t,n){if(IP(t.item)){if("repeat"in n&&n.repeat)return;new Io.Notice($b(t.item)),this.inputEl.focus();return}this.selectionDispatched=!0,super.selectSuggestion(t,n)}renderSuggestion(t,n){n.empty(),n.classList.remove("mod-complex");let i=this.breadcrumbById.get(t.item.id),o=n.createDiv({cls:"quickadd-choice-suggestion-content"});this.renderChoiceIcon(t.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"});Io.MarkdownRenderer.render(this.app,t.item.name,s,"",this.markdownComponent).catch(c=>{s.textContent=t.item.name,this.warnRenderFailure(c)}),n.classList.add("quickadd-choice-suggestion"),t.item.id===xh&&n.classList.add("quickadd-choice-suggestion-back"),t.item.id===Pb&&n.classList.add("quickadd-choice-suggestion-run-template");let a=_ie(t.item),l=a!=="";if(n.classList.toggle("quickadd-choice-suggestion-empty",l),l){n.setAttribute("aria-disabled","true");let c=nr(o,"span");c.classList.add("quickadd-choice-suggestion-empty-flair"),c.textContent=a,o.appendChild(c)}else n.removeAttribute("aria-disabled")}renderChoiceIcon(t,n){let i=this.getChoiceSuggestionIcon(t);if(!i)return;let o=nr(n,"span");o.classList.add("quickadd-choice-icon"),o.setAttribute("aria-hidden","true"),n.appendChild(o),(0,Io.setIcon)(o,i)}getChoiceSuggestionIcon(t){if(t.id!==xh)return t.id===Pb?"file-plus":Cd(t)}getItemText(t){return t.name}getItems(){return this.choices}settleCompletion(t,n){t.then(()=>this.completion?.(),i=>{Lp(i,n),this.completion?.(i)})}onChooseItem(t,n){if(t.id===Pb){this.settleCompletion(KS(this.app,this.plugin,{choiceExecutor:this.choiceExecutor}),"Could not run a template from that folder");return}if(t.type==="Multi")this.onChooseMultiType(t);else{"shiftKey"in n&&n.shiftKey&&(this.choiceExecutor.pickDate=!0);let i=this.choiceExecutor.executeWithFocusedProperty?this.choiceExecutor.executeWithFocusedProperty(t,this.focusedProperty,this.triggerContext):this.choiceExecutor.execute(t);this.settleCompletion(i,`Could not run "${t.name}"`)}}onChooseMultiType(t){let n=t.id===xh;if(!n&&IP(t)){new Io.Notice($b(t)),this.completion?.();return}let i=[...Qe(t)];if(!n){let a=new Em(Eie).addChoices(this.choices);a.id=xh,i.push(a)}let o=n?this.placeholderStack[this.placeholderStack.length-1]:t.placeholder?.trim()||t.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})}};ht();jo();De();oP();wo();nD();var VW=require("obsidian");wa();bf();Je();Jc();Dt();De();tC();wo();es();Je();bf();ev();Dd();es();dv();ud();Lc();N0();wo();var Mb=class extends _a{constructor(t,n,i){super(t);this.app=t;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.scanningSoleValue=!1;this.dateParser=ns,i&&(this.variables=new Map(i.variables))}warn(){}reportProblem(){}async scanString(t,n=!1,i="generic"){let o=this.scanningPathContext,s=this.scanningScope,a=this.scanningSoleValue;this.scanningPathContext=n,this.scanningScope=i,this.scanningSoleValue=QC(i,t);try{let l=await this.replaceGlobalVarInString(t);if(this.scanVariableTokens(l),this.scanDateTokens(l),this.scanFileTokens(l),n){if(new RegExp(pl.source,"i").test(l)){let c=this.requirements.get("value");c&&(c.pathContext=!0)}if(new RegExp(Lw.source,"i").test(l)){let c=this.requirements.get("mvalue");c&&(c.pathContext=!0)}}await this.format(l)}finally{this.scanningPathContext=o,this.scanningScope=s,this.scanningSoleValue=a}}markScanContext(t){this.scanningPathContext&&(t.pathContext=!0)}async format(t){let n=t;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(Ho.source,"gi"),o;for(;(o=i.exec(n))!==null;){let s=o[1];s&&this.templatesToScan.add(s)}}return n}async replaceGlobalVarInString(t){let n=t,i=0,o=new RegExp(ba.source,"gi");for(;o.test(n)&&!(++i>5);)n=n.replace(o,(s,a)=>{let l=String(a??"").trim();if(!l)return s;let c=this.plugin?.settings?.globalVariables?.[l];return typeof c=="string"?c:""});return n}scanVariableTokens(t){let n=new RegExp(Xu.source,"gi"),i;for(;(i=n.exec(t))!==null;){let o=(i[1]??"").trim();if(!o)continue;let s=cv(o,{warn:this.warnSink});if(!s)continue;let{variableName:a,variableKey:l,label:c,defaultValue:u,displayValues:d,hasOptions:f}=s;if(!a)continue;let p=f&&c?c:a,m=!f&&c?c:void 0,v=l;if(this.requirements.has(v)){let g=this.requirements.get(v);if(this.markScanContext(g),f&&!this.hasOptionList(g)&&(g.type=this.optionFieldType(s),g.label=p,this.applyOptionFields(g,s),g.defaultValue!==void 0&&!s.allowCustomInput)){let y=sD(g.defaultValue);g.defaultValue=s.suggestedValues.includes(y)?y:void 0}u&&g.defaultValue===void 0&&(g.defaultValue=u),!g.displayOptions&&d&&(g.displayOptions=d),g.optional=(g.optional??!1)&&s.optional}else{let g=!f&&s.inputTypeOverride==="checkbox",y=!f&&s.inputTypeOverride==="number",w=!f&&s.inputTypeOverride==="slider",T=s.inputTypeOverride==="multiline"||this.plugin.settings.inputPrompt==="multi-line"?"textarea":"text",b={id:v,label:p,type:f?this.optionFieldType(s):g?"dropdown":y?"number":w?"slider":T,description:m,optional:s.optional};f?this.applyOptionFields(b,s):g?b.options=["true","false"]:y?b.numericConfig=s.numericConfig:w&&(b.numericConfig=s.numericConfig,b.sliderConfig=s.sliderConfig),u&&(b.defaultValue=u),this.markScanContext(b),this.requirements.set(v,b)}}}optionFieldType(t){return t.allowCustomInput||t.multiSelect?"suggester":"dropdown"}hasOptionList(t){return Array.isArray(t.options)&&t.options.length>0}applyOptionFields(t,n){t.options=n.suggestedValues,n.displayValues&&(t.displayOptions=n.displayValues),n.multiSelect?t.multiEmit=n.multiEmit??"text":delete t.multiEmit,n.allowCustomInput||n.multiSelect?t.suggesterConfig={allowCustomInput:n.allowCustomInput,caseSensitive:!1,multiSelect:n.multiSelect??!1}:delete t.suggesterConfig}scanDateTokens(t){let n=new RegExp(yc.source,"gi"),i;for(;(i=n.exec(t))!==null;){let o=i[1]?.trim();if(!o)continue;let{defaultValue:s,optional:a,withTime:l}=uv(i[3]),c=i[2]?.trim()||(l?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"),u=this.requirements.get(o);u?(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:o,type:"date",defaultValue:s,dateFormat:c,withTime:l,optional:a,source:"collected"})}}async promptForValue(t){let n="value";if(!this.requirements.has(n)){let i=this.valuePromptContext?.inputTypeOverride==="checkbox",o=this.valuePromptContext?.inputTypeOverride==="number",s=this.valuePromptContext?.inputTypeOverride==="slider",a=ZC(this.scanningScope,this.scanningSoleValue);this.requirements.set(n,{id:n,label:a.title||t||"Enter value",type:i?"dropdown":o?"number":s?"slider":this.valuePromptContext?.inputTypeOverride==="multiline"||this.plugin.settings.inputPrompt==="multi-line"?"textarea":"text",description:this.valuePromptContext?.description,placeholder:a.placeholder,defaultValue:this.valuePromptContext?.defaultValue,numericConfig:this.valuePromptContext?.numericConfig,sliderConfig:this.valuePromptContext?.sliderConfig,options:i?["true","false"]:void 0,source:"collected",optional:this.valuePromptContext?.optional})}return this.markScanContext(this.requirements.get(n)),""}async promptForVariable(t,n){if(!t)return"";let i=n?.variableKey??t;if(n?.type==="VDATE")return n.defaultValue??"@date:1970-01-01T00:00:00.000Z";if(!this.requirements.has(i)){let o=sv(t).map(f=>f.trim()).filter(Boolean),s=o.length>1,a=!s&&n?.inputTypeOverride==="number",l=!s&&n?.inputTypeOverride==="slider",c=!s&&n?.inputTypeOverride==="checkbox",u=n?.inputTypeOverride==="multiline"||this.plugin.settings.inputPrompt==="multi-line"?"textarea":"text",d={id:i,label:t,type:s||c?"dropdown":a?"number":l?"slider":u,description:n?.description,numericConfig:n?.numericConfig,sliderConfig:n?.sliderConfig,source:"collected"};s?d.options=o:c&&(d.options=["true","false"]),n?.defaultValue&&(d.defaultValue=n.defaultValue),this.requirements.set(i,d)}return this.markScanContext(this.requirements.get(i)),n?.defaultValue??""}async promptForMathValue(){let t="mvalue";return this.requirements.has(t)||this.requirements.set(t,{id:t,label:"Math expression",type:"text",placeholder:"e.g., 2+2*3"}),this.markScanContext(this.requirements.get(t)),""}async suggestForField(t){let n=hi.parse(t),i=`${Zu}${t}`;if(!this.requirements.has(i)){let o={id:i,label:n.fieldName||t,type:"field-suggest",source:"collected",runtimeOnly:n.multiSelect};if(!n.multiSelect&&n.filters.defaultFrom==="active"){let s=pS(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(t){let n=new RegExp(Rw.source,"gi"),i;for(;(i=n.exec(t))!==null;){let o=NC(i[1]??"");o&&this.recordFileRequirement(o)}}recordFileRequirement(t){let n=t.variableKey,i=this.requirements.get(n);if(i){i.optional=(i.optional??!1)&&t.optional,i.type="file-picker",i.suggesterConfig={allowCustomInput:(i.suggesterConfig?.allowCustomInput??!1)||t.allowCustomInput,caseSensitive:!1,multiSelect:(i.suggesterConfig?.multiSelect??!1)||t.multiSelect};return}let o=di.filterFiles(this.app.vault.getMarkdownFiles(),t.filter,u=>this.app.metadataCache.getFileCache(u)),s=o.map(u=>`${Ta}${u.path}`),a=Sl(o,u=>this.app.metadataCache.getFileCache(u)),l=t.allowCustomInput||s.length===0,c=t.mode==="name"?`File from ${t.folderPath}`:`File from ${t.folderPath} (${t.mode})`;this.requirements.set(n,{id:n,label:t.label??c,type:"file-picker",source:"collected",options:s,displayOptions:a,optional:t.optional,suggesterConfig:{allowCustomInput:l,caseSensitive:!1,multiSelect:t.multiSelect}})}suggestForFile(t){return""}async suggestForValue(t,n,i){return""}getVariableValue(t){return""}async getTemplateContent(t){return""}async getSelectedText(){return""}async getClipboardContent(){return""}getCurrentFileLink(){return null}getCurrentFileName(){return null}async getMacroValue(t,n){return""}isTemplatePropertyTypesEnabled(){return!1}};ev();Tr();function PP(r=null){return{collect:{kind:"none"},opaque:null,deferred:r}}function $P(r){return{collect:{kind:"none"},opaque:r,deferred:r}}function MP(r){return r.type==="Template"}function Fie(r){return r.type==="Capture"}function NW(r){if(!r)return PP("unresolvableChoice");switch(r.type){case"Template":case"Capture":return MP(r)||Fie(r)?{collect:{kind:"scanChoice",choice:r},opaque:null,deferred:null}:PP("unresolvableChoice");case"Macro":return $P("nestedMacroGroup");case"Multi":return $P("interactivePicker");default:return r.type}}function BW(r,e){switch(r.type){case"NestedChoice":return NW(r.choice??null);case"Choice":return NW(e(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 $P("conditionalBranch");case"Obsidian":case"EditorCommand":case"Wait":case"OpenFile":return PP();default:return r.type}}Qn();function Pie(r){return{id:r.id,label:r.name}}function $ie(r){return{id:r.id,label:r.name}}function OP(r,e){let t=[],n=[],i=!1;for(let o of ar(e.macro?.commands)){if(!mn(o))continue;let s=BW(o,r);if(s.collect.kind==="scanChoice"){let a=s.collect.choice;a.onePageInput==="never"?n.push({label:a.name,reason:"choiceOptedOut"}):i?n.push({label:a.name,reason:"afterOpaqueStep"}):t.push({kind:"choice",choice:a,group:Pie(a)})}else s.collect.kind==="scriptInputs"?t.push({kind:"script",command:s.collect.command,group:$ie(s.collect.command)}):s.deferred&&n.push({label:o.name,reason:s.deferred});s.opaque&&(i=!0)}return{members:t,deferred:n}}var Mie=["text","number","textarea","dropdown","slider","date","field-suggest","file-picker","suggester"];function Oie(r){return typeof r=="string"&&Mie.includes(r)}function Rie(r){if(!r||typeof r!="object")return null;let e=r,t=e.id,n=e.type;if(typeof t!="string"||!Oie(n))return null;let i=Lie(e.numericConfig),o=Nie(e.sliderConfig),s=n==="slider"&&!o?"number":n;return{id:t,label:typeof e.label=="string"?e.label:t,type:s,placeholder:typeof e.placeholder=="string"?e.placeholder:void 0,defaultValue:typeof e.defaultValue=="string"?e.defaultValue:void 0,numericConfig:o??i,sliderConfig:o,options:Array.isArray(e.options)?e.options.filter(a=>typeof a=="string"):void 0,dateFormat:typeof e.dateFormat=="string"?e.dateFormat:void 0,description:typeof e.description=="string"?e.description:void 0,optional:typeof e.optional=="boolean"?e.optional:void 0,source:"script"}}function Lie(r){if(!r||typeof r!="object")return;let e=r,t=typeof e.min=="number"&&Number.isFinite(e.min)?e.min:void 0,n=typeof e.max=="number"&&Number.isFinite(e.max)?e.max:void 0,i=typeof e.step=="number"&&Number.isFinite(e.step)&&e.step>0?e.step:void 0;if(t!==void 0&&n!==void 0&&n<t)return i===void 0?void 0:{step:i};let o={};return t!==void 0&&(o.min=t),n!==void 0&&(o.max=n),i!==void 0&&(o.step=i),Object.keys(o).length>0?o:void 0}function Nie(r){if(!r||typeof r!="object")return;let e=r,t=typeof e.min=="number"?e.min:void 0,n=typeof e.max=="number"?e.max:void 0,i=e.step===void 0?1:typeof e.step=="number"?e.step:void 0;if(!(t===void 0||n===void 0||i===void 0||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(i)||n<=t||i<=0))return{min:t,max:n,step:i}}function Bie(r){let e=t=>{if(!t||typeof t!="object"&&typeof t!="function")return[];let n=t.quickadd;if(!n||typeof n!="object")return[];let i=n.inputs;return Array.isArray(i)?i:[]};return e(r)}async function qW(r,e){let t=Mi(r,e);return t?await r.vault.cachedRead(t):""}function Vie(r){let e=new Set,t=new RegExp(Ho.source,"gi"),n;for(;(n=t.exec(r))!==null;)n[1]&&e.add(n[1]);return e}async function xu(r,e,t,n=new Set,i=0,o="generic"){let s=XC(o),a=Vie(t);e.templatesToScan.clear(),await e.scanString(t,s,o);let l=[...e.templatesToScan].filter(c=>a.has(c));if(e.templatesToScan.clear(),!(i>=lE))for(let c of l){if(n.has(c))continue;let u=`${s?"path":"content"}:${c}`,d=e.scannedTemplateRefDepths.get(u);if(!(d!==void 0&&d<=i)){e.scannedTemplateRefDepths.set(u,i),n.add(c);try{await xu(r,e,await qW(r,c),n,i+1,o)}finally{n.delete(c)}}}}async function UW(r,e,t){if(await e.scanString(t,!0,"templatePath"),_c(t)){P.logMessage(`Preflight: template path "${t}" uses format syntax; its body's prompts are collected at run time, not in the one-page form.`);return}await xu(r,e,await qW(r,t),new Set([t]),0,"noteBody")}async function zW(r,e,t,n){let i=new Mb(r,e,t);if(n.fileNameFormat?.enabled&&await xu(r,i,n.fileNameFormat.format,void 0,0,"noteTitle"),n.folder?.enabled)for(let s of n.folder.folders??[])await xu(r,i,s,void 0,0,"folder");n.templatePath&&await UW(r,i,n.templatePath);let o=n.fileNameFormat?.enabled?n.fileNameFormat.format:zo;if(qD(n,o)){let s=i.requirements.get("value");s&&(s.runtimeOnly=!0)}return i}async function HW(r,e,t,n,i){let o=new Mb(r,e,t);await xu(r,o,n.captureTo,void 0,0,"captureTarget"),n.format?.enabled&&await xu(r,o,n.format.format,void 0,0,"captureText"),n.insertAfter?.enabled&&!n.insertAfter.promptHeading&&await xu(r,o,n.insertAfter.after,void 0,0,"lineTarget"),n.insertBefore?.enabled&&await xu(r,o,n.insertBefore.before,void 0,0,"lineTarget");let s=n.createFileIfItDoesntExist;s?.enabled&&s.createWithTemplate&&s.template&&await UW(r,o,s.template);let a=jS({isFolder:l=>zp(r,l),markdownFileExists:l=>r.vault.getAbstractFileByPath(WS(l))instanceof VW.TFile},n.captureTo??"",n.captureToActiveFile);if(a){let l=[];switch(a.kind){case"property":l=Wp(r,a.field,a.value,a.filter);break;case"filter":l=Hp(r,a.filter);break;case"tag":l=xg(r,a.tag);break;case"folder":l=ho(r,a.folderPathSlash);break}let c=ep(l,tp(r)),u=c.map(m=>m.path),d=Sl(c,m=>r.metadataCache?.getFileCache(m)??null),f=n.createFileIfItDoesntExist?.enabled??!1,p=xP(n.id);u.length===0&&f?o.requirements.set(p,{id:p,label:"Select capture target file",type:"file-picker",source:"collected",options:u,displayOptions:d,runtimeOnly:!0,placeholder:"Type a new note name in the capture target picker"}):o.requirements.set(p,{id:p,label:"Select capture target file",type:"dropdown",options:u,displayOptions:d,placeholder:u.length?void 0:"No files found in target scope"})}if(i){let l=n.useSelectionAsCaptureValue,c=e.settings.useSelectionAsCaptureValue??!0;if(typeof l=="boolean"?l:c){let d=t.variables.get("value");if(d==null){let f=rd(r);f.trim().length>0&&t.variables.set("value",f)}}}return o}async function qie(r,e,t){let n=[];try{let i=eC(e),o=i!==void 0?t?.get(i):void 0;o===void 0&&(o=await Fs(e,r,{reportLoadErrors:!1}),i!==void 0&&o!==void 0&&t?.set(i,o));let s=Bie(o);for(let a of s){let l=Rie(a);l&&n.push(l)}}catch(i){let o=e.path??e.id,s=i instanceof Error?i.message:String(i);if(HO(i))return P.logMessage(`QuickAdd preflight could not inspect user script '${o}': ${s}`),n;P.logWarning(`Preflight could not inspect user script '${o}': ${s}`)}return n}function WW(r){return e=>{try{return r.getChoiceById(e)}catch{return null}}}function Uie(r){return r.type==="Macro"}async function zie(r,e,t,n,i){let o=OP(WW(e),n),s=new Map,a=i?.seedCaptureSelectionAsValue??!1;for(let l of o.members){let c=l.kind==="script"?await qie(r,l.command,i?.preloadedUserScripts):MP(l.choice)?Array.from((await zW(r,e,t,l.choice)).requirements.values()):Array.from((await HW(r,e,t,l.choice,a)).requirements.values());for(let u of c){let d=s.get(u.id);if(d){d.optional=(d.optional??!1)&&(u.optional??!1),u.pathContext&&(d.pathContext=!0),u.runtimeOnly&&(d.runtimeOnly=!0);continue}s.set(u.id,{...u,group:l.group})}}return Hie(t.variables,s),Array.from(s.values())}function Hie(r,e){let t=[];for(let n of e.values())Eh(n.id)&&t.push(n.id);if(!(t.length<2))for(let n of t)r.has(n)||r.set(n,null)}function Wie(r,e){let t=e.pickDate?$f(Ml(r.dateOrigin)):Ml(r.dateOrigin);if(!(t?.kind!=="ask"||e.clocks?.date))return{id:ml,label:`Date for ${r.name}`,type:"date",dateFormat:"YYYY-MM-DD",defaultValue:t.defaultValue,source:"collected"}}function RP(r,e,t){let n=Wie(r,e);return n?[n,...t.filter(i=>i.id!==ml)]:t}async function Ob(r,e,t,n,i){if(n.type==="Template"){let o=await zW(r,e,t,n);return RP(n,t,Array.from(o.requirements.values()))}if(n.type==="Capture"){let o=await HW(r,e,t,n,i?.seedCaptureSelectionAsValue??!1);return RP(n,t,Array.from(o.requirements.values()))}return Uie(n)?RP(n,t,await zie(r,e,t,n,i)):[]}function jW(r,e){return OP(WW(r),e).deferred}function Rb(r,e){let t=r.filter(n=>Eh(n.id)).length;return r.filter(n=>{if(TP(n.id))return _W(e,n.id)!==null?!1:!kW(e,n.id,t);let i=qc(e,n.id);return i?e.get(i)==null:!0})}Je();Jc();ph();function jie(r,e,t){let n=e.pickDate?$f(Ml(r.dateOrigin)):Ml(r.dateOrigin),i=IS({setting:n,clocks:e.clocks,variables:new Map([...e.variables,...Object.entries(t)]),reservedSeed:n?.kind==="ask"?t[ml]:void 0});return i.status!=="set"?e.clocks:{now:e.clocks?.now??new Date,date:i.date}}function GW(r,e){let t=r.trim();if(!t)return[];let n=Array.from(e.keys()).sort((s,a)=>a.length-s.length),i=[],o=t;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,e,t){let n=r.filter(o=>t||e.includes(o)),i=new Set(n);return[...e.filter(o=>i.has(o)),...n.filter((o,s)=>!e.includes(o)&&n.indexOf(o)===s)]}async function YW(r,e,t,n){try{let i=await Ob(r,e,t,n,{seedCaptureSelectionAsValue:!0,preloadedUserScripts:t.preloadedUserScripts});if(i.length===0)return!1;let o=Rb(i,t.variables);if(o.length===0)return!1;let s=o.filter(p=>!p.runtimeOnly);if(s.length===0)return!1;let a=async p=>{try{let m=new Pf(r,e);m.setRunClocks(jie(n,t,p));let v=[];if(n.type==="Template"){let g=n;if(g.fileNameFormat?.enabled){m.setTargetFolderPath(YE(g.folder)??"Folder/Name");for(let[y,w]of Object.entries(p))m.variables.set(y,w);v.push({label:"File name",text:await m.format(g.fileNameFormat.format),diagnostics:m.diagnostics.list()})}}return v}catch{return[]}},l=t.promptProvider,c=null,u;l?u=await l.requestInputs(s):(c=new uh(r,s,t.variables,a),u=await c.waitForClose);let d=new Map,f=new Map;for(let p of s){if(p.id.startsWith(zg)){let m=p.options??[],v=p.displayOptions??m;d.set(p.id,{options:m,displayToValue:new Map(m.map((g,y)=>[(v[y]??g).trim(),g])),allowCustom:p.suggesterConfig?.allowCustomInput??!1,multiSelect:p.suggesterConfig?.multiSelect??!1})}if(p.suggesterConfig?.multiSelect&&!p.id.startsWith(zg)){let m=p.options??[],v=p.displayOptions??m,g=new Map;m.forEach((y,w)=>{g.set((v[w]??y).trim(),y)}),f.set(p.id,{emit:p.multiEmit??"text",allowCustom:p.suggesterConfig.allowCustomInput??!1,displayToValue:g})}}return Object.entries(u).forEach(([p,m])=>{let v=d.get(p);if(v!==void 0){let w=c?.fileSelections.get(p)??(Array.isArray(m)?m.map(String):void 0)??(v.multiSelect?GW(String(m),v.displayToValue).map(E=>v.displayToValue.get(E)??E):[String(m)]),b=Gie(w,v.options,v.allowCustom).map(E=>DL(E,v.options));t.variables.set(p,v.multiSelect?b:b[0]??"");return}let g=f.get(p);if(g!==void 0){let w=(c?.multiSelections.get(p)??GW(String(m),g.displayToValue)).filter(T=>g.allowCustom||g.displayToValue.has(T)).map(T=>g.displayToValue.get(T)??T);t.variables.set(p,g.emit==="linklist"?w.map(iE):w);return}t.variables.set(p,m)}),!0}catch(i){if(i instanceof Tt)throw i;return t.promptProvider||P.logWarning(`One-page input failed for choice "${n.name}"; falling back to step-by-step prompts: ${i instanceof Error?i.message:String(i)}`),!1}}jo();Bi();Er();rr();Dt();sf();qp();Jc();It();Je();BT();ph();De();var ei=class{constructor(e,t){this.app=e;this.plugin=t;this.variables=new Map;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}signalAbort(e){this.pendingAbort=e}consumeAbortSignal(){let e=this.pendingAbort;return this.pendingAbort=null,e??null}recordExecutionResult(e){this.pendingResult=e}beginExecutionContext(){this.executionDepth===0&&(this.focusedProperty=this.focusedPropertyOverride!==void 0?this.focusedPropertyOverride:Gw(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())}async execute(e){this.pendingAbort=null;let t=this.pendingResult;this.beginExecutionContext();let n=Cg(this.app),i=mi.getInstance();i.beginExecutionScope();try{switch(await this.runOnePagePreflightIfEnabled(e),await this.applyDateOrigin(e),e.type){case"Template":{let o=e;await this.onChooseTemplateType(o,n);break}case"Capture":{let o=e;await this.onChooseCaptureType(o,n);break}case"Macro":{let o=e;await this.onChooseMacroType(o,n);break}case"Multi":{let o=e;await this.onChooseMultiType(o);break}default:break}if(this.pendingAbort){i.rollbackExecutionScope();return}i.commitExecutionScope()}catch(o){throw i.rollbackExecutionScope(),o}finally{this.pendingResult=t,this.endExecutionContext()}}async executeWithFocusedProperty(e,t,n){let i=this.focusedPropertyOverride,o=this.triggerContextOverride;this.focusedPropertyOverride=t,this.triggerContextOverride=n;try{await this.execute(e)}finally{this.focusedPropertyOverride=i,this.triggerContextOverride=o}}async executeWithOutcome(e){this.pendingAbort=null,this.pendingResult=null,this.beginExecutionContext();let t=Cg(this.app),n=mi.getInstance();n.beginExecutionScope();try{if(await this.runOnePagePreflightIfEnabled(e),await this.applyDateOrigin(e),e.type==="Template"?await this.onChooseTemplateType(e,t):await this.onChooseCaptureType(e,t),this.pendingAbort){n.rollbackExecutionScope();let o=this.consumeAbortSignal(),s=o instanceof dt;return{status:"cancelled",cancelKind:s?"user":"aborted",reason:s?void 0:o?.message}}n.commitExecutionScope();let i=this.pendingResult;return this.pendingResult=null,i??{status:"error"}}catch(i){return n.rollbackExecutionScope(),i instanceof dt?{status:"cancelled",cancelKind:"user"}:i instanceof Tt?{status:"cancelled",cancelKind:"aborted",reason:i.message}:(We(i,"Error executing choice from URI"),{status:"error",reason:i instanceof Error?i.message:String(i)})}finally{this.endExecutionContext()}}async applyDateOrigin(e){let t=this.pickDate?$f(Ml(e.dateOrigin)):Ml(e.dateOrigin),n=t?.kind==="ask"?this.variables.get(ml):void 0,i=IS({setting:t,clocks:this.clocks,variables:this.variables,reservedSeed:n});if(i.status==="inherit")return;if(i.status==="error")throw P.logError(i.message),new ve(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 ve(`"${e.name}" needs a date. Re-run with date= or the ui flag.`);let o=`Date for ${e.name}`;try{let s=this.promptProvider?await this.promptProvider.datePrompt(o,{defaultValue:i.defaultValue,dateFormat:"YYYY-MM-DD"}):await Hl.Prompt(this.app,o,void 0,i.defaultValue,"YYYY-MM-DD"),a=xb(s);if(!a)throw new ve("Could not parse the date origin.");this.clocks={now:this.clocks?.now??new Date,date:a}}catch(s){throw pt(s)?new dt("Date origin cancelled by user"):s}}async runOnePagePreflightIfEnabled(e){let t=ne.getState().onePageInputEnabled,n=e.onePageInput,i=this.promptProvider!=null;if((n==="always"||n!=="never"&&(t||i))&&(e.type==="Template"||e.type==="Capture"||e.type==="Macro"))try{await YW(this.app,this.plugin,this,e)}catch(s){throw pt(s)?new dt("One-page input cancelled by user"):s}}async onChooseTemplateType(e,t){await new NS(this.app,this.plugin,e,this,t).run()}async onChooseCaptureType(e,t){await new YS(this.app,this.plugin,e,this,t).run()}async onChooseMacroType(e,t){let n=new Wa(this.app,this.plugin,e,this,this.variables,this.preloadedUserScripts,void 0,t);await n.run(),Object.entries(n.params.variables).forEach(([i,o])=>{this.variables.set(i,o)})}async onChooseMultiType(e){let t=Qe(e);if(this.promptProvider||this.interactive===!1){let n=this.promptProvider?"Run one of its choices directly.":"Run one of its choices directly, or re-run with the ui flag.";this.signalAbort(new ve(t.length===0?$b(e):`"${e.name}" is a folder of choices, and picking from it needs someone at the window. ${n}`));return}if(t.length===0){new KW.Notice($b(e));return}await new Promise((n,i)=>{ip.Open(this.plugin,t,{choiceExecutor:this,focusedProperty:this.focusedProperty,triggerContext:this.triggerContext,placeholder:e.placeholder?.trim()||e.name,completion:o=>o===void 0?n():i(o)})})}};Dt();var QW=require("obsidian");var Yie="QuickAdd: No choices yet. Create your first one in Settings \u2192 QuickAdd.";function LP(r){let e=Array.isArray(r.settings.choices)?r.settings.choices:[];if(!(e.length>0||FP(r))){new QW.Notice(Yie,8e3),Pm(r.app,r.manifest.id,{notice:!1});return}ip.Open(r,e,{includeTemplateFolderRow:!0})}aP();De();De();Dt();var XW={description:"Use QuickAdd template folder instead of Obsidian templates plugin folder / Templater templates folder.",migrate:async r=>{try{let e=r.app.plugins.plugins.templater,t=r.app.internalPlugins.plugins.templates;if(!e&&!t){P.logMessage("No template plugin found. Skipping migration.");return}let n=[];if(t){let s=t.instance.options;s.folder&&(n.push(s.folder),P.logMessage("Migrated template folder path to Obsidian Templates' setting."))}if(e){let s=e.settings;s.template_folder&&(n.push(s.template_folder),P.logMessage("Migrated template folder path to Templaters setting."))}let i=ui(r.settings.templateFolderPaths),o=ui([...i,...n]);o.length>0&&(r.settings.templateFolderPaths=o)}catch(e){throw P.logError("Failed to migrate template folder path."),e}}};qn();function QS(r){return r===null||typeof r!="object"||!("type"in r)||!("choices"in r)?!1:r.type==="Multi"&&Array.isArray(r.choices)}function XS(r){return r===null||typeof r!="object"||!("choice"in r)?!1:r.choice!==void 0}It();Qn();function ZW(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="Template"&&"incrementFileName"in r}function JW(r){for(let e of r)QS(e)&&(e.choices=JW(e.choices)),ZW(e)&&(e.setFileExistsBehavior=!0,e.fileExistsMode="Increment the file name",delete e.incrementFileName);return r}function Kie(r){for(let e of r)for(let t of ar(hn(e)))XS(t)&&ZW(t.choice)&&(t.choice.setFileExistsBehavior=!0,t.choice.fileExistsMode="Increment the file name",delete t.choice.incrementFileName);return r}var Qie={description:"'Increment file name' setting moved to 'Set default behavior if file already exists' setting",migrate:async r=>{let e=r.settings,t=!rf(r.settings.choices)&&!Kn(e.macros);if(Array.isArray(r.settings.choices)){let o=Ze(r.settings.choices);r.settings.choices=Ze(JW(o))}let n=Ze(Xf(e.macros)),i=Kie(n);if(Array.isArray(e.macros)&&(e.macros=i),!t)return{complete:!1}}},e6=Qie;qn();function t6(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="Template"}function Xie(r){return r.fileExistsBehavior?r.fileExistsBehavior:r.setFileExistsBehavior?{kind:"apply",mode:S2(r.fileExistsMode)??"increment"}:r.incrementFileName?{kind:"apply",mode:"increment"}:{kind:"prompt"}}function r6(r){r.fileExistsBehavior=Xie(r),delete r.incrementFileName,delete r.setFileExistsBehavior,delete r.fileExistsMode}var Zie={description:"Re-run template file collision normalization for users with older migration state",migrate:async r=>{let e=r.settings,t=!Am(e);if(Array.isArray(r.settings.choices)&&(r.settings.choices=Ze(r.settings.choices)),Array.isArray(e.macros)&&(e.macros=Ze(e.macros)),Dm(r,n=>{t6(n)&&r6(n)}),!t)return{complete:!1}}},ZS=Zie;var Jie={description:"Repair template file collision settings that may have been left in legacy format",migrate:ZS.migrate},n6=Jie;It();function NP(r){return Ne(r)&&r.type==="Capture"}qn();It();Qn();function i6(r){for(let e of r)QS(e)&&(e.choices=i6(e.choices)),NP(e)&&e.insertAfter?.enabled&&e.prepend&&(e.prepend=!1);return r}function eoe(r){for(let e of r)for(let t of ar(hn(e)))XS(t)&&NP(t.choice)&&t.choice.insertAfter?.enabled&&t.choice.prepend&&(t.choice.prepend=!1);return r}var toe={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 e=r.settings,t=!rf(r.settings.choices)&&!Kn(e.macros);if(Array.isArray(r.settings.choices)){let o=Ze(r.settings.choices);r.settings.choices=i6(o)}let n=Ze(Xf(e.macros)),i=eoe(n);if(Array.isArray(e.macros)&&(e.macros=i),!t)return{complete:!1}}},o6=toe;ht();var roe={description:"Set version to the current plugin version.",migrate:async r=>{ne.setState({version:r.manifest.version})}},s6=roe;fo();ht();qn();var noe={description:"Add default AI providers to the settings.",migrate:async r=>{let e=ne.getState().ai,t=Ze(Fw);if("OpenAIApiKey"in e&&typeof e.OpenAIApiKey=="string"){let n=t.find(i=>i.name==="OpenAI");n&&(n.apiKey=e.OpenAIApiKey)}"OpenAIApiKey"in e&&delete e.OpenAIApiKey,ne.setState({ai:{...ne.getState().ai,providers:t}})}},a6=noe;De();It();Qn();var ioe={description:"Remove macro indirection - embed macros directly in macro choices",migrate:async r=>{let e=r.settings;if(rf(e.choices))return P.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(e.choices))return P.logMessage("QuickAdd could not read the choice list, so legacy macros were left in place to be migrated later."),{complete:!1};if(Kn(e.macros))return P.logMessage("QuickAdd could not read the legacy macro list, so it was left in place to be migrated later."),{complete:!1};let t=Xf(e.macros),n=new Map,i=dn(e.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 t){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 Cm(o.name);a.macro={id:o.id,name:o.name,commands:o.commands||[]},a.runOnStartup=o.runOnStartup||!1,e.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&&(P.logMessage(`Removing orphaned macroId reference: ${s.macroId}`),delete s.macroId)}"macros"in e&&delete e.macros}},l6=ioe;De();function JS(r){if(r==null)return null;if(typeof r=="boolean")return{enabled:r};if(typeof r!="object")return null;let e=r;return{enabled:typeof e.enabled=="boolean"?e.enabled:void 0,direction:e.direction==="horizontal"||e.direction==="vertical"?e.direction:void 0,focus:typeof e.focus=="boolean"?e.focus:void 0}}function e_(r,e){let t=r.direction==="horizontal"?"horizontal":"vertical",n=typeof e=="string"&&e!=="default"?e:"default";return qr({location:r.enabled?"split":"tab",direction:t,focus:r.focus??!0,mode:n})}var ooe={description:"Migrate legacy openFileInNewTab settings to new fileOpening format",migrate:async r=>{P.logMessage("Starting migration of file opening settings...");let e=Am(r.settings),t=0;if(Dm(r,i=>{if(i.type!=="Template"&&i.type!=="Capture")return;let o=i,s=o.openFileInNewTab,a=o.openFileInMode,l=JS(s);if(!o.fileOpening&&l){let c={enabled:l?.enabled??!1,direction:l?.direction??"vertical",focus:l?.focus??!0};o.fileOpening=e_(c,a??"default"),t++,P.logMessage(`Migrated file opening settings for choice: ${i.name}`)}}),P.logMessage(`Migration complete. Migrated ${t} choices.`),e)return{complete:!1}}},c6=ooe;De();var soe={description:"Backfill missing file opening defaults for older choices",migrate:async r=>{P.logMessage("Starting file opening defaults backfill...");let e=Am(r.settings),t=0;if(Dm(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,u=JS(l);(!s||s.location==null||s.direction==null||s.mode==null||s.focus==null)&&(!s&&u?o.fileOpening=e_(u,c):o.fileOpening=qr(s),t++)}),P.logMessage(`File opening defaults backfill complete. Updated ${t} choice(s).`),e)return{complete:!1}}},u6=soe;ht();qn();var aoe={description:"Ensure every AI provider has a discovery mode so browsing works without models.dev",migrate:async r=>{let t=ne.getState().ai.providers??[],n=!1;for(let i of t)i.modelSource||(i.modelSource="auto",n=!0);n&&ne.setState(i=>({...i,ai:{...i.ai,providers:Ze(t)}}))}},d6=aoe;qn();De();ht();qn();Nd();var loe={description:"Move AI provider API keys into Obsidian SecretStorage",migrate:async r=>{let e=ne.getState().ai.providers??[],t=()=>e.some(o=>(o.apiKey?.trim()??"")!==""),n=r.app?.secretStorage;if(!n?.getSecret||!n?.setSecret)return t()?(P.logWarning("SecretStorage unavailable; deferring AI provider API key migration until it is available."),{complete:!1}):void 0;let i=!1;for(let o of e){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){P.logWarning(`Failed to migrate secret for ${o.name}: ${l.message??l}`)}continue}if(s)try{let l=await pV(r.app,o,s);l&&(o.apiKeyRef=l,o.apiKey="",i=!0)}catch(l){P.logWarning(`Failed to store API key for ${o.name}: ${l.message??l}`)}}if(i&&ne.setState(o=>({...o,ai:{...o.ai,providers:Ze(e)}})),t())return{complete:!1}}},p6=loe;Dt();var f6={description:"Move the single template folder path into the multi-folder list.",migrate:async r=>{let e=r.settings,t=ui(e.templateFolderPaths);t.length>0?e.templateFolderPaths=t:e.templateFolderPaths=ui([e.templateFolderPath]),delete e.templateFolderPath}};fo();Tr();ht();qn();De();function coe(r){for(let e of[r,`https://${r}`])try{let t=new URL(e).hostname.toLowerCase();if(t)return t}catch{}return""}function uoe(r){let e=coe(r.endpoint??"");return e==="api.openai.com"?"openai":e==="generativelanguage.googleapis.com"?"google":e==="api.anthropic.com"?"anthropic":null}function doe(r,e,t){let n=new Set(e==="anthropic"?[]:UM[e]);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 ag[e]){let s=i.get(o.name);s?(s.maxTokens=o.maxTokens,s.maxOutputTokens=o.maxOutputTokens,s.supportsTemperature=o.supportsTemperature):t.has(o.name)||r.models.push({...o})}}var poe={temperature:1,top_p:1,frequency_penalty:0,presence_penalty:0};function foe(r){return r.type==="AIAssistant"}var moe={description:"Refresh built-in AI provider model lists: drop retired models, add the current generation, and turn on auto-sync.",migrate:async r=>{let e=ne.getState(),t=Ze(e.ai.providers??[]),n=Ze(e.choices??[]),i=new Set;for(let l of t){let c=uoe(l);if(!c)continue;let u=new Set(t.filter(p=>p!==l).flatMap(p=>p.models.map(m=>m.name))),d=l.models.map(p=>p.name);doe(l,c,u);let f=new Set(l.models.map(p=>p.name));for(let p of d)f.has(p)||i.add(p);l.autoSyncModels=!0,c==="openai"&&(l.modelSource="modelsDev")}let o=new Set(t.flatMap(l=>l.models.map(c=>c.name))),s=new Set([...i].filter(l=>!o.has(l)));yT({choices:n},l=>{if(!foe(l))return;l.model&&s.has(l.model)&&(P.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[u,d]of Object.entries(poe))c[u]===d&&delete c[u]});let a=s.has(e.ai.defaultModel)?"Ask me":e.ai.defaultModel;ne.setState({choices:n,ai:{...ne.getState().ai,defaultModel:a,providers:t}})}},m6=moe;fo();ht();qn();De();function hoe(r,e){return r.find(t=>t.models.some(n=>n.name===e))}var goe={description:"Pin AI commands' models to the provider they currently resolve to, and give every provider a stable id.",migrate:async r=>{let e=ne.getState(),t=Ze(e.ai.providers??[]),n=Ze(e.choices??[]);Dw(t),bT(n,t,(s,a)=>{P.logMessage(`Pinned AI command "${s.name}"'s model to ${a.providerId}/${a.name}.`)});let i,o=e.ai.defaultModel;if(e.ai.defaultModelRef&&e.ai.defaultModelRef.name===o)i=e.ai.defaultModelRef;else if(o&&o!=="Ask me"){let s=hoe(t,o);s?.id&&(i={providerId:s.id,name:o},P.logMessage(`Pinned the default model to ${s.id}/${o}.`))}ne.setState({choices:n,ai:{...ne.getState().ai,providers:t,...i?{defaultModelRef:i}:{}}})}},h6=goe;ht();var BP={useQuickAddTemplateFolder:XW,incrementFileNameSettingMoveToDefaultBehavior:e6,consolidateFileExistsBehavior:ZS,repairTemplateFileExistsBehavior:n6,mutualExclusionInsertAfterAndWriteToBottomOfFile:o6,setVersionAfterUpdateModalRelease:s6,addDefaultAIProviders:a6,removeMacroIndirection:l6,migrateFileOpeningSettings:c6,backfillFileOpeningDefaults:u6,setProviderModelDiscoveryMode:d6,migrateProviderApiKeysToSecretStorage:p6,migrateToMultipleTemplateFolders:f6,refreshStaleDefaultModelSeeds:m6,pinAiModelRefs:h6};async function voe(r){let e=Object.keys(BP).filter(t=>!r.settings.migrations[t]);if(e.length===0){P.logMessage("No migrations to run.");return}ne.replaceState(Ze(r.settings));for(let t of e){P.logMessage(`Running migration ${t}: ${BP[t].description}`);let n=Ze(r.settings),i=ne.getState();try{let o=await BP[t].migrate(r);ne.getState()!==i&&(r.settings=Ze(ne.getState()));let s=o?.complete===!1;s||(r.settings.migrations[t]=!0),ne.replaceState(Ze(r.settings)),P.logMessage(s?`Migration ${t} incomplete; will retry on a later launch.`:`Migration ${t} successful.`)}catch(o){P.logError(`Migration '${t}' was unsuccessful. Please create an issue with the following error message:
${o}
QuickAdd will now revert to backup.`),r.settings=n,ne.replaceState(Ze(r.settings))}}r.saveSettings()}var g6=voe;ht();var Ya=require("obsidian");De();async function yoe(r,e,t){let n=await(0,Ya.requestUrl)({url:`https://api.github.com/repos/${r}/${e}/releases`,throw:!1}),i=n.json;if(n.status>=400||!Array.isArray(i)){let a=typeof i=="object"&&i!==null&&"message"in i&&typeof i.message=="string"?i.message:"Unknown error";throw new Error(`Failed to fetch releases: ${a}`)}let o=i,s=o.findIndex(a=>a.tag_name===t);if(s===-1)throw new Error(`Could not find release with tag ${t}`);return o.slice(0,s).filter(a=>!a.draft&&!a.prerelease)}var VP=/^https:\/\/github\.com\/user-attachments\/assets\/[A-Za-z0-9-]+$/,v6=/^\[!\[[^\]]*\]\(([^)\s"]+)\)\]\((https:\/\/github\.com\/user-attachments\/assets\/[A-Za-z0-9-]+)\)$/,boe=/^<!--\s*poster:\s*(https:\/\/[^\s"'>]+)\s*-->$/;function woe(r,e){let t=e?` poster="${e}"`:"";return`<video controls preload="metadata" playsinline style="width: 100%; border-radius: 8px;" src="${r}"${t}></video>`}function Coe(r){let e=r.split(`
`),t=new Set;for(let s of e){let a=s.trim();VP.test(a)&&t.add(a)}let n=new Map;for(let s of e){let a=s.trim().match(v6);a&&t.has(a[2])&&n.set(a[2],a[1])}let i=new Set;for(let s=0;s<e.length;s++)if(VP.test(e[s].trim()))for(let a of[1,-1]){let l=s+a;for(;l>=0&&l<e.length&&e[l].trim()==="";)l+=a;let c=l>=0&&l<e.length?e[l].trim().match(boe):null;if(c){n.set(e[s].trim(),c[1]),i.add(l);break}}let o=[];for(let s=0;s<e.length;s++){let a=e[s],l=a.trim();if(i.has(s))continue;let c=l.match(v6);if(!(c&&t.has(c[2]))){if(VP.test(l)){o.push(woe(l,n.get(l)));continue}o.push(a)}}return o.join(`
`)}function Eoe(r,e=1){let t=r.split(`
`);for(let n=0;n<t.length;n++)t[n].startsWith("#")&&(t[n]="#".repeat(e)+t[n]);return t.join(`
`)}var t_=class extends Ya.Modal{constructor(t,n){super(t);this.markdownComponent=new Ya.Component;this.isClosed=!1;this.previousVersion=n,this.releaseNotesPromise=yoe("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=>{P.logError(`Failed to fetch release notes: ${i}`)})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h1",{text:"Fetching release notes..."}),this.addCloseFooter()}addCloseFooter(){let t=this.contentEl.createDiv("quickadd-update-modal-footer");new Ya.ButtonComponent(t).setButtonText("Done").setCta().onClick(()=>this.close())}onClose(){let{contentEl:t}=this;this.isClosed=!0,this.markdownComponent.unload(),t.empty()}display(){let{contentEl:t}=this;t.empty(),t.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=t.createDiv("quickadd-update-modal"),a=this.releases.map(d=>Coe(d.body??"")).join(`
---
`),l=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,u=`${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}
---
${Eoe(a)}`;this.markdownComponent.load(),Ya.MarkdownRenderer.render(this.app,u,s,this.app.vault.getRoot().path,this.markdownComponent),this.addCloseFooter()}};dS();Er();Bi();var xoe=25e3,Toe=6e4,Soe=3e4,_oe=75e3,koe=32;function Aoe(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r.charCodeAt(n)^e.charCodeAt(n);return t===0}function Doe(r){if(r.origin||r.referer)return!1;let e=(r.host??"").split(":")[0];return e==="127.0.0.1"||e==="localhost"}function Ioe(r){try{let e=window.require;return e?e(r):null}catch{return null}}function r_(){let r=window.crypto;if(r?.randomUUID)return r.randomUUID();if(r?.getRandomValues){let e=r.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}throw new Error("Interactive prompts require a secure random source (crypto), which is unavailable here.")}var n_="No pending prompt for that requestId",qP="The interactive client disconnected, so the run was ended.";function Foe(r,e){if(e.cancelled!==void 0&&typeof e.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(e.cancelled===!0)return null;if(r==="confirm"){let t=e.value;if(!(t===!0||t===!1||t==="true"||t==="false"))return`A confirm prompt needs a boolean reply, or {"cancelled": true} if the user dismissed it. Got ${Poe(t)}.`}return null}function Poe(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}var UP=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 e=Ioe("http");if(!e)throw new Error("Interactive prompts require desktop Obsidian (Node http is unavailable).");let t=this.generation;return this.startPromise=new Promise((n,i)=>{let o=e.createServer((s,a)=>{this.handle(s,a)});o.on("error",s=>{this.generation===t&&(this.startPromise=null),i(s)}),o.listen(0,"127.0.0.1",()=>{if(this.generation!==t){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>=koe)throw new Error("Too many active interactive sessions.");let e=r_(),t=r_()+r_(),n={id:e,token:t,queue:[],waiter:null,waiterTimer:null,pending:new Map,finished:!1,aborted:!1,cleanupTimer:null,attached:!1,attachTimer:null,pollWatchdog:null};return n.attachTimer=window.setTimeout(()=>{!n.attached&&!n.finished&&this.finish(n.id,{kind:"error",error:"No client attached to the interactive session."})},Soe),this.sessions.set(e,n),{id:e,token:t}}emitPrompt(e,t){let n=this.sessions.get(e);if(!n)return Promise.reject(new Error("Unknown session"));if(n.finished)return Promise.reject(new ve(qP));if(n.aborted)return Promise.reject(new dt(wc));let i=r_();return new Promise((o,s)=>{n.pending.set(i,{resolve:o,reject:s,promptType:t.type}),this.push(n,{kind:"prompt",requestId:i,prompt:t})})}finish(e,t){let n=this.sessions.get(e);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);for(let[,i]of n.pending)i.reject(new ve(qP));n.pending.clear(),this.push(n,t),n.cleanupTimer=window.setTimeout(()=>this.destroySession(n),Toe)}}abortSession(e){let t=this.sessions.get(e);if(!t||t.finished)return null;t.aborted=!0;let n=[...t.pending.values()];t.pending.clear();for(let i of n)i.reject(new dt(wc));return t.queue=t.queue.filter(i=>i.kind!=="prompt"),n.length}stop(){this.generation++;for(let e of this.sessions.values()){e.waiterTimer&&window.clearTimeout(e.waiterTimer),e.cleanupTimer&&window.clearTimeout(e.cleanupTimer),e.attachTimer&&window.clearTimeout(e.attachTimer),e.pollWatchdog&&window.clearTimeout(e.pollWatchdog);for(let[,t]of e.pending)t.reject(new ve("QuickAdd was unloaded during an interactive run."));if(e.waiter){let t=e.waiter;e.waiter=null,t({kind:"error",error:"QuickAdd unloaded"})}}this.sessions.clear(),this.server?.close(),this.server=null,this.port=0,this.startPromise=null}push(e,t){if(e.waiter){let n=e.waiter;e.waiter=null,e.waiterTimer&&(window.clearTimeout(e.waiterTimer),e.waiterTimer=null),n(t)}else e.queue.push(t)}destroySession(e){e.waiterTimer&&window.clearTimeout(e.waiterTimer),e.cleanupTimer&&window.clearTimeout(e.cleanupTimer),e.attachTimer&&window.clearTimeout(e.attachTimer),e.pollWatchdog&&window.clearTimeout(e.pollWatchdog);for(let[,t]of e.pending)t.reject(new ve(qP));e.pending.clear(),this.sessions.delete(e.id),this.sessions.size===0&&(this.server?.close(),this.server=null,this.port=0,this.startPromise=null)}authed(e,t){return!!e&&!!t&&Aoe(e.token,t)}originAllowed(e){return Doe({origin:e.headers.origin,referer:e.headers.referer,host:e.headers.host})}submitReply(e,t,n,i=!1){let o=this.sessions.get(e);if(!o)return!1;let s=o.pending.get(t);return s?(o.pending.delete(t),i===!0?s.promptType==="info"?s.resolve(n):s.reject(new dt(wc)):s.resolve(n),!0):!1}pendingPromptType(e,t){return e.pending.get(t)?.promptType}send(e,t,n){let i=JSON.stringify(n);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(i)}async drainBody(e){let t=0;for await(let n of e)if(t+=n.length,t>1e6)throw new Error("Request body too large")}async readBody(e){let t=[],n=0;for await(let i of e){if(n+=i.length,n>1e6)throw new Error("Request body too large");t.push(i)}return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf8"))}async handle(e,t){try{if(!this.originAllowed(e)){this.send(t,403,{ok:!1,error:"Forbidden"});return}let n=new URL(e.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(t,404,{ok:!1,error:"Unknown session or token"});return}if(e.method==="GET"&&n.pathname==="/poll"){this.handlePoll(s,t);return}if(e.method==="POST"&&n.pathname==="/abort"){await this.drainBody(e);let a=this.abortSession(s.id);if(a===null){this.send(t,409,{ok:!1,error:"The interactive session has already ended"});return}this.send(t,200,{ok:!0,interrupted:a});return}if(e.method==="POST"&&n.pathname==="/reply"){let a=await this.readBody(e),l=this.submitWireReply(s.id,a);l.ok?this.send(t,200,{ok:!0}):this.send(t,l.status,{ok:!1,error:l.error});return}this.send(t,404,{ok:!1,error:"Not found"})}catch(n){this.send(t,400,{ok:!1,error:n instanceof Error?n.message:String(n)})}}handlePoll(e,t){e.attached||(e.attached=!0,e.attachTimer&&(window.clearTimeout(e.attachTimer),e.attachTimer=null)),e.pollWatchdog&&window.clearTimeout(e.pollWatchdog),e.pollWatchdog=window.setTimeout(()=>{this.finish(e.id,{kind:"error",error:"Interactive client disconnected."})},_oe);let n=e.queue.shift();if(n){this.send(t,200,n);return}if(e.waiter){this.send(t,200,{kind:"idle"});return}let i=o=>this.send(t,200,o);e.waiter=i,e.waiterTimer=window.setTimeout(()=>{e.waiter===i&&(e.waiter=null,e.waiterTimer=null,this.send(t,200,{kind:"idle"}))},xoe),t.on("close",()=>{e.waiter===i&&(e.waiterTimer&&window.clearTimeout(e.waiterTimer),e.waiter=null,e.waiterTimer=null)})}submitWireReply(e,t){let n=this.sessions.get(e);if(!n)return{ok:!1,status:409,error:n_};if(!t.requestId)return{ok:!1,status:409,error:n_};let i=this.pendingPromptType(n,t.requestId);if(!i)return{ok:!1,status:409,error:n_};let o=Foe(i,t);return o?{ok:!1,status:400,error:o}:this.submitReply(n.id,t.requestId,t.value,t.cancelled)?{ok:!0}:{ok:!1,status:409,error:n_}}},ms=new UP;function zP(r){if(!r||typeof r!="string")return null;let e=r.split("-")[0]?.split("+")[0]?.trim();if(!e)return null;let t=e.split(".");if(t.length!==3)return null;let n=Number.parseInt(t[0]??"",10),i=Number.parseInt(t[1]??"",10),o=Number.parseInt(t[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}}It();K0();ph();Dt();De();Rm();var op="\0qa-idx:";function $oe(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}var i_=class{constructor(e,t=ms){this.sessionId=e;this.server=t}async suggester(e,t,n,i=!1){let o=typeof e=="function"?t.map((c,u,d)=>String(e(c,u,d))):e.map(c=>String(c)),s=t.map((c,u)=>({title:o[u]??String(c),value:`${op}${u}`})),a=await this.server.emitPrompt(this.sessionId,{type:"suggester",placeholder:n,allowCustomInput:i,items:s});if(a==null)return"";let l=String(a);if(l.startsWith(op)){let c=Number(l.slice(op.length));if(Number.isInteger(c)&&c>=0&&c<t.length)return t[c]}return l}async suggesterMulti(e,t,n){let i=t.map((a,l)=>({title:e[l]??String(a),value:`${op}${l}`})),o=[];for(let a of n?.preselected??[]){let l=t.indexOf(a);if(l>=0)o.push(`${op}${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=>{let l=String(a);if(l.startsWith(op)){let c=Number(l.slice(op.length));if(Number.isInteger(c)&&c>=0&&c<t.length)return t[c]}return l}):[]}async inputPrompt(e,t,n){return this.textPrompt(e,t,n,!1)}async wideInputPrompt(e,t,n){return this.textPrompt(e,t,n,!0)}async textPrompt(e,t,n,i){let o=await this.server.emitPrompt(this.sessionId,{type:"input",header:e,placeholder:t,defaultValue:n,multiline:i});return o==null?"":String(o)}async datePrompt(e,t){let n=await this.server.emitPrompt(this.sessionId,{type:"date",header:e,placeholder:t?.placeholder,defaultValue:t?.defaultValue,dateFormat:t?.dateFormat,withTime:t?.withTime}),i=String(n??"");if(!i)return"";let o=i.startsWith("@date:")?i.slice(6):i,s=t?.dateFormat;return(s?qa(o,s):null)??o}async yesNoPrompt(e,t){let n=await this.server.emitPrompt(this.sessionId,{type:"confirm",header:e,text:t});if(n===!0||n==="true")return!0;if(n===!1||n==="false")return!1;throw new Error(`A confirm prompt needs a boolean reply, or {"cancelled": true} if the user dismissed it. Got ${$oe(n)}.`)}async checkboxPrompt(e,t,n){let i=new Set(t??[]),o=await this.server.emitPrompt(this.sessionId,{type:"checkbox",header:n,items:e.map(s=>({title:String(s),value:String(s),checked:i.has(s)}))});return Array.isArray(o)?o.map(s=>String(s)):[]}async infoDialog(e,t){await this.server.emitPrompt(this.sessionId,{type:"info",header:e,text:Array.isArray(t)?t:[t]})}async requestInputs(e){let t=e.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})),n=await this.server.emitPrompt(this.sessionId,{type:"form",fields:t});if(!n||typeof n!="object")return{};let i=new Set(e.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}};Je();It();ph();UC();var o_="quickadd:save-clipboard-image",y6={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"}},Moe=Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="),r=>r.charCodeAt(0));function Ooe(r){if(r===void 0||r==="")return;let e=r.toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="on")return!0;if(e==="false"||e==="0"||e==="no"||e==="off")return!1;throw new Error(`Invalid nameAfterNoteTitle: ${r}. Use true or false.`)}async function b6(r,e){try{let t=typeof e.sourcePath=="string"?e.sourcePath:"",n=Ooe(typeof e.nameAfterNoteTitle=="string"?e.nameAfterNoteTitle:void 0),i=await VC(r.app,Moe.buffer,"image/png",t,n===void 0?void 0:{nameAfterNoteTitle:n});return JSON.stringify({ok:!0,command:o_,path:i.path,name:i.name,sourcePath:t||"",nameAfterNoteTitle:n??r.settings.namePastedImagesAfterNoteTitle})}catch(t){return JSON.stringify({ok:!1,command:o_,error:t instanceof Error?t.message:String(t)})}}var w6={choice:{value:"<name>",description:"Choice name"},id:{value:"<id>",description:"Choice id"},vars:{value:"<json>",description:"Variables object as JSON"},ui:{description:"Allow interactive prompts"},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:{value:"<when>",description:"Day for {{DATE}} (YYYY-MM-DD, last week, last friday, ask, @date:ISO)"}},Roe={type:{value:"<Template|Capture|Macro|Multi>",description:"Filter by choice type"},commands:{description:"Only include command-enabled choices"}},Loe={path:{value:"<vault-path>",description:"Path to a template file in the vault"},vars:{value:"<json>",description:"Variables object as JSON"},ui:{description:"Allow interactive prompts"},date:{value:"<when>",description:"Day for {{DATE}} (YYYY-MM-DD, last week, last friday, ask, @date:ISO)"}},Noe={choice:{value:"<name>",description:"Choice name"},id:{value:"<id>",description:"Choice id"},vars:{value:"<json>",description:"Variables object as JSON"},fields:{description:"Include full field metadata (options, defaults, widget config)"}},Boe={choice:{value:"<name>",description:"Choice name"},id:{value:"<id>",description:"Choice id"},vars:{value:"<json>",description:"Variables object as JSON (pre-seeded inputs)"}},Voe={path:{value:"<vault-path>",description:"Path to a .quickadd.json package file in the vault"},decode:{description:"Inline decoded contents for each bundled file"}},qoe=new Set(["choice","id","vars","ui","verify","date"]),C6=new Set(["path","vars","ui","date"]),Uoe=new Set(["choice","id","vars","fields"]),zoe=new Set(["choice","id","vars"]),Rr={runDefault:"quickadd",run:"quickadd:run",runTemplate:"quickadd:run-template",list:"quickadd:list",check:"quickadd:check",preview:"quickadd:package-preview",interactive:"quickadd:interactive",saveClipboardImage:o_},Hoe=new Set(["template","capture","macro","multi"]);function Jt(r){return JSON.stringify(r)}function Th(r){if(r===void 0)return!1;let e=r.toLowerCase();return e==="true"||e==="1"||e==="yes"||e==="on"}function Woe(r){let e;try{e=JSON.parse(r)}catch(t){throw new Error(`Invalid vars JSON: ${t instanceof Error?t.message:String(t)}`)}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid vars JSON: expected an object");return e}function s_(r,e){let t={};typeof r.vars=="string"&&Object.assign(t,Woe(r.vars));for(let[n,i]of Object.entries(r)){if(n.startsWith("value-")){let o=n.slice(6);o&&(t[o]=i);continue}e.has(n)||(t[n]=i)}return t}function x6(r,e=[]){let t=[];for(let n of Wr(r)){if(!Ne(n))continue;let i=[...e,n.name],o=i.join(" / "),s=n.type==="Multi";t.push({id:n.id,name:n.name,type:n.type,command:n.command,path:o,runnable:!s}),s&&t.push(...x6(Qe(n),i))}return t}function HP(r,e){if(typeof e.id=="string"&&e.id.trim().length>0)return r.getChoiceById(e.id);if(typeof e.choice=="string"&&e.choice.trim().length>0)return r.getChoiceByName(e.choice);throw new Error("Missing choice selector. Provide either choice=<name> or id=<id>")}function WP(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 joe(r){return{...WP(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 jP(r,e){for(let[t,n]of Object.entries(e))r.variables.set(t,n)}function Vi(r){return{id:r.id,name:r.name,type:r.type}}function Goe(r){return r.type==="Macro"}async function T6(r,e,t,n,i,o=!1){let s=Date.now();try{if(n.type==="Multi")return Jt({ok:!1,command:t,error:"Multi choices are interactive and cannot be run via CLI.",choice:Vi(n)});let a=s_(e,i),l=new ei(r.app,r);if(jP(l,a),!dh(l,e.date))return Jt({ok:!1,command:t,error:`Could not parse date origin '${e.date}'.`,choice:Vi(n)});let c=Th(e.ui);if(l.interactive=c,!c){let f=await Ob(r.app,r,l,n,{preloadedUserScripts:l.preloadedUserScripts}),p=Rb(f,l.variables);if(p.length>0)return Jt({ok:!1,command:t,error:"Missing required inputs for non-interactive CLI run.",choice:Vi(n),missing:p.map(WP),missingFlags:p.map(m=>m.id===ml?"date=<when>":`value-${m.id}=<value>`)})}if(o&&(n.type==="Template"||n.type==="Capture")&&typeof l.executeWithOutcome=="function"){let f=await l.executeWithOutcome(n),p=Date.now()-s;return f.status==="success"?Jt({ok:!0,command:t,choice:Vi(n),file:f.file?.path,verified:!0,effect:f.effect,durationMs:p}):f.status==="cancelled"?Jt({ok:!1,command:t,error:f.reason||(f.cancelKind==="user"?"Execution cancelled by user":"Execution aborted"),aborted:!0,choice:Vi(n),durationMs:p}):Jt({ok:!1,command:t,error:f.reason||"Choice execution failed; no file was created.",choice:Vi(n),durationMs:p})}await l.execute(n);let u=l.consumeAbortSignal?.(),d=Date.now()-s;return Jt(u?{ok:!1,command:t,error:u.message||"Choice execution aborted",aborted:!0,choice:Vi(n),durationMs:d}:{ok:!0,command:t,choice:Vi(n),verified:!1,effect:"unknown",durationMs:d})}catch(a){return Jt({ok:!1,command:t,error:a instanceof Error?a.message:String(a)})}}async function E6(r,e,t){let n;try{n=HP(r,e)}catch(i){return Jt({ok:!1,command:t,error:i instanceof Error?i.message:String(i)})}return T6(r,e,t,n,qoe,Th(e.verify))}async function Yoe(r,e){let t=Rr.runTemplate;try{let n=typeof e.path=="string"?e.path.trim():"";if(!n)return Jt({ok:!1,command:t,error:"Missing template path. Provide path=<vault-path>."});let i=Mi(r.app,n);if(!i)return Jt({ok:!1,command:t,error:`No template file found at '${n}'.`});let o=AP(i.path);if(!Th(e.ui)){let a=s_(e,C6).value;if(a==null||String(a).trim().length===0)return Jt({ok:!1,command:t,error:"Missing required inputs for non-interactive CLI run.",choice:Vi(o),missing:[{id:"value",label:"New note name",type:"text",source:"collected",optionCount:0}],missingFlags:["value-value=<value>"]})}return await T6(r,e,t,o,C6,!0)}catch(n){return Jt({ok:!1,command:t,error:n instanceof Error?n.message:String(n)})}}function Koe(r,e){try{let t=typeof e.type=="string"?e.type.trim():"",n=t.toLowerCase(),i=Th(e.commands);if(n&&!Hoe.has(n))return Jt({ok:!1,command:Rr.list,error:`Invalid type filter '${t}'.`});let s=x6(r.settings.choices).filter(a=>!(n&&a.type.toLowerCase()!==n||i&&!a.command));return Jt({ok:!0,command:Rr.list,count:s.length,choices:s})}catch(t){return Jt({ok:!1,command:Rr.list,error:t instanceof Error?t.message:String(t)})}}async function Qoe(r,e){try{let t=HP(r,e);if(t.type==="Multi")return Jt({ok:!1,command:Rr.check,error:"Multi choices are interactive and cannot be checked via CLI.",choice:Vi(t)});let n=s_(e,Uoe),i=new ei(r.app,r);jP(i,n);let o=await Ob(r.app,r,i,t),s=Rb(o,i.variables),a=Th(e.fields)?joe:WP;return Jt({ok:s.length===0,command:Rr.check,choice:Vi(t),requiredInputCount:o.length,missingInputCount:s.length,missing:s.map(a),missingFlags:s.map(l=>`value-${l.id}=<value>`),...Goe(t)?{deferred:jW(r,t)}:{}})}catch(t){return Jt({ok:!1,command:Rr.check,error:t instanceof Error?t.message:String(t)})}}async function Xoe(r,e){let t=Rr.interactive,n;try{n=HP(r,e)}catch(i){return Jt({ok:!1,command:t,error:i instanceof Error?i.message:String(i)})}if(n.type==="Multi")return Jt({ok:!1,command:t,error:"Multi choices cannot be run interactively via CLI.",choice:Vi(n)});try{let i=await ms.ensureStarted(),{id:o,token:s}=ms.createSession(),a=new ei(r.app,r);return jP(a,s_(e,zoe)),a.interactive=!0,a.promptProvider=new i_(o),(async()=>{try{if((n.type==="Template"||n.type==="Capture")&&typeof a.executeWithOutcome=="function"){let c=await a.executeWithOutcome(n);if(c.status==="success"){ms.finish(o,{kind:"done",result:{ok:!0,choice:Vi(n),file:c.file?.path,verified:!0,effect:c.effect}});return}ms.finish(o,{kind:"error",error:c.status==="cancelled"?c.reason||(c.cancelKind==="user"?"Execution cancelled by user":"Execution aborted"):c.reason||"Choice execution failed; no file was created."});return}await a.execute(n);let l=a.consumeAbortSignal?.();if(l){ms.finish(o,{kind:"error",error:l.message||"Choice execution aborted"});return}ms.finish(o,{kind:"done",result:{ok:!0,choice:Vi(n),verified:!1,effect:"unknown"}})}catch(l){ms.finish(o,{kind:"error",error:l instanceof Error?l.message:String(l)})}})(),Jt({ok:!0,command:t,choice:Vi(n),host:"127.0.0.1",port:i,sessionId:o,token:s,capabilities:["abort","outcome-effect"]})}catch(i){return Jt({ok:!1,command:t,error:i instanceof Error?i.message:String(i)})}}async function Zoe(r,e){try{let t=typeof e.path=="string"?e.path.trim():"";if(!t)return Jt({ok:!1,command:Rr.preview,error:"Missing package path. Provide path=<vault-path>."});let{pkg:n}=await QV(r.app,t),i=await TT(r.app,r.settings.choices,n),o={ok:!0,command:Rr.preview,preview:i};return Th(e.decode)&&(o.contents=i.files.map(s=>({path:s.originalPath,...ET(n,s.originalPath)}))),Jt(o)}catch(t){return Jt({ok:!1,command:Rr.preview,error:t instanceof Error?t.message:String(t)})}}function S6(r){let e=r;if(typeof e.registerCliHandler!="function")return P.logMessage("Skipping QuickAdd CLI handler registration: registerCliHandler is unavailable."),!1;let t=e.registerCliHandler.bind(e);return t(Rr.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)",w6,n=>E6(r,n,Rr.runDefault)),t(Rr.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)",w6,n=>E6(r,n,Rr.run)),t(Rr.runTemplate,"Create a new note from a template file (no Template choice required)",Loe,n=>Yoe(r,n)),t(Rr.list,"List QuickAdd choices",Roe,n=>Koe(r,n)),t(Rr.check,"Check missing inputs for a QuickAdd choice",Noe,n=>Qoe(r,n)),t(Rr.preview,"Preview a QuickAdd package before importing (files + capabilities)",Voe,n=>Zoe(r,n)),t(Rr.interactive,"Run a choice interactively: forwards its runtime prompts to the caller over a local server (returns host/port/sessionId/token to attach)",Boe,n=>Xoe(r,n)),t(Rr.saveClipboardImage,"Save a 1x1 PNG as a vault attachment using QuickAdd clipboard-image naming",y6,n=>b6(r,n)),P.logMessage("Registered QuickAdd CLI handlers."),!0}var Tu={run:"Run",runTemplateFromFolder:"New note from template",applyTemplate:"Apply template to active note",reloadDev:"Reload (dev)",openSettings:"Open settings",resumePrompt:"Return to prompt"};ZA();Kg();xa();sP();var Joe=new Set(["shortcuts:","obsidian:"]);function a_(r){return typeof r=="string"&&r.length>0?r:void 0}function _6(r){let e=a_(r["x-success"]),t=a_(r["x-error"]),n=a_(r["x-cancel"]);if(e||t||n)return{success:e,error:t,cancel:n,any:!0};let i=a_(r["x-callback-url"]);return i?{success:i,cancel:i,any:!0}:{any:!1}}function k6(r){return[r.success,r.error,r.cancel].filter(e=>typeof e=="string"&&e.length>0)}function GP(r){try{let e=new URL(r).protocol.toLowerCase();return Joe.has(e)}catch{return!1}}function A6(r,e){let t=new URL(r);for(let[n,i]of Object.entries(e))t.searchParams.set(n,i);return t.toString()}function D6(r,e){return"obsidian://open?vault="+encodeURIComponent(r)+"&file="+encodeURIComponent(e)}var ese=1e3,l_=class extends Sh.Plugin{constructor(){super(...arguments);this.requestSave=(0,Sh.debounce)(()=>{(async()=>await this.saveData(this.settings))()},ese)}get api(){return gh.GetApi(this.app,this,new ei(this.app,this))}ingestImagesIntoActivePrompt(t){return NL(t)}async onload(){P.logMessage("Loading QuickAdd"),bL(this),await this.loadSettings(),ne.replaceState(this.settings),this.unsubscribeSettingsStore=ne.subscribe(o=>{this.settings=o,this.requestSave()}),this.addCommand({id:"runQuickAdd",name:Tu.run,callback:()=>{LP(this)}}),this.addCommand({id:"resumePrompt",name:Tu.resumePrompt,checkCallback:o=>Bc.isPeeking()?(o||Bc.getActive()?.resume(),!0):!1}),this.addCommand({id:"runTemplateFromFolder",name:Tu.runTemplateFromFolder,callback:()=>{KS(this.app,this,{choiceExecutor:new ei(this.app,this)})}}),this.addCommand({id:"applyTemplateToActiveFile",name:Tu.applyTemplate,checkCallback:o=>{let s=this.app.workspace.getActiveFile(),a=s?.extension==="md";if(o)return a;a&&Sb(this.app,this,{file:s,choiceExecutor:new ei(this.app,this)})}}),this.registerEvent(this.app.workspace.on("file-menu",(o,s)=>{s instanceof Sh.TFile&&s.extension==="md"&&o.addItem(a=>a.setTitle(`QuickAdd: ${Tu.applyTemplate}`).setIcon("file-plus").onClick(()=>{Sb(this.app,this,{file:s,choiceExecutor:new ei(this.app,this)})}))})),this.addCommand({id:"reloadQuickAdd",name:Tu.reloadDev,checkCallback:o=>{if(o)return this.settings.devMode;let s=this.manifest.id,a=this.app.plugins;a.disablePlugin(s).then(()=>a.enablePlugin(s))}});let t=Gl.getInstance();t.startAutomaticCleanup(o=>this.registerInterval(o)),t.registerInvalidationListeners(this.app,o=>this.registerEvent(o)),this.addCommand({id:"openQuickAddSettings",name:Tu.openSettings,callback:()=>{Pm(this.app,this.manifest.id)}}),this.registerObsidianProtocolHandler("quickadd",async o=>{let s=o,a=this.settings.enableUriCallbacks?_6(s):{any:!1};if(!a.any){await this.runUriChoiceLegacy(s);return}let l=k6(a).filter(f=>!GP(f));if(l.length>0){P.logWarning(`QuickAdd URI: ignoring disallowed callback URL(s): ${l.join(", ")}`),a.error&&GP(a.error)&&this.openUriCallback(a.error,{status:"error",errorCode:"bad-callback-url"});return}if(!s.choice){P.logWarning("URI was executed without a `choice` parameter."),this.fireUriError(a,"choice-not-found");return}let c=this.getChoice("name",s.choice);if(!c){P.logWarning(`URI could not find any choice named '${s.choice}'`),this.fireUriError(a,"choice-not-found");return}if(this.warnIfChoiceNameAmbiguous(s.choice),c.type!=="Template"&&c.type!=="Capture"){P.logWarning(`QuickAdd URI x-callback supports Template and Capture choices only ('${c.name}' is ${c.type}). A URI with x-* callback params cannot run a ${c.type} choice while "Enable URI callbacks" is on; remove the x-* params to run it on the legacy path.`),this.fireUriError(a,"unsupported-choice-type");return}let u=new ei(this.app,this);if(!this.applyUriValueParameters(u,s)){P.logWarning(`QuickAdd URI: could not parse date origin '${s.date}'.`),this.fireUriError(a,"execution-failed");return}let d=await u.executeWithOutcome(c);switch(d.status){case"success":this.fireUriSuccess(a,d.file,d.effect);break;case"cancelled":d.cancelKind==="user"?this.fireUriCancel(a):this.fireUriError(a,"execution-aborted");break;case"error":this.fireUriError(a,"execution-failed");break}}),P.register(new Uy).register(new IT(this)),bq(this),this.settings.enableRibbonIcon&&this.addRibbonIcon("file-plus","QuickAdd",()=>{LP(this)}),this.addSettingTab(new DT(this.app,this)),this.addCommandsForChoices(this.settings.choices);try{await g6(this)}catch(o){We(o,"QuickAdd could not run its settings migrations")}let n=()=>{try{S6(this)}catch(o){We(o,"QuickAdd could not register its CLI handlers")}};this.app.workspace.layoutReady?n():this.app.workspace.onLayoutReady(n);let i=async()=>{try{await new RS(this.app,this,this.settings.choices,new ei(this.app,this)).run()}catch(o){We(o,"QuickAdd could not run its startup macros")}};this.app.workspace.layoutReady?i():this.app.workspace.onLayoutReady(i),this.app.workspace.onLayoutReady(()=>{window.setTimeout(()=>{mV(this.app)},5e3)}),this.announceUpdate()}async runUriChoiceLegacy(t){if(!t.choice){P.logWarning("URI was executed without a `choice` parameter.");return}let n=this.getChoice("name",t.choice);if(!n){We(new Error(`URI could not find any choice named '${t.choice}'`),"URI handler error");return}this.warnIfChoiceNameAmbiguous(t.choice);let i=new ei(this.app,this);if(!this.applyUriValueParameters(i,t)){We(new Error(`Could not parse date origin '${t.date}'`),"URI handler error");return}try{await i.execute(n)}catch(o){Lp(o,`Could not run "${n.name}"`)}}applyUriValueParameters(t,n){return Object.entries(n).filter(([i])=>i.startsWith("value-")).forEach(([i,o])=>{let s=i.slice(6);s&&typeof o=="string"&&!wS(s)&&t.variables.set(s,o)}),!!dh(t,n.date)}fireUriSuccess(t,n,i){let o={status:"success",effect:i};n&&(o.path=n.path,o.url=D6(this.app.vault.getName(),n.path)),t.success&&this.openUriCallback(t.success,o)}fireUriError(t,n){t.error&&this.openUriCallback(t.error,{status:"error",errorCode:n})}fireUriCancel(t){t.cancel&&this.openUriCallback(t.cancel,{status:"cancel"})}openUriCallback(t,n){wO(()=>{window.open(A6(t,n))},"QuickAdd URI: failed to open callback URL")}onunload(){P.logMessage("Unloading QuickAdd"),this.requestSave.run(),this.unsubscribeSettingsStore?.call(this),ug.loggers.forEach(n=>{n instanceof Uy&&n.clearErrorLog()}),Gl.getInstance().destroy(),ms.stop(),Bc.getActive()?.cancel()}async loadSettings(){let t=await this.loadData(),n=Object.assign({},$w,t);typeof n.announceUpdates=="boolean"&&(n.announceUpdates=n.announceUpdates?"all":"none"),Array.isArray(n.choices)&&(n.choices=ZR(n.choices)),this.settings=n}async saveSettings(){this.requestSave.cancel(),await this.saveData(this.settings)}addCommandsForChoices(t){for(let n of Wr(t))if(Ne(n))try{this.addCommandForChoice(n)}catch(i){We(i,"Could not add a command for a QuickAdd choice")}}addCommandForChoice(t){if(t.type==="Multi"&&this.addCommandsForChoices(Qe(t)),t.command){let n=t.id;this.addCommand({id:qE(n),name:t.name,icon:Cd(t),callback:()=>this.runRegisteredChoice(n,t.name)}),o2({origin:t.dateOrigin,enabled:t.pickDayCommand})&&this.addCommand({id:DD(n),name:ID(t.name),icon:Cd(t),callback:()=>this.runRegisteredChoice(n,t.name,!0)})}}async runRegisteredChoice(t,n,i=!1){let o;try{o=this.getChoiceById(t);let s=new ei(this.app,this);s.pickDate=i,await s.execute(o)}catch(s){Lp(s,`Could not run "${o?.name??n}"`)}}getChoiceById(t){let n=this.getChoice("id",t);if(!n)throw new Error(`Choice ${t} not found`);return n}getChoiceByName(t){let n=this.getChoice("name",t);if(!n)throw new Error(`Choice ${t} not found`);return n}getChoice(t,n,i=this.settings.choices){for(let o of Wr(i))if(Ne(o)){if(o[t]===n)return o;if(o.type==="Multi"){let s=this.getChoice(t,n,Qe(o));if(s)return s}}return null}countChoicesByName(t,n=this.settings.choices){let i=0;for(let o of Wr(n))Ne(o)&&(o.name===t&&i++,o.type==="Multi"&&(i+=this.countChoicesByName(t,Qe(o))));return i}warnIfChoiceNameAmbiguous(t){let n=this.countChoicesByName(t);n>1&&P.logWarning(`QuickAdd URI: ${n} choices are named '${t}'. Ran the first match \u2014 rename choices to keep names unique so URIs target the right one.`)}removeCommandForChoice(t,n){if(n?.recursive&&t.type==="Multi")for(let i of Qe(t))Ne(i)&&this.removeCommandForChoice(i,n);nC(this.app,`quickadd:${qE(t.id)}`),nC(this.app,`quickadd:${DD(t.id)}`)}getTemplateFiles(){let t=ui(this.settings.templateFolderPaths);return this.app.vault.getFiles().filter(n=>Qw(n.path)).filter(n=>qk(n.path,t))}announceUpdate(){let t=(l,c)=>{let u=zP(l),d=zP(c);return!u||!d?!0:u.major!==d.major?u.major>d.major:u.minor>d.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"&&!t(n,i))&&(s=!1),this.settings.version=n,this.saveSettings(),!s)return;new t_(this.app,i).open()}};
/* nosourcemap */