@livetemplate/client 0.11.6 → 0.11.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var LiveTemplateClient=(()=>{var Oe=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var on=Object.getOwnPropertyNames;var an=Object.prototype.hasOwnProperty;var ln=(i,e)=>{for(var t in e)Oe(i,t,{get:e[t],enumerable:!0})},cn=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of on(e))!an.call(i,r)&&r!==t&&Oe(i,r,{get:()=>e[r],enumerable:!(n=sn(e,r))||n.enumerable});return i};var dn=i=>cn(Oe({},"__esModule",{value:!0}),i);var Jn={};ln(Jn,{LiveTemplateClient:()=>De,compareHTML:()=>rn,loadAndApplyUpdate:()=>nn,setupReactiveAttributeListeners:()=>me});var Ze=11;function un(i,e){var t=e.attributes,n,r,s,a,o;if(!(e.nodeType===Ze||i.nodeType===Ze)){for(var c=t.length-1;c>=0;c--)n=t[c],r=n.name,s=n.namespaceURI,a=n.value,s?(r=n.localName||r,o=i.getAttributeNS(s,r),o!==a&&(n.prefix==="xmlns"&&(r=n.name),i.setAttributeNS(s,r,a))):(o=i.getAttribute(r),o!==a&&i.setAttribute(r,a));for(var l=i.attributes,d=l.length-1;d>=0;d--)n=l[d],r=n.name,s=n.namespaceURI,s?(r=n.localName||r,e.hasAttributeNS(s,r)||i.removeAttributeNS(s,r)):e.hasAttribute(r)||i.removeAttribute(r)}}var ce,pn="http://www.w3.org/1999/xhtml",U=typeof document=="undefined"?void 0:document,fn=!!U&&"content"in U.createElement("template"),gn=!!U&&U.createRange&&"createContextualFragment"in U.createRange();function hn(i){var e=U.createElement("template");return e.innerHTML=i,e.content.childNodes[0]}function mn(i){ce||(ce=U.createRange(),ce.selectNode(U.body));var e=ce.createContextualFragment(i);return e.childNodes[0]}function vn(i){var e=U.createElement("body");return e.innerHTML=i,e.childNodes[0]}function yn(i){return i=i.trim(),fn?hn(i):gn?mn(i):vn(i)}function de(i,e){var t=i.nodeName,n=e.nodeName,r,s;return t===n?!0:(r=t.charCodeAt(0),s=n.charCodeAt(0),r<=90&&s>=97?t===n.toUpperCase():s<=90&&r>=97?n===t.toUpperCase():!1)}function bn(i,e){return!e||e===pn?U.createElement(i):U.createElementNS(e,i)}function En(i,e){for(var t=i.firstChild;t;){var n=t.nextSibling;e.appendChild(t),t=n}return e}function Fe(i,e,t){i[t]!==e[t]&&(i[t]=e[t],i[t]?i.setAttribute(t,""):i.removeAttribute(t))}var et={OPTION:function(i,e){var t=i.parentNode;if(t){var n=t.nodeName.toUpperCase();n==="OPTGROUP"&&(t=t.parentNode,n=t&&t.nodeName.toUpperCase()),n==="SELECT"&&!t.hasAttribute("multiple")&&(i.hasAttribute("selected")&&!e.selected&&(i.setAttribute("selected","selected"),i.removeAttribute("selected")),t.selectedIndex=-1)}Fe(i,e,"selected")},INPUT:function(i,e){Fe(i,e,"checked"),Fe(i,e,"disabled"),i.value!==e.value&&(i.value=e.value),e.hasAttribute("value")||i.removeAttribute("value")},TEXTAREA:function(i,e){var t=e.value;i.value!==t&&(i.value=t);var n=i.firstChild;if(n){var r=n.nodeValue;if(r==t||!t&&r==i.placeholder)return;n.nodeValue=t}},SELECT:function(i,e){if(!e.hasAttribute("multiple")){for(var t=-1,n=0,r=i.firstChild,s,a;r;)if(a=r.nodeName&&r.nodeName.toUpperCase(),a==="OPTGROUP")s=r,r=s.firstChild,r||(r=s.nextSibling,s=null);else{if(a==="OPTION"){if(r.hasAttribute("selected")){t=n;break}n++}r=r.nextSibling,!r&&s&&(r=s.nextSibling,s=null)}i.selectedIndex=t}}},ie=1,tt=11,nt=3,rt=8;function z(){}function wn(i){if(i)return i.getAttribute&&i.getAttribute("id")||i.id}function An(i){return function(t,n,r){if(r||(r={}),typeof n=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"||t.nodeName==="BODY"){var s=n;n=U.createElement("html"),n.innerHTML=s}else n=yn(n);else n.nodeType===tt&&(n=n.firstElementChild);var a=r.getNodeKey||wn,o=r.onBeforeNodeAdded||z,c=r.onNodeAdded||z,l=r.onBeforeElUpdated||z,d=r.onElUpdated||z,u=r.onBeforeNodeDiscarded||z,p=r.onNodeDiscarded||z,g=r.onBeforeElChildrenUpdated||z,h=r.skipFromChildren||z,H=r.addChild||function(v,m){return v.appendChild(m)},I=r.childrenOnly===!0,R=Object.create(null),x=[];function w(v){x.push(v)}function $(v,m){if(v.nodeType===ie)for(var L=v.firstChild;L;){var b=void 0;m&&(b=a(L))?w(b):(p(L),L.firstChild&&$(L,m)),L=L.nextSibling}}function f(v,m,L){u(v)!==!1&&(m&&m.removeChild(v),p(v),$(v,L))}function E(v){if(v.nodeType===ie||v.nodeType===tt)for(var m=v.firstChild;m;){var L=a(m);L&&(R[L]=m),E(m),m=m.nextSibling}}E(t);function _(v){c(v);for(var m=v.firstChild;m;){var L=m.nextSibling,b=a(m);if(b){var y=R[b];y&&de(m,y)?(m.parentNode.replaceChild(y,m),W(y,m)):_(m)}else _(m);m=L}}function M(v,m,L){for(;m;){var b=m.nextSibling;(L=a(m))?w(L):f(m,v,!0),m=b}}function W(v,m,L){var b=a(m);if(b&&delete R[b],!L){var y=l(v,m);if(y===!1||(y instanceof HTMLElement&&(v=y,E(v)),i(v,m),d(v),g(v,m)===!1))return}v.nodeName!=="TEXTAREA"?T(v,m):et.TEXTAREA(v,m)}function T(v,m){var L=h(v,m),b=m.firstChild,y=v.firstChild,D,F,K,Z,B;e:for(;b;){for(Z=b.nextSibling,D=a(b);!L&&y;){if(K=y.nextSibling,b.isSameNode&&b.isSameNode(y)){b=Z,y=K;continue e}F=a(y);var q=y.nodeType,j=void 0;if(q===b.nodeType&&(q===ie?(D?D!==F&&((B=R[D])?K===B?j=!1:(v.insertBefore(B,y),F?w(F):f(y,v,!0),y=B,F=a(y)):j=!1):F&&(j=!1),j=j!==!1&&de(y,b),j&&W(y,b)):(q===nt||q==rt)&&(j=!0,y.nodeValue!==b.nodeValue&&(y.nodeValue=b.nodeValue))),j){b=Z,y=K;continue e}F?w(F):f(y,v,!0),y=K}if(D&&(B=R[D])&&de(B,b))L||H(v,B),W(B,b);else{var _e=o(b);_e!==!1&&(_e&&(b=_e),b.actualize&&(b=b.actualize(v.ownerDocument||U)),H(v,b),_(b))}b=Z,y=K}M(v,y,F);var Qe=et[v.nodeName];Qe&&Qe(v,m)}var A=t,O=A.nodeType,N=n.nodeType;if(!I){if(O===ie)N===ie?de(t,n)||(p(t),A=En(t,bn(n.nodeName,n.namespaceURI))):A=n;else if(O===nt||O===rt){if(N===O)return A.nodeValue!==n.nodeValue&&(A.nodeValue=n.nodeValue),A;A=n}}if(A===n)p(t);else{if(n.isSameNode&&n.isSameNode(A))return;if(W(A,n,I),x)for(var S=0,C=x.length;S<C;S++){var k=R[x[S]];k&&f(k,k.parentNode,!1)}}return!I&&A!==t&&t.parentNode&&(A.actualize&&(A=A.actualize(t.ownerDocument||U)),t.parentNode.replaceChild(A,t)),A}}var Tn=An(un),ue=Tn;var Ne=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"];var pe=class{constructor(e){this.logger=e;this.wrapperElement=null;this.focusableElements=[];this.lastFocusedElement=null;this.lastFocusedSelectionStart=null;this.lastFocusedSelectionEnd=null}attach(e){this.wrapperElement=e,e&&(this.updateFocusableElements(),this.setupFocusTracking())}reset(){this.wrapperElement=null,this.focusableElements=[],this.lastFocusedElement=null,this.lastFocusedSelectionStart=null,this.lastFocusedSelectionEnd=null}updateFocusableElements(){if(!this.wrapperElement)return;let n=`${Ne.map(r=>r==="textarea"?"textarea:not([disabled])":`input[type="${r}"]:not([disabled])`).join(", ")}, select:not([disabled]), button:not([disabled]), [contenteditable="true"], [tabindex]:not([tabindex="-1"])`;this.focusableElements=Array.from(this.wrapperElement.querySelectorAll(n))}setupFocusTracking(){if(!this.wrapperElement)return;let e=this.wrapperElement.getAttribute("data-lvt-id"),t=`__lvt_focus_tracker_${e}`,n=`__lvt_blur_tracker_${e}`,r=a=>{var c;let o=a.target;!o||!((c=this.wrapperElement)!=null&&c.contains(o))||(this.isTextualInput(o)||o instanceof HTMLSelectElement)&&(this.lastFocusedElement=o,this.logger.debug("[Focus] Tracked focus on:",o.tagName,o.id||o.getAttribute("name")),this.isTextualInput(o)&&(this.lastFocusedSelectionStart=o.selectionStart,this.lastFocusedSelectionEnd=o.selectionEnd))},s=a=>{var c;let o=a.target;!o||!((c=this.wrapperElement)!=null&&c.contains(o))||this.isTextualInput(o)&&o===this.lastFocusedElement&&(this.lastFocusedSelectionStart=o.selectionStart,this.lastFocusedSelectionEnd=o.selectionEnd,this.logger.debug("[Focus] Saved cursor on blur:",this.lastFocusedSelectionStart,"-",this.lastFocusedSelectionEnd))};document[t]&&document.removeEventListener("focus",document[t],!0),document[n]&&document.removeEventListener("blur",document[n],!0),document[t]=r,document[n]=s,document.addEventListener("focus",r,!0),document.addEventListener("blur",s,!0),this.logger.debug("[Focus] Focus tracking set up")}restoreFocusedElement(){var a,o,c;if(this.logger.debug("[Focus] restoreFocusedElement - lastFocusedElement:",(a=this.lastFocusedElement)==null?void 0:a.tagName,((o=this.lastFocusedElement)==null?void 0:o.id)||((c=this.lastFocusedElement)==null?void 0:c.getAttribute("name"))),!this.lastFocusedElement||!this.wrapperElement){this.logger.debug("[Focus] No element to restore");return}let e=this.getElementSelector(this.lastFocusedElement);if(this.logger.debug("[Focus] Selector for last focused:",e),!e){this.logger.debug("[Focus] Could not generate selector");return}let t=null;if(e.startsWith("data-focus-index-")){this.updateFocusableElements();let l=parseInt(e.replace("data-focus-index-",""),10);t=this.focusableElements[l]||null,this.logger.debug("[Focus] Found by index:",l,t==null?void 0:t.tagName)}else t=this.wrapperElement.querySelector(e),this.logger.debug("[Focus] Found by selector:",e,t==null?void 0:t.tagName);if(!t){this.logger.debug("[Focus] Element not found in updated DOM");return}let n=t.matches(":focus");if(this.logger.debug("[Focus] Already focused:",n),n){this.logger.debug("[Focus] Element retained focus \u2014 skipping restoration");return}let r=this.lastFocusedSelectionStart,s=this.lastFocusedSelectionEnd;t.focus(),this.logger.debug("[Focus] Restored focus"),this.isTextualInput(t)&&r!==null&&s!==null&&(t.setSelectionRange(r,s),this.logger.debug("[Focus] Restored cursor:",r,"-",s))}isTextualInput(e){return e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?Ne.indexOf(e.type)>=0:!1}shouldSkipUpdate(e){return e!==document.activeElement||e.hasAttribute("data-lvt-force-update")?!1:!!(this.isTextualInput(e)||e instanceof HTMLSelectElement)}getLastFocusedElement(){return this.lastFocusedElement}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;if(e.getAttribute("data-key"))return`[data-key="${e.getAttribute("data-key")}"]`;let t=this.focusableElements.indexOf(e);return t>=0?`data-focus-index-${t}`:null}};var it=["pending","success","error","done"],Ue=new Set(it),fe=new Set(["click-away"]),$e={reset:"reset",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"};function Sn(i,e){let n=i.toLowerCase().match(/^lvt-el:(\w+):on:(.+)$/);if(n){let r=n[1],s=$e[r];if(!s)return null;let a=n[2];if(fe.has(a)||!Ue.has(a)&&!a.includes(":"))return null;let o=a.split(":"),c=o[o.length-1];if(!Ue.has(c))return null;let l=c,d=o.length>1?o.slice(0,-1).join(":"):void 0;return{action:s,lifecycle:l,actionName:d||void 0,param:e||void 0}}return null}function G(i){let e=i.getAttribute("data-lvt-target");return e?e.startsWith("#")?document.getElementById(e.slice(1))||i:e.startsWith("closest:")&&i.closest(e.slice(8))||i:i}function ge(i,e,t){switch(e){case"reset":i instanceof HTMLFormElement&&i.reset();break;case"addClass":if(t){let n=t.split(/\s+/).filter(Boolean);i.classList.add(...n)}break;case"removeClass":if(t){let n=t.split(/\s+/).filter(Boolean);i.classList.remove(...n)}break;case"toggleClass":t&&t.split(/\s+/).filter(Boolean).forEach(r=>i.classList.toggle(r));break;case"setAttr":if(t){let n=t.indexOf(":");if(n>0){let r=t.substring(0,n),s=t.substring(n+1);i.setAttribute(r,s)}}break;case"toggleAttr":t&&i.toggleAttribute(t);break}}function Ln(i,e,t){return i.lifecycle!==e?!1:i.actionName?i.actionName===t:!0}function kn(i,e){let t=Object.keys($e),n=[],r=e?e.replace(/([^\w-])/g,"\\$1"):void 0;for(let o of t)n.push(`[lvt-el\\:${o}\\:on\\:${i}]`),r&&n.push(`[lvt-el\\:${o}\\:on\\:${r}\\:${i}]`);let s=n.join(", "),a;try{a=document.querySelectorAll(s)}catch(o){let c=t.map(l=>`[lvt-el\\:${l}\\:on\\:${i}]`);try{a=document.querySelectorAll(c.join(", "))}catch(l){return}}a.forEach(o=>{Array.from(o.attributes).forEach(c=>{if(!c.name.startsWith("lvt-el:")||!c.name.includes(":on:"))return;let l=Sn(c.name,c.value);l&&Ln(l,i,e)&&ge(G(o),l.action,l.param)})})}function he(i,e){for(let t of i.attributes){let n=t.name.match(/^lvt-el:(\w+):on:([a-z-]+)$/i);if(!n||n[2].toLowerCase()!==e)continue;let r=n[1].toLowerCase(),s=$e[r];s&&ge(G(i),s,t.value)}}function st(i){return!Ue.has(i)&&!fe.has(i)}function me(){it.forEach(i=>{document.addEventListener(`lvt:${i}`,e=>{var r;let n=(r=e.detail)==null?void 0:r.action;kn(i,n)},!0)})}var ut=new Set(["pending","success","error","done"]),ot=new WeakSet,ve=new WeakMap,Y=new Map;function pt(i){let e=i.match(/^lvt-fx:\w+:on:(.+)$/i);if(!e)return{trigger:null};let t=e[1].split(":");return t.length===1?{trigger:t[0].toLowerCase()}:{trigger:t[t.length-1].toLowerCase(),actionName:t.slice(0,-1).join(":")}}function ft(i,e){let t=e||i,n="__lvtFxDirectListeners",r=(t[n]||[]).filter(a=>a.el.isConnected),s=a=>{var o;for(let c of a.attributes){if(!c.name.startsWith("lvt-fx:"))continue;let l=pt(c.name);if(!l.trigger||ut.has(l.trigger)||fe.has(l.trigger))continue;let d=`__lvt_fx_${c.name}`;if(a[d])continue;let u=(o=c.name.match(/^lvt-fx:(\w+)/i))==null?void 0:o[1];if(!u)continue;let p=c.name,g=()=>{if(!a.hasAttribute(p))return;let h=a.getAttribute(p)||"",H=G(a);oe(H,u,h)};a.addEventListener(l.trigger,g),a[d]=g,r.push({el:a,event:l.trigger,handler:g,guardKey:d})}};s(i),i.querySelectorAll("*").forEach(s),t[n]=r}function gt(i){let e="__lvtFxDirectListeners",t=i[e];t&&(t.forEach(({el:n,event:r,handler:s,guardKey:a})=>{n.removeEventListener(r,s),delete n[a]}),delete i[e])}function Mn(i,e,t){let n=r=>{var s;for(let a of r.attributes){if(!a.name.startsWith("lvt-fx:"))continue;let o=pt(a.name);if(!o.trigger||!ut.has(o.trigger)||o.trigger!==e||o.actionName&&o.actionName!==t)continue;let c=(s=a.name.match(/^lvt-fx:(\w+)/i))==null?void 0:s[1];c&&oe(r,c,a.value)}};n(i),i.querySelectorAll("*").forEach(n)}function oe(i,e,t){let n=getComputedStyle(i);switch(e){case"highlight":{if(i.__lvtHighlighting)break;i.__lvtHighlighting=!0;let r=parseInt(n.getPropertyValue("--lvt-highlight-duration").trim()||"500",10),s=n.getPropertyValue("--lvt-highlight-color").trim()||"#ffc107",a=i.style.backgroundColor,o=i.style.transition;i.style.transition=`background-color ${r}ms ease-out`,i.style.backgroundColor=s,setTimeout(()=>{if(!i.isConnected){i.style.backgroundColor=a,i.style.transition=o,i.style.length===0&&i.removeAttribute("style"),i.__lvtHighlighting=!1;return}i.style.backgroundColor=a,setTimeout(()=>{i.isConnected&&(i.style.transition=o,i.style.length===0&&i.removeAttribute("style")),i.__lvtHighlighting=!1},r)},50);break}case"animate":{if(ot.has(i))break;ot.add(i);let r=parseInt(n.getPropertyValue("--lvt-animate-duration").trim()||"500",10),s=t||"fade",a="";switch(s){case"fade":a=`lvt-fade-in ${r}ms ease-out`;break;case"slide":a=`lvt-slide-in ${r}ms ease-out`;break;case"scale":a=`lvt-scale-in ${r}ms ease-out`;break;default:console.warn(`Unknown lvt-fx:animate mode: ${s}`)}if(!a)break;i.style.animation=a,i.addEventListener("animationend",()=>{i.style.removeProperty("animation"),i.style.length===0&&i.removeAttribute("style")},{once:!0});break}case"scroll":{let r=n.getPropertyValue("--lvt-scroll-behavior").trim(),s=xn.has(r)?r:"auto",a=parseInt(n.getPropertyValue("--lvt-scroll-threshold").trim()||"100",10),o=t||"bottom";switch(o){case"bottom":i.scrollTo({top:i.scrollHeight,behavior:s});break;case"bottom-sticky":{i.dataset.lvtScrollSticky==="1"?i.scrollHeight-i.scrollTop-i.clientHeight<=a&&i.scrollTo({top:i.scrollHeight,behavior:s}):(i.dataset.lvtScrollSticky="1",i.scrollTo({top:i.scrollHeight,behavior:"instant"}));break}case"top":i.scrollTo({top:0,behavior:s});break;case"into-view":{i.dataset.lvtIvDone!=="1"&&(i.scrollIntoView({block:"center",inline:"nearest",behavior:s}),i.dataset.lvtIvDone="1");break}case"preserve":break;default:{if(o.startsWith("reset-on:")){let c=o.slice(9);if(!c){console.warn('lvt-fx:scroll="reset-on:" requires an attribute name');break}let l=i.getAttribute(c);ve.has(i)?ve.get(i)!==l&&(ve.set(i,l),i.scrollLeft=0,i.scrollTop=0):ve.set(i,l);break}console.warn(`Unknown lvt-fx:scroll mode: ${o}`)}}break}default:console.warn(`Unknown lvt-fx effect: ${e}`)}}function ht(i){let e="__lvtFxLifecycleSetup";if(i[e])return;i[e]=!0;let t=[];["pending","success","error","done"].forEach(r=>{let s=a=>{var l;let c=(l=a.detail)==null?void 0:l.action;Mn(i,r,c)};document.addEventListener(`lvt:${r}`,s,!0),t.push({event:`lvt:${r}`,handler:s})}),i.__lvtFxLifecycleListeners=t}function mt(i){let e=i.__lvtFxLifecycleListeners;e&&(e.forEach(({event:t,handler:n})=>{document.removeEventListener(t,n,!0)}),delete i.__lvtFxLifecycleListeners),delete i.__lvtFxLifecycleSetup}var xn=new Set(["auto","smooth","instant"]);function vt(i){i.querySelectorAll("[lvt-fx\\:scroll]").forEach(e=>{let t=e.getAttribute("lvt-fx:scroll");t&&oe(e,"scroll",t)})}function yt(){for(let{timer:i}of Y.values())clearTimeout(i);Y.clear()}function bt(i){if(!(Y.size===0&&i.querySelector("[lvt-fx\\:auto-click]")===null)){for(let[e,t]of Array.from(Y))(!e.isConnected||!e.hasAttribute("lvt-fx:auto-click"))&&(clearTimeout(t.timer),Y.delete(e));i.querySelectorAll("[lvt-fx\\:auto-click]").forEach(e=>{let t=e.getAttribute("lvt-fx:auto-click");if(!t)return;let n=Y.get(e);if(n&&n.spec===t)return;n&&clearTimeout(n.timer);let r=t.indexOf(":"),s=r>0?t.slice(0,r):"",a=/^\d+$/.test(s)?parseInt(s,10):NaN,o=r>0?t.slice(r+1):"";if(!Number.isFinite(a)||a<0||!o||!/^[\w-]+$/.test(o)){console.warn(`lvt-fx:auto-click expects "<delay-ms>:<button-name>", got: ${t}`),Y.delete(e);return}let c=setTimeout(()=>{if(!e.isConnected)return;let l=e.querySelector(`button[name="${o}"]`);l&&l.click()},a);Y.set(e,{timer:c,spec:t})})}}function Et(i){i.querySelectorAll("[lvt-fx\\:highlight]").forEach(e=>{let t=e.getAttribute("lvt-fx:highlight");t&&oe(e,"highlight",t)})}function wt(i){i.querySelectorAll("[lvt-fx\\:animate]").forEach(e=>{let t=e.getAttribute("lvt-fx:animate");t&&oe(e,"animate",t)}),Cn()}function Cn(){if(!document.getElementById("lvt-animate-styles")){let i=document.createElement("style");i.id="lvt-animate-styles",i.textContent=`
1
+ "use strict";var LiveTemplateClient=(()=>{var Ue=Object.defineProperty;var pn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var gn=Object.prototype.hasOwnProperty;var hn=(i,e)=>{for(var t in e)Ue(i,t,{get:e[t],enumerable:!0})},mn=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fn(e))!gn.call(i,r)&&r!==t&&Ue(i,r,{get:()=>e[r],enumerable:!(n=pn(e,r))||n.enumerable});return i};var vn=i=>mn(Ue({},"__esModule",{value:!0}),i);var or={};hn(or,{LiveTemplateClient:()=>Fe,compareHTML:()=>un,loadAndApplyUpdate:()=>dn,setupReactiveAttributeListeners:()=>ye});var rt=11;function yn(i,e){var t=e.attributes,n,r,s,a,o;if(!(e.nodeType===rt||i.nodeType===rt)){for(var c=t.length-1;c>=0;c--)n=t[c],r=n.name,s=n.namespaceURI,a=n.value,s?(r=n.localName||r,o=i.getAttributeNS(s,r),o!==a&&(n.prefix==="xmlns"&&(r=n.name),i.setAttributeNS(s,r,a))):(o=i.getAttribute(r),o!==a&&i.setAttribute(r,a));for(var l=i.attributes,d=l.length-1;d>=0;d--)n=l[d],r=n.name,s=n.namespaceURI,s?(r=n.localName||r,e.hasAttributeNS(s,r)||i.removeAttributeNS(s,r)):e.hasAttribute(r)||i.removeAttribute(r)}}var ue,bn="http://www.w3.org/1999/xhtml",U=typeof document=="undefined"?void 0:document,En=!!U&&"content"in U.createElement("template"),wn=!!U&&U.createRange&&"createContextualFragment"in U.createRange();function An(i){var e=U.createElement("template");return e.innerHTML=i,e.content.childNodes[0]}function Tn(i){ue||(ue=U.createRange(),ue.selectNode(U.body));var e=ue.createContextualFragment(i);return e.childNodes[0]}function Sn(i){var e=U.createElement("body");return e.innerHTML=i,e.childNodes[0]}function Ln(i){return i=i.trim(),En?An(i):wn?Tn(i):Sn(i)}function pe(i,e){var t=i.nodeName,n=e.nodeName,r,s;return t===n?!0:(r=t.charCodeAt(0),s=n.charCodeAt(0),r<=90&&s>=97?t===n.toUpperCase():s<=90&&r>=97?n===t.toUpperCase():!1)}function kn(i,e){return!e||e===bn?U.createElement(i):U.createElementNS(e,i)}function Mn(i,e){for(var t=i.firstChild;t;){var n=t.nextSibling;e.appendChild(t),t=n}return e}function $e(i,e,t){i[t]!==e[t]&&(i[t]=e[t],i[t]?i.setAttribute(t,""):i.removeAttribute(t))}var it={OPTION:function(i,e){var t=i.parentNode;if(t){var n=t.nodeName.toUpperCase();n==="OPTGROUP"&&(t=t.parentNode,n=t&&t.nodeName.toUpperCase()),n==="SELECT"&&!t.hasAttribute("multiple")&&(i.hasAttribute("selected")&&!e.selected&&(i.setAttribute("selected","selected"),i.removeAttribute("selected")),t.selectedIndex=-1)}$e(i,e,"selected")},INPUT:function(i,e){$e(i,e,"checked"),$e(i,e,"disabled"),i.value!==e.value&&(i.value=e.value),e.hasAttribute("value")||i.removeAttribute("value")},TEXTAREA:function(i,e){var t=e.value;i.value!==t&&(i.value=t);var n=i.firstChild;if(n){var r=n.nodeValue;if(r==t||!t&&r==i.placeholder)return;n.nodeValue=t}},SELECT:function(i,e){if(!e.hasAttribute("multiple")){for(var t=-1,n=0,r=i.firstChild,s,a;r;)if(a=r.nodeName&&r.nodeName.toUpperCase(),a==="OPTGROUP")s=r,r=s.firstChild,r||(r=s.nextSibling,s=null);else{if(a==="OPTION"){if(r.hasAttribute("selected")){t=n;break}n++}r=r.nextSibling,!r&&s&&(r=s.nextSibling,s=null)}i.selectedIndex=t}}},oe=1,st=11,ot=3,at=8;function j(){}function xn(i){if(i)return i.getAttribute&&i.getAttribute("id")||i.id}function Hn(i){return function(t,n,r){if(r||(r={}),typeof n=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"||t.nodeName==="BODY"){var s=n;n=U.createElement("html"),n.innerHTML=s}else n=Ln(n);else n.nodeType===st&&(n=n.firstElementChild);var a=r.getNodeKey||xn,o=r.onBeforeNodeAdded||j,c=r.onNodeAdded||j,l=r.onBeforeElUpdated||j,d=r.onElUpdated||j,u=r.onBeforeNodeDiscarded||j,p=r.onNodeDiscarded||j,g=r.onBeforeElChildrenUpdated||j,h=r.skipFromChildren||j,R=r.addChild||function(v,m){return v.appendChild(m)},D=r.childrenOnly===!0,C=Object.create(null),x=[];function w(v){x.push(v)}function $(v,m){if(v.nodeType===oe)for(var L=v.firstChild;L;){var b=void 0;m&&(b=a(L))?w(b):(p(L),L.firstChild&&$(L,m)),L=L.nextSibling}}function f(v,m,L){u(v)!==!1&&(m&&m.removeChild(v),p(v),$(v,L))}function E(v){if(v.nodeType===oe||v.nodeType===st)for(var m=v.firstChild;m;){var L=a(m);L&&(C[L]=m),E(m),m=m.nextSibling}}E(t);function _(v){c(v);for(var m=v.firstChild;m;){var L=m.nextSibling,b=a(m);if(b){var y=C[b];y&&pe(m,y)?(m.parentNode.replaceChild(y,m),W(y,m)):_(m)}else _(m);m=L}}function M(v,m,L){for(;m;){var b=m.nextSibling;(L=a(m))?w(L):f(m,v,!0),m=b}}function W(v,m,L){var b=a(m);if(b&&delete C[b],!L){var y=l(v,m);if(y===!1||(y instanceof HTMLElement&&(v=y,E(v)),i(v,m),d(v),g(v,m)===!1))return}v.nodeName!=="TEXTAREA"?T(v,m):it.TEXTAREA(v,m)}function T(v,m){var L=h(v,m),b=m.firstChild,y=v.firstChild,I,F,K,ee,B;e:for(;b;){for(ee=b.nextSibling,I=a(b);!L&&y;){if(K=y.nextSibling,b.isSameNode&&b.isSameNode(y)){b=ee,y=K;continue e}F=a(y);var V=y.nodeType,z=void 0;if(V===b.nodeType&&(V===oe?(I?I!==F&&((B=C[I])?K===B?z=!1:(v.insertBefore(B,y),F?w(F):f(y,v,!0),y=B,F=a(y)):z=!1):F&&(z=!1),z=z!==!1&&pe(y,b),z&&W(y,b)):(V===ot||V==at)&&(z=!0,y.nodeValue!==b.nodeValue&&(y.nodeValue=b.nodeValue))),z){b=ee,y=K;continue e}F?w(F):f(y,v,!0),y=K}if(I&&(B=C[I])&&pe(B,b))L||R(v,B),W(B,b);else{var Ne=o(b);Ne!==!1&&(Ne&&(b=Ne),b.actualize&&(b=b.actualize(v.ownerDocument||U)),R(v,b),_(b))}b=ee,y=K}M(v,y,F);var nt=it[v.nodeName];nt&&nt(v,m)}var A=t,O=A.nodeType,N=n.nodeType;if(!D){if(O===oe)N===oe?pe(t,n)||(p(t),A=Mn(t,kn(n.nodeName,n.namespaceURI))):A=n;else if(O===ot||O===at){if(N===O)return A.nodeValue!==n.nodeValue&&(A.nodeValue=n.nodeValue),A;A=n}}if(A===n)p(t);else{if(n.isSameNode&&n.isSameNode(A))return;if(W(A,n,D),x)for(var S=0,H=x.length;S<H;S++){var k=C[x[S]];k&&f(k,k.parentNode,!1)}}return!D&&A!==t&&t.parentNode&&(A.actualize&&(A=A.actualize(t.ownerDocument||U)),t.parentNode.replaceChild(A,t)),A}}var Rn=Hn(yn),fe=Rn;var Pe=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"];var ge=class{constructor(e){this.logger=e;this.wrapperElement=null;this.focusableElements=[];this.lastFocusedElement=null;this.lastFocusedSelectionStart=null;this.lastFocusedSelectionEnd=null}attach(e){this.wrapperElement=e,e&&(this.updateFocusableElements(),this.setupFocusTracking())}reset(){this.wrapperElement=null,this.focusableElements=[],this.lastFocusedElement=null,this.lastFocusedSelectionStart=null,this.lastFocusedSelectionEnd=null}updateFocusableElements(){if(!this.wrapperElement)return;let n=`${Pe.map(r=>r==="textarea"?"textarea:not([disabled])":`input[type="${r}"]:not([disabled])`).join(", ")}, select:not([disabled]), button:not([disabled]), [contenteditable="true"], [tabindex]:not([tabindex="-1"])`;this.focusableElements=Array.from(this.wrapperElement.querySelectorAll(n))}setupFocusTracking(){if(!this.wrapperElement)return;let e=this.wrapperElement.getAttribute("data-lvt-id"),t=`__lvt_focus_tracker_${e}`,n=`__lvt_blur_tracker_${e}`,r=a=>{var c;let o=a.target;!o||!((c=this.wrapperElement)!=null&&c.contains(o))||(this.isTextualInput(o)||o instanceof HTMLSelectElement)&&(this.lastFocusedElement=o,this.logger.debug("[Focus] Tracked focus on:",o.tagName,o.id||o.getAttribute("name")),this.isTextualInput(o)&&(this.lastFocusedSelectionStart=o.selectionStart,this.lastFocusedSelectionEnd=o.selectionEnd))},s=a=>{var c;let o=a.target;!o||!((c=this.wrapperElement)!=null&&c.contains(o))||this.isTextualInput(o)&&o===this.lastFocusedElement&&(this.lastFocusedSelectionStart=o.selectionStart,this.lastFocusedSelectionEnd=o.selectionEnd,this.logger.debug("[Focus] Saved cursor on blur:",this.lastFocusedSelectionStart,"-",this.lastFocusedSelectionEnd))};document[t]&&document.removeEventListener("focus",document[t],!0),document[n]&&document.removeEventListener("blur",document[n],!0),document[t]=r,document[n]=s,document.addEventListener("focus",r,!0),document.addEventListener("blur",s,!0),this.logger.debug("[Focus] Focus tracking set up")}restoreFocusedElement(){var a,o,c;if(this.logger.debug("[Focus] restoreFocusedElement - lastFocusedElement:",(a=this.lastFocusedElement)==null?void 0:a.tagName,((o=this.lastFocusedElement)==null?void 0:o.id)||((c=this.lastFocusedElement)==null?void 0:c.getAttribute("name"))),!this.lastFocusedElement||!this.wrapperElement){this.logger.debug("[Focus] No element to restore");return}let e=this.getElementSelector(this.lastFocusedElement);if(this.logger.debug("[Focus] Selector for last focused:",e),!e){this.logger.debug("[Focus] Could not generate selector");return}let t=null;if(e.startsWith("data-focus-index-")){this.updateFocusableElements();let l=parseInt(e.replace("data-focus-index-",""),10);t=this.focusableElements[l]||null,this.logger.debug("[Focus] Found by index:",l,t==null?void 0:t.tagName)}else t=this.wrapperElement.querySelector(e),this.logger.debug("[Focus] Found by selector:",e,t==null?void 0:t.tagName);if(!t){this.logger.debug("[Focus] Element not found in updated DOM");return}let n=t.matches(":focus");if(this.logger.debug("[Focus] Already focused:",n),n){this.logger.debug("[Focus] Element retained focus \u2014 skipping restoration");return}let r=this.lastFocusedSelectionStart,s=this.lastFocusedSelectionEnd;t.focus(),this.logger.debug("[Focus] Restored focus"),this.isTextualInput(t)&&r!==null&&s!==null&&(t.setSelectionRange(r,s),this.logger.debug("[Focus] Restored cursor:",r,"-",s))}isTextualInput(e){return e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?Pe.indexOf(e.type)>=0:!1}shouldSkipUpdate(e){return e!==document.activeElement||e.hasAttribute("data-lvt-force-update")?!1:!!(this.isTextualInput(e)||e instanceof HTMLSelectElement)}getLastFocusedElement(){return this.lastFocusedElement}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;if(e.getAttribute("data-key"))return`[data-key="${e.getAttribute("data-key")}"]`;let t=this.focusableElements.indexOf(e);return t>=0?`data-focus-index-${t}`:null}};var lt=["pending","success","error","done"],We=new Set(lt),he=new Set(["click-away"]),Be={reset:"reset",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"};function Cn(i,e){let n=i.toLowerCase().match(/^lvt-el:(\w+):on:(.+)$/);if(n){let r=n[1],s=Be[r];if(!s)return null;let a=n[2];if(he.has(a)||!We.has(a)&&!a.includes(":"))return null;let o=a.split(":"),c=o[o.length-1];if(!We.has(c))return null;let l=c,d=o.length>1?o.slice(0,-1).join(":"):void 0;return{action:s,lifecycle:l,actionName:d||void 0,param:e||void 0}}return null}function G(i){let e=i.getAttribute("data-lvt-target");return e?e.startsWith("#")?document.getElementById(e.slice(1))||i:e.startsWith("closest:")&&i.closest(e.slice(8))||i:i}function me(i,e,t){switch(e){case"reset":i instanceof HTMLFormElement&&i.reset();break;case"addClass":if(t){let n=t.split(/\s+/).filter(Boolean);i.classList.add(...n)}break;case"removeClass":if(t){let n=t.split(/\s+/).filter(Boolean);i.classList.remove(...n)}break;case"toggleClass":t&&t.split(/\s+/).filter(Boolean).forEach(r=>i.classList.toggle(r));break;case"setAttr":if(t){let n=t.indexOf(":");if(n>0){let r=t.substring(0,n),s=t.substring(n+1);i.setAttribute(r,s)}}break;case"toggleAttr":t&&i.toggleAttribute(t);break}}function Dn(i,e,t){return i.lifecycle!==e?!1:i.actionName?i.actionName===t:!0}function In(i,e){let t=Object.keys(Be),n=[],r=e?e.replace(/([^\w-])/g,"\\$1"):void 0;for(let o of t)n.push(`[lvt-el\\:${o}\\:on\\:${i}]`),r&&n.push(`[lvt-el\\:${o}\\:on\\:${r}\\:${i}]`);let s=n.join(", "),a;try{a=document.querySelectorAll(s)}catch(o){let c=t.map(l=>`[lvt-el\\:${l}\\:on\\:${i}]`);try{a=document.querySelectorAll(c.join(", "))}catch(l){return}}a.forEach(o=>{Array.from(o.attributes).forEach(c=>{if(!c.name.startsWith("lvt-el:")||!c.name.includes(":on:"))return;let l=Cn(c.name,c.value);l&&Dn(l,i,e)&&me(G(o),l.action,l.param)})})}function ve(i,e){for(let t of i.attributes){let n=t.name.match(/^lvt-el:(\w+):on:([a-z-]+)$/i);if(!n||n[2].toLowerCase()!==e)continue;let r=n[1].toLowerCase(),s=Be[r];s&&me(G(i),s,t.value)}}function ct(i){return!We.has(i)&&!he.has(i)}function ye(){lt.forEach(i=>{document.addEventListener(`lvt:${i}`,e=>{var r;let n=(r=e.detail)==null?void 0:r.action;In(i,n)},!0)})}var vt=new Set(["pending","success","error","done"]),dt=new WeakSet,be=new WeakMap,Y=new Map;function yt(i){let e=i.match(/^lvt-fx:\w+:on:(.+)$/i);if(!e)return{trigger:null};let t=e[1].split(":");return t.length===1?{trigger:t[0].toLowerCase()}:{trigger:t[t.length-1].toLowerCase(),actionName:t.slice(0,-1).join(":")}}function bt(i,e){let t=e||i,n="__lvtFxDirectListeners",r=(t[n]||[]).filter(a=>a.el.isConnected),s=a=>{var o;for(let c of a.attributes){if(!c.name.startsWith("lvt-fx:"))continue;let l=yt(c.name);if(!l.trigger||vt.has(l.trigger)||he.has(l.trigger))continue;let d=`__lvt_fx_${c.name}`;if(a[d])continue;let u=(o=c.name.match(/^lvt-fx:(\w+)/i))==null?void 0:o[1];if(!u)continue;let p=c.name,g=()=>{if(!a.hasAttribute(p))return;let h=a.getAttribute(p)||"",R=G(a);le(R,u,h)};a.addEventListener(l.trigger,g),a[d]=g,r.push({el:a,event:l.trigger,handler:g,guardKey:d})}};s(i),i.querySelectorAll("*").forEach(s),t[n]=r}function Et(i){let e="__lvtFxDirectListeners",t=i[e];t&&(t.forEach(({el:n,event:r,handler:s,guardKey:a})=>{n.removeEventListener(r,s),delete n[a]}),delete i[e])}function _n(i,e,t){let n=r=>{var s;for(let a of r.attributes){if(!a.name.startsWith("lvt-fx:"))continue;let o=yt(a.name);if(!o.trigger||!vt.has(o.trigger)||o.trigger!==e||o.actionName&&o.actionName!==t)continue;let c=(s=a.name.match(/^lvt-fx:(\w+)/i))==null?void 0:s[1];c&&le(r,c,a.value)}};n(i),i.querySelectorAll("*").forEach(n)}function le(i,e,t){let n=getComputedStyle(i);switch(e){case"highlight":{if(i.__lvtHighlighting)break;i.__lvtHighlighting=!0;let r=parseInt(n.getPropertyValue("--lvt-highlight-duration").trim()||"500",10),s=n.getPropertyValue("--lvt-highlight-color").trim()||"#ffc107",a=i.style.backgroundColor,o=i.style.transition;i.style.transition=`background-color ${r}ms ease-out`,i.style.backgroundColor=s,setTimeout(()=>{if(!i.isConnected){i.style.backgroundColor=a,i.style.transition=o,i.style.length===0&&i.removeAttribute("style"),i.__lvtHighlighting=!1;return}i.style.backgroundColor=a,setTimeout(()=>{i.isConnected&&(i.style.transition=o,i.style.length===0&&i.removeAttribute("style")),i.__lvtHighlighting=!1},r)},50);break}case"animate":{if(dt.has(i))break;dt.add(i);let r=parseInt(n.getPropertyValue("--lvt-animate-duration").trim()||"500",10),s=t||"fade",a="";switch(s){case"fade":a=`lvt-fade-in ${r}ms ease-out`;break;case"slide":a=`lvt-slide-in ${r}ms ease-out`;break;case"scale":a=`lvt-scale-in ${r}ms ease-out`;break;default:console.warn(`Unknown lvt-fx:animate mode: ${s}`)}if(!a)break;i.style.animation=a,i.addEventListener("animationend",()=>{i.style.removeProperty("animation"),i.style.length===0&&i.removeAttribute("style")},{once:!0});break}case"scroll":{let r=n.getPropertyValue("--lvt-scroll-behavior").trim(),s=On.has(r)?r:"auto",a=parseInt(n.getPropertyValue("--lvt-scroll-threshold").trim()||"100",10),o=t||"bottom";switch(o){case"bottom":i.scrollTo({top:i.scrollHeight,behavior:s});break;case"bottom-sticky":{i.dataset.lvtScrollSticky==="1"?i.scrollHeight-i.scrollTop-i.clientHeight<=a&&i.scrollTo({top:i.scrollHeight,behavior:s}):(i.dataset.lvtScrollSticky="1",i.scrollTo({top:i.scrollHeight,behavior:"instant"}));break}case"top":i.scrollTo({top:0,behavior:s});break;case"into-view":{i.dataset.lvtIvDone!=="1"&&(i.scrollIntoView({block:"center",inline:"nearest",behavior:s}),i.dataset.lvtIvDone="1");break}case"preserve":break;default:{if(o.startsWith("reset-on:")){let c=o.slice(9);if(!c){console.warn('lvt-fx:scroll="reset-on:" requires an attribute name');break}let l=i.getAttribute(c);be.has(i)?be.get(i)!==l&&(be.set(i,l),i.scrollLeft=0,i.scrollTop=0):be.set(i,l);break}console.warn(`Unknown lvt-fx:scroll mode: ${o}`)}}break}default:console.warn(`Unknown lvt-fx effect: ${e}`)}}function wt(i){let e="__lvtFxLifecycleSetup";if(i[e])return;i[e]=!0;let t=[];["pending","success","error","done"].forEach(r=>{let s=a=>{var l;let c=(l=a.detail)==null?void 0:l.action;_n(i,r,c)};document.addEventListener(`lvt:${r}`,s,!0),t.push({event:`lvt:${r}`,handler:s})}),i.__lvtFxLifecycleListeners=t}function At(i){let e=i.__lvtFxLifecycleListeners;e&&(e.forEach(({event:t,handler:n})=>{document.removeEventListener(t,n,!0)}),delete i.__lvtFxLifecycleListeners),delete i.__lvtFxLifecycleSetup}var On=new Set(["auto","smooth","instant"]);function Tt(i){i.querySelectorAll("[lvt-fx\\:scroll]").forEach(e=>{let t=e.getAttribute("lvt-fx:scroll");t&&le(e,"scroll",t)})}function St(){for(let{timer:i}of Y.values())clearTimeout(i);Y.clear()}function Lt(i){if(!(Y.size===0&&i.querySelector("[lvt-fx\\:auto-click]")===null)){for(let[e,t]of Array.from(Y))(!e.isConnected||!e.hasAttribute("lvt-fx:auto-click"))&&(clearTimeout(t.timer),Y.delete(e));i.querySelectorAll("[lvt-fx\\:auto-click]").forEach(e=>{let t=e.getAttribute("lvt-fx:auto-click");if(!t)return;let n=Y.get(e);if(n&&n.spec===t)return;n&&clearTimeout(n.timer);let r=t.indexOf(":"),s=r>0?t.slice(0,r):"",a=/^\d+$/.test(s)?parseInt(s,10):NaN,o=r>0?t.slice(r+1):"";if(!Number.isFinite(a)||a<0||!o||!/^[\w-]+$/.test(o)){console.warn(`lvt-fx:auto-click expects "<delay-ms>:<button-name>", got: ${t}`),Y.delete(e);return}let c=setTimeout(()=>{if(!e.isConnected)return;let l=e.querySelector(`button[name="${o}"]`);l&&l.click()},a);Y.set(e,{timer:c,spec:t})})}}function kt(i){i.querySelectorAll("[lvt-fx\\:highlight]").forEach(e=>{let t=e.getAttribute("lvt-fx:highlight");t&&le(e,"highlight",t)})}function Mt(i){i.querySelectorAll("[lvt-fx\\:animate]").forEach(e=>{let t=e.getAttribute("lvt-fx:animate");t&&le(e,"animate",t)}),Fn()}function Fn(){if(!document.getElementById("lvt-animate-styles")){let i=document.createElement("style");i.id="lvt-animate-styles",i.textContent=`
2
2
  @keyframes lvt-fade-in {
3
3
  from { opacity: 0; }
4
4
  to { opacity: 1; }
@@ -11,7 +11,7 @@
11
11
  from { opacity: 0; transform: scale(0.95); }
12
12
  to { opacity: 1; transform: scale(1); }
13
13
  }
14
- `,document.head.appendChild(i)}}var at="__lvtPendingProcessed";function At(i){i.querySelectorAll("[data-toast-trigger]").forEach(e=>{let t=e.getAttribute("data-pending");if(!t||e[at]===t)return;e[at]=t;let n;try{n=JSON.parse(t)}catch(a){return}if(!Array.isArray(n)||!n.length)return;let r=e.getAttribute("data-position")||"top-right",s=Hn(r);n.forEach(a=>{let o=In(a);s.appendChild(o),typeof a.dismissMS=="number"&&a.dismissMS>0&&setTimeout(()=>o.remove(),a.dismissMS)})})}function Tt(){let i="__lvt_toast_click_outside",e=document[i];e&&document.removeEventListener("click",e);let t=n=>{let r=document.querySelector("[data-lvt-toast-stack]");!r||r.contains(n.target)||r.querySelectorAll("[data-lvt-toast-item]").forEach(s=>s.remove())};document[i]=t,document.addEventListener("click",t)}function Hn(i){let e=document.querySelector("[data-lvt-toast-stack]");return e||(e=document.createElement("div"),e.setAttribute("data-lvt-toast-stack",""),e.setAttribute("aria-live","polite"),Rn(e,i),document.body.appendChild(e)),e}function Rn(i,e){let t=i.style;switch(e){case"top-left":t.top="1rem",t.left="1rem";break;case"top-center":t.top="1rem",t.left="50%",t.transform="translateX(-50%)";break;case"bottom-right":t.bottom="1rem",t.right="1rem";break;case"bottom-left":t.bottom="1rem",t.left="1rem";break;case"bottom-center":t.bottom="1rem",t.left="50%",t.transform="translateX(-50%)";break;default:t.top="1rem",t.right="1rem";break}}function In(i){let e=document.createElement("div");e.setAttribute("role","alert"),e.setAttribute("data-lvt-toast-item",i.id),i.type&&e.setAttribute("data-type",i.type);let t=document.createElement("div");if(t.setAttribute("data-lvt-toast-content",""),i.title){let n=document.createElement("strong");n.textContent=i.title,t.appendChild(n)}if(i.body){let n=document.createElement("p");n.textContent=i.body,t.appendChild(n)}if(e.appendChild(t),i.dismissible){let n=document.createElement("button");n.type="button",n.setAttribute("aria-label","Dismiss"),n.textContent="\xD7",n.addEventListener("click",()=>e.remove()),e.appendChild(n)}return e}var lt=new WeakMap;function St(i){var t;let e=i.querySelectorAll("template[shadowrootmode]");if(e.length!==0)for(let n of e){let r=n.parentElement;if(!r){n.remove();continue}let s=n.getAttribute("shadowrootmode");if(s!=="open"&&s!=="closed"){console.warn(`livetemplate: invalid shadowrootmode=${JSON.stringify(s)}; expected "open" or "closed". Template removed.`,n),n.remove();continue}let a=s,o=(t=r.shadowRoot)!=null?t:lt.get(r);if(o&&o.mode!==s&&console.warn(`livetemplate: shadowrootmode changed from "${o.mode}" to "${s}" on re-render \u2014 mode is fixed at first attach and cannot be changed.`,r),!o)try{o=r.attachShadow({mode:a,delegatesFocus:n.hasAttribute("shadowrootdelegatesfocus"),clonable:n.hasAttribute("shadowrootclonable"),serializable:n.hasAttribute("shadowrootserializable")}),a==="closed"&&lt.set(r,o)}catch(c){if(!(c instanceof DOMException))throw c;console.warn(`livetemplate: attachShadow rejected on <${r.tagName.toLowerCase()}> (${c.name}: ${c.message}). Template removed.`,r),n.remove();continue}o.replaceChildren(n.content),n.remove()}}var se=new Map,ct=new WeakSet,dt=.02;function Lt(i,e){for(let[n,r]of Array.from(se))(!n.isConnected||!n.hasAttribute("lvt-fx:area-select"))&&r.cleanup();let t=i.querySelectorAll("[lvt-fx\\:area-select]");if(t.length!==0)for(let n of t){let r=n.getAttribute("lvt-fx:area-select");if(!r){console.warn(`lvt-fx:area-select requires an action name, got: ${JSON.stringify(r)}`);continue}let s=se.get(n);if(s&&s.action===r){s.updateSend(e);continue}s&&s.cleanup(),se.set(n,Dn(n,r,e))}}function kt(i){for(let[e,t]of Array.from(se))i.contains(e)&&t.cleanup()}function Dn(i,e,t){let n=t,r=null,s=0,a=0,o=-1,c=null,l=null,d=()=>{r&&r.remove(),r=null},u=(f,E)=>{if(o===-1)return;let _=o,M=l;o=-1,c=null,l=null;try{i.releasePointerCapture(_)}catch(L){}if(i.removeEventListener("pointerleave",p),!E||!f||!M){d();return}if(M.width<=0||M.height<=0){d();return}let W=M.left+M.width,T=M.top+M.height,A=ye(Math.min(s,f.clientX),M.left,W),O=ye(Math.min(a,f.clientY),M.top,T),N=ye(Math.max(s,f.clientX),M.left,W),S=ye(Math.max(a,f.clientY),M.top,T),C=(A-M.left)/M.width,k=(O-M.top)/M.height,v=(N-A)/M.width,m=(S-O)/M.height;d(),!(v<=0||m<=0)&&(v<dt&&m<dt||n({action:e,data:{x:C,y:k,w:v,h:m}}))},p=f=>{f.pointerId===o&&u(null,!1)},g=f=>f.preventDefault(),h=f=>{if(!f.isPrimary||f.button!==0)return;o!==-1&&u(null,!1);let E=i.parentElement;if(!E)return;if(!ct.has(E)){let M=window.getComputedStyle(E).position;M!=="relative"&&M!=="absolute"&&M!=="fixed"&&M!=="sticky"&&(console.warn("lvt-fx:area-select: parentElement has no positioning context; the drag overlay will be mis-positioned. Add position:relative (or absolute/fixed/sticky) to the parent.",E),ct.add(E))}s=f.clientX,a=f.clientY,o=f.pointerId,c=E,l=i.getBoundingClientRect();let _=!1;try{i.setPointerCapture(o),_=!0}catch(M){}_||i.addEventListener("pointerleave",p,{once:!0}),r=document.createElement("div"),r.className="lvt-area-select-overlay",r.setAttribute("aria-hidden","true"),r.style.cssText="position:absolute;pointer-events:none;border:2px solid var(--lvt-area-select-color,#4cc2ff);background:var(--lvt-area-select-fill,rgba(76,194,255,0.18));box-sizing:border-box;z-index:var(--lvt-area-select-z-index,9999);",E.appendChild(r),H(f)},H=f=>{if(!r)return;let E=c;if(!E)return;let _=i.getBoundingClientRect(),M=E.getBoundingClientRect(),W=E.clientLeft,T=E.clientTop,A=E.scrollLeft,O=E.scrollTop,N=q=>q-M.left-W+A,S=q=>q-M.top-T+O,C=N(Math.min(s,f.clientX)),k=S(Math.min(a,f.clientY)),v=Math.abs(f.clientX-s),m=Math.abs(f.clientY-a),L=N(_.left),b=S(_.top),y=L+_.width,D=b+_.height,F=Math.max(L,Math.min(C,y)),K=Math.max(b,Math.min(k,D)),Z=Math.max(L,Math.min(C+v,y)),B=Math.max(b,Math.min(k+m,D));r.style.left=`${F}px`,r.style.top=`${K}px`,r.style.width=`${Math.max(0,Z-F)}px`,r.style.height=`${Math.max(0,B-K)}px`},I=f=>{if(f.pointerId===o){if(!i.isConnected){u(null,!1);return}H(f)}},R=f=>{if(f.pointerId===o){if(!i.isConnected){u(null,!1);return}u(f,!0)}},x=f=>{f.pointerId===o&&u(f,!1)},w=f=>{f.pointerId===o&&u(null,!1)};return i.addEventListener("pointerdown",h),i.addEventListener("pointermove",I),i.addEventListener("pointerup",R),i.addEventListener("pointercancel",x),i.addEventListener("lostpointercapture",w),i.addEventListener("dragstart",g),{action:e,cleanup:()=>{i.removeEventListener("pointerdown",h),i.removeEventListener("pointermove",I),i.removeEventListener("pointerup",R),i.removeEventListener("pointercancel",x),i.removeEventListener("lostpointercapture",w),i.removeEventListener("pointerleave",p),i.removeEventListener("dragstart",g),u(null,!1),se.delete(i)},updateSend:f=>{n=f}}}function ye(i,e,t){return!Number.isFinite(i)||i<e?e:i>t?t:i}function ae(i,e){let t=null;return function(...r){let s=this;t!==null&&clearTimeout(t),t=window.setTimeout(()=>{i.apply(s,r)},e)}}function Pe(i,e){let t=!1;return function(...r){let s=this;t||(i.apply(s,r),t=!0,setTimeout(()=>{t=!1},e))}}function We(i,e){let t=i.replace(/:/g,"\\:");if(e===void 0)return`[${t}]`;let n=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`[${t}="${n}"]`}var Mt=!1;function ee(i,e,t){return i.hasAttribute(e)?!0:i.hasAttribute("lvt-no-intercept")?(Mt||(Mt=!0,t.warn(`lvt-no-intercept is deprecated; use ${e}. The shim will be removed in v0.9.0.`)),!0):!1}var Ht={reset:"reset",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"},_n=Object.keys(Ht),On=new Set(["mouseenter","mouseleave","focus","blur"]),xt="application/x-lvt-key",Fn=new Set(["dragstart","dragover","drop","dragend","dragenter","dragleave"]),Ct=["click","submit","change","input","search","keydown","keyup","focus","blur","mouseenter","mouseleave","dragstart","dragover","drop","dragend","dragenter","dragleave"],be=class{constructor(e,t){this.context=e;this.logger=t;this.warnedEmitSubmitterGETForms=new WeakSet}teardownForWrapper(e){if(e)for(let t of Ct){let n=`__lvt_delegated_${t}_${e}`,r=document[n];r&&(document.removeEventListener(t,r,!1),delete document[n])}}extractButtonData(e,t){e.value&&(t.value=this.context.parseValue(e.value)),Array.from(e.attributes).forEach(n=>{if(n.name.startsWith("data-")&&n.name!=="data-key"){let r=n.name.slice(5);t[r]=this.context.parseValue(n.value)}})}setupEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=Ct,n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(s=>{let a=`__lvt_delegated_${s}_${n}`,o=document[a];o&&document.removeEventListener(s,o,!1);let c=l=>{var H,I,R;let d=this.context.getWrapperElement();if(!d)return;let u=l.target;if(this.logger.debug("Event listener triggered:",s,l.target),!u)return;let p=u,g=!1;for(;p;){if(p===d){g=!0;break}p=p.parentElement}if(!g)return;let h=`lvt-on:${s}`;for(p=u;p&&p!==d.parentElement;){let x=p.getAttribute(h),w=p,$=!1;if(!x&&s==="submit"&&p instanceof HTMLFormElement){let f=p.getAttribute("lvt-persist");f&&(x=`persist:${f}`,w=p)}if(!x&&s==="click"){let f=p instanceof HTMLButtonElement?p:null;f&&f.name&&!f.disabled&&f.type!=="reset"&&f.form===null&&!f.hasAttribute("commandfor")&&(x=f.name,w=f,$=!0)}if(!x&&s==="submit"&&p instanceof HTMLFormElement)if(ee(p,"lvt-form:no-intercept",this.logger)){if(p.hasAttribute("lvt-form:emit-submitter")){let f=l.submitter;if(f!=null&&f.name){p.method==="get"&&!this.warnedEmitSubmitterGETForms.has(p)&&(this.logger.warn('lvt-form:emit-submitter on a GET form serializes lvt-submitter into the URL query string, polluting browser history and any shared/bookmarked URLs. Use method="POST" or remove the directive if URL pollution is unacceptable.',p),this.warnedEmitSubmitterGETForms.add(p));let E=p.querySelector('input[type="hidden"][name="lvt-submitter"]');E||(E=document.createElement("input"),E.type="hidden",E.name="lvt-submitter",p.appendChild(E)),E.value=f.name}else(I=p.querySelector('input[type="hidden"][name="lvt-submitter"]'))==null||I.remove()}}else{let f=p.getAttribute("lvt-form:action"),E=l.submitter;f?x=f:E instanceof HTMLButtonElement&&E.name?x=E.name:p.getAttribute("name")?x=p.getAttribute("name"):x="submit",w=p,E&&(p.__lvtSubmitter=E);let _=p.closest("dialog");_&&((H=p.getAttribute("method"))==null?void 0:H.toLowerCase())==="dialog"&&(p.__lvtCloseDialog=_)}if(x!=null&&w){if(s==="submit"&&l.preventDefault(),Fn.has(s)){let T=l;if(s==="dragstart"&&T.dataTransfer){let A=w.closest("[data-key]"),O=(R=A==null?void 0:A.getAttribute("data-key"))!=null?R:"";T.dataTransfer.setData(xt,O),T.dataTransfer.effectAllowed="move"}else if(s==="dragover")T.preventDefault(),T.dataTransfer&&(T.dataTransfer.dropEffect="move");else if(s==="drop")T.preventDefault();else if(s==="dragenter"||s==="dragleave"){let A=T.relatedTarget;if(A&&w.contains(A))return}if(x==="")return}if((s==="keydown"||s==="keyup")&&w.hasAttribute("lvt-key")){let T=w.getAttribute("lvt-key");if(T&&l.key!==T){p=p.parentElement;continue}}let f=w,E=()=>{var O,N;this.logger.debug("handleAction called",{action:x,eventType:s,targetElement:f});let T={action:x,data:{}};if(f instanceof HTMLFormElement){this.logger.debug("Processing form element");let S=new FormData(f),C=Array.from(f.querySelectorAll('input[type="checkbox"][name]')),k=new Map;C.forEach(y=>{let D=k.get(y.name)||[];D.push(y),k.set(y.name,D)}),k.forEach((y,D)=>{y.length===1?T.data[D]=y[0].checked:T.data[D]=y.filter(F=>F.checked).map(F=>F.value)});let v=new Set(Array.from(f.querySelectorAll('input[type="password"][name]')).map(y=>y.name)),m=f.__lvtSubmitter,L=m==null?void 0:m.name;S.forEach((y,D)=>{y instanceof File||L&&D===L||k.has(D)||(v.has(D)?T.data[D]=y:T.data[D]=this.context.parseValue(y))});let b=f.__lvtSubmitter;b&&(this.extractButtonData(b,T.data),b.name&&(T.submitter=b.name),delete f.__lvtSubmitter),this.logger.debug("Form data collected:",T.data)}else if(s==="change"||s==="input"||s==="search"){if(f instanceof HTMLInputElement){let S=f.name||"value";T.data[S]=this.context.parseValue(f.value)}else if(f instanceof HTMLSelectElement){let S=f.name||"value";T.data[S]=this.context.parseValue(f.value)}else if(f instanceof HTMLTextAreaElement){let S=f.name||"value";T.data[S]=this.context.parseValue(f.value)}}if($&&this.extractButtonData(w,T.data),!(f instanceof HTMLFormElement)&&!$&&Array.from(w.attributes).forEach(S=>{if(S.name.startsWith("data-")&&S.name!=="data-key"&&S.name!=="data-lvt-id"){let C=S.name.slice(5);T.data[C]=this.context.parseValue(S.value)}}),s==="drop"){let S=(O=l.dataTransfer)==null?void 0:O.getData(xt);S&&(T.data.dragSourceKey=S);let C=(N=w.closest("[data-key]"))==null?void 0:N.getAttribute("data-key");C&&(T.data.dragTargetKey=C)}let A=null;if(s==="submit"&&f instanceof HTMLFormElement){let S=f.querySelectorAll('input[type="file"]:not([lvt-upload])');if(Array.from(S).some(k=>k.files&&k.files.length>0)){let k=l.submitter;A=new FormData(f),k!=null&&k.name&&A.set(k.name,k.value),A.set("lvt-action",x),k!=null&&k.name&&A.set("lvt-submitter",k.name)}}if(s==="submit"&&f instanceof HTMLFormElement){let C=l.submitter,k=null;C&&C.hasAttribute("lvt-form:disable-with")&&(k=C.textContent,C.disabled=!0,C.textContent=C.getAttribute("lvt-form:disable-with"),this.logger.debug("Disabled submit button")),this.context.setActiveSubmission(f,C||null,k),f.querySelectorAll('input[type="file"][lvt-upload]').forEach(m=>{let L=m.getAttribute("lvt-upload");L&&(this.logger.debug("Triggering pending uploads for:",L),this.context.triggerPendingUploads(L))}),f.dispatchEvent(new CustomEvent("lvt:pending",{detail:T})),this.logger.debug("Emitted lvt:pending event")}if(this.logger.debug("About to send message:",T),this.logger.debug("WebSocket state:",this.context.getWebSocketReadyState()),A!==null){this.logger.debug("Tier 1 file upload detected, using HTTP fetch"),this.context.sendHTTPMultipart(f,x,A);return}if(this.context.send(T),this.logger.debug("send() called"),f instanceof HTMLFormElement){let S=f.__lvtCloseDialog;S&&(S.close(),delete f.__lvtCloseDialog)}},_=w.getAttribute("lvt-mod:throttle"),M=w.getAttribute("lvt-mod:debounce");if((_||M)&&s!=="search"){r.has(w)||r.set(w,new Map);let T=r.get(w),A=`${s}:${x}`,O=`__lvt_callback_${A}`,N=w;N[O]||(N[O]={current:E}),N[O].current=E;let S=T.get(A);if(!S){let C=()=>N[O].current();if(_){let k=parseInt(_,10);S=Pe(C,k)}else if(M){let k=parseInt(M,10);S=ae(C,k)}S&&T.set(A,S)}S&&S()}else E();return}p=p.parentElement}};document[a]=c,document.addEventListener(s,c,!1),this.logger.debug("Registered event listener:",s,"with key:",a)})}setupWindowEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=["keydown","keyup","scroll","resize","focus","blur"],n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(s=>{let a=`__lvt_window_${s}_${n}`,o=window[a];o&&window.removeEventListener(s,o);let c=l=>{let d=this.context.getWrapperElement();if(!d)return;let u=`lvt-on:window:${s}`;d.querySelectorAll(We(u)).forEach(g=>{let h=g.getAttribute(u);if(!h)return;if((s==="keydown"||s==="keyup")&&g.hasAttribute("lvt-key")){let w=g.getAttribute("lvt-key");if(w&&l.key!==w)return}let H={action:h,data:{}};Array.from(g.attributes).forEach(w=>{if(w.name.startsWith("data-")&&w.name!=="data-key"&&w.name!=="data-lvt-id"){let $=w.name.slice(5);H.data[$]=this.context.parseValue(w.value)}});let I=g.getAttribute("lvt-mod:throttle"),R=g.getAttribute("lvt-mod:debounce"),x=()=>this.context.send(H);if(I||R){r.has(g)||r.set(g,new Map);let w=r.get(g),$=`window-${s}:${h}`,f=w.get($);if(!f){if(I){let E=parseInt(I,10);f=Pe(x,E)}else if(R){let E=parseInt(R,10);f=ae(x,E)}f&&w.set($,f)}f&&f()}else x()})};window[a]=c,window.addEventListener(s,c)})}setupClickAwayDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_click_away_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let s=a=>{let o=this.context.getWrapperElement();if(!o)return;let c=a.target,l=_n.map(u=>We(`lvt-el:${u}:on:click-away`)).join(", ");o.querySelectorAll(l).forEach(u=>{u.contains(c)||Array.from(u.attributes).forEach(p=>{if(!p.name.includes(":on:click-away"))return;let g=p.name.match(/^lvt-el:(\w+):on:click-away$/);if(!g)return;let h=Ht[g[1].toLowerCase()];h&&ge(G(u),h,p.value)})})};document[n]=s,document.addEventListener("click",s)}setupDOMEventTriggerDelegation(e){let t=this.context.getWrapperElement();if(!t)return;let n=t.getAttribute("data-lvt-id");if(!n)return;let r=`__lvt_el_delegated_${n}`,s=t[r]||new Set,a=`__lvt_el_listeners_${n}`,o=(t[a]||[]).filter(d=>d.el.isConnected),c=e||t,l=d=>{let u=new Set;for(let p of d.attributes){if(!p.name.startsWith("lvt-el:"))continue;let g=p.name.match(/^lvt-el:\w+:on:([a-z-]+)$/i);if(!g)continue;let h=g[1].toLowerCase();st(h)&&u.add(h)}for(let p of u)if(On.has(p)){let g=`__lvt_el_${p}`;if(d[g])continue;let h=()=>he(d,p);d.addEventListener(p,h),d[g]=h,o.push({el:d,event:p,handler:h,guardKey:g})}else if(!s.has(p)){let g=p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=new RegExp(`^lvt-el:\\w+:on:${g}$`,"i"),H=I=>{let R=I.target;for(;R&&R!==t;){let x=!1;for(let w of R.attributes)if(h.test(w.name)){x=!0;break}if(x){he(R,p);return}R=R.parentElement}R===t&&he(t,p)};t.addEventListener(p,H),s.add(p),o.push({el:t,event:p,handler:H})}};l(c),c.querySelectorAll("*").forEach(l),t[a]=o,t[r]=s}teardownDOMEventTriggerDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=e.getAttribute("data-lvt-id");if(!t)return;let n=`__lvt_el_listeners_${t}`,r=e[n];r&&(r.forEach(({el:a,event:o,handler:c,guardKey:l})=>{a.removeEventListener(o,c),l&&delete a[l]}),delete e[n]);let s=`__lvt_el_delegated_${t}`;delete e[s]}setupFocusTrapDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_focus_trap_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("keydown",r);let s=o=>{let c=["a[href]:not([disabled])","button:not([disabled])","textarea:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])','[contenteditable="true"]'].join(", ");return Array.from(o.querySelectorAll(c)).filter(l=>{let d=l,u=window.getComputedStyle(d),p=u.display!=="none",g=u.visibility!=="hidden",h=d.offsetParent!==null||u.position==="fixed"||u.position==="absolute"||typeof process!="undefined"&&!1;return p&&g&&h})},a=o=>{if(o.key!=="Tab")return;let c=this.context.getWrapperElement();if(!c)return;let l=c.querySelectorAll("[lvt-focus-trap]"),d=null;if(l.forEach(h=>{h.contains(document.activeElement)&&(!d||h.contains(d))&&(d=h)}),d||l.forEach(h=>{let H=h,I=window.getComputedStyle(H);I.display!=="none"&&I.visibility!=="hidden"&&(d=h)}),!d)return;let u=s(d);if(u.length===0)return;let p=u[0],g=u[u.length-1];o.shiftKey?document.activeElement===p&&(o.preventDefault(),g.focus()):document.activeElement===g&&(o.preventDefault(),p.focus())};document[n]=a,document.addEventListener("keydown",a),this.logger.debug("Focus trap delegation set up")}setupAutofocusDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_autofocus_observer_${e.getAttribute("data-lvt-id")}`,r=e[n];r&&r.disconnect();let s=()=>{let o=this.context.getWrapperElement();if(!o)return;o.querySelectorAll("[lvt-autofocus]").forEach(l=>{let d=l,u=window.getComputedStyle(d),p=u.display!=="none",g=u.visibility!=="hidden",h=d.offsetParent!==null||u.position==="fixed"||u.position==="absolute"||d.tagName==="BODY"||typeof process!="undefined"&&!1,H=p&&g&&h,I=d.getAttribute("data-lvt-autofocused")==="true";H&&!I?(d.setAttribute("data-lvt-autofocused","true"),requestAnimationFrame(()=>{d.focus(),this.logger.debug("Autofocused element:",d.tagName,d.id||d.getAttribute("name"))})):!H&&I&&d.removeAttribute("data-lvt-autofocused")})};s();let a=new MutationObserver(o=>{let c=!1;o.forEach(l=>{l.type==="childList"&&l.addedNodes.length>0&&l.addedNodes.forEach(d=>{d instanceof Element&&(d.hasAttribute("lvt-autofocus")||d.querySelector("[lvt-autofocus]"))&&(c=!0)}),l.type==="attributes"&&(l.target.hasAttribute("lvt-autofocus")||l.attributeName==="hidden"||l.attributeName==="style"||l.attributeName==="class")&&(c=!0)}),c&&s()});a.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","style","class","lvt-autofocus"]}),e[n]=a,this.logger.debug("Autofocus delegation set up")}};function Be(i){try{return i.matches(":popover-open")}catch(e){return!1}}var Nn=[{matches:i=>i instanceof HTMLDialogElement,isOpen:i=>i.open,open:i=>i.showModal(),close:i=>i.close()},{matches:i=>i instanceof HTMLElement&&i.hasAttribute("popover"),isOpen:i=>Be(i),open:i=>{typeof i.showPopover=="function"&&i.showPopover()},close:i=>{typeof i.hidePopover=="function"&&i.hidePopover()}},{matches:i=>i instanceof HTMLDetailsElement,isOpen:i=>i.open,open:i=>{i.open=!0},close:i=>{i.open=!1}}];function X(i){return Nn.find(e=>e.matches(i))}var Un=new Set(["show-modal","show-popover"]);function Rt(i){let e=i.target;if(!e||!(e instanceof Element))return;let t=e.closest("button[command][commandfor]");if(!t||t.disabled)return;let n=t.getAttribute("command");if(!n)return;let r=t.getAttribute("commandfor");if(!r)return;let s=document.getElementById(r);if(!s)return;let a=X(s);if(a){if(Un.has(n)){if(location.hash==="#"+r)return;history.pushState(null,"","#"+r)}else if(n==="toggle-popover"&&!a.isOpen(s)){if(location.hash==="#"+r)return;history.pushState(null,"","#"+r)}}}function It(i){let e=i.target;e instanceof Element&&e.id&&X(e)&&location.hash==="#"+e.id&&history.replaceState(null,"",location.pathname+location.search)}function Dt(i){let e=i.target;if(!(e instanceof Element)||!e.id)return;let t=X(e);if(t)if(t.isOpen(e)){if(location.hash==="#"+e.id)return;history.pushState(null,"","#"+e.id)}else{if(location.hash!=="#"+e.id)return;history.replaceState(null,"",location.pathname+location.search)}}function _t(){let i=location.hash.slice(1);if(document.querySelectorAll("dialog, [popover]").forEach(e=>{let t=X(e);t&&t.isOpen(e)&&e.id!==i&&t.close(e)}),i){let e=document.getElementById(i);if(e){let t=X(e);t&&!t.isOpen(e)&&t.open(e)}}}function Ke(){let i=location.hash.slice(1);if(!i)return;let e=document.getElementById(i);if(!e)return;let t=X(e);t&&(t.isOpen(e)||t.open(e))}function Ot(i){let e=document.getElementById(i);return e?!!X(e):!1}function Ft(i){let e=document.getElementById(i);if(!e)return;let t=X(e);!t||t.isOpen(e)||(history.pushState(null,"","#"+i),t.open(e))}var Ee=!1;function Nt(){Ee||(Ee=!0,document.addEventListener("click",Rt),document.addEventListener("close",It,!0),document.addEventListener("toggle",Dt,!0),window.addEventListener("popstate",_t),Ke())}function Ut(){Ee&&(Ee=!1,document.removeEventListener("click",Rt),document.removeEventListener("close",It,!0),document.removeEventListener("toggle",Dt,!0),window.removeEventListener("popstate",_t))}var we=class{constructor(e,t){this.context=e;this.logger=t;this.popstateListener=null;this.abortController=null;this.currentHref=window.location.href}teardownForWrapper(e){var r;if((r=this.abortController)==null||r.abort(),this.abortController=null,!e)return;let t=`__lvt_link_intercept_${e}`,n=document[t];n&&(document.removeEventListener("click",n,!1),delete document[t])}setup(e){this.currentHref=window.location.href;let n=`__lvt_link_intercept_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let s=a=>{var l;let o=(l=a.target)==null?void 0:l.closest("a[href]");if(!o)return;let c=this.context.getWrapperElement();if(!(!c||!c.contains(o))&&!this.shouldSkip(o)){if(o.pathname===window.location.pathname&&o.search===window.location.search&&o.hash){let d=o.hash.slice(1);d&&Ot(d)&&(a.preventDefault(),Ft(d));return}a.preventDefault(),this.navigate(o.href)}};document.addEventListener("click",s),document[n]=s,this.popstateListener||(this.popstateListener=()=>{let a=this.currentHref;this.currentHref=window.location.href,this.navigate(window.location.href,!1,a)},window.addEventListener("popstate",this.popstateListener))}shouldSkip(e){if(e.origin!==window.location.origin||e.target&&e.target!=="_self"||e.hasAttribute("download")||ee(e,"lvt-nav:no-intercept",this.logger))return!0;let t=e.protocol;return t!=="http:"&&t!=="https:"}async navigate(e,t=!0,n=window.location.href){var o,c,l;let r=new URL(e,window.location.origin),s=new URL(n,window.location.origin);if(r.origin===s.origin&&r.pathname===s.pathname){if(r.search===s.search){(o=this.abortController)==null||o.abort(),this.abortController=null;return}if(t&&this.context.canSendNavigate()&&((c=this.abortController)==null||c.abort(),this.abortController=null,this.context.sendNavigate(e))){window.history.pushState(null,"",e),this.currentHref=e;return}}(l=this.abortController)==null||l.abort(),this.abortController=new AbortController;try{let d=await fetch(e,{credentials:"include",headers:{Accept:"text/html"},signal:this.abortController.signal});if(!d.ok){window.location.href=e;return}let u=await d.text();t&&window.history.pushState(null,"",e),this.currentHref=e,this.context.handleNavigationResponse(u,e)}catch(d){if(d instanceof DOMException&&d.name==="AbortError")return;window.location.href=e}}};var le=class le{constructor(e,t){this.context=e;this.logger=t;this.infiniteScrollObserver=null;this.mutationObserver=null;this.observedSentinel=null;this.updatedListener=null;this.updatedListenerWrapper=null;this.loadMorePending=!1;this.loadMoreTimeoutId=null}setupInfiniteScrollObserver(){let e=this.context.getWrapperElement();if(!e)return;this.ensureUpdatedListener(e);let t=e.querySelector("[lvt-scroll-sentinel]");if(!t){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null,this.observedSentinel=null),this.releaseLoadMore();return}this.infiniteScrollObserver&&this.observedSentinel===t||(this.infiniteScrollObserver&&this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=new IntersectionObserver(n=>{if(n[0].isIntersecting){if(this.loadMorePending){this.logger.debug("Sentinel visible but load_more already pending, skipping");return}this.loadMorePending=!0,this.armLoadMoreTimeout(),this.logger.debug("Sentinel visible, sending load_more action"),this.context.send({action:"load_more"})}},{rootMargin:"200px"}),this.infiniteScrollObserver.observe(t),this.observedSentinel=t,this.logger.debug("Observer set up successfully"))}ensureUpdatedListener(e){this.updatedListener&&this.updatedListenerWrapper===e||(this.updatedListener&&this.updatedListenerWrapper&&this.updatedListenerWrapper.removeEventListener("lvt:updated",this.updatedListener),this.updatedListener=t=>{let n=t.detail;(n==null?void 0:n.action)==="load_more"&&(this.releaseLoadMore(),this.observedSentinel=null,this.setupInfiniteScrollObserver())},e.addEventListener("lvt:updated",this.updatedListener),this.updatedListenerWrapper=e)}armLoadMoreTimeout(){this.clearLoadMoreTimeout(),this.loadMoreTimeoutId=window.setTimeout(()=>{this.logger.warn(`load_more response not received within ${le.LOAD_MORE_TIMEOUT_MS}ms; releasing throttle`),this.loadMoreTimeoutId=null,this.loadMorePending=!1,this.observedSentinel=null,this.setupInfiniteScrollObserver()},le.LOAD_MORE_TIMEOUT_MS)}releaseLoadMore(){this.loadMorePending=!1,this.clearLoadMoreTimeout()}clearLoadMoreTimeout(){this.loadMoreTimeoutId!==null&&(clearTimeout(this.loadMoreTimeoutId),this.loadMoreTimeoutId=null)}setupInfiniteScrollMutationObserver(){let e=this.context.getWrapperElement();e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.setupInfiniteScrollObserver()}),this.mutationObserver.observe(e,{childList:!0,subtree:!0}),this.logger.debug("MutationObserver set up successfully"))}teardown(){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.updatedListener&&this.updatedListenerWrapper&&this.updatedListenerWrapper.removeEventListener("lvt:updated",this.updatedListener),this.updatedListener=null,this.updatedListenerWrapper=null,this.observedSentinel=null,this.releaseLoadMore()}};le.LOAD_MORE_TIMEOUT_MS=3e4;var Ae=le;var Te=class{constructor(){this.bar=null;this.actionTimer=null;this.pendingCount=0;this.pendingHandler=null;this.updatedHandler=null;this.currentDebounceMs=null}show(){if(this.bar)return;let e=document.createElement("div");if(e.className="lvt-loading-bar",e.style.cssText=`
14
+ `,document.head.appendChild(i)}}var ut="__lvtPendingProcessed";function xt(i){i.querySelectorAll("[data-toast-trigger]").forEach(e=>{let t=e.getAttribute("data-pending");if(!t||e[ut]===t)return;e[ut]=t;let n;try{n=JSON.parse(t)}catch(a){return}if(!Array.isArray(n)||!n.length)return;let r=e.getAttribute("data-position")||"top-right",s=Nn(r);n.forEach(a=>{let o=$n(a);s.appendChild(o),typeof a.dismissMS=="number"&&a.dismissMS>0&&setTimeout(()=>o.remove(),a.dismissMS)})})}function Ht(){let i="__lvt_toast_click_outside",e=document[i];e&&document.removeEventListener("click",e);let t=n=>{let r=document.querySelector("[data-lvt-toast-stack]");!r||r.contains(n.target)||r.querySelectorAll("[data-lvt-toast-item]").forEach(s=>s.remove())};document[i]=t,document.addEventListener("click",t)}function Nn(i){let e=document.querySelector("[data-lvt-toast-stack]");return e||(e=document.createElement("div"),e.setAttribute("data-lvt-toast-stack",""),e.setAttribute("aria-live","polite"),Un(e,i),document.body.appendChild(e)),e}function Un(i,e){let t=i.style;switch(e){case"top-left":t.top="1rem",t.left="1rem";break;case"top-center":t.top="1rem",t.left="50%",t.transform="translateX(-50%)";break;case"bottom-right":t.bottom="1rem",t.right="1rem";break;case"bottom-left":t.bottom="1rem",t.left="1rem";break;case"bottom-center":t.bottom="1rem",t.left="50%",t.transform="translateX(-50%)";break;default:t.top="1rem",t.right="1rem";break}}function $n(i){let e=document.createElement("div");e.setAttribute("role","alert"),e.setAttribute("data-lvt-toast-item",i.id),i.type&&e.setAttribute("data-type",i.type);let t=document.createElement("div");if(t.setAttribute("data-lvt-toast-content",""),i.title){let n=document.createElement("strong");n.textContent=i.title,t.appendChild(n)}if(i.body){let n=document.createElement("p");n.textContent=i.body,t.appendChild(n)}if(e.appendChild(t),i.dismissible){let n=document.createElement("button");n.type="button",n.setAttribute("aria-label","Dismiss"),n.textContent="\xD7",n.addEventListener("click",()=>e.remove()),e.appendChild(n)}return e}var pt=new WeakMap;function Rt(i){var t;let e=i.querySelectorAll("template[shadowrootmode]");if(e.length!==0)for(let n of e){let r=n.parentElement;if(!r){n.remove();continue}let s=n.getAttribute("shadowrootmode");if(s!=="open"&&s!=="closed"){console.warn(`livetemplate: invalid shadowrootmode=${JSON.stringify(s)}; expected "open" or "closed". Template removed.`,n),n.remove();continue}let a=s,o=(t=r.shadowRoot)!=null?t:pt.get(r);if(o&&o.mode!==s&&console.warn(`livetemplate: shadowrootmode changed from "${o.mode}" to "${s}" on re-render \u2014 mode is fixed at first attach and cannot be changed.`,r),!o)try{o=r.attachShadow({mode:a,delegatesFocus:n.hasAttribute("shadowrootdelegatesfocus"),clonable:n.hasAttribute("shadowrootclonable"),serializable:n.hasAttribute("shadowrootserializable")}),a==="closed"&&pt.set(r,o)}catch(c){if(!(c instanceof DOMException))throw c;console.warn(`livetemplate: attachShadow rejected on <${r.tagName.toLowerCase()}> (${c.name}: ${c.message}). Template removed.`,r),n.remove();continue}o.replaceChildren(n.content),n.remove()}}var ae=new Map,ft=new WeakSet,gt=.02;function Ct(i,e){for(let[n,r]of Array.from(ae))(!n.isConnected||!n.hasAttribute("lvt-fx:area-select"))&&r.cleanup();let t=i.querySelectorAll("[lvt-fx\\:area-select]");if(t.length!==0)for(let n of t){let r=n.getAttribute("lvt-fx:area-select");if(!r){console.warn(`lvt-fx:area-select requires an action name, got: ${JSON.stringify(r)}`);continue}let s=ae.get(n);if(s&&s.action===r){s.updateSend(e);continue}s&&s.cleanup(),ae.set(n,Bn(n,r,e))}}function Dt(i){for(let[e,t]of Array.from(ae))i.contains(e)&&t.cleanup()}var J=new Map,te=null;function Ke(i,e){var r;for(let[s,a]of Array.from(J))(!s.isConnected||!s.hasAttribute("lvt-fx:url-hash"))&&a.cleanup();let t=[];i instanceof HTMLElement&&i.hasAttribute("lvt-fx:url-hash")&&t.push(i);let n=(r=i.ownerDocument)==null?void 0:r.body;if(n&&n!==i&&n.hasAttribute("lvt-fx:url-hash")&&!t.includes(n)&&t.push(n),i.querySelectorAll("[lvt-fx\\:url-hash]").forEach(s=>{t.includes(s)||t.push(s)}),t.length!==0)for(let s of t){let a=s.getAttribute("lvt-fx:url-hash");if(!a){console.warn(`lvt-fx:url-hash requires an action name, got: ${JSON.stringify(a)}`);continue}let o=s.getAttribute("data-lvt-url-hash")||"",c=J.get(s);if(c&&c.action===a){c.updateSend(e),ht(c,o);continue}c&&c.cleanup();let l=Wn(s,a,e);J.set(s,l);let d=window.location.hash.replace(/^#/,"");d&&d!==o&&we(d)?(l.currentDataHash=d,e({action:a,data:{hash:d}})):d&&!we(d)?l.currentDataHash=o:ht(l,o)}}function It(i){var t;let e=(t=i.ownerDocument)==null?void 0:t.body;for(let[n,r]of Array.from(J)){if(i.contains(n)){r.cleanup();continue}e&&n===e&&e.contains(i)&&r.cleanup()}}function ht(i,e){if(i.currentDataHash===e)return;let t=window.location.hash.replace(/^#/,"");if(t===e){i.currentDataHash=e;return}if(t!==""&&!we(t)){i.currentDataHash=e;return}Pn(e);let n=e?`#${e}`:window.location.pathname+window.location.search,r=t.split(":")[0],s=e.split(":")[0],a=window.history.state;t!==""&&r!==s?window.history.pushState(a,"",n):window.history.replaceState(a,"",n),i.currentDataHash=e}var mt=new Set;function Pn(i){!i||mt.has(i)||(/[ <>"`#\[\]]/.test(i)||/%(?![0-9A-Fa-f]{2})/.test(i))&&(mt.add(i),console.warn(`lvt-fx:url-hash: data-lvt-url-hash="${i}" contains characters that should be percent-encoded. The directive writes it verbatim into history.pushState/replaceState; malformed URLs result. Server-side FormatHash (or equivalent) should percent-escape path segments and target ids before serialization.`))}function we(i){return i?i.includes(":")||i.includes("/")||i.includes("."):!1}function Wn(i,e,t){let n={action:e,send:t,cleanup:()=>{J.delete(i),J.size===0&&te&&(window.removeEventListener("hashchange",te),te=null)},updateSend:r=>{n.send=r},currentDataHash:""};return te||(te=()=>{let r=window.location.hash.replace(/^#/,"");if(we(r))for(let s of Array.from(J.values()))s.currentDataHash=r,s.send({action:s.action,data:{hash:r}})},window.addEventListener("hashchange",te)),n}function Bn(i,e,t){let n=t,r=null,s=0,a=0,o=-1,c=null,l=null,d=()=>{r&&r.remove(),r=null},u=(f,E)=>{if(o===-1)return;let _=o,M=l;o=-1,c=null,l=null;try{i.releasePointerCapture(_)}catch(L){}if(i.removeEventListener("pointerleave",p),!E||!f||!M){d();return}if(M.width<=0||M.height<=0){d();return}let W=M.left+M.width,T=M.top+M.height,A=Ee(Math.min(s,f.clientX),M.left,W),O=Ee(Math.min(a,f.clientY),M.top,T),N=Ee(Math.max(s,f.clientX),M.left,W),S=Ee(Math.max(a,f.clientY),M.top,T),H=(A-M.left)/M.width,k=(O-M.top)/M.height,v=(N-A)/M.width,m=(S-O)/M.height;d(),!(v<=0||m<=0)&&(v<gt&&m<gt||n({action:e,data:{x:H,y:k,w:v,h:m}}))},p=f=>{f.pointerId===o&&u(null,!1)},g=f=>f.preventDefault(),h=f=>{if(!f.isPrimary||f.button!==0)return;o!==-1&&u(null,!1);let E=i.parentElement;if(!E)return;if(!ft.has(E)){let M=window.getComputedStyle(E).position;M!=="relative"&&M!=="absolute"&&M!=="fixed"&&M!=="sticky"&&(console.warn("lvt-fx:area-select: parentElement has no positioning context; the drag overlay will be mis-positioned. Add position:relative (or absolute/fixed/sticky) to the parent.",E),ft.add(E))}s=f.clientX,a=f.clientY,o=f.pointerId,c=E,l=i.getBoundingClientRect();let _=!1;try{i.setPointerCapture(o),_=!0}catch(M){}_||i.addEventListener("pointerleave",p,{once:!0}),r=document.createElement("div"),r.className="lvt-area-select-overlay",r.setAttribute("aria-hidden","true"),r.style.cssText="position:absolute;pointer-events:none;border:2px solid var(--lvt-area-select-color,#4cc2ff);background:var(--lvt-area-select-fill,rgba(76,194,255,0.18));box-sizing:border-box;z-index:var(--lvt-area-select-z-index,9999);",E.appendChild(r),R(f)},R=f=>{if(!r)return;let E=c;if(!E)return;let _=i.getBoundingClientRect(),M=E.getBoundingClientRect(),W=E.clientLeft,T=E.clientTop,A=E.scrollLeft,O=E.scrollTop,N=V=>V-M.left-W+A,S=V=>V-M.top-T+O,H=N(Math.min(s,f.clientX)),k=S(Math.min(a,f.clientY)),v=Math.abs(f.clientX-s),m=Math.abs(f.clientY-a),L=N(_.left),b=S(_.top),y=L+_.width,I=b+_.height,F=Math.max(L,Math.min(H,y)),K=Math.max(b,Math.min(k,I)),ee=Math.max(L,Math.min(H+v,y)),B=Math.max(b,Math.min(k+m,I));r.style.left=`${F}px`,r.style.top=`${K}px`,r.style.width=`${Math.max(0,ee-F)}px`,r.style.height=`${Math.max(0,B-K)}px`},D=f=>{if(f.pointerId===o){if(!i.isConnected){u(null,!1);return}R(f)}},C=f=>{if(f.pointerId===o){if(!i.isConnected){u(null,!1);return}u(f,!0)}},x=f=>{f.pointerId===o&&u(f,!1)},w=f=>{f.pointerId===o&&u(null,!1)};return i.addEventListener("pointerdown",h),i.addEventListener("pointermove",D),i.addEventListener("pointerup",C),i.addEventListener("pointercancel",x),i.addEventListener("lostpointercapture",w),i.addEventListener("dragstart",g),{action:e,cleanup:()=>{i.removeEventListener("pointerdown",h),i.removeEventListener("pointermove",D),i.removeEventListener("pointerup",C),i.removeEventListener("pointercancel",x),i.removeEventListener("lostpointercapture",w),i.removeEventListener("pointerleave",p),i.removeEventListener("dragstart",g),u(null,!1),ae.delete(i)},updateSend:f=>{n=f}}}function Ee(i,e,t){return!Number.isFinite(i)||i<e?e:i>t?t:i}function ce(i,e){let t=null;return function(...r){let s=this;t!==null&&clearTimeout(t),t=window.setTimeout(()=>{i.apply(s,r)},e)}}function qe(i,e){let t=!1;return function(...r){let s=this;t||(i.apply(s,r),t=!0,setTimeout(()=>{t=!1},e))}}function Ve(i,e){let t=i.replace(/:/g,"\\:");if(e===void 0)return`[${t}]`;let n=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`[${t}="${n}"]`}var _t=!1;function ne(i,e,t){return i.hasAttribute(e)?!0:i.hasAttribute("lvt-no-intercept")?(_t||(_t=!0,t.warn(`lvt-no-intercept is deprecated; use ${e}. The shim will be removed in v0.9.0.`)),!0):!1}var Nt={reset:"reset",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"},Kn=Object.keys(Nt),qn=new Set(["mouseenter","mouseleave","focus","blur"]),Ot="application/x-lvt-key",Vn=new Set(["dragstart","dragover","drop","dragend","dragenter","dragleave"]),Ft=["click","submit","change","input","search","keydown","keyup","focus","blur","mouseenter","mouseleave","dragstart","dragover","drop","dragend","dragenter","dragleave"],Ae=class{constructor(e,t){this.context=e;this.logger=t;this.warnedEmitSubmitterGETForms=new WeakSet}teardownForWrapper(e){if(e)for(let t of Ft){let n=`__lvt_delegated_${t}_${e}`,r=document[n];r&&(document.removeEventListener(t,r,!1),delete document[n])}}extractButtonData(e,t){e.value&&(t.value=this.context.parseValue(e.value)),Array.from(e.attributes).forEach(n=>{if(n.name.startsWith("data-")&&n.name!=="data-key"){let r=n.name.slice(5);t[r]=this.context.parseValue(n.value)}})}setupEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=Ft,n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(s=>{let a=`__lvt_delegated_${s}_${n}`,o=document[a];o&&document.removeEventListener(s,o,!1);let c=l=>{var R,D,C;let d=this.context.getWrapperElement();if(!d)return;let u=l.target;if(this.logger.debug("Event listener triggered:",s,l.target),!u)return;let p=u,g=!1;for(;p;){if(p===d){g=!0;break}p=p.parentElement}if(!g)return;let h=`lvt-on:${s}`;for(p=u;p&&p!==d.parentElement;){let x=p.getAttribute(h),w=p,$=!1;if(!x&&s==="submit"&&p instanceof HTMLFormElement){let f=p.getAttribute("lvt-persist");f&&(x=`persist:${f}`,w=p)}if(!x&&s==="click"){let f=p instanceof HTMLButtonElement?p:null;f&&f.name&&!f.disabled&&f.type!=="reset"&&f.form===null&&!f.hasAttribute("commandfor")&&(x=f.name,w=f,$=!0)}if(!x&&s==="submit"&&p instanceof HTMLFormElement)if(ne(p,"lvt-form:no-intercept",this.logger)){if(p.hasAttribute("lvt-form:emit-submitter")){let f=l.submitter;if(f!=null&&f.name){p.method==="get"&&!this.warnedEmitSubmitterGETForms.has(p)&&(this.logger.warn('lvt-form:emit-submitter on a GET form serializes lvt-submitter into the URL query string, polluting browser history and any shared/bookmarked URLs. Use method="POST" or remove the directive if URL pollution is unacceptable.',p),this.warnedEmitSubmitterGETForms.add(p));let E=p.querySelector('input[type="hidden"][name="lvt-submitter"]');E||(E=document.createElement("input"),E.type="hidden",E.name="lvt-submitter",p.appendChild(E)),E.value=f.name}else(D=p.querySelector('input[type="hidden"][name="lvt-submitter"]'))==null||D.remove()}}else{let f=p.getAttribute("lvt-form:action"),E=l.submitter;f?x=f:E instanceof HTMLButtonElement&&E.name?x=E.name:p.getAttribute("name")?x=p.getAttribute("name"):x="submit",w=p,E&&(p.__lvtSubmitter=E);let _=p.closest("dialog");_&&((R=p.getAttribute("method"))==null?void 0:R.toLowerCase())==="dialog"&&(p.__lvtCloseDialog=_)}if(x!=null&&w){if(s==="submit"&&l.preventDefault(),Vn.has(s)){let T=l;if(s==="dragstart"&&T.dataTransfer){let A=w.closest("[data-key]"),O=(C=A==null?void 0:A.getAttribute("data-key"))!=null?C:"";T.dataTransfer.setData(Ot,O),T.dataTransfer.effectAllowed="move"}else if(s==="dragover")T.preventDefault(),T.dataTransfer&&(T.dataTransfer.dropEffect="move");else if(s==="drop")T.preventDefault();else if(s==="dragenter"||s==="dragleave"){let A=T.relatedTarget;if(A&&w.contains(A))return}if(x==="")return}if((s==="keydown"||s==="keyup")&&w.hasAttribute("lvt-key")){let T=w.getAttribute("lvt-key");if(T&&l.key!==T){p=p.parentElement;continue}}let f=w,E=()=>{var O,N;this.logger.debug("handleAction called",{action:x,eventType:s,targetElement:f});let T={action:x,data:{}};if(f instanceof HTMLFormElement){this.logger.debug("Processing form element");let S=new FormData(f),H=Array.from(f.querySelectorAll('input[type="checkbox"][name]')),k=new Map;H.forEach(y=>{let I=k.get(y.name)||[];I.push(y),k.set(y.name,I)}),k.forEach((y,I)=>{y.length===1?T.data[I]=y[0].checked:T.data[I]=y.filter(F=>F.checked).map(F=>F.value)});let v=new Set(Array.from(f.querySelectorAll('input[type="password"][name]')).map(y=>y.name)),m=f.__lvtSubmitter,L=m==null?void 0:m.name;S.forEach((y,I)=>{y instanceof File||L&&I===L||k.has(I)||(v.has(I)?T.data[I]=y:T.data[I]=this.context.parseValue(y))});let b=f.__lvtSubmitter;b&&(this.extractButtonData(b,T.data),b.name&&(T.submitter=b.name),delete f.__lvtSubmitter),this.logger.debug("Form data collected:",T.data)}else if(s==="change"||s==="input"||s==="search"){if(f instanceof HTMLInputElement){let S=f.name||"value";T.data[S]=this.context.parseValue(f.value)}else if(f instanceof HTMLSelectElement){let S=f.name||"value";T.data[S]=this.context.parseValue(f.value)}else if(f instanceof HTMLTextAreaElement){let S=f.name||"value";T.data[S]=this.context.parseValue(f.value)}}if($&&this.extractButtonData(w,T.data),!(f instanceof HTMLFormElement)&&!$&&Array.from(w.attributes).forEach(S=>{if(S.name.startsWith("data-")&&S.name!=="data-key"&&S.name!=="data-lvt-id"){let H=S.name.slice(5);T.data[H]=this.context.parseValue(S.value)}}),s==="drop"){let S=(O=l.dataTransfer)==null?void 0:O.getData(Ot);S&&(T.data.dragSourceKey=S);let H=(N=w.closest("[data-key]"))==null?void 0:N.getAttribute("data-key");H&&(T.data.dragTargetKey=H)}let A=null;if(s==="submit"&&f instanceof HTMLFormElement){let S=f.querySelectorAll('input[type="file"]:not([lvt-upload])');if(Array.from(S).some(k=>k.files&&k.files.length>0)){let k=l.submitter;A=new FormData(f),k!=null&&k.name&&A.set(k.name,k.value),A.set("lvt-action",x),k!=null&&k.name&&A.set("lvt-submitter",k.name)}}if(s==="submit"&&f instanceof HTMLFormElement){let H=l.submitter,k=null;H&&H.hasAttribute("lvt-form:disable-with")&&(k=H.textContent,H.disabled=!0,H.textContent=H.getAttribute("lvt-form:disable-with"),this.logger.debug("Disabled submit button")),this.context.setActiveSubmission(f,H||null,k),f.querySelectorAll('input[type="file"][lvt-upload]').forEach(m=>{let L=m.getAttribute("lvt-upload");L&&(this.logger.debug("Triggering pending uploads for:",L),this.context.triggerPendingUploads(L))}),f.dispatchEvent(new CustomEvent("lvt:pending",{detail:T})),this.logger.debug("Emitted lvt:pending event")}if(this.logger.debug("About to send message:",T),this.logger.debug("WebSocket state:",this.context.getWebSocketReadyState()),A!==null){this.logger.debug("Tier 1 file upload detected, using HTTP fetch"),this.context.sendHTTPMultipart(f,x,A);return}if(this.context.send(T),this.logger.debug("send() called"),f instanceof HTMLFormElement){let S=f.__lvtCloseDialog;S&&(S.close(),delete f.__lvtCloseDialog)}},_=w.getAttribute("lvt-mod:throttle"),M=w.getAttribute("lvt-mod:debounce");if((_||M)&&s!=="search"){r.has(w)||r.set(w,new Map);let T=r.get(w),A=`${s}:${x}`,O=`__lvt_callback_${A}`,N=w;N[O]||(N[O]={current:E}),N[O].current=E;let S=T.get(A);if(!S){let H=()=>N[O].current();if(_){let k=parseInt(_,10);S=qe(H,k)}else if(M){let k=parseInt(M,10);S=ce(H,k)}S&&T.set(A,S)}S&&S()}else E();return}p=p.parentElement}};document[a]=c,document.addEventListener(s,c,!1),this.logger.debug("Registered event listener:",s,"with key:",a)})}setupWindowEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=["keydown","keyup","scroll","resize","focus","blur"],n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(s=>{let a=`__lvt_window_${s}_${n}`,o=window[a];o&&window.removeEventListener(s,o);let c=l=>{let d=this.context.getWrapperElement();if(!d)return;let u=`lvt-on:window:${s}`;d.querySelectorAll(Ve(u)).forEach(g=>{let h=g.getAttribute(u);if(!h)return;if((s==="keydown"||s==="keyup")&&g.hasAttribute("lvt-key")){let w=g.getAttribute("lvt-key");if(w&&l.key!==w)return}let R={action:h,data:{}};Array.from(g.attributes).forEach(w=>{if(w.name.startsWith("data-")&&w.name!=="data-key"&&w.name!=="data-lvt-id"){let $=w.name.slice(5);R.data[$]=this.context.parseValue(w.value)}});let D=g.getAttribute("lvt-mod:throttle"),C=g.getAttribute("lvt-mod:debounce"),x=()=>this.context.send(R);if(D||C){r.has(g)||r.set(g,new Map);let w=r.get(g),$=`window-${s}:${h}`,f=w.get($);if(!f){if(D){let E=parseInt(D,10);f=qe(x,E)}else if(C){let E=parseInt(C,10);f=ce(x,E)}f&&w.set($,f)}f&&f()}else x()})};window[a]=c,window.addEventListener(s,c)})}setupClickAwayDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_click_away_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let s=a=>{let o=this.context.getWrapperElement();if(!o)return;let c=a.target,l=Kn.map(u=>Ve(`lvt-el:${u}:on:click-away`)).join(", ");o.querySelectorAll(l).forEach(u=>{u.contains(c)||Array.from(u.attributes).forEach(p=>{if(!p.name.includes(":on:click-away"))return;let g=p.name.match(/^lvt-el:(\w+):on:click-away$/);if(!g)return;let h=Nt[g[1].toLowerCase()];h&&me(G(u),h,p.value)})})};document[n]=s,document.addEventListener("click",s)}setupDOMEventTriggerDelegation(e){let t=this.context.getWrapperElement();if(!t)return;let n=t.getAttribute("data-lvt-id");if(!n)return;let r=`__lvt_el_delegated_${n}`,s=t[r]||new Set,a=`__lvt_el_listeners_${n}`,o=(t[a]||[]).filter(d=>d.el.isConnected),c=e||t,l=d=>{let u=new Set;for(let p of d.attributes){if(!p.name.startsWith("lvt-el:"))continue;let g=p.name.match(/^lvt-el:\w+:on:([a-z-]+)$/i);if(!g)continue;let h=g[1].toLowerCase();ct(h)&&u.add(h)}for(let p of u)if(qn.has(p)){let g=`__lvt_el_${p}`;if(d[g])continue;let h=()=>ve(d,p);d.addEventListener(p,h),d[g]=h,o.push({el:d,event:p,handler:h,guardKey:g})}else if(!s.has(p)){let g=p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=new RegExp(`^lvt-el:\\w+:on:${g}$`,"i"),R=D=>{let C=D.target;for(;C&&C!==t;){let x=!1;for(let w of C.attributes)if(h.test(w.name)){x=!0;break}if(x){ve(C,p);return}C=C.parentElement}C===t&&ve(t,p)};t.addEventListener(p,R),s.add(p),o.push({el:t,event:p,handler:R})}};l(c),c.querySelectorAll("*").forEach(l),t[a]=o,t[r]=s}teardownDOMEventTriggerDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=e.getAttribute("data-lvt-id");if(!t)return;let n=`__lvt_el_listeners_${t}`,r=e[n];r&&(r.forEach(({el:a,event:o,handler:c,guardKey:l})=>{a.removeEventListener(o,c),l&&delete a[l]}),delete e[n]);let s=`__lvt_el_delegated_${t}`;delete e[s]}setupFocusTrapDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_focus_trap_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("keydown",r);let s=o=>{let c=["a[href]:not([disabled])","button:not([disabled])","textarea:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])','[contenteditable="true"]'].join(", ");return Array.from(o.querySelectorAll(c)).filter(l=>{let d=l,u=window.getComputedStyle(d),p=u.display!=="none",g=u.visibility!=="hidden",h=d.offsetParent!==null||u.position==="fixed"||u.position==="absolute"||typeof process!="undefined"&&!1;return p&&g&&h})},a=o=>{if(o.key!=="Tab")return;let c=this.context.getWrapperElement();if(!c)return;let l=c.querySelectorAll("[lvt-focus-trap]"),d=null;if(l.forEach(h=>{h.contains(document.activeElement)&&(!d||h.contains(d))&&(d=h)}),d||l.forEach(h=>{let R=h,D=window.getComputedStyle(R);D.display!=="none"&&D.visibility!=="hidden"&&(d=h)}),!d)return;let u=s(d);if(u.length===0)return;let p=u[0],g=u[u.length-1];o.shiftKey?document.activeElement===p&&(o.preventDefault(),g.focus()):document.activeElement===g&&(o.preventDefault(),p.focus())};document[n]=a,document.addEventListener("keydown",a),this.logger.debug("Focus trap delegation set up")}setupAutofocusDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_autofocus_observer_${e.getAttribute("data-lvt-id")}`,r=e[n];r&&r.disconnect();let s=()=>{let o=this.context.getWrapperElement();if(!o)return;o.querySelectorAll("[lvt-autofocus]").forEach(l=>{let d=l,u=window.getComputedStyle(d),p=u.display!=="none",g=u.visibility!=="hidden",h=d.offsetParent!==null||u.position==="fixed"||u.position==="absolute"||d.tagName==="BODY"||typeof process!="undefined"&&!1,R=p&&g&&h,D=d.getAttribute("data-lvt-autofocused")==="true";R&&!D?(d.setAttribute("data-lvt-autofocused","true"),requestAnimationFrame(()=>{d.focus(),this.logger.debug("Autofocused element:",d.tagName,d.id||d.getAttribute("name"))})):!R&&D&&d.removeAttribute("data-lvt-autofocused")})};s();let a=new MutationObserver(o=>{let c=!1;o.forEach(l=>{l.type==="childList"&&l.addedNodes.length>0&&l.addedNodes.forEach(d=>{d instanceof Element&&(d.hasAttribute("lvt-autofocus")||d.querySelector("[lvt-autofocus]"))&&(c=!0)}),l.type==="attributes"&&(l.target.hasAttribute("lvt-autofocus")||l.attributeName==="hidden"||l.attributeName==="style"||l.attributeName==="class")&&(c=!0)}),c&&s()});a.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","style","class","lvt-autofocus"]}),e[n]=a,this.logger.debug("Autofocus delegation set up")}};function ze(i){try{return i.matches(":popover-open")}catch(e){return!1}}var zn=[{matches:i=>i instanceof HTMLDialogElement,isOpen:i=>i.open,open:i=>i.showModal(),close:i=>i.close()},{matches:i=>i instanceof HTMLElement&&i.hasAttribute("popover"),isOpen:i=>ze(i),open:i=>{typeof i.showPopover=="function"&&i.showPopover()},close:i=>{typeof i.hidePopover=="function"&&i.hidePopover()}},{matches:i=>i instanceof HTMLDetailsElement,isOpen:i=>i.open,open:i=>{i.open=!0},close:i=>{i.open=!1}}];function X(i){return zn.find(e=>e.matches(i))}var jn=new Set(["show-modal","show-popover"]);function Ut(i){let e=i.target;if(!e||!(e instanceof Element))return;let t=e.closest("button[command][commandfor]");if(!t||t.disabled)return;let n=t.getAttribute("command");if(!n)return;let r=t.getAttribute("commandfor");if(!r)return;let s=document.getElementById(r);if(!s)return;let a=X(s);if(a){if(jn.has(n)){if(location.hash==="#"+r)return;history.pushState(null,"","#"+r)}else if(n==="toggle-popover"&&!a.isOpen(s)){if(location.hash==="#"+r)return;history.pushState(null,"","#"+r)}}}function $t(i){let e=i.target;e instanceof Element&&e.id&&X(e)&&location.hash==="#"+e.id&&history.replaceState(null,"",location.pathname+location.search)}function Pt(i){let e=i.target;if(!(e instanceof Element)||!e.id)return;let t=X(e);if(t)if(t.isOpen(e)){if(location.hash==="#"+e.id)return;history.pushState(null,"","#"+e.id)}else{if(location.hash!=="#"+e.id)return;history.replaceState(null,"",location.pathname+location.search)}}function Wt(){let i=location.hash.slice(1);if(document.querySelectorAll("dialog, [popover]").forEach(e=>{let t=X(e);t&&t.isOpen(e)&&e.id!==i&&t.close(e)}),i){let e=document.getElementById(i);if(e){let t=X(e);t&&!t.isOpen(e)&&t.open(e)}}}function je(){let i=location.hash.slice(1);if(!i)return;let e=document.getElementById(i);if(!e)return;let t=X(e);t&&(t.isOpen(e)||t.open(e))}function Bt(i){let e=document.getElementById(i);return e?!!X(e):!1}function Kt(i){let e=document.getElementById(i);if(!e)return;let t=X(e);!t||t.isOpen(e)||(history.pushState(null,"","#"+i),t.open(e))}var Te=!1;function qt(){Te||(Te=!0,document.addEventListener("click",Ut),document.addEventListener("close",$t,!0),document.addEventListener("toggle",Pt,!0),window.addEventListener("popstate",Wt),je())}function Vt(){Te&&(Te=!1,document.removeEventListener("click",Ut),document.removeEventListener("close",$t,!0),document.removeEventListener("toggle",Pt,!0),window.removeEventListener("popstate",Wt))}var Se=class{constructor(e,t){this.context=e;this.logger=t;this.popstateListener=null;this.abortController=null;this.currentHref=window.location.href}teardownForWrapper(e){var r;if((r=this.abortController)==null||r.abort(),this.abortController=null,!e)return;let t=`__lvt_link_intercept_${e}`,n=document[t];n&&(document.removeEventListener("click",n,!1),delete document[t])}setup(e){this.currentHref=window.location.href;let n=`__lvt_link_intercept_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let s=a=>{var l;let o=(l=a.target)==null?void 0:l.closest("a[href]");if(!o)return;let c=this.context.getWrapperElement();if(!(!c||!c.contains(o))&&!this.shouldSkip(o)){if(o.pathname===window.location.pathname&&o.search===window.location.search&&o.hash){let d=o.hash.slice(1);d&&Bt(d)&&(a.preventDefault(),Kt(d));return}a.preventDefault(),this.navigate(o.href)}};document.addEventListener("click",s),document[n]=s,this.popstateListener||(this.popstateListener=()=>{let a=this.currentHref;this.currentHref=window.location.href,this.navigate(window.location.href,!1,a)},window.addEventListener("popstate",this.popstateListener))}shouldSkip(e){if(e.origin!==window.location.origin||e.target&&e.target!=="_self"||e.hasAttribute("download")||ne(e,"lvt-nav:no-intercept",this.logger))return!0;let t=e.protocol;return t!=="http:"&&t!=="https:"}async navigate(e,t=!0,n=window.location.href){var o,c,l;let r=new URL(e,window.location.origin),s=new URL(n,window.location.origin);if(r.origin===s.origin&&r.pathname===s.pathname){if(r.search===s.search){(o=this.abortController)==null||o.abort(),this.abortController=null;return}if(t&&this.context.canSendNavigate()&&((c=this.abortController)==null||c.abort(),this.abortController=null,this.context.sendNavigate(e))){window.history.pushState(null,"",e),this.currentHref=e;return}}(l=this.abortController)==null||l.abort(),this.abortController=new AbortController;try{let d=await fetch(e,{credentials:"include",headers:{Accept:"text/html"},signal:this.abortController.signal});if(!d.ok){window.location.href=e;return}let u=await d.text();t&&window.history.pushState(null,"",e),this.currentHref=e,this.context.handleNavigationResponse(u,e)}catch(d){if(d instanceof DOMException&&d.name==="AbortError")return;window.location.href=e}}};var de=class de{constructor(e,t){this.context=e;this.logger=t;this.infiniteScrollObserver=null;this.mutationObserver=null;this.observedSentinel=null;this.updatedListener=null;this.updatedListenerWrapper=null;this.loadMorePending=!1;this.loadMoreTimeoutId=null}setupInfiniteScrollObserver(){let e=this.context.getWrapperElement();if(!e)return;this.ensureUpdatedListener(e);let t=e.querySelector("[lvt-scroll-sentinel]");if(!t){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null,this.observedSentinel=null),this.releaseLoadMore();return}this.infiniteScrollObserver&&this.observedSentinel===t||(this.infiniteScrollObserver&&this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=new IntersectionObserver(n=>{if(n[0].isIntersecting){if(this.loadMorePending){this.logger.debug("Sentinel visible but load_more already pending, skipping");return}this.loadMorePending=!0,this.armLoadMoreTimeout(),this.logger.debug("Sentinel visible, sending load_more action"),this.context.send({action:"load_more"})}},{rootMargin:"200px"}),this.infiniteScrollObserver.observe(t),this.observedSentinel=t,this.logger.debug("Observer set up successfully"))}ensureUpdatedListener(e){this.updatedListener&&this.updatedListenerWrapper===e||(this.updatedListener&&this.updatedListenerWrapper&&this.updatedListenerWrapper.removeEventListener("lvt:updated",this.updatedListener),this.updatedListener=t=>{let n=t.detail;(n==null?void 0:n.action)==="load_more"&&(this.releaseLoadMore(),this.observedSentinel=null,this.setupInfiniteScrollObserver())},e.addEventListener("lvt:updated",this.updatedListener),this.updatedListenerWrapper=e)}armLoadMoreTimeout(){this.clearLoadMoreTimeout(),this.loadMoreTimeoutId=window.setTimeout(()=>{this.logger.warn(`load_more response not received within ${de.LOAD_MORE_TIMEOUT_MS}ms; releasing throttle`),this.loadMoreTimeoutId=null,this.loadMorePending=!1,this.observedSentinel=null,this.setupInfiniteScrollObserver()},de.LOAD_MORE_TIMEOUT_MS)}releaseLoadMore(){this.loadMorePending=!1,this.clearLoadMoreTimeout()}clearLoadMoreTimeout(){this.loadMoreTimeoutId!==null&&(clearTimeout(this.loadMoreTimeoutId),this.loadMoreTimeoutId=null)}setupInfiniteScrollMutationObserver(){let e=this.context.getWrapperElement();e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.setupInfiniteScrollObserver()}),this.mutationObserver.observe(e,{childList:!0,subtree:!0}),this.logger.debug("MutationObserver set up successfully"))}teardown(){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.updatedListener&&this.updatedListenerWrapper&&this.updatedListenerWrapper.removeEventListener("lvt:updated",this.updatedListener),this.updatedListener=null,this.updatedListenerWrapper=null,this.observedSentinel=null,this.releaseLoadMore()}};de.LOAD_MORE_TIMEOUT_MS=3e4;var Le=de;var ke=class{constructor(){this.bar=null;this.actionTimer=null;this.pendingCount=0;this.pendingHandler=null;this.updatedHandler=null;this.currentDebounceMs=null}show(){if(this.bar)return;let e=document.createElement("div");if(e.className="lvt-loading-bar",e.style.cssText=`
15
15
  position: fixed;
16
16
  top: 0;
17
17
  left: 0;
@@ -26,7 +26,7 @@
26
26
  0% { background-position: 200% 0; }
27
27
  100% { background-position: -200% 0; }
28
28
  }
29
- `,document.head.appendChild(t)}document.body.insertBefore(e,document.body.firstChild),this.bar=e}hide(){this.bar&&(this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),this.bar=null)}enablePerActionIndicator(e){if(this.pendingHandler){if(this.currentDebounceMs===e)return;this.disablePerActionIndicator()}this.pendingCount=0,this.currentDebounceMs=e,this.pendingHandler=()=>{this.pendingCount++,this.pendingCount===1&&this.actionTimer===null&&this.bar===null&&(this.actionTimer=setTimeout(()=>{this.actionTimer=null,this.pendingCount>0&&this.show()},e))},this.updatedHandler=()=>{this.pendingCount=Math.max(0,this.pendingCount-1),this.pendingCount===0&&(this.actionTimer!==null&&(clearTimeout(this.actionTimer),this.actionTimer=null),this.hide())},document.addEventListener("lvt:pending",this.pendingHandler,!0),document.addEventListener("lvt:updated",this.updatedHandler,!0)}disablePerActionIndicator(){this.pendingHandler&&(document.removeEventListener("lvt:pending",this.pendingHandler,!0),this.pendingHandler=null),this.updatedHandler&&(document.removeEventListener("lvt:updated",this.updatedHandler,!0),this.updatedHandler=null),this.actionTimer!==null&&(clearTimeout(this.actionTimer),this.actionTimer=null),this.pendingCount=0,this.currentDebounceMs=null,this.hide()}};var Se=class{disable(e){if(!e)return;e.querySelectorAll("form").forEach(n=>{n.querySelectorAll("input, textarea, select, button").forEach(s=>{s.disabled=!0})})}enable(e){if(!e)return;e.querySelectorAll("form").forEach(n=>{n.querySelectorAll("input, textarea, select, button").forEach(s=>{s.disabled=!1})})}};var $t=!1;function $n(i){let e=i.target;if(!e||!(e instanceof Element))return;let t=e.closest("button[commandfor]");if(!t||t.disabled)return;let n=t.getAttribute("commandfor");if(!n)return;let r=t.getAttribute("command"),s=document.getElementById(n);s&&(s instanceof HTMLDialogElement?r==="show-modal"&&!s.open?s.showModal():r==="close"&&s.open&&s.close():s instanceof HTMLElement&&s.hasAttribute("popover")&&(r==="show-popover"&&typeof s.showPopover=="function"?s.showPopover():r==="hide-popover"&&typeof s.hidePopover=="function"?s.hidePopover():r==="toggle-popover"&&typeof s.togglePopover=="function"&&s.togglePopover()))}function Pt(){"commandForElement"in HTMLButtonElement.prototype||$t||($t=!0,document.addEventListener("click",$n))}var te="__lvt_scroll_away",V=[];function Pn(){for(let i=V.length-1;i>=0;i--){let e=V[i];e.trigger.isConnected||(e.target.removeEventListener("scroll",e.handler),delete e.trigger[te],V.splice(i,1))}}function Bt(i){Pn();let e=t=>{let n=t.getAttribute("lvt-scroll-away");if(!n)return;if(n!=="bottom"&&n!=="top"){console.warn(`Unknown lvt-scroll-away edge: ${n}`);return}let r=G(t);if(!r||r===t){let u=t[te];u&&(u.target.removeEventListener("scroll",u.handler),Wt(u),delete t[te]),console.warn("lvt-scroll-away requires data-lvt-target pointing to a scrollable container");return}let s=t[te];if(s){if(s.target===r)return;s.target.removeEventListener("scroll",s.handler),Wt(s)}let a=parseInt(getComputedStyle(t).getPropertyValue("--lvt-scroll-threshold").trim(),10),o=isNaN(a)?200:a,c=!1,l=()=>{c||(c=!0,requestAnimationFrame(()=>{c=!1,(n==="top"?r.scrollTop:r.scrollHeight-r.scrollTop-r.clientHeight)>o?t.classList.add("visible"):t.classList.remove("visible")}))};r.addEventListener("scroll",l,{passive:!0}),l();let d={trigger:t,target:r,handler:l};t[te]=d,V.push(d)};e(i),i.querySelectorAll("[lvt-scroll-away]").forEach(e)}function Wt(i){let e=V.indexOf(i);e!==-1&&V.splice(e,1)}function Kt(i){for(let e=V.length-1;e>=0;e--){let t=V[e];i&&t.trigger.isConnected&&!i.contains(t.trigger)||(t.target.removeEventListener("scroll",t.handler),t.trigger.classList.remove("visible"),delete t.trigger[te],V.splice(e,1))}}var Vt="lvt-active",qe="__lvt_spy",re="__lvt_spy_link_handler",P=[],qt=new WeakSet;function Wn(){for(let i=P.length-1;i>=0;i--){let e=P[i];e.container.isConnected||(je(e),P.splice(i,1))}if(P.length===0){let i=document[re];i&&(document.removeEventListener("click",i),delete document[re])}}function je(i){ne(i,null),i.scrollTarget.removeEventListener("scroll",i.scrollHandler),window.removeEventListener("resize",i.resizeHandler),delete i.container[qe]}function Ve(i){let e=getComputedStyle(i).getPropertyValue("--lvt-spy-margin").trim(),t=Math.round(window.innerHeight*.25);if(!e)return t;let n=parseFloat(e);return isNaN(n)?t:e.endsWith("vh")?Math.round(n/100*window.innerHeight):e.endsWith("px")||/^-?\d+(\.\d+)?$/.test(e)?n:(console.warn(`lvt-spy: unsupported --lvt-spy-margin unit ${JSON.stringify(e)}; supported units are vh and px (or unitless). Falling back to 25vh.`),t)}function Gt(i){let e=i.getAttribute("lvt-spy");if(e&&e.trim()!=="")try{return Array.from(i.querySelectorAll(e))}catch(t){return console.warn(`lvt-spy: invalid selector ${JSON.stringify(e)}:`,t),[]}return[i]}function ne(i,e){for(let t of i.links){let n=t.getAttribute("href")||"",r=n.startsWith("#")?n.slice(1):"";e!==null&&r===e?t.classList.add(Vt):t.classList.remove(Vt)}}function Yt(i){let e=new Set;for(let n of i.targets)n.id&&e.add(n.id);let t=[];document.querySelectorAll("[lvt-spy-link]").forEach(n=>{let r=n.getAttribute("href")||"",s=r.startsWith("#")?r.slice(1):"";e.has(s)&&t.push(n)}),i.links=t}function Bn(i){for(let e of P)for(let t of e.targets)if(t.id===i)return e;return null}function Le(i,e){let t=null;for(let n of i){if(!n.id)continue;n.getBoundingClientRect().top<=e&&(t=n.id)}return t}function Kn(i){let e=i.parentElement;for(;e&&e!==document.documentElement;){let t=getComputedStyle(e).overflowY;if(t==="auto"||t==="scroll"||t==="overlay")return e;e=e.parentElement}return window}function Vn(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(i[t]!==e[t])return!1;return!0}function jt(i,e){let t=e!=null?e:Gt(i);if(t.length===0)return;let n=t.filter(a=>!a.id&&!qt.has(a));if(n.length>0){console.warn(`lvt-spy: ${n.length} target(s) without an id attribute; they cannot be linked from [lvt-spy-link]. Add id="..." or drop them from the selector. First offender:`,n[0]);for(let a of n)qt.add(a)}let r={container:i,targets:t,marginPx:Ve(i),links:[],scrollTarget:Kn(i),scrollHandler:()=>{},resizeHandler:()=>{}};Yt(r);let s=!1;r.scrollHandler=()=>{s||(s=!0,requestAnimationFrame(()=>{s=!1,ne(r,Le(r.targets,r.marginPx))}))},r.resizeHandler=()=>{r.marginPx=Ve(r.container),ne(r,Le(r.targets,r.marginPx))},r.scrollTarget.addEventListener("scroll",r.scrollHandler,{passive:!0}),window.addEventListener("resize",r.resizeHandler,{passive:!0}),i[qe]=r,P.push(r),ne(r,Le(r.targets,r.marginPx))}function zt(i){let e=i[qe];if(e){let t=Gt(i);if(Vn(e.targets,t)){e.marginPx=Ve(i),Yt(e),ne(e,Le(e.targets,e.marginPx));return}je(e);let n=P.indexOf(e);n!==-1&&P.splice(n,1),jt(i,t);return}jt(i)}function qn(){if(document[re])return;let i=e=>{var a;let t=(a=e.target)==null?void 0:a.closest("[lvt-spy-link]");if(!t)return;let n=t.getAttribute("href")||"",r=n.startsWith("#")?n.slice(1):"";if(!r)return;let s=Bn(r);s&&ne(s,r)};document.addEventListener("click",i,{passive:!0}),document[re]=i}function Xt(i){Wn(),qn(),i.hasAttribute("lvt-spy")&&zt(i),i.querySelectorAll("[lvt-spy]").forEach(zt)}function Jt(i){for(let e=P.length-1;e>=0;e--){let t=P[e];i&&t.container.isConnected&&!i.contains(t.container)||(je(t),P.splice(e,1))}if(P.length===0){let e=document[re];e&&(document.removeEventListener("click",e),delete document[re])}}function Qt(i){return typeof structuredClone=="function"?structuredClone(i):JSON.parse(JSON.stringify(i))}function jn(i){return i!=null&&typeof i=="object"&&Array.isArray(i.d)&&Array.isArray(i.s)}function ze(i,e=0){if(e>50||i==null||typeof i!="object"||Array.isArray(i))return!1;if(jn(i))return!0;for(let n of Object.keys(i))if(/^\d+$/.test(n)){let r=i[n];if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&ze(r,e+1))return!0}return!1}function zn(i,e){if(!e.s||!Array.isArray(e.s))return!1;if(ze(i)&&!ze(e))return!0;for(let t of Object.keys(i))if(/^\d+$/.test(t)&&!(t in e))return!0;return!1}var ke=class{constructor(e){this.logger=e;this.treeState={};this.rangeState={};this.rangeIdKeys={}}applyUpdate(e,t){var c,l;let n=!1,r=[],s=new Set;for(let[d,u]of Object.entries(e))if(Array.isArray(u)&&u.length>0&&Array.isArray(u[0])&&typeof u[0][0]=="string"){let g=this.treeState[d];g&&typeof g=="object"&&!Array.isArray(g)&&Array.isArray(g.d)&&Array.isArray(g.s)?((c=t==null?void 0:t.canApplyTargeted)==null?void 0:c.call(t,g,d))===!0?(this.applyDifferentialOpsToRange(g,u,d),r.push({rangePath:d,ops:u,statics:g.s,idKey:(l=g.m)==null?void 0:l.idKey}),s.add(d)):(this.treeState[d]=Qt(g),this.applyDifferentialOpsToRange(this.treeState[d],u,d)):this.treeState[d]=u,n=!0}else{let g=this.treeState[d],h=typeof u=="object"&&u!==null&&!Array.isArray(u)?this.deepMergeTreeNodes(g,u,d):u;JSON.stringify(g)!==JSON.stringify(h)&&(this.treeState[d]=h,n=!0)}let o={html:this.reconstructFromTree(this.treeState,"",s.size>0?s:void 0),changed:n};return r.length>0&&(o.targetedOps=r),o}reset(){this.treeState={},this.rangeState={},this.rangeIdKeys={}}getTreeState(){return{...this.treeState}}getStaticStructure(){return this.treeState.s||null}renderState(){return this.reconstructFromTree(this.treeState,"")}deepMergeTreeNodes(e,t,n=""){var s;if(typeof t!="object"||t===null||Array.isArray(t)||typeof e!="object"||e===null||Array.isArray(e))return t;if(zn(e,t))return this.logger.debug(`[deepMerge] Structure transition at path ${n}, replacing instead of merging`),t;let r={...e};for(let[a,o]of Object.entries(t)){let c=n?`${n}.${a}`:a,l=Array.isArray(o)&&o.length>0&&Array.isArray(o[0])&&typeof o[0][0]=="string",d=r[a]&&typeof r[a]=="object"&&!Array.isArray(r[a])&&Array.isArray(r[a].d)&&Array.isArray(r[a].s);l&&d?(r[a]=Qt(r[a]),this.logger.debug(`[deepMerge] Applying diff ops at path ${c}`,{ops:o,rangeItems:(s=r[a].d)==null?void 0:s.length}),this.applyDifferentialOpsToRange(r[a],o,c)):typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof r[a]=="object"&&r[a]!==null&&!Array.isArray(r[a])?r[a]=this.deepMergeTreeNodes(r[a],o,c):r[a]=o}return r}applyDifferentialOpsToRange(e,t,n){if(!e||typeof e!="object"||!Array.isArray(e.d)||!Array.isArray(e.s)){this.logger.error(`[applyDiffOpsToRange] Invalid rangeStructure at path ${n}`,{rangeStructure:e});return}let r=e.d;this.rangeState[n]||(this.rangeState[n]={items:r,statics:e.s}),e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[n]=e.m.idKey),this.logger.debug(`[applyDiffOpsToRange] path=${n}, idKey=${this.rangeIdKeys[n]}, items=${r.length}, ops=${t.length}`);for(let s of t){if(!Array.isArray(s)||s.length<2)continue;switch(s[0]){case"r":{let o=s[1],c=this.findItemIndexByKey(r,o,e.s,n);this.logger.debug(`[applyDiffOpsToRange] Remove: key=${o}, index=${c}, total=${r.length}`),c>=0?(r.splice(c,1),this.logger.debug(`[applyDiffOpsToRange] After removal: ${r.length} items`)):this.logger.debug(`[applyDiffOpsToRange] Remove failed: key ${o} not found`);break}case"u":{let o=this.findItemIndexByKey(r,s[1],e.s,n),c=s[2];o>=0&&c&&(r[o]=this.mergeRangeItem(r[o],c,n));break}case"a":{let o=Array.isArray(s[1])?s[1]:[s[1]];s[2]&&(e.s=s[2]),r.push(...o),s[3]&&typeof s[3]=="object"&&s[3].idKey&&(this.rangeIdKeys[n]=s[3].idKey);break}case"p":{let o=Array.isArray(s[1])?s[1]:[s[1]];s[2]&&(e.s=s[2]),r.unshift(...o);break}case"i":{let o=this.findItemIndexByKey(r,s[1],e.s,n);if(o>=0){let c=Array.isArray(s[2])?s[2]:[s[2]];r.splice(o+1,0,...c)}break}case"o":{let o=s[1],c=[],l=new Map;for(let d of r){let u=this.getItemKey(d,e.s,n);u&&l.set(u,d)}for(let d of o){let u=l.get(d);u&&c.push(u)}r.length=0,r.push(...c);break}default:break}}this.rangeState[n]={items:r,statics:e.s}}reconstructFromTree(e,t,n){if(e.s&&Array.isArray(e.s)){let r="";for(let s=0;s<e.s.length;s++){let a=e.s[s];if(r+=a,s<e.s.length-1){let o=s.toString();if(e[o]!==void 0){let c=t?`${t}.${o}`:o;if(n&&n.has(c)){r+=`<!--lvt-targeted-skip:${c}-->`;continue}r+=this.renderValue(e[o],o,c)}}}return r=r.replace(/<root>/g,"").replace(/<\/root>/g,""),r}return this.renderValue(e,"",t)}renderValue(e,t,n){if(e==null||typeof e=="string"&&e.startsWith("{{")&&e.endsWith("}}"))return"";if(typeof e=="object"&&!Array.isArray(e)){if(e.d&&Array.isArray(e.d)&&e.s&&Array.isArray(e.s)){let a=n||t||"";return a&&(this.rangeState[a]={items:e.d,statics:e.s},e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[a]=e.m.idKey)),this.renderRangeStructure(e,t,n)}if("s"in e&&Array.isArray(e.s))return this.reconstructFromTree(e,n||"");let r=Object.keys(e),s=r.filter(a=>/^\d+$/.test(a)).sort((a,o)=>parseInt(a)-parseInt(o));if(s.length>0&&s.length===r.length)return s.map(a=>{let o=n?`${n}.${a}`:a;return this.renderValue(e[a],a,o)}).join("")}return Array.isArray(e)?e.length>0&&Array.isArray(e[0])&&typeof e[0][0]=="string"?this.applyDifferentialOperations(e,n):e.map((r,s)=>{let a=s.toString(),o=n?`${n}.${a}`:a;return typeof r=="object"&&r&&r.s?this.reconstructFromTree(r,o):this.renderValue(r,a,o)}).join(""):typeof e=="object"?(this.logger.debug("Skipping plain object value (not a tree node) - this is normal for state-only data"),""):String(e)}renderRangeStructure(e,t,n){let{d:r,s}=e;if(!r||!Array.isArray(r))return"";if(r.length===0){if(e.else){let a="else",o=n?`${n}.else`:"else";return this.renderValue(e.else,a,o)}return""}return s&&Array.isArray(s)?r.map((a,o)=>this.renderRangeItem(a,o,s,n)).join(""):r.map((a,o)=>{let c=o.toString(),l=n?`${n}.${c}`:c;return this.renderValue(a,c,l)}).join("")}renderRangeItem(e,t,n,r){let s=n,a="";for(let o=0;o<s.length;o++)if(a+=s[o],o<s.length-1){let c=o.toString();if(e[c]!==void 0){let l=r?`${r}.${t}.${c}`:`${t}.${c}`;a+=this.renderValue(e[c],c,l)}}return a}applyDifferentialOperations(e,t){if(!t||!this.rangeState[t])return"";let n=this.rangeState[t],r=[...n.items],s=n.statics;for(let o of e){if(!Array.isArray(o)||o.length<2)continue;switch(o[0]){case"r":{let l=this.findItemIndexByKey(r,o[1],s,t);l>=0&&r.splice(l,1);break}case"u":{let l=this.findItemIndexByKey(r,o[1],s,t),d=o[2];l>=0&&d&&(r[l]=this.mergeRangeItem(r[l],d,t||""));break}case"a":{this.addItemsToRange(r,o[1],o[2],n,!1),o[3]&&typeof o[3]=="object"&&o[3].idKey&&(this.rangeIdKeys[t||""]=o[3].idKey);break}case"p":{this.addItemsToRange(r,o[1],o[2],n,!0);break}case"i":{let l=this.findItemIndexByKey(r,o[1],s,t);if(l>=0){let d=Array.isArray(o[2])?o[2]:[o[2]];r.splice(l+1,0,...d)}break}case"o":{let l=o[1],d=[],u=new Map;for(let p of r){let g=this.getItemKey(p,s,t);g&&u.set(g,p)}for(let p of l){let g=u.get(p);g&&d.push(g)}r.length=0,r.push(...d);break}default:break}}this.rangeState[t]={items:r,statics:n.statics},this.treeState[t]={d:r,s:n.statics};let a=this.getCurrentRangeStructure(t);return a&&a.s?this.renderItemsWithStatics(r,a.s,t):r.map(o=>this.renderValue(o)).join("")}getCurrentRangeStructure(e){if(this.rangeState[e])return{d:this.rangeState[e].items,s:this.rangeState[e].statics};let t=this.treeState[e];return t&&typeof t=="object"&&t.s?t:null}renderItemsWithStatics(e,t,n){let r=e.map((s,a)=>this.renderRangeItem(s,a,t,n)).join("");return this.logger.isDebugEnabled()&&(this.logger.debug("[renderItemsWithStatics] statics:",t),this.logger.debug("[renderItemsWithStatics] items count:",e.length),this.logger.debug("[renderItemsWithStatics] result snippet:",r.substring(0,200))),r}addItemsToRange(e,t,n,r,s){if(n&&(r.statics=n),!t)return;let a=Array.isArray(t)?t:[t];s?e.unshift(...a):e.push(...a)}getItemKey(e,t,n){if(e._k&&typeof e._k=="string")return e._k;if(!n||!this.rangeIdKeys[n])return null;let r=this.rangeIdKeys[n];return e[r]||null}findItemIndexByKey(e,t,n,r){return e.findIndex(s=>this.getItemKey(s,n,r)===t)}mergeRangeItem(e,t,n){return this.deepMergeTreeNodes(e,t,`${n}.item`)}};var Ge=["data-key","data-lvt-key"],Gn=Ge.map(i=>new RegExp(`(?:^|[\\s<])${i}\\s*=`)),J="data-lvt-targeted-applied",Q="data-lvt-targeted-skip",Me=class{constructor(e){this.ctx=e;this.containerCache=new Map}invalidate(){this.containerCache.clear()}invalidatePath(e){this.containerCache.delete(e)}findContainer(e,t,n){let r=this.containerCache.get(t);if(r&&r.isConnected&&e.contains(r))return r;if(r&&this.containerCache.delete(t),n===void 0)return null;let s=this.findItemByKey(e,n);if(!s||!s.parentElement)return null;let a=s.parentElement;return this.containerCache.set(t,a),a}canApplyTargeted(e,t,n){if(!t||typeof t!="object")return{ok:!1,reason:"no range structure"};if(!Array.isArray(t.s)||t.s.length===0)return{ok:!1,reason:"no statics"};let r=[t.s];if(t.sm&&typeof t.sm=="object")for(let d of Object.values(t.sm))Array.isArray(d)&&r.push(d);if(!r.some(d=>this.staticsContainKeyAttribute(d)))return{ok:!1,reason:"no data-key attribute in statics"};let a=t.d;if(Array.isArray(a)){for(let d of a)if(this.itemHasNestedRange(d))return{ok:!1,reason:"nested-range item"}}let o=this.extractItemKey(a==null?void 0:a[0],t),c=this.findContainer(e,n,o);if(!c)return{ok:!1,reason:"container not found in DOM"};let l=c;for(;l;){if(l.hasAttribute("lvt-ignore"))return{ok:!1,reason:"lvt-ignore ancestor"};if(l===e)break;l=l.parentElement}return{ok:!0,container:c,containerKey:o}}apply(e,t,n){let{rangePath:r,ops:s,statics:a}=t,o=this.firstKnownKey(s),c=this.findContainer(e,r,o);if(!c)return this.ctx.logger.debug(`[RangeDomApplier] container not found for range ${r}; cannot apply`),null;let l=!0;for(let d of s){if(!Array.isArray(d)||d.length<1)continue;let u=d[0];try{let p=!0;switch(u){case"r":p=this.applyRemove(c,d[1]);break;case"u":p=this.applyUpdateRow(c,d[1],a,r,n);break;case"i":p=this.applyInsertAfter(c,d[1],d[2],a,r);break;case"a":p=this.applyAppend(c,d[1],a,r);break;case"p":p=this.applyPrepend(c,d[1],a,r);break;case"o":p=this.applyReorder(c,d[1]);break;default:this.ctx.logger.warn(`[RangeDomApplier] unknown op type ${u}; falling back`),p=!1}p||(l=!1)}catch(p){return this.ctx.logger.error(`[RangeDomApplier] op ${u} failed for range ${r}`,p),null}}return l?(typeof window!="undefined"&&"__lvtTargetedHits"in window&&window.__lvtTargetedHits++,c):null}cleanupMarkers(e){e.querySelectorAll(`[${J}]`).forEach(r=>r.removeAttribute(J)),e.hasAttribute(J)&&e.removeAttribute(J),e.querySelectorAll(`[${Q}]`).forEach(r=>r.removeAttribute(Q)),e.hasAttribute(Q)&&e.removeAttribute(Q)}applyRemove(e,t){let n=this.findItemByKey(e,t);return n?(this.fireHookOnSubtree(n,"lvt-destroyed"),n.remove(),!0):(this.ctx.logger.debug(`[RangeDomApplier] r: row with key ${t} not found (idempotent no-op)`),!0)}applyUpdateRow(e,t,n,r,s){var u,p;let a=this.findItemByKey(e,t);if(!a)return this.ctx.logger.debug(`[RangeDomApplier] u: row with key ${t} not found in DOM; falling back`),!1;let o=this.indexOfChild(e,a),c=this.lookupCurrentItem(r,t);if(!c)return this.ctx.logger.debug(`[RangeDomApplier] u: item state for key ${t} not available; falling back`),!1;let l=this.ctx.renderItem(c,o,n,r),d=this.parseSingleRow(l);return d?(s?ue(a,d,{...s,childrenOnly:!1}):(this.fireHookOnSubtree(a,"lvt-destroyed"),a.replaceWith(d),(p=(u=this.ctx).onNodeAdded)==null||p.call(u,d),this.fireHookOnSubtree(d,"lvt-mounted")),!0):(this.ctx.logger.warn("[RangeDomApplier] u: failed to parse rendered row HTML; falling back"),!1)}applyInsertAfter(e,t,n,r,s){let a=this.findItemByKey(e,t);return a?this.renderItemsAtomic(n,r,s,this.indexOfChild(e,a)+1,o=>e.insertBefore(o,a.nextSibling)):(this.ctx.logger.debug(`[RangeDomApplier] i: anchor key ${t} not found; falling back`),!1)}applyAppend(e,t,n,r){return this.renderItemsAtomic(t,n,r,e.children.length,s=>e.appendChild(s))}applyPrepend(e,t,n,r){return this.renderItemsAtomic(t,n,r,0,s=>e.insertBefore(s,e.firstChild))}renderItemsAtomic(e,t,n,r,s){var l,d;let a=Array.isArray(e)?e:[e],o=document.createDocumentFragment(),c=[];for(let u=0;u<a.length;u++){let p=this.renderAndParse(a[u],r+u,t,n);if(!p)return!1;o.appendChild(p),c.push(p)}s(o);for(let u of c)(d=(l=this.ctx).onNodeAdded)==null||d.call(l,u),this.fireHookOnSubtree(u,"lvt-mounted");return!0}applyReorder(e,t){if(!Array.isArray(t))return!1;let n=new Map;Array.from(e.children).forEach(a=>{for(let o of Ge){let c=a.getAttribute(o);if(c!==null){n.set(c,a);break}}});let r=document.createDocumentFragment(),s=new Set(t);for(let a of t){let o=n.get(a);o&&r.appendChild(o)}if(s.size<n.size){this.ctx.logger.warn(`[RangeDomApplier] o: newKeyOrder (${s.size}) shorter than existing children (${n.size}); ${n.size-s.size} children will be dropped`);for(let[a,o]of n)s.has(a)||this.fireHookOnSubtree(o,"lvt-destroyed")}return e.replaceChildren(r),!0}renderAndParse(e,t,n,r){let s=this.ctx.renderItem(e,t,n,r);return this.parseSingleRow(s)}parseSingleRow(e){let t=document.createElement("template");t.innerHTML=e.trim();let n=t.content.firstElementChild;return n!=null?n:null}findItemByKey(e,t){let n;typeof CSS!="undefined"&&typeof CSS.escape=="function"?n=CSS.escape(t):(/[\[\]():.#>~+*=^$|! \t\n\r]/.test(t)&&this.ctx.logger.warn(`[RangeDomApplier] CSS.escape unavailable; key "${t}" contains characters that need escaping. Lookup may miss the row.`),n=t.replace(/(["\\])/g,"\\$1"));for(let r of Ge){let s=e.querySelector(`[${r}="${n}"]`);if(s)return s}return null}indexOfChild(e,t){let n=0,r=e.firstElementChild;for(;r;){if(r===t)return n;n++,r=r.nextElementSibling}return-1}firstKnownKey(e){for(let t of e){if(!Array.isArray(t)||t.length<2)continue;let n=t[0];if(n==="r"||n==="u"||n==="i")return typeof t[1]=="string"?t[1]:void 0;if(n==="o"&&Array.isArray(t[1])&&t[1].length>0)return typeof t[1][0]=="string"?t[1][0]:void 0;if(n==="a"||n==="p"){let r=Array.isArray(t[1])?t[1]:[t[1]];for(let s of r)if(s&&typeof s=="object"&&s._k!==void 0)return String(s._k)}}}staticsContainKeyAttribute(e){for(let t of e)if(typeof t=="string"){for(let n of Gn)if(n.test(t))return!0}return!1}itemHasNestedRange(e){if(!e||typeof e!="object")return!1;for(let[t,n]of Object.entries(e))if(!t.startsWith("_")&&n&&typeof n=="object"&&!Array.isArray(n)){let r=n;if(Array.isArray(r.d)&&Array.isArray(r.s)||this.itemHasNestedRange(r))return!0}return!1}extractItemKey(e,t){var r;if(!e||typeof e!="object")return;if(e._k!==void 0)return String(e._k);let n=(r=t==null?void 0:t.m)==null?void 0:r.idKey;if(n&&e[n]!==void 0)return String(e[n])}lookupCurrentItem(e,t){return this.ctx.itemLookup(e,t)}fireHookOnSubtree(e,t){e.hasAttribute(t)&&this.ctx.executeLifecycleHook(e,t),e.querySelectorAll(`[${t}]`).forEach(r=>this.ctx.executeLifecycleHook(r,t))}};var xe=class{constructor(){this.activeForm=null;this.activeButton=null;this.originalButtonText=null}setActiveSubmission(e,t,n){if(this.activeForm=e,this.activeButton=t,this.originalButtonText=n,e){e.setAttribute("aria-busy","true");let r=e.querySelector("fieldset");r&&(r.disabled=!0)}}handleResponse(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:done",{detail:e})),e.success?this.handleSuccess(e):this.handleError(e),this.restoreFormState()}reset(){this.restoreFormState()}handleSuccess(e){if(!this.activeForm)return;this.activeForm.dispatchEvent(new CustomEvent("lvt:success",{detail:e}));let t=this.activeForm.closest("dialog");t&&t.open&&t.close(),this.activeForm.hasAttribute("lvt-form:preserve")||this.activeForm.reset()}handleError(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:error",{detail:e}))}restoreFormState(){if(this.activeForm){this.activeForm.removeAttribute("aria-busy");let e=this.activeForm.querySelector("fieldset");e&&(e.disabled=!1)}this.activeButton&&this.originalButtonText!==null&&(this.activeButton.disabled=!1,this.activeButton.textContent=this.originalButtonText),this.activeForm=null,this.activeButton=null,this.originalButtonText=null}};var Ce=class{constructor(e,t){this.context=e;this.logger=t;this.boundFields=new Map;this.enabled=!1;this.wiredElements=new Set;this.elementCleanups=new Map}setCapabilities(e){this.enabled=e.includes("change"),this.logger.debug("Capabilities received, change auto-wiring:",this.enabled?"enabled":"disabled")}analyzeStatics(e){let t=this.boundFields.size;this.walkTree(e),this.boundFields.size>t&&this.logger.debug(`Detected ${this.boundFields.size} bound field(s):`,Array.from(this.boundFields.keys()))}wireElements(){if(!this.enabled)return;let e=this.context.getWrapperElement();if(!e)return;for(let n of this.elementCleanups.keys())n.isConnected||(this.elementCleanups.get(n)(),this.elementCleanups.delete(n),this.wiredElements.delete(n));for(let[n,r]of this.boundFields){let s=this.escapeCSSSelector(n),a=e.querySelectorAll(`[name="${s}"]`);for(let o of a){if(this.wiredElements.has(o)||o.hasAttribute("lvt-input")||o.hasAttribute("lvt-change"))continue;let c=o.closest("form");c&&(c.hasAttribute("lvt-change")||ee(c,"lvt-form:no-intercept",this.logger))||o instanceof HTMLInputElement&&(o.type==="hidden"||o.type==="submit"||o.type==="button")||o instanceof HTMLButtonElement||(this.attachListener(o,n,r),this.wiredElements.add(o))}}let t=e.querySelectorAll("select[name]");for(let n of t){if(this.wiredElements.has(n)||n.hasAttribute("lvt-input")||n.hasAttribute("lvt-change"))continue;let r=n.closest("form");if(r&&(r.hasAttribute("lvt-change")||r.hasAttribute("lvt-form:no-intercept")))continue;let s=n.getAttribute("name");s&&(this.attachListener(n,s,"value"),this.wiredElements.add(n))}}teardown(){for(let e of this.elementCleanups.values())e();this.elementCleanups.clear(),this.wiredElements.clear(),this.boundFields.clear(),this.enabled=!1}getBoundFields(){return this.boundFields}isEnabled(){return this.enabled}walkTree(e){if(!(!e||typeof e!="object"||Array.isArray(e))){e.s&&Array.isArray(e.s)&&this.analyzeStaticsArray(e.s);for(let t of Object.keys(e))if(/^\d+$/.test(t)){let n=e[t];n&&typeof n=="object"&&!Array.isArray(n)&&this.walkTree(n)}if(e.d&&Array.isArray(e.d))for(let t of e.d)t&&typeof t=="object"&&!Array.isArray(t)&&this.walkTree(t)}}analyzeStaticsArray(e){for(let t=0;t<e.length-1;t++){let n=e[t],r=e[t+1],s=this.detectBinding(n,r);s&&!this.boundFields.has(s.fieldName)&&this.boundFields.set(s.fieldName,s.bindingType)}}detectBinding(e,t){let n=this.detectValueBinding(e);return n?{fieldName:n,bindingType:"value"}:(n=this.detectTextareaBinding(e,t),n?{fieldName:n,bindingType:"content"}:(n=this.detectAttributeBinding(e,t),n?{fieldName:n,bindingType:"attribute"}:null))}escapeCSSSelector(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}extractUnclosedTag(e){let t=e.lastIndexOf("<"),n=e.lastIndexOf(">");return t===-1||t<=n?null:e.substring(t)}extractNameFromTag(e){let t=e.match(/\sname="([^"]+)"/);return t?t[1]:null}detectValueBinding(e){if(!e.endsWith('value="'))return null;let t=this.extractUnclosedTag(e);return t?this.extractNameFromTag(t):null}detectTextareaBinding(e,t){if(!t.startsWith("</textarea"))return null;let n=e.match(/<textarea[^>]*\sname="([^"]+)"[^>]*>$/);return n?n[1]:null}detectAttributeBinding(e,t){if(!e.endsWith(" ")||!/^[a-zA-Z>/\s]/.test(t))return null;let n=this.extractUnclosedTag(e);if(!n||!/^<input\s/i.test(n))return null;let r=n.match(/\stype="([^"]+)"/i);if(!r)return null;let s=r[1].toLowerCase();return s!=="checkbox"&&s!=="radio"?null:this.extractNameFromTag(n)}attachListener(e,t,n){let r=e.getAttribute("lvt-debounce"),s=r?parseInt(r,10):NaN,a=Number.isNaN(s)||s<0?300:s,c=ae(()=>{if(!this.enabled)return;let d=n==="attribute"&&e.type==="checkbox"?e.checked:e.value;this.context.send({action:"change",data:{[t]:d}})},a),l=n==="attribute"||e instanceof HTMLSelectElement?"change":"input";e.addEventListener(l,c),this.elementCleanups.set(e,()=>{e.removeEventListener(l,c)}),this.logger.debug(`Auto-wired ${l} listener on [name="${t}"] (debounce: ${a}ms)`)}};var Ye=class{constructor(e){this.options=e;this.socket=null;this.reconnectTimer=null;this.manuallyClosed=!1;this.reconnectAttempts=0}connect(){this.manuallyClosed=!1,this.clearReconnectTimer(),this.socket=new WebSocket(this.options.url);let e=this.socket;e.onopen=()=>{var t,n;this.reconnectAttempts=0,(n=(t=this.options).onOpen)==null||n.call(t,e)},e.onmessage=t=>{var n,r;(r=(n=this.options).onMessage)==null||r.call(n,t)},e.onclose=t=>{var n,r;(r=(n=this.options).onClose)==null||r.call(n,t),!this.manuallyClosed&&this.options.autoReconnect&&this.scheduleReconnect()},e.onerror=t=>{var n,r;(r=(n=this.options).onError)==null||r.call(n,t)}}send(e){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(e)}disconnect(){var e,t;this.manuallyClosed=!0,this.clearReconnectTimer(),this.socket&&(this.socket.readyState!==WebSocket.CLOSED&&((t=(e=this.options).onClose)==null||t.call(e,new CloseEvent("close",{code:1e3,reason:"",wasClean:this.socket.readyState===WebSocket.OPEN}))),this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close(),this.socket=null)}getSocket(){return this.socket}scheduleReconnect(){var o,c,l,d,u;this.clearReconnectTimer();let e=(o=this.options.maxReconnectAttempts)!=null?o:10;if(e>0&&this.reconnectAttempts>=e){(l=(c=this.options).onReconnectFailed)==null||l.call(c);return}this.reconnectAttempts++;let t=(d=this.options.reconnectDelay)!=null?d:1e3,n=(u=this.options.maxReconnectDelay)!=null?u:16e3,r=t*Math.pow(2,this.reconnectAttempts-1),s=Math.random()*1e3,a=Math.min(r+s,n);this.reconnectTimer=window.setTimeout(()=>{var p,g;(g=(p=this.options).onReconnectAttempt)==null||g.call(p,this.reconnectAttempts,a),this.connect()},a)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},He=class{constructor(e){this.config=e;this.transport=null;this.liveUrlOverride=null}setLiveUrl(e){this.liveUrlOverride=e}async connect(){var d;let e=this.getLiveUrl();if(!await Xn(e,this.config.logger))return{usingWebSocket:!1,initialState:await Zt(e,this.config.logger)};let n,r,s=new Promise((u,p)=>{n=u,r=p}),a=!1,o=!1,c=null,l=u=>{a||(a=!0,c!==null&&(clearTimeout(c),c=null),u?r(u):n({usingWebSocket:!0}))};c=setTimeout(()=>{l(new Error("WebSocket open timed out after 10s"))},1e4),this.transport=new Ye({url:this.getWebSocketUrl(),autoReconnect:this.config.options.autoReconnect,reconnectDelay:this.config.options.reconnectDelay,maxReconnectDelay:16e3,maxReconnectAttempts:10,onOpen:()=>{o=!0,this.config.onConnected(),l()},onMessage:u=>{try{let p=JSON.parse(u.data);this.config.onMessage(p,u)}catch(p){this.config.logger.error("Failed to parse WebSocket message:",p)}},onClose:()=>{o?this.config.onDisconnected():l(new Error("WebSocket closed before it opened"))},onReconnectAttempt:(u,p)=>{var g,h;(h=(g=this.config).onReconnectAttempt)==null||h.call(g,u,p)},onReconnectFailed:()=>{var u,p;(p=(u=this.config).onReconnectFailed)==null||p.call(u)},onError:u=>{var p,g;(g=(p=this.config).onError)==null||g.call(p,u),l(new Error("WebSocket errored before it opened"))}}),this.transport.connect();try{return await s}catch(u){return this.config.logger.warn("WebSocket open failed, falling back to HTTP",u),(d=this.transport)==null||d.disconnect(),this.transport=null,{usingWebSocket:!1,initialState:await Zt(e,this.config.logger)}}}disconnect(){var e;(e=this.transport)==null||e.disconnect(),this.transport=null}send(e){var t;(t=this.transport)==null||t.send(e)}getReadyState(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())==null?void 0:t.readyState}getSocket(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())!=null?t:null}getWebSocketUrl(){let e=this.liveUrlOverride||this.config.options.liveUrl||"/live",t=this.config.options.wsUrl;return t||`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}${e}`}getLiveUrl(){return this.liveUrlOverride||this.config.options.liveUrl||window.location.pathname+window.location.search}};async function Xn(i,e){try{let n=(await fetch(i,{method:"HEAD"})).headers.get("X-LiveTemplate-WebSocket");return n?n==="enabled":!0}catch(t){return e==null||e.warn("Failed to check WebSocket availability:",t),!0}}async function Zt(i,e){try{let t=await fetch(i,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to fetch initial state: ${t.status}`);return await t.json()}catch(t){return e==null||e.warn("Failed to fetch initial state:",t),null}}var Re=class{async upload(e,t,n){let{file:r}=e;e.abortController=new AbortController;try{let s=new XMLHttpRequest;s.upload.addEventListener("progress",o=>{o.lengthComputable&&(e.bytesUploaded=o.loaded,e.progress=Math.round(o.loaded/o.total*100),n&&n(e))}),e.abortController.signal.addEventListener("abort",()=>{s.abort()});let a=new Promise((o,c)=>{s.addEventListener("load",()=>{s.status>=200&&s.status<300?(e.done=!0,e.progress=100,o()):c(new Error(`S3 upload failed with status ${s.status}: ${s.statusText}`))}),s.addEventListener("error",()=>{c(new Error("S3 upload failed: Network error"))}),s.addEventListener("abort",()=>{c(new Error("S3 upload cancelled"))})});if(s.open("PUT",t.url),t.headers)for(let[o,c]of Object.entries(t.headers))s.setRequestHeader(o,c);s.send(r),await a}catch(s){throw e.error=s instanceof Error?s.message:String(s),s}}};var Ie=class{constructor(e,t={}){this.sendMessage=e;this.entries=new Map;this.pendingFiles=new Map;this.autoUploadConfig=new Map;this.uploaders=new Map;this.inputHandlers=new WeakMap;this.chunkSize=t.chunkSize||256*1024,this.onProgress=t.onProgress,this.onComplete=t.onComplete,this.onError=t.onError,this.uploaders.set("s3",new Re)}initializeFileInputs(e){e.querySelectorAll('input[type="file"][lvt-upload]').forEach(n=>{let r=n.getAttribute("lvt-upload");if(!r)return;let s=this.inputHandlers.get(n);s&&n.removeEventListener("change",s);let a=o=>{let c=o.target.files;!c||c.length===0||this.startUpload(r,Array.from(c))};n.addEventListener("change",a),this.inputHandlers.set(n,a)})}async startUpload(e,t){this.pendingFiles.set(e,t);let n=t.map(s=>({name:s.name,type:s.type||"application/octet-stream",size:s.size})),r={action:"upload_start",upload_name:e,files:n};this.sendMessage(r)}async handleUploadStartResponse(e){let{upload_name:t,entries:n}=e;n.length>0&&this.autoUploadConfig.set(t,n[0].auto_upload);let r=this.pendingFiles.get(t);if(!r){console.error(`No pending files found for upload: ${t}`);return}this.pendingFiles.delete(t);let s=new Map;for(let o of r)s.set(o.name,o);let a=[];for(let o of n){let c=s.get(o.client_name);if(!c){console.warn(`No file found for entry ${o.entry_id} (client_name: ${o.client_name})`);continue}let l={id:o.entry_id,file:c,uploadName:t,progress:0,bytesUploaded:0,valid:o.valid,done:!1,error:o.error,external:o.external};if(this.entries.set(l.id,l),a.push(l),!o.valid){this.onError&&o.error&&this.onError(l,o.error);continue}o.auto_upload&&(o.external?this.uploadExternal(l,o.external):this.uploadChunked(l))}}async uploadExternal(e,t){try{let n=this.uploaders.get(t.uploader);if(!n)throw new Error(`Unknown uploader: ${t.uploader}`);await n.upload(e,t,this.onProgress);let r={action:"upload_complete",upload_name:e.uploadName,entry_ids:[e.id]};this.sendMessage(r),this.onComplete&&this.onComplete(e.uploadName,[e]),this.clearFileInput(e.uploadName),this.cleanupEntries(e.uploadName)}catch(n){let r=n instanceof Error?n.message:String(n);e.error=r,this.onError&&this.onError(e,r),this.cleanupEntries(e.uploadName)}}async uploadChunked(e){let{file:t,id:n}=e,r=0;e.abortController=new AbortController;try{for(;r<t.size;){if(e.abortController.signal.aborted)throw new Error("Upload cancelled");let a=Math.min(r+this.chunkSize,t.size),o=t.slice(r,a),c=await this.fileToBase64(o),l={action:"upload_chunk",entry_id:n,chunk_base64:c,offset:r,total:t.size};this.sendMessage(l),r=a,e.bytesUploaded=r,e.progress=Math.round(r/t.size*100),this.onProgress&&this.onProgress(e)}e.done=!0;let s={action:"upload_complete",upload_name:e.uploadName,entry_ids:[n]};this.sendMessage(s),this.onComplete&&this.onComplete(e.uploadName,[e]),this.clearFileInput(e.uploadName),this.cleanupEntries(e.uploadName)}catch(s){let a=s instanceof Error?s.message:String(s);e.error=a,this.onError&&this.onError(e,a),this.cleanupEntries(e.uploadName)}}handleProgressMessage(e){let t=this.entries.get(e.entry_id);t&&(t.progress=e.progress,t.bytesUploaded=e.bytes_recv,this.onProgress&&this.onProgress(t))}cancelUpload(e){let t=this.entries.get(e);t&&(t.abortController&&t.abortController.abort(),this.sendMessage({action:"cancel_upload",entry_id:e}),this.entries.delete(e))}getEntries(e){let t=[];for(let n of this.entries.values())n.uploadName===e&&t.push(n);return t}triggerPendingUploads(e){let t=[];for(let n of this.entries.values())n.uploadName===e&&n.progress===0&&!n.done&&!n.error&&t.push(n);for(let n of t)n.external?this.uploadExternal(n,n.external):this.uploadChunked(n)}registerUploader(e,t){this.uploaders.set(e,t)}clearFileInput(e){document.querySelectorAll(`input[type="file"][lvt-upload="${e}"]`).forEach(n=>{n.value=""})}cleanupEntries(e,t=5e3){setTimeout(()=>{let n=[];for(let[r,s]of this.entries)e&&s.uploadName!==e||(s.done||s.error)&&n.push(r);for(let r of n)this.entries.delete(r)},t)}fileToBase64(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];t(a)},r.onerror=n,r.readAsDataURL(e)})}};var en={silent:0,error:1,warn:2,info:3,debug:4},tn="LiveTemplate",Xe=class i{constructor(e,t=[],n=console){this.state=e;this.scope=t;this.sink=n}setLevel(e){this.state.level=e}getLevel(){return this.state.level}child(e){return new i(this.state,[...this.scope,e],this.sink)}isDebugEnabled(){return this.shouldLog("debug")}error(...e){this.log("error","error",e)}warn(...e){this.log("warn","warn",e)}info(...e){this.log("info","info",e)}debug(...e){this.log("debug","debug",e)}log(e,t,n){if(!this.shouldLog(e))return;(this.sink[t]||console[t]||console.log).apply(this.sink,[this.formatPrefix(),...n])}shouldLog(e){return en[e]<=en[this.state.level]}formatPrefix(){return this.scope.length===0?`[${tn}]`:`[${tn}:${this.scope.join(":")}]`}};function Je(i={}){var n,r;let e={level:(n=i.level)!=null?n:"info"},t=Array.isArray(i.scope)?i.scope:i.scope?[i.scope]:[];return new Xe(e,t,(r=i.sink)!=null?r:console)}async function nn(i,e){try{let t=globalThis==null?void 0:globalThis.require;if(typeof t=="function"){let s=t("fs"),a=JSON.parse(s.readFileSync(e,"utf8"));return i.applyUpdate(a)}let r=await(await fetch(e)).json();return i.applyUpdate(r)}catch(t){throw new Error(`Failed to load update from ${e}: ${t}`)}}function rn(i,e){let t=[],n=l=>l.replace(/\s+/g," ").replace(/>\s+</g,"><").trim(),r=n(i),s=n(e);if(r===s)return{match:!0,differences:[]};let a=r.split(`
29
+ `,document.head.appendChild(t)}document.body.insertBefore(e,document.body.firstChild),this.bar=e}hide(){this.bar&&(this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),this.bar=null)}enablePerActionIndicator(e){if(this.pendingHandler){if(this.currentDebounceMs===e)return;this.disablePerActionIndicator()}this.pendingCount=0,this.currentDebounceMs=e,this.pendingHandler=()=>{this.pendingCount++,this.pendingCount===1&&this.actionTimer===null&&this.bar===null&&(this.actionTimer=setTimeout(()=>{this.actionTimer=null,this.pendingCount>0&&this.show()},e))},this.updatedHandler=()=>{this.pendingCount=Math.max(0,this.pendingCount-1),this.pendingCount===0&&(this.actionTimer!==null&&(clearTimeout(this.actionTimer),this.actionTimer=null),this.hide())},document.addEventListener("lvt:pending",this.pendingHandler,!0),document.addEventListener("lvt:updated",this.updatedHandler,!0)}disablePerActionIndicator(){this.pendingHandler&&(document.removeEventListener("lvt:pending",this.pendingHandler,!0),this.pendingHandler=null),this.updatedHandler&&(document.removeEventListener("lvt:updated",this.updatedHandler,!0),this.updatedHandler=null),this.actionTimer!==null&&(clearTimeout(this.actionTimer),this.actionTimer=null),this.pendingCount=0,this.currentDebounceMs=null,this.hide()}};var Me=class{disable(e){if(!e)return;e.querySelectorAll("form").forEach(n=>{n.querySelectorAll("input, textarea, select, button").forEach(s=>{s.disabled=!0})})}enable(e){if(!e)return;e.querySelectorAll("form").forEach(n=>{n.querySelectorAll("input, textarea, select, button").forEach(s=>{s.disabled=!1})})}};var zt=!1;function Gn(i){let e=i.target;if(!e||!(e instanceof Element))return;let t=e.closest("button[commandfor]");if(!t||t.disabled)return;let n=t.getAttribute("commandfor");if(!n)return;let r=t.getAttribute("command"),s=document.getElementById(n);s&&(s instanceof HTMLDialogElement?r==="show-modal"&&!s.open?s.showModal():r==="close"&&s.open&&s.close():s instanceof HTMLElement&&s.hasAttribute("popover")&&(r==="show-popover"&&typeof s.showPopover=="function"?s.showPopover():r==="hide-popover"&&typeof s.hidePopover=="function"?s.hidePopover():r==="toggle-popover"&&typeof s.togglePopover=="function"&&s.togglePopover()))}function jt(){"commandForElement"in HTMLButtonElement.prototype||zt||(zt=!0,document.addEventListener("click",Gn))}var re="__lvt_scroll_away",q=[];function Yn(){for(let i=q.length-1;i>=0;i--){let e=q[i];e.trigger.isConnected||(e.target.removeEventListener("scroll",e.handler),delete e.trigger[re],q.splice(i,1))}}function Yt(i){Yn();let e=t=>{let n=t.getAttribute("lvt-scroll-away");if(!n)return;if(n!=="bottom"&&n!=="top"){console.warn(`Unknown lvt-scroll-away edge: ${n}`);return}let r=G(t);if(!r||r===t){let u=t[re];u&&(u.target.removeEventListener("scroll",u.handler),Gt(u),delete t[re]),console.warn("lvt-scroll-away requires data-lvt-target pointing to a scrollable container");return}let s=t[re];if(s){if(s.target===r)return;s.target.removeEventListener("scroll",s.handler),Gt(s)}let a=parseInt(getComputedStyle(t).getPropertyValue("--lvt-scroll-threshold").trim(),10),o=isNaN(a)?200:a,c=!1,l=()=>{c||(c=!0,requestAnimationFrame(()=>{c=!1,(n==="top"?r.scrollTop:r.scrollHeight-r.scrollTop-r.clientHeight)>o?t.classList.add("visible"):t.classList.remove("visible")}))};r.addEventListener("scroll",l,{passive:!0}),l();let d={trigger:t,target:r,handler:l};t[re]=d,q.push(d)};e(i),i.querySelectorAll("[lvt-scroll-away]").forEach(e)}function Gt(i){let e=q.indexOf(i);e!==-1&&q.splice(e,1)}function Xt(i){for(let e=q.length-1;e>=0;e--){let t=q[e];i&&t.trigger.isConnected&&!i.contains(t.trigger)||(t.target.removeEventListener("scroll",t.handler),t.trigger.classList.remove("visible"),delete t.trigger[re],q.splice(e,1))}}var Jt="lvt-active",Ye="__lvt_spy",se="__lvt_spy_link_handler",P=[],Qt=new WeakSet;function Xn(){for(let i=P.length-1;i>=0;i--){let e=P[i];e.container.isConnected||(Xe(e),P.splice(i,1))}if(P.length===0){let i=document[se];i&&(document.removeEventListener("click",i),delete document[se])}}function Xe(i){ie(i,null),i.scrollTarget.removeEventListener("scroll",i.scrollHandler),window.removeEventListener("resize",i.resizeHandler),delete i.container[Ye]}function Ge(i){let e=getComputedStyle(i).getPropertyValue("--lvt-spy-margin").trim(),t=Math.round(window.innerHeight*.25);if(!e)return t;let n=parseFloat(e);return isNaN(n)?t:e.endsWith("vh")?Math.round(n/100*window.innerHeight):e.endsWith("px")||/^-?\d+(\.\d+)?$/.test(e)?n:(console.warn(`lvt-spy: unsupported --lvt-spy-margin unit ${JSON.stringify(e)}; supported units are vh and px (or unitless). Falling back to 25vh.`),t)}function tn(i){let e=i.getAttribute("lvt-spy");if(e&&e.trim()!=="")try{return Array.from(i.querySelectorAll(e))}catch(t){return console.warn(`lvt-spy: invalid selector ${JSON.stringify(e)}:`,t),[]}return[i]}function ie(i,e){for(let t of i.links){let n=t.getAttribute("href")||"",r=n.startsWith("#")?n.slice(1):"";e!==null&&r===e?t.classList.add(Jt):t.classList.remove(Jt)}}function nn(i){let e=new Set;for(let n of i.targets)n.id&&e.add(n.id);let t=[];document.querySelectorAll("[lvt-spy-link]").forEach(n=>{let r=n.getAttribute("href")||"",s=r.startsWith("#")?r.slice(1):"";e.has(s)&&t.push(n)}),i.links=t}function Jn(i){for(let e of P)for(let t of e.targets)if(t.id===i)return e;return null}function xe(i,e){let t=null;for(let n of i){if(!n.id)continue;n.getBoundingClientRect().top<=e&&(t=n.id)}return t}function Qn(i){let e=i.parentElement;for(;e&&e!==document.documentElement;){let t=getComputedStyle(e).overflowY;if(t==="auto"||t==="scroll"||t==="overlay")return e;e=e.parentElement}return window}function Zn(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(i[t]!==e[t])return!1;return!0}function Zt(i,e){let t=e!=null?e:tn(i);if(t.length===0)return;let n=t.filter(a=>!a.id&&!Qt.has(a));if(n.length>0){console.warn(`lvt-spy: ${n.length} target(s) without an id attribute; they cannot be linked from [lvt-spy-link]. Add id="..." or drop them from the selector. First offender:`,n[0]);for(let a of n)Qt.add(a)}let r={container:i,targets:t,marginPx:Ge(i),links:[],scrollTarget:Qn(i),scrollHandler:()=>{},resizeHandler:()=>{}};nn(r);let s=!1;r.scrollHandler=()=>{s||(s=!0,requestAnimationFrame(()=>{s=!1,ie(r,xe(r.targets,r.marginPx))}))},r.resizeHandler=()=>{r.marginPx=Ge(r.container),ie(r,xe(r.targets,r.marginPx))},r.scrollTarget.addEventListener("scroll",r.scrollHandler,{passive:!0}),window.addEventListener("resize",r.resizeHandler,{passive:!0}),i[Ye]=r,P.push(r),ie(r,xe(r.targets,r.marginPx))}function en(i){let e=i[Ye];if(e){let t=tn(i);if(Zn(e.targets,t)){e.marginPx=Ge(i),nn(e),ie(e,xe(e.targets,e.marginPx));return}Xe(e);let n=P.indexOf(e);n!==-1&&P.splice(n,1),Zt(i,t);return}Zt(i)}function er(){if(document[se])return;let i=e=>{var a;let t=(a=e.target)==null?void 0:a.closest("[lvt-spy-link]");if(!t)return;let n=t.getAttribute("href")||"",r=n.startsWith("#")?n.slice(1):"";if(!r)return;let s=Jn(r);s&&ie(s,r)};document.addEventListener("click",i,{passive:!0}),document[se]=i}function rn(i){Xn(),er(),i.hasAttribute("lvt-spy")&&en(i),i.querySelectorAll("[lvt-spy]").forEach(en)}function sn(i){for(let e=P.length-1;e>=0;e--){let t=P[e];i&&t.container.isConnected&&!i.contains(t.container)||(Xe(t),P.splice(e,1))}if(P.length===0){let e=document[se];e&&(document.removeEventListener("click",e),delete document[se])}}function on(i){return typeof structuredClone=="function"?structuredClone(i):JSON.parse(JSON.stringify(i))}function tr(i){return i!=null&&typeof i=="object"&&Array.isArray(i.d)&&Array.isArray(i.s)}function Je(i,e=0){if(e>50||i==null||typeof i!="object"||Array.isArray(i))return!1;if(tr(i))return!0;for(let n of Object.keys(i))if(/^\d+$/.test(n)){let r=i[n];if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&Je(r,e+1))return!0}return!1}function nr(i,e){if(!e.s||!Array.isArray(e.s))return!1;if(Je(i)&&!Je(e))return!0;for(let t of Object.keys(i))if(/^\d+$/.test(t)&&!(t in e))return!0;return!1}var He=class{constructor(e){this.logger=e;this.treeState={};this.rangeState={};this.rangeIdKeys={}}applyUpdate(e,t){var c,l;let n=!1,r=[],s=new Set;for(let[d,u]of Object.entries(e))if(Array.isArray(u)&&u.length>0&&Array.isArray(u[0])&&typeof u[0][0]=="string"){let g=this.treeState[d];g&&typeof g=="object"&&!Array.isArray(g)&&Array.isArray(g.d)&&Array.isArray(g.s)?((c=t==null?void 0:t.canApplyTargeted)==null?void 0:c.call(t,g,d))===!0?(this.applyDifferentialOpsToRange(g,u,d),r.push({rangePath:d,ops:u,statics:g.s,idKey:(l=g.m)==null?void 0:l.idKey}),s.add(d)):(this.treeState[d]=on(g),this.applyDifferentialOpsToRange(this.treeState[d],u,d)):this.treeState[d]=u,n=!0}else{let g=this.treeState[d],h=typeof u=="object"&&u!==null&&!Array.isArray(u)?this.deepMergeTreeNodes(g,u,d):u;JSON.stringify(g)!==JSON.stringify(h)&&(this.treeState[d]=h,n=!0)}let o={html:this.reconstructFromTree(this.treeState,"",s.size>0?s:void 0),changed:n};return r.length>0&&(o.targetedOps=r),o}reset(){this.treeState={},this.rangeState={},this.rangeIdKeys={}}getTreeState(){return{...this.treeState}}getStaticStructure(){return this.treeState.s||null}renderState(){return this.reconstructFromTree(this.treeState,"")}deepMergeTreeNodes(e,t,n=""){var s;if(typeof t!="object"||t===null||Array.isArray(t)||typeof e!="object"||e===null||Array.isArray(e))return t;if(nr(e,t))return this.logger.debug(`[deepMerge] Structure transition at path ${n}, replacing instead of merging`),t;let r={...e};for(let[a,o]of Object.entries(t)){let c=n?`${n}.${a}`:a,l=Array.isArray(o)&&o.length>0&&Array.isArray(o[0])&&typeof o[0][0]=="string",d=r[a]&&typeof r[a]=="object"&&!Array.isArray(r[a])&&Array.isArray(r[a].d)&&Array.isArray(r[a].s);l&&d?(r[a]=on(r[a]),this.logger.debug(`[deepMerge] Applying diff ops at path ${c}`,{ops:o,rangeItems:(s=r[a].d)==null?void 0:s.length}),this.applyDifferentialOpsToRange(r[a],o,c)):typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof r[a]=="object"&&r[a]!==null&&!Array.isArray(r[a])?r[a]=this.deepMergeTreeNodes(r[a],o,c):r[a]=o}return r}applyDifferentialOpsToRange(e,t,n){if(!e||typeof e!="object"||!Array.isArray(e.d)||!Array.isArray(e.s)){this.logger.error(`[applyDiffOpsToRange] Invalid rangeStructure at path ${n}`,{rangeStructure:e});return}let r=e.d;this.rangeState[n]||(this.rangeState[n]={items:r,statics:e.s}),e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[n]=e.m.idKey),this.logger.debug(`[applyDiffOpsToRange] path=${n}, idKey=${this.rangeIdKeys[n]}, items=${r.length}, ops=${t.length}`);for(let s of t){if(!Array.isArray(s)||s.length<2)continue;switch(s[0]){case"r":{let o=s[1],c=this.findItemIndexByKey(r,o,e.s,n);this.logger.debug(`[applyDiffOpsToRange] Remove: key=${o}, index=${c}, total=${r.length}`),c>=0?(r.splice(c,1),this.logger.debug(`[applyDiffOpsToRange] After removal: ${r.length} items`)):this.logger.debug(`[applyDiffOpsToRange] Remove failed: key ${o} not found`);break}case"u":{let o=this.findItemIndexByKey(r,s[1],e.s,n),c=s[2];o>=0&&c&&(r[o]=this.mergeRangeItem(r[o],c,n));break}case"a":{let o=Array.isArray(s[1])?s[1]:[s[1]];s[2]&&(e.s=s[2]),r.push(...o),s[3]&&typeof s[3]=="object"&&s[3].idKey&&(this.rangeIdKeys[n]=s[3].idKey);break}case"p":{let o=Array.isArray(s[1])?s[1]:[s[1]];s[2]&&(e.s=s[2]),r.unshift(...o);break}case"i":{let o=this.findItemIndexByKey(r,s[1],e.s,n);if(o>=0){let c=Array.isArray(s[2])?s[2]:[s[2]];r.splice(o+1,0,...c)}break}case"o":{let o=s[1],c=[],l=new Map;for(let d of r){let u=this.getItemKey(d,e.s,n);u&&l.set(u,d)}for(let d of o){let u=l.get(d);u&&c.push(u)}r.length=0,r.push(...c);break}default:break}}this.rangeState[n]={items:r,statics:e.s}}reconstructFromTree(e,t,n){if(e.s&&Array.isArray(e.s)){let r="";for(let s=0;s<e.s.length;s++){let a=e.s[s];if(r+=a,s<e.s.length-1){let o=s.toString();if(e[o]!==void 0){let c=t?`${t}.${o}`:o;if(n&&n.has(c)){r+=`<!--lvt-targeted-skip:${c}-->`;continue}r+=this.renderValue(e[o],o,c)}}}return r=r.replace(/<root>/g,"").replace(/<\/root>/g,""),r}return this.renderValue(e,"",t)}renderValue(e,t,n){if(e==null||typeof e=="string"&&e.startsWith("{{")&&e.endsWith("}}"))return"";if(typeof e=="object"&&!Array.isArray(e)){if(e.d&&Array.isArray(e.d)&&e.s&&Array.isArray(e.s)){let a=n||t||"";return a&&(this.rangeState[a]={items:e.d,statics:e.s},e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[a]=e.m.idKey)),this.renderRangeStructure(e,t,n)}if("s"in e&&Array.isArray(e.s))return this.reconstructFromTree(e,n||"");let r=Object.keys(e),s=r.filter(a=>/^\d+$/.test(a)).sort((a,o)=>parseInt(a)-parseInt(o));if(s.length>0&&s.length===r.length)return s.map(a=>{let o=n?`${n}.${a}`:a;return this.renderValue(e[a],a,o)}).join("")}return Array.isArray(e)?e.length>0&&Array.isArray(e[0])&&typeof e[0][0]=="string"?this.applyDifferentialOperations(e,n):e.map((r,s)=>{let a=s.toString(),o=n?`${n}.${a}`:a;return typeof r=="object"&&r&&r.s?this.reconstructFromTree(r,o):this.renderValue(r,a,o)}).join(""):typeof e=="object"?(this.logger.debug("Skipping plain object value (not a tree node) - this is normal for state-only data"),""):String(e)}renderRangeStructure(e,t,n){let{d:r,s}=e;if(!r||!Array.isArray(r))return"";if(r.length===0){if(e.else){let a="else",o=n?`${n}.else`:"else";return this.renderValue(e.else,a,o)}return""}return s&&Array.isArray(s)?r.map((a,o)=>this.renderRangeItem(a,o,s,n)).join(""):r.map((a,o)=>{let c=o.toString(),l=n?`${n}.${c}`:c;return this.renderValue(a,c,l)}).join("")}renderRangeItem(e,t,n,r){let s=n,a="";for(let o=0;o<s.length;o++)if(a+=s[o],o<s.length-1){let c=o.toString();if(e[c]!==void 0){let l=r?`${r}.${t}.${c}`:`${t}.${c}`;a+=this.renderValue(e[c],c,l)}}return a}applyDifferentialOperations(e,t){if(!t||!this.rangeState[t])return"";let n=this.rangeState[t],r=[...n.items],s=n.statics;for(let o of e){if(!Array.isArray(o)||o.length<2)continue;switch(o[0]){case"r":{let l=this.findItemIndexByKey(r,o[1],s,t);l>=0&&r.splice(l,1);break}case"u":{let l=this.findItemIndexByKey(r,o[1],s,t),d=o[2];l>=0&&d&&(r[l]=this.mergeRangeItem(r[l],d,t||""));break}case"a":{this.addItemsToRange(r,o[1],o[2],n,!1),o[3]&&typeof o[3]=="object"&&o[3].idKey&&(this.rangeIdKeys[t||""]=o[3].idKey);break}case"p":{this.addItemsToRange(r,o[1],o[2],n,!0);break}case"i":{let l=this.findItemIndexByKey(r,o[1],s,t);if(l>=0){let d=Array.isArray(o[2])?o[2]:[o[2]];r.splice(l+1,0,...d)}break}case"o":{let l=o[1],d=[],u=new Map;for(let p of r){let g=this.getItemKey(p,s,t);g&&u.set(g,p)}for(let p of l){let g=u.get(p);g&&d.push(g)}r.length=0,r.push(...d);break}default:break}}this.rangeState[t]={items:r,statics:n.statics},this.treeState[t]={d:r,s:n.statics};let a=this.getCurrentRangeStructure(t);return a&&a.s?this.renderItemsWithStatics(r,a.s,t):r.map(o=>this.renderValue(o)).join("")}getCurrentRangeStructure(e){if(this.rangeState[e])return{d:this.rangeState[e].items,s:this.rangeState[e].statics};let t=this.treeState[e];return t&&typeof t=="object"&&t.s?t:null}renderItemsWithStatics(e,t,n){let r=e.map((s,a)=>this.renderRangeItem(s,a,t,n)).join("");return this.logger.isDebugEnabled()&&(this.logger.debug("[renderItemsWithStatics] statics:",t),this.logger.debug("[renderItemsWithStatics] items count:",e.length),this.logger.debug("[renderItemsWithStatics] result snippet:",r.substring(0,200))),r}addItemsToRange(e,t,n,r,s){if(n&&(r.statics=n),!t)return;let a=Array.isArray(t)?t:[t];s?e.unshift(...a):e.push(...a)}getItemKey(e,t,n){if(e._k&&typeof e._k=="string")return e._k;if(!n||!this.rangeIdKeys[n])return null;let r=this.rangeIdKeys[n];return e[r]||null}findItemIndexByKey(e,t,n,r){return e.findIndex(s=>this.getItemKey(s,n,r)===t)}mergeRangeItem(e,t,n){return this.deepMergeTreeNodes(e,t,`${n}.item`)}};var Qe=["data-key","data-lvt-key"],rr=Qe.map(i=>new RegExp(`(?:^|[\\s<])${i}\\s*=`)),Q="data-lvt-targeted-applied",Z="data-lvt-targeted-skip",Re=class{constructor(e){this.ctx=e;this.containerCache=new Map}invalidate(){this.containerCache.clear()}invalidatePath(e){this.containerCache.delete(e)}findContainer(e,t,n){let r=this.containerCache.get(t);if(r&&r.isConnected&&e.contains(r))return r;if(r&&this.containerCache.delete(t),n===void 0)return null;let s=this.findItemByKey(e,n);if(!s||!s.parentElement)return null;let a=s.parentElement;return this.containerCache.set(t,a),a}canApplyTargeted(e,t,n){if(!t||typeof t!="object")return{ok:!1,reason:"no range structure"};if(!Array.isArray(t.s)||t.s.length===0)return{ok:!1,reason:"no statics"};let r=[t.s];if(t.sm&&typeof t.sm=="object")for(let d of Object.values(t.sm))Array.isArray(d)&&r.push(d);if(!r.some(d=>this.staticsContainKeyAttribute(d)))return{ok:!1,reason:"no data-key attribute in statics"};let a=t.d;if(Array.isArray(a)){for(let d of a)if(this.itemHasNestedRange(d))return{ok:!1,reason:"nested-range item"}}let o=this.extractItemKey(a==null?void 0:a[0],t),c=this.findContainer(e,n,o);if(!c)return{ok:!1,reason:"container not found in DOM"};let l=c;for(;l;){if(l.hasAttribute("lvt-ignore"))return{ok:!1,reason:"lvt-ignore ancestor"};if(l===e)break;l=l.parentElement}return{ok:!0,container:c,containerKey:o}}apply(e,t,n){let{rangePath:r,ops:s,statics:a}=t,o=this.firstKnownKey(s),c=this.findContainer(e,r,o);if(!c)return this.ctx.logger.debug(`[RangeDomApplier] container not found for range ${r}; cannot apply`),null;let l=!0;for(let d of s){if(!Array.isArray(d)||d.length<1)continue;let u=d[0];try{let p=!0;switch(u){case"r":p=this.applyRemove(c,d[1]);break;case"u":p=this.applyUpdateRow(c,d[1],a,r,n);break;case"i":p=this.applyInsertAfter(c,d[1],d[2],a,r);break;case"a":p=this.applyAppend(c,d[1],a,r);break;case"p":p=this.applyPrepend(c,d[1],a,r);break;case"o":p=this.applyReorder(c,d[1]);break;default:this.ctx.logger.warn(`[RangeDomApplier] unknown op type ${u}; falling back`),p=!1}p||(l=!1)}catch(p){return this.ctx.logger.error(`[RangeDomApplier] op ${u} failed for range ${r}`,p),null}}return l?(typeof window!="undefined"&&"__lvtTargetedHits"in window&&window.__lvtTargetedHits++,c):null}cleanupMarkers(e){e.querySelectorAll(`[${Q}]`).forEach(r=>r.removeAttribute(Q)),e.hasAttribute(Q)&&e.removeAttribute(Q),e.querySelectorAll(`[${Z}]`).forEach(r=>r.removeAttribute(Z)),e.hasAttribute(Z)&&e.removeAttribute(Z)}applyRemove(e,t){let n=this.findItemByKey(e,t);return n?(this.fireHookOnSubtree(n,"lvt-destroyed"),n.remove(),!0):(this.ctx.logger.debug(`[RangeDomApplier] r: row with key ${t} not found (idempotent no-op)`),!0)}applyUpdateRow(e,t,n,r,s){var u,p;let a=this.findItemByKey(e,t);if(!a)return this.ctx.logger.debug(`[RangeDomApplier] u: row with key ${t} not found in DOM; falling back`),!1;let o=this.indexOfChild(e,a),c=this.lookupCurrentItem(r,t);if(!c)return this.ctx.logger.debug(`[RangeDomApplier] u: item state for key ${t} not available; falling back`),!1;let l=this.ctx.renderItem(c,o,n,r),d=this.parseSingleRow(l);return d?(s?fe(a,d,{...s,childrenOnly:!1}):(this.fireHookOnSubtree(a,"lvt-destroyed"),a.replaceWith(d),(p=(u=this.ctx).onNodeAdded)==null||p.call(u,d),this.fireHookOnSubtree(d,"lvt-mounted")),!0):(this.ctx.logger.warn("[RangeDomApplier] u: failed to parse rendered row HTML; falling back"),!1)}applyInsertAfter(e,t,n,r,s){let a=this.findItemByKey(e,t);return a?this.renderItemsAtomic(n,r,s,this.indexOfChild(e,a)+1,o=>e.insertBefore(o,a.nextSibling)):(this.ctx.logger.debug(`[RangeDomApplier] i: anchor key ${t} not found; falling back`),!1)}applyAppend(e,t,n,r){return this.renderItemsAtomic(t,n,r,e.children.length,s=>e.appendChild(s))}applyPrepend(e,t,n,r){return this.renderItemsAtomic(t,n,r,0,s=>e.insertBefore(s,e.firstChild))}renderItemsAtomic(e,t,n,r,s){var l,d;let a=Array.isArray(e)?e:[e],o=document.createDocumentFragment(),c=[];for(let u=0;u<a.length;u++){let p=this.renderAndParse(a[u],r+u,t,n);if(!p)return!1;o.appendChild(p),c.push(p)}s(o);for(let u of c)(d=(l=this.ctx).onNodeAdded)==null||d.call(l,u),this.fireHookOnSubtree(u,"lvt-mounted");return!0}applyReorder(e,t){if(!Array.isArray(t))return!1;let n=new Map;Array.from(e.children).forEach(a=>{for(let o of Qe){let c=a.getAttribute(o);if(c!==null){n.set(c,a);break}}});let r=document.createDocumentFragment(),s=new Set(t);for(let a of t){let o=n.get(a);o&&r.appendChild(o)}if(s.size<n.size){this.ctx.logger.warn(`[RangeDomApplier] o: newKeyOrder (${s.size}) shorter than existing children (${n.size}); ${n.size-s.size} children will be dropped`);for(let[a,o]of n)s.has(a)||this.fireHookOnSubtree(o,"lvt-destroyed")}return e.replaceChildren(r),!0}renderAndParse(e,t,n,r){let s=this.ctx.renderItem(e,t,n,r);return this.parseSingleRow(s)}parseSingleRow(e){let t=document.createElement("template");t.innerHTML=e.trim();let n=t.content.firstElementChild;return n!=null?n:null}findItemByKey(e,t){let n;typeof CSS!="undefined"&&typeof CSS.escape=="function"?n=CSS.escape(t):(/[\[\]():.#>~+*=^$|! \t\n\r]/.test(t)&&this.ctx.logger.warn(`[RangeDomApplier] CSS.escape unavailable; key "${t}" contains characters that need escaping. Lookup may miss the row.`),n=t.replace(/(["\\])/g,"\\$1"));for(let r of Qe){let s=e.querySelector(`[${r}="${n}"]`);if(s)return s}return null}indexOfChild(e,t){let n=0,r=e.firstElementChild;for(;r;){if(r===t)return n;n++,r=r.nextElementSibling}return-1}firstKnownKey(e){for(let t of e){if(!Array.isArray(t)||t.length<2)continue;let n=t[0];if(n==="r"||n==="u"||n==="i")return typeof t[1]=="string"?t[1]:void 0;if(n==="o"&&Array.isArray(t[1])&&t[1].length>0)return typeof t[1][0]=="string"?t[1][0]:void 0;if(n==="a"||n==="p"){let r=Array.isArray(t[1])?t[1]:[t[1]];for(let s of r)if(s&&typeof s=="object"&&s._k!==void 0)return String(s._k)}}}staticsContainKeyAttribute(e){for(let t of e)if(typeof t=="string"){for(let n of rr)if(n.test(t))return!0}return!1}itemHasNestedRange(e){if(!e||typeof e!="object")return!1;for(let[t,n]of Object.entries(e))if(!t.startsWith("_")&&n&&typeof n=="object"&&!Array.isArray(n)){let r=n;if(Array.isArray(r.d)&&Array.isArray(r.s)||this.itemHasNestedRange(r))return!0}return!1}extractItemKey(e,t){var r;if(!e||typeof e!="object")return;if(e._k!==void 0)return String(e._k);let n=(r=t==null?void 0:t.m)==null?void 0:r.idKey;if(n&&e[n]!==void 0)return String(e[n])}lookupCurrentItem(e,t){return this.ctx.itemLookup(e,t)}fireHookOnSubtree(e,t){e.hasAttribute(t)&&this.ctx.executeLifecycleHook(e,t),e.querySelectorAll(`[${t}]`).forEach(r=>this.ctx.executeLifecycleHook(r,t))}};var Ce=class{constructor(){this.activeForm=null;this.activeButton=null;this.originalButtonText=null}setActiveSubmission(e,t,n){if(this.activeForm=e,this.activeButton=t,this.originalButtonText=n,e){e.setAttribute("aria-busy","true");let r=e.querySelector("fieldset");r&&(r.disabled=!0)}}handleResponse(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:done",{detail:e})),e.success?this.handleSuccess(e):this.handleError(e),this.restoreFormState()}reset(){this.restoreFormState()}handleSuccess(e){if(!this.activeForm)return;this.activeForm.dispatchEvent(new CustomEvent("lvt:success",{detail:e}));let t=this.activeForm.closest("dialog");t&&t.open&&t.close(),this.activeForm.hasAttribute("lvt-form:preserve")||this.activeForm.reset()}handleError(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:error",{detail:e}))}restoreFormState(){if(this.activeForm){this.activeForm.removeAttribute("aria-busy");let e=this.activeForm.querySelector("fieldset");e&&(e.disabled=!1)}this.activeButton&&this.originalButtonText!==null&&(this.activeButton.disabled=!1,this.activeButton.textContent=this.originalButtonText),this.activeForm=null,this.activeButton=null,this.originalButtonText=null}};var De=class{constructor(e,t){this.context=e;this.logger=t;this.boundFields=new Map;this.enabled=!1;this.wiredElements=new Set;this.elementCleanups=new Map}setCapabilities(e){this.enabled=e.includes("change"),this.logger.debug("Capabilities received, change auto-wiring:",this.enabled?"enabled":"disabled")}analyzeStatics(e){let t=this.boundFields.size;this.walkTree(e),this.boundFields.size>t&&this.logger.debug(`Detected ${this.boundFields.size} bound field(s):`,Array.from(this.boundFields.keys()))}wireElements(){if(!this.enabled)return;let e=this.context.getWrapperElement();if(!e)return;for(let n of this.elementCleanups.keys())n.isConnected||(this.elementCleanups.get(n)(),this.elementCleanups.delete(n),this.wiredElements.delete(n));for(let[n,r]of this.boundFields){let s=this.escapeCSSSelector(n),a=e.querySelectorAll(`[name="${s}"]`);for(let o of a){if(this.wiredElements.has(o)||o.hasAttribute("lvt-input")||o.hasAttribute("lvt-change"))continue;let c=o.closest("form");c&&(c.hasAttribute("lvt-change")||ne(c,"lvt-form:no-intercept",this.logger))||o instanceof HTMLInputElement&&(o.type==="hidden"||o.type==="submit"||o.type==="button")||o instanceof HTMLButtonElement||(this.attachListener(o,n,r),this.wiredElements.add(o))}}let t=e.querySelectorAll("select[name]");for(let n of t){if(this.wiredElements.has(n)||n.hasAttribute("lvt-input")||n.hasAttribute("lvt-change"))continue;let r=n.closest("form");if(r&&(r.hasAttribute("lvt-change")||r.hasAttribute("lvt-form:no-intercept")))continue;let s=n.getAttribute("name");s&&(this.attachListener(n,s,"value"),this.wiredElements.add(n))}}teardown(){for(let e of this.elementCleanups.values())e();this.elementCleanups.clear(),this.wiredElements.clear(),this.boundFields.clear(),this.enabled=!1}getBoundFields(){return this.boundFields}isEnabled(){return this.enabled}walkTree(e){if(!(!e||typeof e!="object"||Array.isArray(e))){e.s&&Array.isArray(e.s)&&this.analyzeStaticsArray(e.s);for(let t of Object.keys(e))if(/^\d+$/.test(t)){let n=e[t];n&&typeof n=="object"&&!Array.isArray(n)&&this.walkTree(n)}if(e.d&&Array.isArray(e.d))for(let t of e.d)t&&typeof t=="object"&&!Array.isArray(t)&&this.walkTree(t)}}analyzeStaticsArray(e){for(let t=0;t<e.length-1;t++){let n=e[t],r=e[t+1],s=this.detectBinding(n,r);s&&!this.boundFields.has(s.fieldName)&&this.boundFields.set(s.fieldName,s.bindingType)}}detectBinding(e,t){let n=this.detectValueBinding(e);return n?{fieldName:n,bindingType:"value"}:(n=this.detectTextareaBinding(e,t),n?{fieldName:n,bindingType:"content"}:(n=this.detectAttributeBinding(e,t),n?{fieldName:n,bindingType:"attribute"}:null))}escapeCSSSelector(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}extractUnclosedTag(e){let t=e.lastIndexOf("<"),n=e.lastIndexOf(">");return t===-1||t<=n?null:e.substring(t)}extractNameFromTag(e){let t=e.match(/\sname="([^"]+)"/);return t?t[1]:null}detectValueBinding(e){if(!e.endsWith('value="'))return null;let t=this.extractUnclosedTag(e);return t?this.extractNameFromTag(t):null}detectTextareaBinding(e,t){if(!t.startsWith("</textarea"))return null;let n=e.match(/<textarea[^>]*\sname="([^"]+)"[^>]*>$/);return n?n[1]:null}detectAttributeBinding(e,t){if(!e.endsWith(" ")||!/^[a-zA-Z>/\s]/.test(t))return null;let n=this.extractUnclosedTag(e);if(!n||!/^<input\s/i.test(n))return null;let r=n.match(/\stype="([^"]+)"/i);if(!r)return null;let s=r[1].toLowerCase();return s!=="checkbox"&&s!=="radio"?null:this.extractNameFromTag(n)}attachListener(e,t,n){let r=e.getAttribute("lvt-debounce"),s=r?parseInt(r,10):NaN,a=Number.isNaN(s)||s<0?300:s,c=ce(()=>{if(!this.enabled)return;let d=n==="attribute"&&e.type==="checkbox"?e.checked:e.value;this.context.send({action:"change",data:{[t]:d}})},a),l=n==="attribute"||e instanceof HTMLSelectElement?"change":"input";e.addEventListener(l,c),this.elementCleanups.set(e,()=>{e.removeEventListener(l,c)}),this.logger.debug(`Auto-wired ${l} listener on [name="${t}"] (debounce: ${a}ms)`)}};var Ze=class{constructor(e){this.options=e;this.socket=null;this.reconnectTimer=null;this.manuallyClosed=!1;this.reconnectAttempts=0}connect(){this.manuallyClosed=!1,this.clearReconnectTimer(),this.socket=new WebSocket(this.options.url);let e=this.socket;e.onopen=()=>{var t,n;this.reconnectAttempts=0,(n=(t=this.options).onOpen)==null||n.call(t,e)},e.onmessage=t=>{var n,r;(r=(n=this.options).onMessage)==null||r.call(n,t)},e.onclose=t=>{var n,r;(r=(n=this.options).onClose)==null||r.call(n,t),!this.manuallyClosed&&this.options.autoReconnect&&this.scheduleReconnect()},e.onerror=t=>{var n,r;(r=(n=this.options).onError)==null||r.call(n,t)}}send(e){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(e)}disconnect(){var e,t;this.manuallyClosed=!0,this.clearReconnectTimer(),this.socket&&(this.socket.readyState!==WebSocket.CLOSED&&((t=(e=this.options).onClose)==null||t.call(e,new CloseEvent("close",{code:1e3,reason:"",wasClean:this.socket.readyState===WebSocket.OPEN}))),this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close(),this.socket=null)}getSocket(){return this.socket}scheduleReconnect(){var o,c,l,d,u;this.clearReconnectTimer();let e=(o=this.options.maxReconnectAttempts)!=null?o:10;if(e>0&&this.reconnectAttempts>=e){(l=(c=this.options).onReconnectFailed)==null||l.call(c);return}this.reconnectAttempts++;let t=(d=this.options.reconnectDelay)!=null?d:1e3,n=(u=this.options.maxReconnectDelay)!=null?u:16e3,r=t*Math.pow(2,this.reconnectAttempts-1),s=Math.random()*1e3,a=Math.min(r+s,n);this.reconnectTimer=window.setTimeout(()=>{var p,g;(g=(p=this.options).onReconnectAttempt)==null||g.call(p,this.reconnectAttempts,a),this.connect()},a)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},Ie=class{constructor(e){this.config=e;this.transport=null;this.liveUrlOverride=null}setLiveUrl(e){this.liveUrlOverride=e}async connect(){var d;let e=this.getLiveUrl();if(!await sr(e,this.config.logger))return{usingWebSocket:!1,initialState:await an(e,this.config.logger)};let n,r,s=new Promise((u,p)=>{n=u,r=p}),a=!1,o=!1,c=null,l=u=>{a||(a=!0,c!==null&&(clearTimeout(c),c=null),u?r(u):n({usingWebSocket:!0}))};c=setTimeout(()=>{l(new Error("WebSocket open timed out after 10s"))},1e4),this.transport=new Ze({url:this.getWebSocketUrl(),autoReconnect:this.config.options.autoReconnect,reconnectDelay:this.config.options.reconnectDelay,maxReconnectDelay:16e3,maxReconnectAttempts:10,onOpen:()=>{o=!0,this.config.onConnected(),l()},onMessage:u=>{try{let p=JSON.parse(u.data);this.config.onMessage(p,u)}catch(p){this.config.logger.error("Failed to parse WebSocket message:",p)}},onClose:()=>{o?this.config.onDisconnected():l(new Error("WebSocket closed before it opened"))},onReconnectAttempt:(u,p)=>{var g,h;(h=(g=this.config).onReconnectAttempt)==null||h.call(g,u,p)},onReconnectFailed:()=>{var u,p;(p=(u=this.config).onReconnectFailed)==null||p.call(u)},onError:u=>{var p,g;(g=(p=this.config).onError)==null||g.call(p,u),l(new Error("WebSocket errored before it opened"))}}),this.transport.connect();try{return await s}catch(u){return this.config.logger.warn("WebSocket open failed, falling back to HTTP",u),(d=this.transport)==null||d.disconnect(),this.transport=null,{usingWebSocket:!1,initialState:await an(e,this.config.logger)}}}disconnect(){var e;(e=this.transport)==null||e.disconnect(),this.transport=null}send(e){var t;(t=this.transport)==null||t.send(e)}getReadyState(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())==null?void 0:t.readyState}getSocket(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())!=null?t:null}getWebSocketUrl(){let e=this.liveUrlOverride||this.config.options.liveUrl||"/live",t=this.config.options.wsUrl;return t||`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}${e}`}getLiveUrl(){return this.liveUrlOverride||this.config.options.liveUrl||window.location.pathname+window.location.search}};async function sr(i,e){try{let n=(await fetch(i,{method:"HEAD"})).headers.get("X-LiveTemplate-WebSocket");return n?n==="enabled":!0}catch(t){return e==null||e.warn("Failed to check WebSocket availability:",t),!0}}async function an(i,e){try{let t=await fetch(i,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to fetch initial state: ${t.status}`);return await t.json()}catch(t){return e==null||e.warn("Failed to fetch initial state:",t),null}}var _e=class{async upload(e,t,n){let{file:r}=e;e.abortController=new AbortController;try{let s=new XMLHttpRequest;s.upload.addEventListener("progress",o=>{o.lengthComputable&&(e.bytesUploaded=o.loaded,e.progress=Math.round(o.loaded/o.total*100),n&&n(e))}),e.abortController.signal.addEventListener("abort",()=>{s.abort()});let a=new Promise((o,c)=>{s.addEventListener("load",()=>{s.status>=200&&s.status<300?(e.done=!0,e.progress=100,o()):c(new Error(`S3 upload failed with status ${s.status}: ${s.statusText}`))}),s.addEventListener("error",()=>{c(new Error("S3 upload failed: Network error"))}),s.addEventListener("abort",()=>{c(new Error("S3 upload cancelled"))})});if(s.open("PUT",t.url),t.headers)for(let[o,c]of Object.entries(t.headers))s.setRequestHeader(o,c);s.send(r),await a}catch(s){throw e.error=s instanceof Error?s.message:String(s),s}}};var Oe=class{constructor(e,t={}){this.sendMessage=e;this.entries=new Map;this.pendingFiles=new Map;this.autoUploadConfig=new Map;this.uploaders=new Map;this.inputHandlers=new WeakMap;this.chunkSize=t.chunkSize||256*1024,this.onProgress=t.onProgress,this.onComplete=t.onComplete,this.onError=t.onError,this.uploaders.set("s3",new _e)}initializeFileInputs(e){e.querySelectorAll('input[type="file"][lvt-upload]').forEach(n=>{let r=n.getAttribute("lvt-upload");if(!r)return;let s=this.inputHandlers.get(n);s&&n.removeEventListener("change",s);let a=o=>{let c=o.target.files;!c||c.length===0||this.startUpload(r,Array.from(c))};n.addEventListener("change",a),this.inputHandlers.set(n,a)})}async startUpload(e,t){this.pendingFiles.set(e,t);let n=t.map(s=>({name:s.name,type:s.type||"application/octet-stream",size:s.size})),r={action:"upload_start",upload_name:e,files:n};this.sendMessage(r)}async handleUploadStartResponse(e){let{upload_name:t,entries:n}=e;n.length>0&&this.autoUploadConfig.set(t,n[0].auto_upload);let r=this.pendingFiles.get(t);if(!r){console.error(`No pending files found for upload: ${t}`);return}this.pendingFiles.delete(t);let s=new Map;for(let o of r)s.set(o.name,o);let a=[];for(let o of n){let c=s.get(o.client_name);if(!c){console.warn(`No file found for entry ${o.entry_id} (client_name: ${o.client_name})`);continue}let l={id:o.entry_id,file:c,uploadName:t,progress:0,bytesUploaded:0,valid:o.valid,done:!1,error:o.error,external:o.external};if(this.entries.set(l.id,l),a.push(l),!o.valid){this.onError&&o.error&&this.onError(l,o.error);continue}o.auto_upload&&(o.external?this.uploadExternal(l,o.external):this.uploadChunked(l))}}async uploadExternal(e,t){try{let n=this.uploaders.get(t.uploader);if(!n)throw new Error(`Unknown uploader: ${t.uploader}`);await n.upload(e,t,this.onProgress);let r={action:"upload_complete",upload_name:e.uploadName,entry_ids:[e.id]};this.sendMessage(r),this.onComplete&&this.onComplete(e.uploadName,[e]),this.clearFileInput(e.uploadName),this.cleanupEntries(e.uploadName)}catch(n){let r=n instanceof Error?n.message:String(n);e.error=r,this.onError&&this.onError(e,r),this.cleanupEntries(e.uploadName)}}async uploadChunked(e){let{file:t,id:n}=e,r=0;e.abortController=new AbortController;try{for(;r<t.size;){if(e.abortController.signal.aborted)throw new Error("Upload cancelled");let a=Math.min(r+this.chunkSize,t.size),o=t.slice(r,a),c=await this.fileToBase64(o),l={action:"upload_chunk",entry_id:n,chunk_base64:c,offset:r,total:t.size};this.sendMessage(l),r=a,e.bytesUploaded=r,e.progress=Math.round(r/t.size*100),this.onProgress&&this.onProgress(e)}e.done=!0;let s={action:"upload_complete",upload_name:e.uploadName,entry_ids:[n]};this.sendMessage(s),this.onComplete&&this.onComplete(e.uploadName,[e]),this.clearFileInput(e.uploadName),this.cleanupEntries(e.uploadName)}catch(s){let a=s instanceof Error?s.message:String(s);e.error=a,this.onError&&this.onError(e,a),this.cleanupEntries(e.uploadName)}}handleProgressMessage(e){let t=this.entries.get(e.entry_id);t&&(t.progress=e.progress,t.bytesUploaded=e.bytes_recv,this.onProgress&&this.onProgress(t))}cancelUpload(e){let t=this.entries.get(e);t&&(t.abortController&&t.abortController.abort(),this.sendMessage({action:"cancel_upload",entry_id:e}),this.entries.delete(e))}getEntries(e){let t=[];for(let n of this.entries.values())n.uploadName===e&&t.push(n);return t}triggerPendingUploads(e){let t=[];for(let n of this.entries.values())n.uploadName===e&&n.progress===0&&!n.done&&!n.error&&t.push(n);for(let n of t)n.external?this.uploadExternal(n,n.external):this.uploadChunked(n)}registerUploader(e,t){this.uploaders.set(e,t)}clearFileInput(e){document.querySelectorAll(`input[type="file"][lvt-upload="${e}"]`).forEach(n=>{n.value=""})}cleanupEntries(e,t=5e3){setTimeout(()=>{let n=[];for(let[r,s]of this.entries)e&&s.uploadName!==e||(s.done||s.error)&&n.push(r);for(let r of n)this.entries.delete(r)},t)}fileToBase64(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];t(a)},r.onerror=n,r.readAsDataURL(e)})}};var ln={silent:0,error:1,warn:2,info:3,debug:4},cn="LiveTemplate",et=class i{constructor(e,t=[],n=console){this.state=e;this.scope=t;this.sink=n}setLevel(e){this.state.level=e}getLevel(){return this.state.level}child(e){return new i(this.state,[...this.scope,e],this.sink)}isDebugEnabled(){return this.shouldLog("debug")}error(...e){this.log("error","error",e)}warn(...e){this.log("warn","warn",e)}info(...e){this.log("info","info",e)}debug(...e){this.log("debug","debug",e)}log(e,t,n){if(!this.shouldLog(e))return;(this.sink[t]||console[t]||console.log).apply(this.sink,[this.formatPrefix(),...n])}shouldLog(e){return ln[e]<=ln[this.state.level]}formatPrefix(){return this.scope.length===0?`[${cn}]`:`[${cn}:${this.scope.join(":")}]`}};function tt(i={}){var n,r;let e={level:(n=i.level)!=null?n:"info"},t=Array.isArray(i.scope)?i.scope:i.scope?[i.scope]:[];return new et(e,t,(r=i.sink)!=null?r:console)}async function dn(i,e){try{let t=globalThis==null?void 0:globalThis.require;if(typeof t=="function"){let s=t("fs"),a=JSON.parse(s.readFileSync(e,"utf8"));return i.applyUpdate(a)}let r=await(await fetch(e)).json();return i.applyUpdate(r)}catch(t){throw new Error(`Failed to load update from ${e}: ${t}`)}}function un(i,e){let t=[],n=l=>l.replace(/\s+/g," ").replace(/>\s+</g,"><").trim(),r=n(i),s=n(e);if(r===s)return{match:!0,differences:[]};let a=r.split(`
30
30
  `),o=s.split(`
31
- `),c=Math.max(a.length,o.length);for(let l=0;l<c;l++){let d=a[l]||"",u=o[l]||"";d!==u&&(t.push(`Line ${l+1}:`),t.push(` Expected: ${d}`),t.push(` Actual: ${u}`))}return{match:!1,differences:t}}var De=class i{constructor(e={}){this.nodesAddedThisRender=0;this.directiveTouchedThisRender=!1;this.lvtId=null;this.ws=null;this.wrapperElement=null;this.useHTTP=!1;this.sessionCookie=null;this.rateLimitedHandlers=new WeakMap;this.isInitialized=!1;this.messageCount=0;this.navigationEpoch=0;this.liveUrlOverride=null;this.visibilityHandlerAttached=!1;this.hiddenAt=0;this.reconnecting=!1;this.visibilityHandler=null;this.pageshowHandler=null;this.visibilityReconnectTimer=null;let{logger:t,logLevel:n,debug:r,...s}=e,a=n!=null?n:r?"debug":"info",o=t!=null?t:Je({level:a});t?n?t.setLevel(n):r&&t.setLevel("debug"):o.setLevel(a),this.logger=o.child("Client"),this.options={autoReconnect:!1,reconnectDelay:1e3,liveUrl:window.location.pathname+window.location.search,...s},this.treeRenderer=new ke(this.logger.child("TreeRenderer")),this.rangeDomApplier=new Me({logger:this.logger.child("RangeDomApplier"),renderItem:(c,l,d,u)=>this.treeRenderer.renderRangeItem(c,l,d,u),executeLifecycleHook:(c,l)=>this.executeLifecycleHook(c,l),itemLookup:(c,l)=>{var p;let d=this.treeRenderer.getTreeState()[c];if(!d||!Array.isArray(d.d))return null;let u=(p=d.m)==null?void 0:p.idKey;for(let g of d.d)if(!(!g||typeof g!="object")&&(g._k===l||u&&g[u]!==void 0&&String(g[u])===l))return g;return null},onNodeAdded:()=>{this.nodesAddedThisRender++}}),this.focusManager=new pe(this.logger.child("FocusManager")),this.formLifecycleManager=new xe,this.loadingIndicator=new Te,this.formDisabler=new Se,this.uploadHandler=new Ie(c=>this.send(c),{chunkSize:256*1024,onProgress:c=>{this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:progress",{detail:{entry:c}}))},onComplete:(c,l)=>{this.logger.info(`Upload complete: ${c}`,l),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:complete",{detail:{uploadName:c,entries:l}}))},onError:(c,l)=>{this.logger.error(`Upload error for ${c.id}:`,l),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:error",{detail:{entry:c,error:l}}))}}),this.eventDelegator=new be({getWrapperElement:()=>this.wrapperElement,getRateLimitedHandlers:()=>this.rateLimitedHandlers,parseValue:c=>this.parseValue(c),send:c=>this.send(c),sendHTTPMultipart:(c,l,d)=>this.sendHTTPMultipart(c,l,d),setActiveSubmission:(c,l,d)=>this.formLifecycleManager.setActiveSubmission(c,l,d),getWebSocketReadyState:()=>this.webSocketManager.getReadyState(),triggerPendingUploads:c=>this.uploadHandler.triggerPendingUploads(c)},this.logger.child("EventDelegator")),this.linkInterceptor=new we({getWrapperElement:()=>this.wrapperElement,handleNavigationResponse:(c,l)=>this.handleNavigationResponse(c,l),sendNavigate:c=>this.sendNavigate(c),canSendNavigate:()=>!this.useHTTP&&this.webSocketManager.getReadyState()===1},this.logger.child("LinkInterceptor")),this.observerManager=new Ae({getWrapperElement:()=>this.wrapperElement,send:c=>this.send(c)},this.logger.child("ObserverManager")),this.changeAutoWirer=new Ce({getWrapperElement:()=>this.wrapperElement,send:c=>this.send(c)},this.logger.child("ChangeAutoWirer")),this.webSocketManager=new He({options:this.options,logger:this.logger.child("Transport"),onConnected:()=>{var c,l,d;this.ws=this.webSocketManager.getSocket(),this.logger.info("WebSocket connected"),this.clearFlashQueryParams(),(l=(c=this.options).onConnect)==null||l.call(c),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:connected"))},onDisconnected:()=>{var c,l,d;this.ws=null,this.logger.info("WebSocket disconnected"),(l=(c=this.options).onDisconnect)==null||l.call(c),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:disconnected"))},onMessage:(c,l)=>{this.handleWebSocketPayload(c,l)},onReconnectAttempt:()=>{this.logger.info("Attempting to reconnect...")},onError:c=>{var l,d;this.logger.error("WebSocket error:",c),(d=(l=this.options).onError)==null||d.call(l,c)}})}static autoInit(){let e=Je({scope:"Client:autoInit"}),t=()=>{var r,s,a;let n=document.querySelector("[data-lvt-id]");if(n){let o=new i;o.wrapperElement=n,n.getAttribute("data-lvt-loading")==="true"&&(o.loadingIndicator.show(),o.formDisabler.disable(o.wrapperElement));let l=(a=(s=n.getAttribute("data-lvt-loading-debounce-ms"))!=null?s:(r=document.body)==null?void 0:r.getAttribute("data-lvt-loading-debounce-ms"))!=null?a:null;if(l!==null&&/^\d+$/.test(l)){let d=parseInt(l,10);Number.isFinite(d)&&d>=0&&n.addEventListener("lvt:updated",()=>{o.loadingIndicator.enablePerActionIndicator(d)},{once:!0,capture:!0})}o.connect().catch(d=>{e.error("Auto-initialization connect failed:",d)}),window.liveTemplateClient=o}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}handleWebSocketPayload(e,t){var s,a,o;let n=e;if(n.type==="error"){if(typeof n.code!="string"){this.logger.warn("Malformed error envelope (missing string `code`) \u2014 dropping",n);return}this.wrapperElement?this.wrapperElement.dispatchEvent(new CustomEvent("lvt:error",{detail:{code:n.code,topic:n.topic}})):this.logger.warn("lvt:error envelope arrived before wrapperElement was set; dropping",{code:n.code,topic:n.topic});return}let r=e;if(r.type==="upload_progress"){this.uploadHandler.handleProgressMessage(r);return}if(r.upload_name&&r.entries){let c=r;try{this.handleUploadStartResponse(c)}catch(l){this.logger.error("Error handling upload start response:",l)}return}if(r.upload_name&&r.hasOwnProperty("success")){r.success?this.logger.info(`Upload complete: ${r.upload_name}`):this.logger.error(`Upload failed: ${r.upload_name}`,r.error);return}this.isInitialized||(this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.wrapperElement&&this.wrapperElement.hasAttribute("data-lvt-loading")&&this.wrapperElement.removeAttribute("data-lvt-loading"),this.isInitialized=!0,Ke()),this.wrapperElement&&((s=e.meta)!=null&&s.capabilities&&this.changeAutoWirer.setCapabilities(e.meta.capabilities),this.changeAutoWirer.analyzeStatics(e.tree),this.updateDOM(this.wrapperElement,e.tree,e.meta),this.messageCount++,this.wrapperElement.dispatchEvent(new CustomEvent("lvt:updated",{detail:{messageCount:this.messageCount,action:(a=e.meta)==null?void 0:a.action,success:(o=e.meta)==null?void 0:o.success}})))}async connect(e="[data-lvt-id]"){var n,r;if(this.wrapperElement=document.querySelector(e),!this.wrapperElement)throw new Error(`LiveTemplate wrapper not found with selector: ${e}`);this.webSocketManager.disconnect();let t=await this.webSocketManager.connect();this.useHTTP=!t.usingWebSocket,this.useHTTP&&(this.ws=null,this.logger.info("WebSocket not available, using HTTP mode"),(r=(n=this.options).onConnect)==null||r.call(n),t.initialState&&this.wrapperElement&&this.handleWebSocketPayload(t.initialState)),this.eventDelegator.setupEventDelegation(),this.eventDelegator.setupWindowEventDelegation(),this.eventDelegator.setupClickAwayDelegation(),this.eventDelegator.setupDOMEventTriggerDelegation(),Tt(),this.eventDelegator.setupFocusTrapDelegation(),this.eventDelegator.setupAutofocusDelegation(),this.linkInterceptor.setup(this.wrapperElement),me(),Pt(),Nt(),ht(this.wrapperElement),this.focusManager.attach(this.wrapperElement),this.observerManager.setupInfiniteScrollObserver(),this.observerManager.setupInfiniteScrollMutationObserver(),this.setupVisibilityReconnect()}disconnect(){this.webSocketManager.disconnect(),this.ws=null,this.useHTTP=!1,this.hiddenAt=0,this.reconnecting=!1,this.teardownVisibilityReconnect(),this.eventDelegator.teardownDOMEventTriggerDelegation(),Ut(),yt(),this.loadingIndicator.disablePerActionIndicator(),this.wrapperElement&&(gt(this.wrapperElement),mt(this.wrapperElement),Kt(this.wrapperElement),Jt(this.wrapperElement),kt(this.wrapperElement)),this.resetSessionState()}resetSessionState(){this.treeRenderer.reset(),this.rangeDomApplier.invalidate(),this.focusManager.reset(),this.observerManager.teardown(),this.changeAutoWirer.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.lvtId=null,this.isInitialized=!1}setupVisibilityReconnect(){this.visibilityHandlerAttached||typeof document=="undefined"||(this.visibilityHandlerAttached=!0,this.visibilityHandler=()=>{if(document.hidden){!this.useHTTP&&this.webSocketManager.getReadyState()===1&&(this.hiddenAt=Date.now());return}if(this.hiddenAt===0)return;let e=Date.now()-this.hiddenAt;this.hiddenAt=0,!(e<3e3)&&this.scheduleVisibilityReconnect()},this.pageshowHandler=e=>{e.persisted&&this.scheduleVisibilityReconnect()},document.addEventListener("visibilitychange",this.visibilityHandler),window.addEventListener("pageshow",this.pageshowHandler))}teardownVisibilityReconnect(){this.visibilityReconnectTimer!==null&&(clearTimeout(this.visibilityReconnectTimer),this.visibilityReconnectTimer=null),!(!this.visibilityHandlerAttached||typeof document=="undefined")&&(this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.pageshowHandler&&(window.removeEventListener("pageshow",this.pageshowHandler),this.pageshowHandler=null),this.visibilityHandlerAttached=!1)}scheduleVisibilityReconnect(){this.visibilityReconnectTimer!==null&&clearTimeout(this.visibilityReconnectTimer),this.visibilityReconnectTimer=setTimeout(()=>{this.visibilityReconnectTimer=null,this.wrapperElement&&!this.useHTTP&&!this.reconnecting&&this.webSocketManager.getReadyState()!==void 0&&this.performVisibilityReconnect()},500)}async performVisibilityReconnect(){var e;if(!this.reconnecting){this.reconnecting=!0;try{this.logger.info("Reconnecting after visibility change"),this.webSocketManager.disconnect(),this.ws=null,this.resetSessionState();let t=await this.webSocketManager.connect();if(!this.reconnecting)return;this.useHTTP=!t.usingWebSocket,this.useHTTP&&(this.ws=null,t.initialState&&this.wrapperElement&&this.handleWebSocketPayload(t.initialState)),(e=this.wrapperElement)==null||e.dispatchEvent(new Event("lvt:reconnected"))}catch(t){this.logger.error("Visibility reconnect failed:",t)}finally{this.reconnecting=!1}}}clearFlashQueryParams(){let e=new URL(window.location.href),t=["error","success"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&(this.logger.debug("Clearing flash query params from URL"),window.history.replaceState(null,"",e.toString()))}isReady(){let e=this.wrapperElement;return!e||e.hasAttribute("data-lvt-loading")?!1:this.useHTTP?!0:this.webSocketManager.getReadyState()===1}send(e){let t=this.webSocketManager.getReadyState();this.logger.isDebugEnabled()&&this.logger.debug("send() invoked",{message:e,useHTTP:this.useHTTP,hasWebSocket:t!==void 0,readyState:t}),this.useHTTP?(this.logger.debug("Using HTTP mode for send"),this.sendHTTP(e)):t===1?(this.logger.debug("Sending via WebSocket"),this.webSocketManager.send(JSON.stringify(e))):t!==void 0?(this.logger.warn(`WebSocket not ready (state: ${t}), using HTTP fallback`),this.sendHTTP(e)):this.logger.error("No transport available")}getLiveUrl(){return this.liveUrlOverride||this.options.liveUrl||"/live"}sendNavigate(e){let t=new URL(e,window.location.origin),n={},r=new Set;t.searchParams.forEach((a,o)=>{r.has(o)&&this.logger.warn("sendNavigate: duplicate query param key \u2014 last value wins; server may receive incomplete data",{key:o,href:e}),r.add(o),n[o]=a});let s=t.pathname+t.search;if(this.webSocketManager.getReadyState()!==1){let a=this.webSocketManager.getReadyState();return a===3?this.logger.error("sendNavigate: WebSocket is CLOSED and autoReconnect may be disabled; navigate message dropped. Reload or re-enable autoReconnect.",{href:e}):this.options.autoReconnect?this.logger.warn("sendNavigate: WS not open; browser URL is ahead of server state until reconnect",{href:e,readyState:a}):this.logger.error("sendNavigate: WS not open and autoReconnect is disabled; navigate may be permanently lost",{href:e,readyState:a}),!1}return this.liveUrlOverride=s,this.webSocketManager.setLiveUrl(s),this.logger.debug("sendNavigate",{href:e,data:n}),this.send({action:"__navigate__",data:n}),!0}async sendHTTP(e){try{let t=this.getLiveUrl(),n=await fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`HTTP request failed: ${n.status}`);let r=await n.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,r.tree,r.meta)}catch(t){this.logger.error("Failed to send HTTP request:",t)}}sendHTTPMultipart(e,t,n){this.doSendHTTPMultipart(e,t,n)}async doSendHTTPMultipart(e,t,n){try{let r=this.getLiveUrl(),s=await fetch(r,{method:"POST",credentials:"include",headers:{Accept:"application/json"},body:n});if(!s.ok)throw new Error(`HTTP multipart request failed: ${s.status}`);let a=await s.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,a.tree,a.meta)}catch(r){this.logger.error("Failed to send HTTP multipart request:",r)}}stylesheetsDiffer(e,t){let n=document.querySelectorAll('link[rel~="stylesheet"][href]'),r=new Set;n.forEach(c=>{let l=c.href;l&&r.add(l)});let s=e.querySelectorAll('link[rel~="stylesheet"][href]'),a=new Set;if(s.forEach(c=>{let l=c.getAttribute("href");if(l)try{a.add(new URL(l,t).href)}catch(d){a.add(l)}}),r.size!==a.size)return!0;let o=!1;return r.forEach(c=>{a.has(c)||(o=!0)}),o}performFullNavigation(e){window.location.href=e}handleNavigationResponse(e,t){var l;if(!this.wrapperElement)return;let r=new DOMParser().parseFromString(e,"text/html"),s=this.wrapperElement.getAttribute("data-lvt-id"),a=(l=r.querySelector("title"))==null?void 0:l.textContent;if(a&&(document.title=a),this.stylesheetsDiffer(r,t)){this.logger.info('Cross-app navigation detected (different <link rel="stylesheet"> set in fetched HTML); falling back to full navigation'),this.performFullNavigation(t);return}let o=r.querySelector("[data-lvt-id]");if(o){let d=o.getAttribute("data-lvt-id");if(!d){this.logger.warn("Cross-handler navigation: new wrapper has empty data-lvt-id"),window.location.reload();return}this.linkInterceptor.teardownForWrapper(s),this.eventDelegator.teardownForWrapper(s);let u=++this.navigationEpoch;this.disconnect(),this.wrapperElement.setAttribute("data-lvt-id",d),this.wrapperElement.replaceChildren(...Array.from(o.childNodes).map(g=>g.cloneNode(!0))),this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement),window.scrollTo(0,0);let p=window.location.pathname+window.location.search;if(this.liveUrlOverride=p,this.webSocketManager.setLiveUrl(p),!this.useHTTP){let h=`[data-lvt-id="${d.replace(/[\\"]/g,"\\$&")}"]`;this.connect(h).catch(H=>{u===this.navigationEpoch&&(this.logger.error("Cross-handler reconnect failed:",H),window.location.reload())})}return}this.linkInterceptor.teardownForWrapper(s),this.eventDelegator.teardownForWrapper(s),this.disconnect();let c=r.querySelector("body");c&&this.wrapperElement.replaceChildren(...Array.from(c.childNodes).map(d=>d.cloneNode(!0))),this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement)}parseValue(e){let t=e.trim(),n=parseFloat(t);if(!isNaN(n)){if(Number.isInteger(n)&&Math.abs(n)>Number.MAX_SAFE_INTEGER)return t;if(t===n.toString())return n}return e==="true"?!0:e==="false"?!1:e}applyUpdate(e){return this.treeRenderer.applyUpdate(e)}applyUpdateToHTML(e,t){let n=this.applyUpdate(t);if(!this.lvtId){let l=e.match(/data-lvt-id="([^"]+)"/);l&&(this.lvtId=l[1])}let r=n.html;if(!e.match(/<body>([\s\S]*?)<\/body>/))return e;let c=`<div data-lvt-id="${this.lvtId||"lvt-unknown"}">`+r+"</div>";return e.replace(/<body>[\s\S]*?<\/body>/,`<body>${c}</body>`)}updateDOM(e,t,n){this.nodesAddedThisRender=0,this.directiveTouchedThisRender=!1;let r=this.treeRenderer.applyUpdate(t,{canApplyTargeted:(l,d)=>this.rangeDomApplier.canApplyTargeted(e,l,d).ok}),s=l=>!l||typeof l!="object"?!1:l.s&&Array.isArray(l.s)?!0:Object.values(l).some(d=>s(d));if(!r.changed&&!s(t))return;let a=document.createElement(e.tagName);if(this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] element.tagName:",e.tagName),this.logger.debug("[updateDOM] result.html (first 500 chars):",r.html.substring(0,500)),this.logger.debug("[updateDOM] Has <table> tag:",r.html.includes("<table>")),this.logger.debug("[updateDOM] Has <tbody> tag:",r.html.includes("<tbody>")),this.logger.debug("[updateDOM] Has <tr> tag:",r.html.includes("<tr"))),/<script[\s>]/i.test(r.html)){let l=e.tagName.toLowerCase(),d=l==="body"||l==="html"?"div":l,p=new DOMParser().parseFromString(`<${d}>${r.html}</${d}>`,"text/html"),g=p.body.firstElementChild;g?a.replaceChildren(...Array.from(g.childNodes)):(this.logger.warn("[updateDOM] DOMParser: no wrapper root element; using doc.body children"),a.replaceChildren(...Array.from(p.body.childNodes)))}else a.innerHTML=r.html;this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] tempWrapper.innerHTML (first 500 chars):",a.innerHTML.substring(0,500)),this.logger.debug("[updateDOM] tempWrapper has <table>:",a.innerHTML.includes("<table>")),this.logger.debug("[updateDOM] tempWrapper has <tbody>:",a.innerHTML.includes("<tbody>")),this.logger.debug("[updateDOM] tempWrapper has <tr>:",a.innerHTML.includes("<tr")));let o=document.activeElement;if(o instanceof HTMLInputElement&&o.list instanceof HTMLDataListElement&&!a.querySelector("[data-lvt-force-update]")){this.logger.debug("[updateDOM] deferred: datalist input focused"),this.focusManager.restoreFocusedElement();return}let c={childrenOnly:!0,getNodeKey:l=>{if(l.nodeType===1)return l.getAttribute("data-key")||l.getAttribute("data-lvt-key")||void 0},onBeforeElUpdated:(l,d)=>{if(d.nodeType===Node.ELEMENT_NODE&&d.hasAttribute(Q))return!1;if(d.nodeType===Node.ELEMENT_NODE&&l.nodeType===Node.ELEMENT_NODE){let u=d.attributes,p=l;for(let g=0;g<u.length;g++){let h=u[g].name;if(h.length>4&&h.charCodeAt(0)===108&&h.charCodeAt(1)===118&&h.charCodeAt(2)===116&&h.charCodeAt(3)===45&&!p.hasAttribute(h)){this.directiveTouchedThisRender=!0;break}}}if(l.nodeType===Node.ELEMENT_NODE&&l.hasAttribute("lvt-ignore")&&!d.hasAttribute("data-lvt-force-update"))return!1;if(l.nodeType===Node.ELEMENT_NODE&&l.hasAttribute("lvt-ignore-attrs")&&!d.hasAttribute("data-lvt-force-update")&&d.nodeType===Node.ELEMENT_NODE){let u=l.attributes,p=d;for(let g=0;g<u.length;g++){let h=u[g];p.hasAttributeNS(h.namespaceURI,h.localName)||p.setAttributeNS(h.namespaceURI,h.name,h.value)}}if(l instanceof HTMLDataListElement&&!d.hasAttribute("data-lvt-force-update")){let u=document.activeElement;if(u instanceof HTMLInputElement&&u.list===l)return!1}return l instanceof HTMLDialogElement&&l.hasAttribute("open")&&!d.hasAttribute("data-lvt-force-update")&&d.setAttribute("open",""),!d.hasAttribute("data-lvt-force-update")&&l instanceof HTMLElement&&l.hasAttribute("popover")&&Be(l)||(l instanceof HTMLInputElement&&d instanceof HTMLInputElement&&(l.type==="checkbox"||l.type==="radio")&&(d.hasAttribute("data-lvt-force-update")?(l.checked=d.checked,l.type==="checkbox"&&(l.indeterminate=d.indeterminate),l.removeAttribute("data-lvt-force-update")):(d.checked=l.checked,l.checked?d.setAttribute("checked",""):d.removeAttribute("checked"),l.type==="checkbox"&&(d.indeterminate=l.indeterminate))),this.focusManager.shouldSkipUpdate(l))?!1:l.isEqualNode(d)?!(!d.hasAttribute("data-lvt-force-update")&&(d.children.length===0||d.querySelector("[data-lvt-force-update]")===null)):(this.executeLifecycleHook(l,"lvt-updated"),!0)},onElUpdated:l=>{var d;l instanceof HTMLTextAreaElement&&(l.value=(d=l.textContent)!=null?d:""),l instanceof HTMLElement&&l.hasAttribute("data-lvt-force-update")&&l.removeAttribute("data-lvt-force-update")},onNodeAdded:l=>{var d;l instanceof HTMLTextAreaElement&&(l.value=(d=l.textContent)!=null?d:""),l instanceof HTMLElement&&l.hasAttribute("data-lvt-force-update")&&l.removeAttribute("data-lvt-force-update"),l.nodeType===Node.ELEMENT_NODE&&(this.executeLifecycleHook(l,"lvt-mounted"),this.nodesAddedThisRender++)},onBeforeNodeDiscarded:l=>(l.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(l,"lvt-destroyed"),!0)};if(r.targetedOps&&r.targetedOps.length>0){let l=[],d=!1;for(let u of r.targetedOps){let p=this.rangeDomApplier.apply(e,u,c);p?(p.setAttribute(J,""),l.push(p)):d=!0}if(d){this.logger.warn("[updateDOM] one or more targeted DOM ops failed; rebuilding tempWrapper from treeState for a full morphdom sync");for(let p of l)p.removeAttribute(J);let u=this.treeRenderer.renderState();a.innerHTML=u}else this.replaceTargetedSkipPlaceholders(a)}try{ue(e,a,c)}finally{this.rangeDomApplier.cleanupMarkers(e)}this.focusManager.restoreFocusedElement(),vt(e),Et(e),wt(e),At(e),bt(e),Lt(e,l=>this.send(l)),St(e),Bt(e),Xt(e),(this.nodesAddedThisRender>0||this.directiveTouchedThisRender)&&(ft(e,this.wrapperElement||void 0),this.eventDelegator.setupDOMEventTriggerDelegation(e),this.uploadHandler.initializeFileInputs(e)),this.changeAutoWirer.wireElements(),n&&this.formLifecycleManager.handleResponse(n)}handleUploadStartResponse(e){this.uploadHandler.handleUploadStartResponse(e)}replaceTargetedSkipPlaceholders(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[],r;for(;r=t.nextNode();){let s=r;s.nodeValue&&/^lvt-targeted-skip:.+$/.test(s.nodeValue)&&n.push(s)}for(let s of n){let a=s.nodeValue.match(/^lvt-targeted-skip:(.+)$/),o=a?a[1]:"",c=s.parentElement;c&&c.setAttribute(Q,o),s.remove()}}executeLifecycleHook(e,t){let n=e.getAttribute(t);if(n)try{new Function("element",n).call(e,e)}catch(r){this.logger.error(`Error executing ${t} hook:`,r)}}reset(){this.resetSessionState()}getTreeState(){return this.treeRenderer.getTreeState()}getStaticStructure(){return this.treeRenderer.getStaticStructure()}};typeof window!="undefined"&&De.autoInit();return dn(Jn);})();
31
+ `),c=Math.max(a.length,o.length);for(let l=0;l<c;l++){let d=a[l]||"",u=o[l]||"";d!==u&&(t.push(`Line ${l+1}:`),t.push(` Expected: ${d}`),t.push(` Actual: ${u}`))}return{match:!1,differences:t}}var Fe=class i{constructor(e={}){this.nodesAddedThisRender=0;this.directiveTouchedThisRender=!1;this.lvtId=null;this.ws=null;this.wrapperElement=null;this.useHTTP=!1;this.sessionCookie=null;this.rateLimitedHandlers=new WeakMap;this.isInitialized=!1;this.messageCount=0;this.navigationEpoch=0;this.liveUrlOverride=null;this.visibilityHandlerAttached=!1;this.hiddenAt=0;this.reconnecting=!1;this.visibilityHandler=null;this.pageshowHandler=null;this.visibilityReconnectTimer=null;let{logger:t,logLevel:n,debug:r,...s}=e,a=n!=null?n:r?"debug":"info",o=t!=null?t:tt({level:a});t?n?t.setLevel(n):r&&t.setLevel("debug"):o.setLevel(a),this.logger=o.child("Client"),this.options={autoReconnect:!1,reconnectDelay:1e3,liveUrl:window.location.pathname+window.location.search,...s},this.treeRenderer=new He(this.logger.child("TreeRenderer")),this.rangeDomApplier=new Re({logger:this.logger.child("RangeDomApplier"),renderItem:(c,l,d,u)=>this.treeRenderer.renderRangeItem(c,l,d,u),executeLifecycleHook:(c,l)=>this.executeLifecycleHook(c,l),itemLookup:(c,l)=>{var p;let d=this.treeRenderer.getTreeState()[c];if(!d||!Array.isArray(d.d))return null;let u=(p=d.m)==null?void 0:p.idKey;for(let g of d.d)if(!(!g||typeof g!="object")&&(g._k===l||u&&g[u]!==void 0&&String(g[u])===l))return g;return null},onNodeAdded:()=>{this.nodesAddedThisRender++}}),this.focusManager=new ge(this.logger.child("FocusManager")),this.formLifecycleManager=new Ce,this.loadingIndicator=new ke,this.formDisabler=new Me,this.uploadHandler=new Oe(c=>this.send(c),{chunkSize:256*1024,onProgress:c=>{this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:progress",{detail:{entry:c}}))},onComplete:(c,l)=>{this.logger.info(`Upload complete: ${c}`,l),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:complete",{detail:{uploadName:c,entries:l}}))},onError:(c,l)=>{this.logger.error(`Upload error for ${c.id}:`,l),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:error",{detail:{entry:c,error:l}}))}}),this.eventDelegator=new Ae({getWrapperElement:()=>this.wrapperElement,getRateLimitedHandlers:()=>this.rateLimitedHandlers,parseValue:c=>this.parseValue(c),send:c=>this.send(c),sendHTTPMultipart:(c,l,d)=>this.sendHTTPMultipart(c,l,d),setActiveSubmission:(c,l,d)=>this.formLifecycleManager.setActiveSubmission(c,l,d),getWebSocketReadyState:()=>this.webSocketManager.getReadyState(),triggerPendingUploads:c=>this.uploadHandler.triggerPendingUploads(c)},this.logger.child("EventDelegator")),this.linkInterceptor=new Se({getWrapperElement:()=>this.wrapperElement,handleNavigationResponse:(c,l)=>this.handleNavigationResponse(c,l),sendNavigate:c=>this.sendNavigate(c),canSendNavigate:()=>!this.useHTTP&&this.webSocketManager.getReadyState()===1},this.logger.child("LinkInterceptor")),this.observerManager=new Le({getWrapperElement:()=>this.wrapperElement,send:c=>this.send(c)},this.logger.child("ObserverManager")),this.changeAutoWirer=new De({getWrapperElement:()=>this.wrapperElement,send:c=>this.send(c)},this.logger.child("ChangeAutoWirer")),this.webSocketManager=new Ie({options:this.options,logger:this.logger.child("Transport"),onConnected:()=>{var c,l,d;this.ws=this.webSocketManager.getSocket(),this.logger.info("WebSocket connected"),this.clearFlashQueryParams(),(l=(c=this.options).onConnect)==null||l.call(c),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:connected"))},onDisconnected:()=>{var c,l,d;this.ws=null,this.logger.info("WebSocket disconnected"),(l=(c=this.options).onDisconnect)==null||l.call(c),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:disconnected"))},onMessage:(c,l)=>{this.handleWebSocketPayload(c,l)},onReconnectAttempt:()=>{this.logger.info("Attempting to reconnect...")},onError:c=>{var l,d;this.logger.error("WebSocket error:",c),(d=(l=this.options).onError)==null||d.call(l,c)}})}static autoInit(){let e=tt({scope:"Client:autoInit"}),t=()=>{var r,s,a;let n=document.querySelector("[data-lvt-id]");if(n){let o=new i;o.wrapperElement=n,n.getAttribute("data-lvt-loading")==="true"&&(o.loadingIndicator.show(),o.formDisabler.disable(o.wrapperElement));let l=(a=(s=n.getAttribute("data-lvt-loading-debounce-ms"))!=null?s:(r=document.body)==null?void 0:r.getAttribute("data-lvt-loading-debounce-ms"))!=null?a:null;if(l!==null&&/^\d+$/.test(l)){let d=parseInt(l,10);Number.isFinite(d)&&d>=0&&n.addEventListener("lvt:updated",()=>{o.loadingIndicator.enablePerActionIndicator(d)},{once:!0,capture:!0})}o.connect().catch(d=>{e.error("Auto-initialization connect failed:",d)}),window.liveTemplateClient=o}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}handleWebSocketPayload(e,t){var s,a,o;let n=e;if(n.type==="error"){if(typeof n.code!="string"){this.logger.warn("Malformed error envelope (missing string `code`) \u2014 dropping",n);return}this.wrapperElement?this.wrapperElement.dispatchEvent(new CustomEvent("lvt:error",{detail:{code:n.code,topic:n.topic}})):this.logger.warn("lvt:error envelope arrived before wrapperElement was set; dropping",{code:n.code,topic:n.topic});return}let r=e;if(r.type==="upload_progress"){this.uploadHandler.handleProgressMessage(r);return}if(r.upload_name&&r.entries){let c=r;try{this.handleUploadStartResponse(c)}catch(l){this.logger.error("Error handling upload start response:",l)}return}if(r.upload_name&&r.hasOwnProperty("success")){r.success?this.logger.info(`Upload complete: ${r.upload_name}`):this.logger.error(`Upload failed: ${r.upload_name}`,r.error);return}this.isInitialized||(this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.wrapperElement&&this.wrapperElement.hasAttribute("data-lvt-loading")&&this.wrapperElement.removeAttribute("data-lvt-loading"),this.isInitialized=!0,je()),this.wrapperElement&&((s=e.meta)!=null&&s.capabilities&&this.changeAutoWirer.setCapabilities(e.meta.capabilities),this.changeAutoWirer.analyzeStatics(e.tree),this.updateDOM(this.wrapperElement,e.tree,e.meta),this.messageCount++,this.wrapperElement.dispatchEvent(new CustomEvent("lvt:updated",{detail:{messageCount:this.messageCount,action:(a=e.meta)==null?void 0:a.action,success:(o=e.meta)==null?void 0:o.success}})))}async connect(e="[data-lvt-id]"){var n,r;if(this.wrapperElement=document.querySelector(e),!this.wrapperElement)throw new Error(`LiveTemplate wrapper not found with selector: ${e}`);this.webSocketManager.disconnect();let t=await this.webSocketManager.connect();this.useHTTP=!t.usingWebSocket,this.useHTTP&&(this.ws=null,this.logger.info("WebSocket not available, using HTTP mode"),(r=(n=this.options).onConnect)==null||r.call(n),t.initialState&&this.wrapperElement&&this.handleWebSocketPayload(t.initialState)),this.eventDelegator.setupEventDelegation(),this.eventDelegator.setupWindowEventDelegation(),this.eventDelegator.setupClickAwayDelegation(),this.eventDelegator.setupDOMEventTriggerDelegation(),Ht(),this.eventDelegator.setupFocusTrapDelegation(),this.eventDelegator.setupAutofocusDelegation(),this.linkInterceptor.setup(this.wrapperElement),ye(),jt(),qt(),this.wrapperElement&&Ke(this.wrapperElement,s=>this.send(s)),wt(this.wrapperElement),this.focusManager.attach(this.wrapperElement),this.observerManager.setupInfiniteScrollObserver(),this.observerManager.setupInfiniteScrollMutationObserver(),this.setupVisibilityReconnect()}disconnect(){this.webSocketManager.disconnect(),this.ws=null,this.useHTTP=!1,this.hiddenAt=0,this.reconnecting=!1,this.teardownVisibilityReconnect(),this.eventDelegator.teardownDOMEventTriggerDelegation(),Vt(),St(),this.loadingIndicator.disablePerActionIndicator(),this.wrapperElement&&(Et(this.wrapperElement),At(this.wrapperElement),Xt(this.wrapperElement),sn(this.wrapperElement),Dt(this.wrapperElement),It(this.wrapperElement)),this.resetSessionState()}resetSessionState(){this.treeRenderer.reset(),this.rangeDomApplier.invalidate(),this.focusManager.reset(),this.observerManager.teardown(),this.changeAutoWirer.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.lvtId=null,this.isInitialized=!1}setupVisibilityReconnect(){this.visibilityHandlerAttached||typeof document=="undefined"||(this.visibilityHandlerAttached=!0,this.visibilityHandler=()=>{if(document.hidden){!this.useHTTP&&this.webSocketManager.getReadyState()===1&&(this.hiddenAt=Date.now());return}if(this.hiddenAt===0)return;let e=Date.now()-this.hiddenAt;this.hiddenAt=0,!(e<3e3)&&this.scheduleVisibilityReconnect()},this.pageshowHandler=e=>{e.persisted&&this.scheduleVisibilityReconnect()},document.addEventListener("visibilitychange",this.visibilityHandler),window.addEventListener("pageshow",this.pageshowHandler))}teardownVisibilityReconnect(){this.visibilityReconnectTimer!==null&&(clearTimeout(this.visibilityReconnectTimer),this.visibilityReconnectTimer=null),!(!this.visibilityHandlerAttached||typeof document=="undefined")&&(this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.pageshowHandler&&(window.removeEventListener("pageshow",this.pageshowHandler),this.pageshowHandler=null),this.visibilityHandlerAttached=!1)}scheduleVisibilityReconnect(){this.visibilityReconnectTimer!==null&&clearTimeout(this.visibilityReconnectTimer),this.visibilityReconnectTimer=setTimeout(()=>{this.visibilityReconnectTimer=null,this.wrapperElement&&!this.useHTTP&&!this.reconnecting&&this.webSocketManager.getReadyState()!==void 0&&this.performVisibilityReconnect()},500)}async performVisibilityReconnect(){var e;if(!this.reconnecting){this.reconnecting=!0;try{this.logger.info("Reconnecting after visibility change"),this.webSocketManager.disconnect(),this.ws=null,this.resetSessionState();let t=await this.webSocketManager.connect();if(!this.reconnecting)return;this.useHTTP=!t.usingWebSocket,this.useHTTP&&(this.ws=null,t.initialState&&this.wrapperElement&&this.handleWebSocketPayload(t.initialState)),(e=this.wrapperElement)==null||e.dispatchEvent(new Event("lvt:reconnected"))}catch(t){this.logger.error("Visibility reconnect failed:",t)}finally{this.reconnecting=!1}}}clearFlashQueryParams(){let e=new URL(window.location.href),t=["error","success"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&(this.logger.debug("Clearing flash query params from URL"),window.history.replaceState(null,"",e.toString()))}isReady(){let e=this.wrapperElement;return!e||e.hasAttribute("data-lvt-loading")?!1:this.useHTTP?!0:this.webSocketManager.getReadyState()===1}send(e){let t=this.webSocketManager.getReadyState();this.logger.isDebugEnabled()&&this.logger.debug("send() invoked",{message:e,useHTTP:this.useHTTP,hasWebSocket:t!==void 0,readyState:t}),this.useHTTP?(this.logger.debug("Using HTTP mode for send"),this.sendHTTP(e)):t===1?(this.logger.debug("Sending via WebSocket"),this.webSocketManager.send(JSON.stringify(e))):t!==void 0?(this.logger.warn(`WebSocket not ready (state: ${t}), using HTTP fallback`),this.sendHTTP(e)):this.logger.error("No transport available")}getLiveUrl(){return this.liveUrlOverride||this.options.liveUrl||"/live"}sendNavigate(e){let t=new URL(e,window.location.origin),n={},r=new Set;t.searchParams.forEach((a,o)=>{r.has(o)&&this.logger.warn("sendNavigate: duplicate query param key \u2014 last value wins; server may receive incomplete data",{key:o,href:e}),r.add(o),n[o]=a});let s=t.pathname+t.search;if(this.webSocketManager.getReadyState()!==1){let a=this.webSocketManager.getReadyState();return a===3?this.logger.error("sendNavigate: WebSocket is CLOSED and autoReconnect may be disabled; navigate message dropped. Reload or re-enable autoReconnect.",{href:e}):this.options.autoReconnect?this.logger.warn("sendNavigate: WS not open; browser URL is ahead of server state until reconnect",{href:e,readyState:a}):this.logger.error("sendNavigate: WS not open and autoReconnect is disabled; navigate may be permanently lost",{href:e,readyState:a}),!1}return this.liveUrlOverride=s,this.webSocketManager.setLiveUrl(s),this.logger.debug("sendNavigate",{href:e,data:n}),this.send({action:"__navigate__",data:n}),!0}async sendHTTP(e){try{let t=this.getLiveUrl(),n=await fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`HTTP request failed: ${n.status}`);let r=await n.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,r.tree,r.meta)}catch(t){this.logger.error("Failed to send HTTP request:",t)}}sendHTTPMultipart(e,t,n){this.doSendHTTPMultipart(e,t,n)}async doSendHTTPMultipart(e,t,n){try{let r=this.getLiveUrl(),s=await fetch(r,{method:"POST",credentials:"include",headers:{Accept:"application/json"},body:n});if(!s.ok)throw new Error(`HTTP multipart request failed: ${s.status}`);let a=await s.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,a.tree,a.meta)}catch(r){this.logger.error("Failed to send HTTP multipart request:",r)}}stylesheetsDiffer(e,t){let n=document.querySelectorAll('link[rel~="stylesheet"][href]'),r=new Set;n.forEach(c=>{let l=c.href;l&&r.add(l)});let s=e.querySelectorAll('link[rel~="stylesheet"][href]'),a=new Set;if(s.forEach(c=>{let l=c.getAttribute("href");if(l)try{a.add(new URL(l,t).href)}catch(d){a.add(l)}}),r.size!==a.size)return!0;let o=!1;return r.forEach(c=>{a.has(c)||(o=!0)}),o}performFullNavigation(e){window.location.href=e}handleNavigationResponse(e,t){var l;if(!this.wrapperElement)return;let r=new DOMParser().parseFromString(e,"text/html"),s=this.wrapperElement.getAttribute("data-lvt-id"),a=(l=r.querySelector("title"))==null?void 0:l.textContent;if(a&&(document.title=a),this.stylesheetsDiffer(r,t)){this.logger.info('Cross-app navigation detected (different <link rel="stylesheet"> set in fetched HTML); falling back to full navigation'),this.performFullNavigation(t);return}let o=r.querySelector("[data-lvt-id]");if(o){let d=o.getAttribute("data-lvt-id");if(!d){this.logger.warn("Cross-handler navigation: new wrapper has empty data-lvt-id"),window.location.reload();return}this.linkInterceptor.teardownForWrapper(s),this.eventDelegator.teardownForWrapper(s);let u=++this.navigationEpoch;this.disconnect(),this.wrapperElement.setAttribute("data-lvt-id",d),this.wrapperElement.replaceChildren(...Array.from(o.childNodes).map(g=>g.cloneNode(!0))),this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement),window.scrollTo(0,0);let p=window.location.pathname+window.location.search;if(this.liveUrlOverride=p,this.webSocketManager.setLiveUrl(p),!this.useHTTP){let h=`[data-lvt-id="${d.replace(/[\\"]/g,"\\$&")}"]`;this.connect(h).catch(R=>{u===this.navigationEpoch&&(this.logger.error("Cross-handler reconnect failed:",R),window.location.reload())})}return}this.linkInterceptor.teardownForWrapper(s),this.eventDelegator.teardownForWrapper(s),this.disconnect();let c=r.querySelector("body");c&&this.wrapperElement.replaceChildren(...Array.from(c.childNodes).map(d=>d.cloneNode(!0))),this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement)}parseValue(e){let t=e.trim(),n=parseFloat(t);if(!isNaN(n)){if(Number.isInteger(n)&&Math.abs(n)>Number.MAX_SAFE_INTEGER)return t;if(t===n.toString())return n}return e==="true"?!0:e==="false"?!1:e}applyUpdate(e){return this.treeRenderer.applyUpdate(e)}applyUpdateToHTML(e,t){let n=this.applyUpdate(t);if(!this.lvtId){let l=e.match(/data-lvt-id="([^"]+)"/);l&&(this.lvtId=l[1])}let r=n.html;if(!e.match(/<body>([\s\S]*?)<\/body>/))return e;let c=`<div data-lvt-id="${this.lvtId||"lvt-unknown"}">`+r+"</div>";return e.replace(/<body>[\s\S]*?<\/body>/,`<body>${c}</body>`)}updateDOM(e,t,n){this.nodesAddedThisRender=0,this.directiveTouchedThisRender=!1;let r=this.treeRenderer.applyUpdate(t,{canApplyTargeted:(l,d)=>this.rangeDomApplier.canApplyTargeted(e,l,d).ok}),s=l=>!l||typeof l!="object"?!1:l.s&&Array.isArray(l.s)?!0:Object.values(l).some(d=>s(d));if(!r.changed&&!s(t))return;let a=document.createElement(e.tagName);if(this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] element.tagName:",e.tagName),this.logger.debug("[updateDOM] result.html (first 500 chars):",r.html.substring(0,500)),this.logger.debug("[updateDOM] Has <table> tag:",r.html.includes("<table>")),this.logger.debug("[updateDOM] Has <tbody> tag:",r.html.includes("<tbody>")),this.logger.debug("[updateDOM] Has <tr> tag:",r.html.includes("<tr"))),/<script[\s>]/i.test(r.html)){let l=e.tagName.toLowerCase(),d=l==="body"||l==="html"?"div":l,p=new DOMParser().parseFromString(`<${d}>${r.html}</${d}>`,"text/html"),g=p.body.firstElementChild;g?a.replaceChildren(...Array.from(g.childNodes)):(this.logger.warn("[updateDOM] DOMParser: no wrapper root element; using doc.body children"),a.replaceChildren(...Array.from(p.body.childNodes)))}else a.innerHTML=r.html;this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] tempWrapper.innerHTML (first 500 chars):",a.innerHTML.substring(0,500)),this.logger.debug("[updateDOM] tempWrapper has <table>:",a.innerHTML.includes("<table>")),this.logger.debug("[updateDOM] tempWrapper has <tbody>:",a.innerHTML.includes("<tbody>")),this.logger.debug("[updateDOM] tempWrapper has <tr>:",a.innerHTML.includes("<tr")));let o=document.activeElement;if(o instanceof HTMLInputElement&&o.list instanceof HTMLDataListElement&&!a.querySelector("[data-lvt-force-update]")){this.logger.debug("[updateDOM] deferred: datalist input focused"),this.focusManager.restoreFocusedElement();return}let c={childrenOnly:!0,getNodeKey:l=>{if(l.nodeType===1)return l.getAttribute("data-key")||l.getAttribute("data-lvt-key")||void 0},onBeforeElUpdated:(l,d)=>{if(d.nodeType===Node.ELEMENT_NODE&&d.hasAttribute(Z))return!1;if(d.nodeType===Node.ELEMENT_NODE&&l.nodeType===Node.ELEMENT_NODE){let u=d.attributes,p=l;for(let g=0;g<u.length;g++){let h=u[g].name;if(h.length>4&&h.charCodeAt(0)===108&&h.charCodeAt(1)===118&&h.charCodeAt(2)===116&&h.charCodeAt(3)===45&&!p.hasAttribute(h)){this.directiveTouchedThisRender=!0;break}}}if(l.nodeType===Node.ELEMENT_NODE&&l.hasAttribute("lvt-ignore")&&!d.hasAttribute("data-lvt-force-update"))return!1;if(l.nodeType===Node.ELEMENT_NODE&&l.hasAttribute("lvt-ignore-attrs")&&!d.hasAttribute("data-lvt-force-update")&&d.nodeType===Node.ELEMENT_NODE){let u=l.attributes,p=d;for(let g=0;g<u.length;g++){let h=u[g];p.hasAttributeNS(h.namespaceURI,h.localName)||p.setAttributeNS(h.namespaceURI,h.name,h.value)}}if(l instanceof HTMLDataListElement&&!d.hasAttribute("data-lvt-force-update")){let u=document.activeElement;if(u instanceof HTMLInputElement&&u.list===l)return!1}return l instanceof HTMLDialogElement&&l.hasAttribute("open")&&!d.hasAttribute("data-lvt-force-update")&&d.setAttribute("open",""),!d.hasAttribute("data-lvt-force-update")&&l instanceof HTMLElement&&l.hasAttribute("popover")&&ze(l)||(l instanceof HTMLInputElement&&d instanceof HTMLInputElement&&(l.type==="checkbox"||l.type==="radio")&&(d.hasAttribute("data-lvt-force-update")?(l.checked=d.checked,l.type==="checkbox"&&(l.indeterminate=d.indeterminate),l.removeAttribute("data-lvt-force-update")):(d.checked=l.checked,l.checked?d.setAttribute("checked",""):d.removeAttribute("checked"),l.type==="checkbox"&&(d.indeterminate=l.indeterminate))),this.focusManager.shouldSkipUpdate(l))?!1:l.isEqualNode(d)?!(!d.hasAttribute("data-lvt-force-update")&&(d.children.length===0||d.querySelector("[data-lvt-force-update]")===null)):(this.executeLifecycleHook(l,"lvt-updated"),!0)},onElUpdated:l=>{var d;l instanceof HTMLTextAreaElement&&(l.value=(d=l.textContent)!=null?d:""),l instanceof HTMLElement&&l.hasAttribute("data-lvt-force-update")&&l.removeAttribute("data-lvt-force-update")},onNodeAdded:l=>{var d;l instanceof HTMLTextAreaElement&&(l.value=(d=l.textContent)!=null?d:""),l instanceof HTMLElement&&l.hasAttribute("data-lvt-force-update")&&l.removeAttribute("data-lvt-force-update"),l.nodeType===Node.ELEMENT_NODE&&(this.executeLifecycleHook(l,"lvt-mounted"),this.nodesAddedThisRender++)},onBeforeNodeDiscarded:l=>(l.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(l,"lvt-destroyed"),!0)};if(r.targetedOps&&r.targetedOps.length>0){let l=[],d=!1;for(let u of r.targetedOps){let p=this.rangeDomApplier.apply(e,u,c);p?(p.setAttribute(Q,""),l.push(p)):d=!0}if(d){this.logger.warn("[updateDOM] one or more targeted DOM ops failed; rebuilding tempWrapper from treeState for a full morphdom sync");for(let p of l)p.removeAttribute(Q);let u=this.treeRenderer.renderState();a.innerHTML=u}else this.replaceTargetedSkipPlaceholders(a)}try{fe(e,a,c)}finally{this.rangeDomApplier.cleanupMarkers(e)}this.focusManager.restoreFocusedElement(),Tt(e),kt(e),Mt(e),xt(e),Lt(e),Ct(e,l=>this.send(l)),Ke(e,l=>this.send(l)),Rt(e),Yt(e),rn(e),(this.nodesAddedThisRender>0||this.directiveTouchedThisRender)&&(bt(e,this.wrapperElement||void 0),this.eventDelegator.setupDOMEventTriggerDelegation(e),this.uploadHandler.initializeFileInputs(e)),this.changeAutoWirer.wireElements(),n&&this.formLifecycleManager.handleResponse(n)}handleUploadStartResponse(e){this.uploadHandler.handleUploadStartResponse(e)}replaceTargetedSkipPlaceholders(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[],r;for(;r=t.nextNode();){let s=r;s.nodeValue&&/^lvt-targeted-skip:.+$/.test(s.nodeValue)&&n.push(s)}for(let s of n){let a=s.nodeValue.match(/^lvt-targeted-skip:(.+)$/),o=a?a[1]:"",c=s.parentElement;c&&c.setAttribute(Z,o),s.remove()}}executeLifecycleHook(e,t){let n=e.getAttribute(t);if(n)try{new Function("element",n).call(e,e)}catch(r){this.logger.error(`Error executing ${t} hook:`,r)}}reset(){this.resetSessionState()}getTreeState(){return this.treeRenderer.getTreeState()}getStaticStructure(){return this.treeRenderer.getStaticStructure()}};typeof window!="undefined"&&Fe.autoInit();return vn(or);})();
32
32
  //# sourceMappingURL=livetemplate-client.browser.js.map