zero-query 0.9.0 → 0.9.1

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,7 +1,7 @@
1
1
  /**
2
- * zQuery (zeroQuery) v0.9.0
2
+ * zQuery (zeroQuery) v0.9.1
3
3
  * Lightweight Frontend Library
4
4
  * https://github.com/tonywied17/zero-query
5
5
  * (c) 2026 Anthony Wiedman - MIT License
6
6
  */
7
- (function(global){'use strict';const ErrorCode=Object.freeze({REACTIVE_CALLBACK:'ZQ_REACTIVE_CALLBACK',SIGNAL_CALLBACK:'ZQ_SIGNAL_CALLBACK',EFFECT_EXEC:'ZQ_EFFECT_EXEC',EXPR_PARSE:'ZQ_EXPR_PARSE',EXPR_EVAL:'ZQ_EXPR_EVAL',EXPR_UNSAFE_ACCESS:'ZQ_EXPR_UNSAFE_ACCESS',COMP_INVALID_NAME:'ZQ_COMP_INVALID_NAME',COMP_NOT_FOUND:'ZQ_COMP_NOT_FOUND',COMP_MOUNT_TARGET:'ZQ_COMP_MOUNT_TARGET',COMP_RENDER:'ZQ_COMP_RENDER',COMP_LIFECYCLE:'ZQ_COMP_LIFECYCLE',COMP_RESOURCE:'ZQ_COMP_RESOURCE',COMP_DIRECTIVE:'ZQ_COMP_DIRECTIVE',ROUTER_LOAD:'ZQ_ROUTER_LOAD',ROUTER_GUARD:'ZQ_ROUTER_GUARD',ROUTER_RESOLVE:'ZQ_ROUTER_RESOLVE',STORE_ACTION:'ZQ_STORE_ACTION',STORE_MIDDLEWARE:'ZQ_STORE_MIDDLEWARE',STORE_SUBSCRIBE:'ZQ_STORE_SUBSCRIBE',HTTP_REQUEST:'ZQ_HTTP_REQUEST',HTTP_TIMEOUT:'ZQ_HTTP_TIMEOUT',HTTP_INTERCEPTOR:'ZQ_HTTP_INTERCEPTOR',HTTP_PARSE:'ZQ_HTTP_PARSE',INVALID_ARGUMENT:'ZQ_INVALID_ARGUMENT',});class ZQueryError extends Error{constructor(code,message,context={},cause){super(message);this.name='ZQueryError';this.code=code;this.context=context;if(cause)this.cause=cause;}}let _errorHandler=null;function onError(handler){_errorHandler=typeof handler==='function'?handler:null;}function reportError(code,message,context={},cause){const err=cause instanceof ZQueryError?cause:new ZQueryError(code,message,context,cause);if(_errorHandler){try{_errorHandler(err);}catch{}}console.error(`[zQuery ${code}] ${message}`,context,cause||'');}function guardCallback(fn,code,context={}){return(...args)=>{try{return fn(...args);}catch(err){reportError(code,err.message||'Callback error',context,err);}};}function validate(value,name,expectedType){if(value===undefined||value===null){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" is required but got ${value}`);}if(expectedType&&typeof value!==expectedType){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" must be a ${expectedType}, got ${typeof value}`);}}function reactive(target,onChange,_path=''){if(typeof target!=='object'||target===null)return target;if(typeof onChange!=='function'){reportError(ErrorCode.REACTIVE_CALLBACK,'reactive() onChange must be a function',{received:typeof onChange});onChange=()=>{};}const proxyCache=new WeakMap();const handler={get(obj,key){if(key==='__isReactive')return true;if(key==='__raw')return obj;const value=obj[key];if(typeof value==='object'&&value!==null){if(proxyCache.has(value))return proxyCache.get(value);const childProxy=new Proxy(value,handler);proxyCache.set(value,childProxy);return childProxy;}return value;},set(obj,key,value){const old=obj[key];if(old===value)return true;obj[key]=value;if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,value,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,value,old},err);}return true;},deleteProperty(obj,key){const old=obj[key];delete obj[key];if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,undefined,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,old},err);}return true;}};return new Proxy(target,handler);}class Signal{constructor(value){this._value=value;this._subscribers=new Set();}get value(){if(Signal._activeEffect){this._subscribers.add(Signal._activeEffect);if(Signal._activeEffect._deps){Signal._activeEffect._deps.add(this);}}return this._value;}set value(newVal){if(this._value===newVal)return;this._value=newVal;this._notify();}peek(){return this._value;}_notify(){const subs=[...this._subscribers];for(let i=0;i<subs.length;i++){try{subs[i]();}catch(err){reportError(ErrorCode.SIGNAL_CALLBACK,'Signal subscriber threw',{signal:this},err);}}}subscribe(fn){this._subscribers.add(fn);return()=>this._subscribers.delete(fn);}toString(){return String(this._value);}}Signal._activeEffect=null;function signal(initial){return new Signal(initial);}function computed(fn){const s=new Signal(undefined);effect(()=>{s._value=fn();s._notify();});return s;}function effect(fn){const execute=()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=execute;try{fn();}catch(err){reportError(ErrorCode.EFFECT_EXEC,'Effect function threw',{},err);}finally{Signal._activeEffect=null;}};execute._deps=new Set();execute();return()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=null;};}class ZQueryCollection{constructor(elements){this.elements=Array.isArray(elements)?elements:[elements];this.length=this.elements.length;this.elements.forEach((el,i)=>{this[i]=el;});}each(fn){this.elements.forEach((el,i)=>fn.call(el,i,el));return this;}map(fn){return this.elements.map((el,i)=>fn.call(el,i,el));}forEach(fn){this.elements.forEach((el,i)=>fn(el,i,this.elements));return this;}first(){return this.elements[0]||null;}last(){return this.elements[this.length-1]||null;}eq(i){return new ZQueryCollection(this.elements[i]?[this.elements[i]]:[]);}toArray(){return[...this.elements];}[Symbol.iterator](){return this.elements[Symbol.iterator]();}find(selector){const found=[];this.elements.forEach(el=>found.push(...el.querySelectorAll(selector)));return new ZQueryCollection(found);}parent(){const parents=[...new Set(this.elements.map(el=>el.parentElement).filter(Boolean))];return new ZQueryCollection(parents);}closest(selector){return new ZQueryCollection(this.elements.map(el=>el.closest(selector)).filter(Boolean));}children(selector){const kids=[];this.elements.forEach(el=>{kids.push(...(selector?el.querySelectorAll(`:scope > ${selector}`):el.children));});return new ZQueryCollection([...kids]);}siblings(){const sibs=[];this.elements.forEach(el=>{sibs.push(...[...el.parentElement.children].filter(c=>c!==el));});return new ZQueryCollection(sibs);}next(selector){const els=this.elements.map(el=>el.nextElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}prev(selector){const els=this.elements.map(el=>el.previousElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}nextAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}nextUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}prevAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}prevUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}parents(selector){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(!selector||parent.matches(selector))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}parentsUntil(selector,filter){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(selector&&parent.matches(selector))break;if(!filter||parent.matches(filter))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}contents(){const result=[];this.elements.forEach(el=>result.push(...el.childNodes));return new ZQueryCollection(result);}filter(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter(selector));}return new ZQueryCollection(this.elements.filter(el=>el.matches(selector)));}not(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter((el,i)=>!selector.call(el,i,el)));}return new ZQueryCollection(this.elements.filter(el=>!el.matches(selector)));}has(selector){return new ZQueryCollection(this.elements.filter(el=>el.querySelector(selector)));}is(selector){if(typeof selector==='function'){return this.elements.some((el,i)=>selector.call(el,i,el));}return this.elements.some(el=>el.matches(selector));}slice(start,end){return new ZQueryCollection(this.elements.slice(start,end));}add(selector,context){const toAdd=(selector instanceof ZQueryCollection)?selector.elements:(selector instanceof Node)?[selector]:Array.from((context||document).querySelectorAll(selector));return new ZQueryCollection([...this.elements,...toAdd]);}get(index){if(index===undefined)return[...this.elements];return index<0?this.elements[this.length+index]:this.elements[index];}index(selector){if(selector===undefined){const el=this.first();return el?Array.from(el.parentElement.children).indexOf(el):-1;}const target=(typeof selector==='string')?document.querySelector(selector):selector;return this.elements.indexOf(target);}addClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(...classes);return this;}removeClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(...classes);return this;}toggleClass(...args){const force=typeof args[args.length-1]==='boolean'?args.pop():undefined;if(args.length===1&&args[0].indexOf(' ')===-1){const c=args[0];for(let i=0;i<this.elements.length;i++){force!==undefined?this.elements[i].classList.toggle(c,force):this.elements[i].classList.toggle(c);}return this;}const classes=args.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++){const el=this.elements[i];for(let j=0;j<classes.length;j++){force!==undefined?el.classList.toggle(classes[j],force):el.classList.toggle(classes[j]);}}return this;}hasClass(name){return this.first()?.classList.contains(name)||false;}attr(name,value){if(value===undefined)return this.first()?.getAttribute(name);return this.each((_,el)=>el.setAttribute(name,value));}removeAttr(name){return this.each((_,el)=>el.removeAttribute(name));}prop(name,value){if(value===undefined)return this.first()?.[name];return this.each((_,el)=>{el[name]=value;});}data(key,value){if(value===undefined){if(key===undefined)return this.first()?.dataset;const raw=this.first()?.dataset[key];try{return JSON.parse(raw);}catch{return raw;}}return this.each((_,el)=>{el.dataset[key]=typeof value==='object'?JSON.stringify(value):value;});}css(props){if(typeof props==='string'){const el=this.first();return el?getComputedStyle(el)[props]:undefined;}return this.each((_,el)=>Object.assign(el.style,props));}width(){return this.first()?.getBoundingClientRect().width;}height(){return this.first()?.getBoundingClientRect().height;}offset(){const r=this.first()?.getBoundingClientRect();return r?{top:r.top+window.scrollY,left:r.left+window.scrollX,width:r.width,height:r.height}:null;}position(){const el=this.first();return el?{top:el.offsetTop,left:el.offsetLeft}:null;}scrollTop(value){if(value===undefined){const el=this.first();return el===window?window.scrollY:el?.scrollTop;}return this.each((_,el)=>{if(el===window)window.scrollTo(window.scrollX,value);else el.scrollTop=value;});}scrollLeft(value){if(value===undefined){const el=this.first();return el===window?window.scrollX:el?.scrollLeft;}return this.each((_,el)=>{if(el===window)window.scrollTo(value,window.scrollY);else el.scrollLeft=value;});}innerWidth(){const el=this.first();return el?.clientWidth;}innerHeight(){const el=this.first();return el?.clientHeight;}outerWidth(includeMargin=false){const el=this.first();if(!el)return undefined;let w=el.offsetWidth;if(includeMargin){const style=getComputedStyle(el);w+=parseFloat(style.marginLeft)+parseFloat(style.marginRight);}return w;}outerHeight(includeMargin=false){const el=this.first();if(!el)return undefined;let h=el.offsetHeight;if(includeMargin){const style=getComputedStyle(el);h+=parseFloat(style.marginTop)+parseFloat(style.marginBottom);}return h;}html(content){if(content===undefined)return this.first()?.innerHTML;return this.each((_,el)=>{if(el.childNodes.length>0){_morph(el,content);}else{el.innerHTML=content;}});}morph(content){return this.each((_,el)=>{_morph(el,content);});}text(content){if(content===undefined)return this.first()?.textContent;return this.each((_,el)=>{el.textContent=content;});}val(value){if(value===undefined)return this.first()?.value;return this.each((_,el)=>{el.value=value;});}append(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforeend',content);else if(content instanceof ZQueryCollection)content.each((__,c)=>el.appendChild(c));else if(content instanceof Node)el.appendChild(content);});}prepend(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterbegin',content);else if(content instanceof Node)el.insertBefore(content,el.firstChild);});}after(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterend',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el.nextSibling);});}before(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforebegin',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el);});}wrap(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);el.parentNode.insertBefore(w,el);w.appendChild(el);});}remove(){return this.each((_,el)=>el.remove());}empty(){return this.each((_,el)=>{el.textContent='';});}clone(deep=true){return new ZQueryCollection(this.elements.map(el=>el.cloneNode(deep)));}replaceWith(content){return this.each((_,el)=>{if(typeof content==='string'){_morphElement(el,content);}else if(content instanceof Node){el.parentNode.replaceChild(content,el);}});}appendTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.appendChild(el));return this;}prependTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.insertBefore(el,dest.firstChild));return this;}insertAfter(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref.nextSibling));return this;}insertBefore(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref));return this;}replaceAll(target){const targets=typeof target==='string'?Array.from(document.querySelectorAll(target)):target instanceof ZQueryCollection?target.elements:[target];targets.forEach((t,i)=>{const nodes=i===0?this.elements:this.elements.map(el=>el.cloneNode(true));nodes.forEach(el=>t.parentNode.insertBefore(el,t));t.remove();});return this;}unwrap(selector){this.elements.forEach(el=>{const parent=el.parentElement;if(!parent||parent===document.body)return;if(selector&&!parent.matches(selector))return;parent.replaceWith(...parent.childNodes);});return this;}wrapAll(wrapper){const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);const first=this.first();if(!first)return this;first.parentNode.insertBefore(w,first);this.each((_,el)=>w.appendChild(el));return this;}wrapInner(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);while(el.firstChild)w.appendChild(el.firstChild);el.appendChild(w);});}detach(){return this.each((_,el)=>el.remove());}show(display=''){return this.each((_,el)=>{el.style.display=display;});}hide(){return this.each((_,el)=>{el.style.display='none';});}toggle(display=''){return this.each((_,el)=>{const hidden=el.style.display==='none'||(el.style.display!==''?false:getComputedStyle(el).display==='none');el.style.display=hidden?display:'none';});}on(event,selectorOrHandler,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{if(typeof selectorOrHandler==='function'){el.addEventListener(evt,selectorOrHandler);}else if(typeof selectorOrHandler==='string'){el.addEventListener(evt,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target&&el.contains(target))handler.call(target,e);});}});});}off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>el.removeEventListener(evt,handler));});}one(event,handler){return this.each((_,el)=>{el.addEventListener(event,handler,{once:true});});}trigger(event,detail){return this.each((_,el)=>{el.dispatchEvent(new CustomEvent(event,{detail,bubbles:true,cancelable:true}));});}click(fn){return fn?this.on('click',fn):this.trigger('click');}submit(fn){return fn?this.on('submit',fn):this.trigger('submit');}focus(){this.first()?.focus();return this;}blur(){this.first()?.blur();return this;}hover(enterFn,leaveFn){this.on('mouseenter',enterFn);return this.on('mouseleave',leaveFn||enterFn);}animate(props,duration=300,easing='ease'){return new Promise(resolve=>{const count={done:0};this.each((_,el)=>{el.style.transition=`all ${duration}ms ${easing}`;requestAnimationFrame(()=>{Object.assign(el.style,props);const onEnd=()=>{el.removeEventListener('transitionend',onEnd);el.style.transition='';if(++count.done>=this.length)resolve(this);};el.addEventListener('transitionend',onEnd);});});setTimeout(()=>resolve(this),duration+50);});}fadeIn(duration=300){return this.css({opacity:'0',display:''}).animate({opacity:'1'},duration);}fadeOut(duration=300){return this.animate({opacity:'0'},duration).then(col=>col.hide());}fadeToggle(duration=300){return Promise.all(this.elements.map(el=>{const visible=getComputedStyle(el).opacity!=='0'&&getComputedStyle(el).display!=='none';const col=new ZQueryCollection([el]);return visible?col.fadeOut(duration):col.fadeIn(duration);})).then(()=>this);}fadeTo(duration,opacity){return this.animate({opacity:String(opacity)},duration);}slideDown(duration=300){return this.each((_,el)=>{el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideUp(duration=300){return this.each((_,el)=>{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideToggle(duration=300){return this.each((_,el)=>{if(el.style.display==='none'||getComputedStyle(el).display==='none'){el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}else{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}});}serialize(){const form=this.first();if(!form||form.tagName!=='FORM')return'';return new URLSearchParams(new FormData(form)).toString();}serializeObject(){const form=this.first();if(!form||form.tagName!=='FORM')return{};const obj={};new FormData(form).forEach((v,k)=>{if(obj[k]!==undefined){if(!Array.isArray(obj[k]))obj[k]=[obj[k]];obj[k].push(v);}else{obj[k]=v;}});return obj;}}function createFragment(html){const tpl=document.createElement('template');tpl.innerHTML=html.trim();return tpl.content;}function query(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}function queryAll(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}query.id=(id)=>document.getElementById(id);query.class=(name)=>document.querySelector(`.${name}`);query.classes=(name)=>new ZQueryCollection(Array.from(document.getElementsByClassName(name)));query.tag=(name)=>new ZQueryCollection(Array.from(document.getElementsByTagName(name)));Object.defineProperty(query,'name',{value:(name)=>new ZQueryCollection(Array.from(document.getElementsByName(name))),writable:true,configurable:true});query.children=(parentId)=>{const p=document.getElementById(parentId);return new ZQueryCollection(p?Array.from(p.children):[]);};query.create=(tag,attrs={},...children)=>{const el=document.createElement(tag);for(const[k,v]of Object.entries(attrs)){if(k==='class')el.className=v;else if(k==='style'&&typeof v==='object')Object.assign(el.style,v);else if(k.startsWith('on')&&typeof v==='function')el.addEventListener(k.slice(2),v);else if(k==='data'&&typeof v==='object')Object.entries(v).forEach(([dk,dv])=>{el.dataset[dk]=dv;});else el.setAttribute(k,v);}children.flat().forEach(child=>{if(typeof child==='string')el.appendChild(document.createTextNode(child));else if(child instanceof Node)el.appendChild(child);});return new ZQueryCollection(el);};query.ready=(fn)=>{if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);};query.on=(event,selectorOrHandler,handler)=>{if(typeof selectorOrHandler==='function'){document.addEventListener(event,selectorOrHandler);return;}if(typeof selectorOrHandler==='object'&&typeof selectorOrHandler.addEventListener==='function'){selectorOrHandler.addEventListener(event,handler);return;}document.addEventListener(event,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target)handler.call(target,e);});};query.off=(event,handler)=>{document.removeEventListener(event,handler);};query.fn=ZQueryCollection.prototype;const T={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7};const PREC={'??':2,'||':3,'&&':4,'==':8,'!=':8,'===':8,'!==':8,'<':9,'>':9,'<=':9,'>=':9,'instanceof':9,'in':9,'+':11,'-':11,'*':12,'/':12,'%':12,};const KEYWORDS=new Set(['true','false','null','undefined','typeof','instanceof','in','new','void']);function tokenize(expr){const tokens=[];let i=0;const len=expr.length;while(i<len){const ch=expr[i];if(ch===' '||ch==='\t'||ch==='\n'||ch==='\r'){i++;continue;}if((ch>='0'&&ch<='9')||(ch==='.'&&i+1<len&&expr[i+1]>='0'&&expr[i+1]<='9')){let num='';if(ch==='0'&&i+1<len&&(expr[i+1]==='x'||expr[i+1]==='X')){num='0x';i+=2;while(i<len&&/[0-9a-fA-F]/.test(expr[i]))num+=expr[i++];}else{while(i<len&&((expr[i]>='0'&&expr[i]<='9')||expr[i]==='.'))num+=expr[i++];if(i<len&&(expr[i]==='e'||expr[i]==='E')){num+=expr[i++];if(i<len&&(expr[i]==='+'||expr[i]==='-'))num+=expr[i++];while(i<len&&expr[i]>='0'&&expr[i]<='9')num+=expr[i++];}}tokens.push({t:T.NUM,v:Number(num)});continue;}if(ch==="'"||ch==='"'){const quote=ch;let str='';i++;while(i<len&&expr[i]!==quote){if(expr[i]==='\\'&&i+1<len){const esc=expr[++i];if(esc==='n')str+='\n';else if(esc==='t')str+='\t';else if(esc==='r')str+='\r';else if(esc==='\\')str+='\\';else if(esc===quote)str+=quote;else str+=esc;}else{str+=expr[i];}i++;}i++;tokens.push({t:T.STR,v:str});continue;}if(ch==='`'){const parts=[];let str='';i++;while(i<len&&expr[i]!=='`'){if(expr[i]==='$'&&i+1<len&&expr[i+1]==='{'){parts.push(str);str='';i+=2;let depth=1;let inner='';while(i<len&&depth>0){if(expr[i]==='{')depth++;else if(expr[i]==='}'){depth--;if(depth===0)break;}inner+=expr[i++];}i++;parts.push({expr:inner});}else{if(expr[i]==='\\'&&i+1<len){str+=expr[++i];}else str+=expr[i];i++;}}i++;parts.push(str);tokens.push({t:T.TMPL,v:parts});continue;}if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||ch==='_'||ch==='$'){let ident='';while(i<len&&/[\w$]/.test(expr[i]))ident+=expr[i++];tokens.push({t:T.IDENT,v:ident});continue;}const two=expr.slice(i,i+3);if(two==='==='||two==='!=='||two==='?.'){if(two==='?.'){tokens.push({t:T.OP,v:'?.'});i+=2;}else{tokens.push({t:T.OP,v:two});i+=3;}continue;}const pair=expr.slice(i,i+2);if(pair==='=='||pair==='!='||pair==='<='||pair==='>='||pair==='&&'||pair==='||'||pair==='??'||pair==='?.'||pair==='=>'){tokens.push({t:T.OP,v:pair});i+=2;continue;}if('+-*/%'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('<>=!'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('()[]{},.?:'.includes(ch)){tokens.push({t:T.PUNC,v:ch});i++;continue;}i++;}tokens.push({t:T.EOF,v:null});return tokens;}class Parser{constructor(tokens,scope){this.tokens=tokens;this.pos=0;this.scope=scope;}peek(){return this.tokens[this.pos];}next(){return this.tokens[this.pos++];}expect(type,val){const t=this.next();if(t.t!==type||(val!==undefined&&t.v!==val)){throw new Error(`Expected ${val || type} but got ${t.v}`);}return t;}match(type,val){const t=this.peek();if(t.t===type&&(val===undefined||t.v===val)){return this.next();}return null;}parse(){const result=this.parseExpression(0);return result;}parseExpression(minPrec){let left=this.parseUnary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='?'){if(this.tokens[this.pos+1]?.v!=='.'){if(1<=minPrec)break;this.next();const truthy=this.parseExpression(0);this.expect(T.PUNC,':');const falsy=this.parseExpression(1);left={type:'ternary',cond:left,truthy,falsy};continue;}}if(tok.t===T.OP&&tok.v in PREC){const prec=PREC[tok.v];if(prec<=minPrec)break;this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}if(tok.t===T.IDENT&&(tok.v==='instanceof'||tok.v==='in')&&PREC[tok.v]>minPrec){const prec=PREC[tok.v];this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}break;}return left;}parseUnary(){const tok=this.peek();if(tok.t===T.IDENT&&tok.v==='typeof'){this.next();const arg=this.parseUnary();return{type:'typeof',arg};}if(tok.t===T.IDENT&&tok.v==='void'){this.next();this.parseUnary();return{type:'literal',value:undefined};}if(tok.t===T.OP&&tok.v==='!'){this.next();const arg=this.parseUnary();return{type:'not',arg};}if(tok.t===T.OP&&(tok.v==='-'||tok.v==='+')){this.next();const arg=this.parseUnary();return{type:'unary',op:tok.v,arg};}return this.parsePostfix();}parsePostfix(){let left=this.parsePrimary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='.'){this.next();const prop=this.next();left={type:'member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.OP&&tok.v==='?.'){this.next();const next=this.peek();if(next.t===T.PUNC&&next.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'optional_member',obj:left,prop,computed:true};}else if(next.t===T.PUNC&&next.v==='('){left={type:'optional_call',callee:left,args:this._parseArgs()};}else{const prop=this.next();left={type:'optional_member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}}continue;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'member',obj:left,prop,computed:true};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.PUNC&&tok.v==='('){left=this._parseCall(left);continue;}break;}return left;}_parseCall(callee){const args=this._parseArgs();return{type:'call',callee,args};}_parseArgs(){this.expect(T.PUNC,'(');const args=[];while(!(this.peek().t===T.PUNC&&this.peek().v===')')&&this.peek().t!==T.EOF){args.push(this.parseExpression(0));if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,')');return args;}parsePrimary(){const tok=this.peek();if(tok.t===T.NUM){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.STR){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.TMPL){this.next();return{type:'template',parts:tok.v};}if(tok.t===T.PUNC&&tok.v==='('){const savedPos=this.pos;this.next();const params=[];let couldBeArrow=true;if(this.peek().t===T.PUNC&&this.peek().v===')'){}else{while(couldBeArrow){const p=this.peek();if(p.t===T.IDENT&&!KEYWORDS.has(p.v)){params.push(this.next().v);if(this.peek().t===T.PUNC&&this.peek().v===','){this.next();}else{break;}}else{couldBeArrow=false;}}}if(couldBeArrow&&this.peek().t===T.PUNC&&this.peek().v===')'){this.next();if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params,body};}}this.pos=savedPos;this.next();const expr=this.parseExpression(0);this.expect(T.PUNC,')');return expr;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const elements=[];while(!(this.peek().t===T.PUNC&&this.peek().v===']')&&this.peek().t!==T.EOF){elements.push(this.parseExpression(0));if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,']');return{type:'array',elements};}if(tok.t===T.PUNC&&tok.v==='{'){this.next();const properties=[];while(!(this.peek().t===T.PUNC&&this.peek().v==='}')&&this.peek().t!==T.EOF){const keyTok=this.next();let key;if(keyTok.t===T.IDENT||keyTok.t===T.STR)key=keyTok.v;else if(keyTok.t===T.NUM)key=String(keyTok.v);else throw new Error('Invalid object key: '+keyTok.v);if(this.peek().t===T.PUNC&&(this.peek().v===','||this.peek().v==='}')){properties.push({key,value:{type:'ident',name:key}});}else{this.expect(T.PUNC,':');properties.push({key,value:this.parseExpression(0)});}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,'}');return{type:'object',properties};}if(tok.t===T.IDENT){this.next();if(tok.v==='true')return{type:'literal',value:true};if(tok.v==='false')return{type:'literal',value:false};if(tok.v==='null')return{type:'literal',value:null};if(tok.v==='undefined')return{type:'literal',value:undefined};if(tok.v==='new'){const classExpr=this.parsePostfix();let args=[];if(this.peek().t===T.PUNC&&this.peek().v==='('){args=this._parseArgs();}return{type:'new',callee:classExpr,args};}if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params:[tok.v],body};}return{type:'ident',name:tok.v};}this.next();return{type:'literal',value:undefined};}}const SAFE_ARRAY_METHODS=new Set(['length','map','filter','find','findIndex','some','every','reduce','reduceRight','forEach','includes','indexOf','lastIndexOf','join','slice','concat','flat','flatMap','reverse','sort','fill','keys','values','entries','at','toString',]);const SAFE_STRING_METHODS=new Set(['length','charAt','charCodeAt','includes','indexOf','lastIndexOf','slice','substring','trim','trimStart','trimEnd','toLowerCase','toUpperCase','split','replace','replaceAll','match','search','startsWith','endsWith','padStart','padEnd','repeat','at','toString','valueOf',]);const SAFE_NUMBER_METHODS=new Set(['toFixed','toPrecision','toString','valueOf',]);const SAFE_OBJECT_METHODS=new Set(['hasOwnProperty','toString','valueOf',]);const SAFE_MATH_PROPS=new Set(['PI','E','LN2','LN10','LOG2E','LOG10E','SQRT2','SQRT1_2','abs','ceil','floor','round','trunc','max','min','pow','sqrt','sign','random','log','log2','log10',]);const SAFE_JSON_PROPS=new Set(['parse','stringify']);function _isSafeAccess(obj,prop){const BLOCKED=new Set(['constructor','__proto__','prototype','__defineGetter__','__defineSetter__','__lookupGetter__','__lookupSetter__',]);if(typeof prop==='string'&&BLOCKED.has(prop))return false;if(obj!==null&&obj!==undefined&&(typeof obj==='object'||typeof obj==='function'))return true;if(typeof obj==='string')return SAFE_STRING_METHODS.has(prop);if(typeof obj==='number')return SAFE_NUMBER_METHODS.has(prop);return false;}function evaluate(node,scope){if(!node)return undefined;switch(node.type){case'literal':return node.value;case'ident':{const name=node.name;for(const layer of scope){if(layer&&typeof layer==='object'&&name in layer){return layer[name];}}if(name==='Math')return Math;if(name==='JSON')return JSON;if(name==='Date')return Date;if(name==='Array')return Array;if(name==='Object')return Object;if(name==='String')return String;if(name==='Number')return Number;if(name==='Boolean')return Boolean;if(name==='parseInt')return parseInt;if(name==='parseFloat')return parseFloat;if(name==='isNaN')return isNaN;if(name==='isFinite')return isFinite;if(name==='Infinity')return Infinity;if(name==='NaN')return NaN;if(name==='encodeURIComponent')return encodeURIComponent;if(name==='decodeURIComponent')return decodeURIComponent;if(name==='console')return console;return undefined;}case'template':{let result='';for(const part of node.parts){if(typeof part==='string'){result+=part;}else if(part&&part.expr){result+=String(safeEval(part.expr,scope)??'');}}return result;}case'member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'optional_member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'call':{const result=_resolveCall(node,scope,false);return result;}case'optional_call':{const callee=evaluate(node.callee,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;const args=node.args.map(a=>evaluate(a,scope));return callee(...args);}case'new':{const Ctor=evaluate(node.callee,scope);if(typeof Ctor!=='function')return undefined;if(Ctor===Date||Ctor===Array||Ctor===Map||Ctor===Set||Ctor===RegExp||Ctor===Error||Ctor===URL||Ctor===URLSearchParams){const args=node.args.map(a=>evaluate(a,scope));return new Ctor(...args);}return undefined;}case'binary':return _evalBinary(node,scope);case'unary':{const val=evaluate(node.arg,scope);return node.op==='-'?-val:+val;}case'not':return!evaluate(node.arg,scope);case'typeof':{try{return typeof evaluate(node.arg,scope);}catch{return'undefined';}}case'ternary':{const cond=evaluate(node.cond,scope);return cond?evaluate(node.truthy,scope):evaluate(node.falsy,scope);}case'array':return node.elements.map(e=>evaluate(e,scope));case'object':{const obj={};for(const{key,value}of node.properties){obj[key]=evaluate(value,scope);}return obj;}case'arrow':{const paramNames=node.params;const bodyNode=node.body;const closedScope=scope;return function(...args){const arrowScope={};paramNames.forEach((name,i)=>{arrowScope[name]=args[i];});return evaluate(bodyNode,[arrowScope,...closedScope]);};}default:return undefined;}}function _resolveCall(node,scope){const callee=node.callee;const args=node.args.map(a=>evaluate(a,scope));if(callee.type==='member'||callee.type==='optional_member'){const obj=evaluate(callee.obj,scope);if(obj==null)return undefined;const prop=callee.computed?evaluate(callee.prop,scope):callee.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}const fn=evaluate(callee,scope);if(typeof fn!=='function')return undefined;return fn(...args);}function _evalBinary(node,scope){if(node.op==='&&'){const left=evaluate(node.left,scope);return left?evaluate(node.right,scope):left;}if(node.op==='||'){const left=evaluate(node.left,scope);return left?left:evaluate(node.right,scope);}if(node.op==='??'){const left=evaluate(node.left,scope);return left!=null?left:evaluate(node.right,scope);}const left=evaluate(node.left,scope);const right=evaluate(node.right,scope);switch(node.op){case'+':return left+right;case'-':return left-right;case'*':return left*right;case'/':return left/right;case'%':return left%right;case'==':return left==right;case'!=':return left!=right;case'===':return left===right;case'!==':return left!==right;case'<':return left<right;case'>':return left>right;case'<=':return left<=right;case'>=':return left>=right;case'instanceof':return left instanceof right;case'in':return left in right;default:return undefined;}}const _astCache=new Map();const _AST_CACHE_MAX=512;function safeEval(expr,scope){try{const trimmed=expr.trim();if(!trimmed)return undefined;if(/^[a-zA-Z_$][\w$]*$/.test(trimmed)){for(const layer of scope){if(layer&&typeof layer==='object'&&trimmed in layer){return layer[trimmed];}}}let ast=_astCache.get(trimmed);if(!ast){const tokens=tokenize(trimmed);const parser=new Parser(tokens,scope);ast=parser.parse();if(_astCache.size>=_AST_CACHE_MAX){const first=_astCache.keys().next().value;_astCache.delete(first);}_astCache.set(trimmed,ast);}return evaluate(ast,scope);}catch(err){if(typeof console!=='undefined'&&console.debug){console.debug(`[zQuery EXPR_EVAL] Failed to evaluate: "${expr}"`,err.message);}return undefined;}}let _tpl=null;function _getTemplate(){if(!_tpl)_tpl=document.createElement('template');return _tpl;}function morph(rootEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newRoot=tpl.content;const tempDiv=document.createElement('div');while(newRoot.firstChild)tempDiv.appendChild(newRoot.firstChild);_morphChildren(rootEl,tempDiv);if(start)window.__zqMorphHook(rootEl,performance.now()-start);}function morphElement(oldEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newEl=tpl.content.firstElementChild;if(!newEl)return oldEl;if(oldEl.nodeName===newEl.nodeName){_morphAttributes(oldEl,newEl);_morphChildren(oldEl,newEl);if(start)window.__zqMorphHook(oldEl,performance.now()-start);return oldEl;}const clone=newEl.cloneNode(true);oldEl.parentNode.replaceChild(clone,oldEl);if(start)window.__zqMorphHook(clone,performance.now()-start);return clone;}function _morphChildren(oldParent,newParent){const oldCN=oldParent.childNodes;const newCN=newParent.childNodes;const oldLen=oldCN.length;const newLen=newCN.length;const oldChildren=new Array(oldLen);const newChildren=new Array(newLen);for(let i=0;i<oldLen;i++)oldChildren[i]=oldCN[i];for(let i=0;i<newLen;i++)newChildren[i]=newCN[i];let hasKeys=false;let oldKeyMap,newKeyMap;for(let i=0;i<oldLen;i++){if(_getKey(oldChildren[i])!=null){hasKeys=true;break;}}if(!hasKeys){for(let i=0;i<newLen;i++){if(_getKey(newChildren[i])!=null){hasKeys=true;break;}}}if(hasKeys){oldKeyMap=new Map();newKeyMap=new Map();for(let i=0;i<oldLen;i++){const key=_getKey(oldChildren[i]);if(key!=null)oldKeyMap.set(key,i);}for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null)newKeyMap.set(key,i);}_morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap);}else{_morphChildrenUnkeyed(oldParent,oldChildren,newChildren);}}function _morphChildrenUnkeyed(oldParent,oldChildren,newChildren){const oldLen=oldChildren.length;const newLen=newChildren.length;const minLen=oldLen<newLen?oldLen:newLen;for(let i=0;i<minLen;i++){_morphNode(oldParent,oldChildren[i],newChildren[i]);}if(newLen>oldLen){for(let i=oldLen;i<newLen;i++){oldParent.appendChild(newChildren[i].cloneNode(true));}}if(oldLen>newLen){for(let i=oldLen-1;i>=newLen;i--){oldParent.removeChild(oldChildren[i]);}}}function _morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap){const consumed=new Set();const newLen=newChildren.length;const matched=new Array(newLen);for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null&&oldKeyMap.has(key)){const oldIdx=oldKeyMap.get(key);matched[i]=oldChildren[oldIdx];consumed.add(oldIdx);}else{matched[i]=null;}}for(let i=oldChildren.length-1;i>=0;i--){if(!consumed.has(i)){const key=_getKey(oldChildren[i]);if(key!=null&&!newKeyMap.has(key)){oldParent.removeChild(oldChildren[i]);}}}const oldIndices=[];for(let i=0;i<newLen;i++){if(matched[i]){const key=_getKey(newChildren[i]);oldIndices.push(oldKeyMap.get(key));}else{oldIndices.push(-1);}}const lisSet=_lis(oldIndices);let cursor=oldParent.firstChild;const unkeyedOld=[];for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)&&_getKey(oldChildren[i])==null){unkeyedOld.push(oldChildren[i]);}}let unkeyedIdx=0;for(let i=0;i<newLen;i++){const newNode=newChildren[i];const newKey=_getKey(newNode);let oldNode=matched[i];if(!oldNode&&newKey==null){oldNode=unkeyedOld[unkeyedIdx++]||null;}if(oldNode){if(!lisSet.has(i)){oldParent.insertBefore(oldNode,cursor);}_morphNode(oldParent,oldNode,newNode);cursor=oldNode.nextSibling;}else{const clone=newNode.cloneNode(true);if(cursor){oldParent.insertBefore(clone,cursor);}else{oldParent.appendChild(clone);}}}while(unkeyedIdx<unkeyedOld.length){const leftover=unkeyedOld[unkeyedIdx++];if(leftover.parentNode===oldParent){oldParent.removeChild(leftover);}}for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)){const node=oldChildren[i];if(node.parentNode===oldParent&&_getKey(node)!=null&&!newKeyMap.has(_getKey(node))){oldParent.removeChild(node);}}}}function _lis(arr){const len=arr.length;const result=new Set();if(len===0)return result;const tails=[];const prev=new Array(len).fill(-1);const tailIndices=[];for(let i=0;i<len;i++){if(arr[i]===-1)continue;const val=arr[i];let lo=0,hi=tails.length;while(lo<hi){const mid=(lo+hi)>>1;if(tails[mid]<val)lo=mid+1;else hi=mid;}tails[lo]=val;tailIndices[lo]=i;prev[i]=lo>0?tailIndices[lo-1]:-1;}let k=tailIndices[tails.length-1];for(let i=tails.length-1;i>=0;i--){result.add(k);k=prev[k];}return result;}function _morphNode(parent,oldNode,newNode){if(oldNode.nodeType===3||oldNode.nodeType===8){if(newNode.nodeType===oldNode.nodeType){if(oldNode.nodeValue!==newNode.nodeValue){oldNode.nodeValue=newNode.nodeValue;}return;}parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType!==newNode.nodeType||oldNode.nodeName!==newNode.nodeName){parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType===1){if(oldNode.hasAttribute('z-skip'))return;if(oldNode.isEqualNode(newNode))return;_morphAttributes(oldNode,newNode);const tag=oldNode.nodeName;if(tag==='INPUT'){_syncInputValue(oldNode,newNode);return;}if(tag==='TEXTAREA'){if(oldNode.value!==newNode.textContent){oldNode.value=newNode.textContent||'';}return;}if(tag==='SELECT'){_morphChildren(oldNode,newNode);if(oldNode.value!==newNode.value){oldNode.value=newNode.value;}return;}_morphChildren(oldNode,newNode);}}function _morphAttributes(oldEl,newEl){const newAttrs=newEl.attributes;const oldAttrs=oldEl.attributes;const newLen=newAttrs.length;const oldLen=oldAttrs.length;if(newLen===oldLen){let same=true;for(let i=0;i<newLen;i++){const na=newAttrs[i];if(oldEl.getAttribute(na.name)!==na.value){same=false;break;}}if(same){for(let i=0;i<oldLen;i++){if(!newEl.hasAttribute(oldAttrs[i].name)){same=false;break;}}}if(same)return;}const newNames=new Set();for(let i=0;i<newLen;i++){const attr=newAttrs[i];newNames.add(attr.name);if(oldEl.getAttribute(attr.name)!==attr.value){oldEl.setAttribute(attr.name,attr.value);}}for(let i=oldLen-1;i>=0;i--){if(!newNames.has(oldAttrs[i].name)){oldEl.removeAttribute(oldAttrs[i].name);}}}function _syncInputValue(oldEl,newEl){const type=(oldEl.type||'').toLowerCase();if(type==='checkbox'||type==='radio'){if(oldEl.checked!==newEl.checked)oldEl.checked=newEl.checked;}else{if(oldEl.value!==(newEl.getAttribute('value')||'')){oldEl.value=newEl.getAttribute('value')||'';}}if(oldEl.disabled!==newEl.disabled)oldEl.disabled=newEl.disabled;}function _getKey(node){if(node.nodeType!==1)return null;const zk=node.getAttribute('z-key');if(zk)return zk;if(node.id)return'\0id:'+node.id;const ds=node.dataset;if(ds){if(ds.id)return'\0data-id:'+ds.id;if(ds.key)return'\0data-key:'+ds.key;}return null;}const _registry=new Map();const _instances=new Map();const _resourceCache=new Map();let _uid=0;if(typeof document!=='undefined'&&!document.querySelector('[data-zq-cloak]')){const _s=document.createElement('style');_s.textContent='[z-cloak]{display:none!important}*,*::before,*::after{-webkit-tap-highlight-color:transparent}';_s.setAttribute('data-zq-cloak','');document.head.appendChild(_s);}const _debounceTimers=new WeakMap();const _throttleTimers=new WeakMap();function _fetchResource(url){if(_resourceCache.has(url))return _resourceCache.get(url);if(typeof window!=='undefined'&&window.__zqInline){for(const[path,content]of Object.entries(window.__zqInline)){if(url===path||url.endsWith('/'+path)||url.endsWith('\\'+path)){const resolved=Promise.resolve(content);_resourceCache.set(url,resolved);return resolved;}}}let resolvedUrl=url;if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){try{const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');resolvedUrl=new URL(url,root).href;}catch{}}const promise=fetch(resolvedUrl).then(res=>{if(!res.ok)throw new Error(`zQuery: Failed to load resource "${url}" (${res.status})`);return res.text();});_resourceCache.set(url,promise);return promise;}function _resolveUrl(url,base){if(!base||!url||typeof url!=='string')return url;if(url.startsWith('/')||url.includes('://')||url.startsWith('//'))return url;try{if(base.includes('://')){return new URL(url,base).href;}const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');const absBase=new URL(base.endsWith('/')?base:base+'/',root).href;return new URL(url,absBase).href;}catch{return url;}}let _ownScriptUrl;try{if(typeof document!=='undefined'&&document.currentScript&&document.currentScript.src){_ownScriptUrl=document.currentScript.src.replace(/[?#].*$/,'');}}catch{}function _detectCallerBase(){try{const stack=new Error().stack||'';const urls=stack.match(/(?:https?|file):\/\/[^\s\)]+/g)||[];for(const raw of urls){const url=raw.replace(/:\d+:\d+$/,'').replace(/:\d+$/,'');if(/zquery(\.min)?\.js$/i.test(url))continue;if(_ownScriptUrl&&url.replace(/[?#].*$/,'')===_ownScriptUrl)continue;return url.replace(/\/[^/]*$/,'/');}}catch{}return undefined;}function _getPath(obj,path){return path.split('.').reduce((o,k)=>o?.[k],obj);}function _setPath(obj,path,value){const keys=path.split('.');const last=keys.pop();const target=keys.reduce((o,k)=>(o&&typeof o==='object')?o[k]:undefined,obj);if(target&&typeof target==='object')target[last]=value;}class Component{constructor(el,definition,props={}){this._uid=++_uid;this._el=el;this._def=definition;this._mounted=false;this._destroyed=false;this._updateQueued=false;this._listeners=[];this._watchCleanups=[];this.refs={};this._slotContent={};const defaultSlotNodes=[];[...el.childNodes].forEach(node=>{if(node.nodeType===1&&node.hasAttribute('slot')){const slotName=node.getAttribute('slot');if(!this._slotContent[slotName])this._slotContent[slotName]='';this._slotContent[slotName]+=node.outerHTML;}else if(node.nodeType===1||(node.nodeType===3&&node.textContent.trim())){defaultSlotNodes.push(node.nodeType===1?node.outerHTML:node.textContent);}});if(defaultSlotNodes.length){this._slotContent['default']=defaultSlotNodes.join('');}this.props=Object.freeze({...props});const initialState=typeof definition.state==='function'?definition.state():{...(definition.state||{})};this.state=reactive(initialState,(key,value,old)=>{if(!this._destroyed){this._runWatchers(key,value,old);this._scheduleUpdate();}});this.computed={};if(definition.computed){for(const[name,fn]of Object.entries(definition.computed)){Object.defineProperty(this.computed,name,{get:()=>fn.call(this,this.state.__raw||this.state),enumerable:true});}}for(const[key,val]of Object.entries(definition)){if(typeof val==='function'&&!_reservedKeys.has(key)){this[key]=val.bind(this);}}if(definition.init){try{definition.init.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${definition._name}" init() threw`,{component:definition._name},err);}}if(definition.watch){this._prevWatchValues={};for(const key of Object.keys(definition.watch)){this._prevWatchValues[key]=_getPath(this.state.__raw||this.state,key);}}}_runWatchers(changedKey,value,old){const watchers=this._def.watch;if(!watchers)return;for(const[key,handler]of Object.entries(watchers)){if(changedKey===key||key.startsWith(changedKey+'.')||changedKey.startsWith(key+'.')||changedKey===key){const currentVal=_getPath(this.state.__raw||this.state,key);const prevVal=this._prevWatchValues?.[key];if(currentVal!==prevVal){const fn=typeof handler==='function'?handler:handler.handler;if(typeof fn==='function')fn.call(this,currentVal,prevVal);if(this._prevWatchValues)this._prevWatchValues[key]=currentVal;}}}}_scheduleUpdate(){if(this._updateQueued)return;this._updateQueued=true;queueMicrotask(()=>{try{if(!this._destroyed)this._render();}finally{this._updateQueued=false;}});}async _loadExternals(){const def=this._def;const base=def._base;if(def.templateUrl&&!def._templateLoaded){const tu=def.templateUrl;if(typeof tu==='string'){def._externalTemplate=await _fetchResource(_resolveUrl(tu,base));}else if(Array.isArray(tu)){const urls=tu.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalTemplates={};results.forEach((html,i)=>{def._externalTemplates[i]=html;});}else if(typeof tu==='object'){const entries=Object.entries(tu);const results=await Promise.all(entries.map(([,url])=>_fetchResource(_resolveUrl(url,base))));def._externalTemplates={};entries.forEach(([key],i)=>{def._externalTemplates[key]=results[i];});}def._templateLoaded=true;}if(def.styleUrl&&!def._styleLoaded){const su=def.styleUrl;if(typeof su==='string'){const resolved=_resolveUrl(su,base);def._externalStyles=await _fetchResource(resolved);def._resolvedStyleUrls=[resolved];}else if(Array.isArray(su)){const urls=su.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalStyles=results.join('\n');def._resolvedStyleUrls=urls;}def._styleLoaded=true;}}_render(){if((this._def.templateUrl&&!this._def._templateLoaded)||(this._def.styleUrl&&!this._def._styleLoaded)){this._loadExternals().then(()=>{if(!this._destroyed)this._render();});return;}if(this._def._externalTemplates){this.templates=this._def._externalTemplates;}let html;if(this._def.render){html=this._def.render.call(this);html=this._expandZFor(html);}else if(this._def._externalTemplate){html=this._expandZFor(this._def._externalTemplate);html=html.replace(/\{\{(.+?)\}\}/g,(_,expr)=>{try{const result=safeEval(expr.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});}else{html='';}html=this._expandContentDirectives(html);if(html.includes('<slot')){html=html.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(_,name,fallback)=>{const slotName=name||'default';return this._slotContent[slotName]||fallback||'';});}const combinedStyles=[this._def.styles||'',this._def._externalStyles||''].filter(Boolean).join('\n');if(!this._mounted&&combinedStyles){const scopeAttr=`z-s${this._uid}`;this._el.setAttribute(scopeAttr,'');let inAtBlock=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(inAtBlock>0)inAtBlock--;return match;}const trimmed=selector.trim();if(trimmed.startsWith('@')){inAtBlock++;return match;}if(inAtBlock>0&&/^[\d%\s,fromto]+$/.test(trimmed.replace(/\s/g,''))){return match;}return selector.split(',').map(s=>`[${scopeAttr}] ${s.trim()}`).join(', ')+' {';});const styleEl=document.createElement('style');styleEl.textContent=scoped;styleEl.setAttribute('data-zq-component',this._def._name||'');styleEl.setAttribute('data-zq-scope',scopeAttr);if(this._def._resolvedStyleUrls){styleEl.setAttribute('data-zq-style-urls',this._def._resolvedStyleUrls.join(' '));if(this._def.styles){styleEl.setAttribute('data-zq-inline',this._def.styles);}}document.head.appendChild(styleEl);this._styleEl=styleEl;}let _focusInfo=null;const _active=document.activeElement;if(_active&&this._el.contains(_active)){const modelKey=_active.getAttribute?.('z-model');const refKey=_active.getAttribute?.('z-ref');let selector=null;if(modelKey){selector=`[z-model="${modelKey}"]`;}else if(refKey){selector=`[z-ref="${refKey}"]`;}else{const tag=_active.tagName.toLowerCase();if(tag==='input'||tag==='textarea'||tag==='select'){let s=tag;if(_active.type)s+=`[type="${_active.type}"]`;if(_active.name)s+=`[name="${_active.name}"]`;if(_active.placeholder)s+=`[placeholder="${CSS.escape(_active.placeholder)}"]`;selector=s;}}if(selector){_focusInfo={selector,start:_active.selectionStart,end:_active.selectionEnd,dir:_active.selectionDirection,};}}const _renderStart=typeof window!=='undefined'&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(!this._mounted){this._el.innerHTML=html;if(_renderStart&&window.__zqRenderHook)window.__zqRenderHook(this._el,performance.now()-_renderStart,'mount',this._def._name);}else{morph(this._el,html);}this._processDirectives();this._bindEvents();this._bindRefs();this._bindModels();if(_focusInfo){const el=this._el.querySelector(_focusInfo.selector);if(el&&el!==document.activeElement){el.focus();try{if(_focusInfo.start!==null&&_focusInfo.start!==undefined){el.setSelectionRange(_focusInfo.start,_focusInfo.end,_focusInfo.dir);}}catch(_){}}}mountAll(this._el);if(!this._mounted){this._mounted=true;if(this._def.mounted){try{this._def.mounted.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" mounted() threw`,{component:this._def._name},err);}}}else{if(this._def.updated){try{this._def.updated.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" updated() threw`,{component:this._def._name},err);}}}}_bindEvents(){const eventMap=new Map();const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{if(child.closest('[z-pre]'))return;const attrs=child.attributes;for(let a=0;a<attrs.length;a++){const attr=attrs[a];let raw;if(attr.name.charCodeAt(0)===64){raw=attr.name.slice(1);}else if(attr.name.startsWith('z-on:')){raw=attr.name.slice(5);}else{continue;}const parts=raw.split('.');const event=parts[0];const modifiers=parts.slice(1);const methodExpr=attr.value;if(!child.dataset.zqEid){child.dataset.zqEid=String(++_uid);}const selector=`[data-zq-eid="${child.dataset.zqEid}"]`;if(!eventMap.has(event))eventMap.set(event,[]);eventMap.get(event).push({selector,methodExpr,modifiers,el:child});}});this._eventBindings=eventMap;if(this._delegatedEvents){for(const event of eventMap.keys()){if(!this._delegatedEvents.has(event)){this._attachDelegatedEvent(event,eventMap.get(event));}}for(const event of this._delegatedEvents.keys()){if(!eventMap.has(event)){const{handler,opts}=this._delegatedEvents.get(event);this._el.removeEventListener(event,handler,opts);this._delegatedEvents.delete(event);this._listeners=this._listeners.filter(l=>l.event!==event);}}return;}this._delegatedEvents=new Map();for(const[event,bindings]of eventMap){this._attachDelegatedEvent(event,bindings);}}_attachDelegatedEvent(event,bindings){const needsCapture=bindings.some(b=>b.modifiers.includes('capture'));const needsPassive=bindings.some(b=>b.modifiers.includes('passive'));const listenerOpts=(needsCapture||needsPassive)?{capture:needsCapture,passive:needsPassive}:false;const handler=(e)=>{const currentBindings=this._eventBindings?.get(event)||[];for(const{selector,methodExpr,modifiers,el}of currentBindings){if(!e.target.closest(selector))continue;if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop'))e.stopPropagation();const invoke=(evt)=>{const match=methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const methodName=match[1];const fn=this[methodName];if(typeof fn!=='function')return;if(match[2]!==undefined){const args=match[2].split(',').map(a=>{a=a.trim();if(a==='')return undefined;if(a==='$event')return evt;if(a==='true')return true;if(a==='false')return false;if(a==='null')return null;if(/^-?\d+(\.\d+)?$/.test(a))return Number(a);if((a.startsWith("'")&&a.endsWith("'"))||(a.startsWith('"')&&a.endsWith('"')))return a.slice(1,-1);if(a.startsWith('state.'))return _getPath(this.state,a.slice(6));return a;}).filter(a=>a!==undefined);fn(...args);}else{fn(evt);}};const debounceIdx=modifiers.indexOf('debounce');if(debounceIdx!==-1){const ms=parseInt(modifiers[debounceIdx+1],10)||250;const timers=_debounceTimers.get(el)||{};clearTimeout(timers[event]);timers[event]=setTimeout(()=>invoke(e),ms);_debounceTimers.set(el,timers);continue;}const throttleIdx=modifiers.indexOf('throttle');if(throttleIdx!==-1){const ms=parseInt(modifiers[throttleIdx+1],10)||250;const timers=_throttleTimers.get(el)||{};if(timers[event])continue;invoke(e);timers[event]=setTimeout(()=>{timers[event]=null;},ms);_throttleTimers.set(el,timers);continue;}if(modifiers.includes('once')){if(el.dataset.zqOnce===event)continue;el.dataset.zqOnce=event;}invoke(e);}};this._el.addEventListener(event,handler,listenerOpts);this._listeners.push({event,handler});this._delegatedEvents.set(event,{handler,opts:listenerOpts});}_bindRefs(){this.refs={};this._el.querySelectorAll('[z-ref]').forEach(el=>{this.refs[el.getAttribute('z-ref')]=el;});}_bindModels(){this._el.querySelectorAll('[z-model]').forEach(el=>{const key=el.getAttribute('z-model');const tag=el.tagName.toLowerCase();const type=(el.type||'').toLowerCase();const isEditable=el.hasAttribute('contenteditable');const isLazy=el.hasAttribute('z-lazy');const isTrim=el.hasAttribute('z-trim');const isNum=el.hasAttribute('z-number');const currentVal=_getPath(this.state,key);if(tag==='input'&&type==='checkbox'){el.checked=!!currentVal;}else if(tag==='input'&&type==='radio'){el.checked=el.value===String(currentVal);}else if(tag==='select'&&el.multiple){const vals=Array.isArray(currentVal)?currentVal.map(String):[];[...el.options].forEach(opt=>{opt.selected=vals.includes(opt.value);});}else if(isEditable){if(el.textContent!==String(currentVal??'')){el.textContent=currentVal??'';}}else{el.value=currentVal??'';}const event=isLazy||tag==='select'||type==='checkbox'||type==='radio'?'change':isEditable?'input':'input';if(el._zqModelBound)return;el._zqModelBound=true;const handler=()=>{let val;if(type==='checkbox')val=el.checked;else if(tag==='select'&&el.multiple)val=[...el.selectedOptions].map(o=>o.value);else if(isEditable)val=el.textContent;else val=el.value;if(isTrim&&typeof val==='string')val=val.trim();if(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};el.addEventListener(event,handler);});}_evalExpr(expr){return safeEval(expr,[this.state.__raw||this.state,{props:this.props,refs:this.refs,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);}_expandZFor(html){if(!html.includes('z-for'))return html;const temp=document.createElement('div');temp.innerHTML=html;const _recurse=(root)=>{let forEls=[...root.querySelectorAll('[z-for]')].filter(el=>!el.querySelector('[z-for]'));if(!forEls.length)return;for(const el of forEls){if(!el.parentNode)continue;const expr=el.getAttribute('z-for');const m=expr.match(/^\s*(?:\(\s*(\w+)(?:\s*,\s*(\w+))?\s*\)|(\w+))\s+in\s+(.+)\s*$/);if(!m){el.removeAttribute('z-for');continue;}const itemVar=m[1]||m[3];const indexVar=m[2]||'$index';const listExpr=m[4].trim();let list=this._evalExpr(listExpr);if(list==null){el.remove();continue;}if(typeof list==='number'){list=Array.from({length:list},(_,i)=>i+1);}if(!Array.isArray(list)&&typeof list==='object'&&typeof list[Symbol.iterator]!=='function'){list=Object.entries(list).map(([k,v])=>({key:k,value:v}));}if(!Array.isArray(list)&&typeof list[Symbol.iterator]==='function'){list=[...list];}if(!Array.isArray(list)){el.remove();continue;}const parent=el.parentNode;const tplEl=el.cloneNode(true);tplEl.removeAttribute('z-for');const tplOuter=tplEl.outerHTML;const fragment=document.createDocumentFragment();const evalReplace=(str,item,index)=>str.replace(/\{\{(.+?)\}\}/g,(_,inner)=>{try{const loopScope={};loopScope[itemVar]=item;loopScope[indexVar]=index;const result=safeEval(inner.trim(),[loopScope,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});for(let i=0;i<list.length;i++){const processed=evalReplace(tplOuter,list[i],i);const wrapper=document.createElement('div');wrapper.innerHTML=processed;while(wrapper.firstChild)fragment.appendChild(wrapper.firstChild);}parent.replaceChild(fragment,el);}if(root.querySelector('[z-for]'))_recurse(root);};_recurse(temp);return temp.innerHTML;}_expandContentDirectives(html){if(!html.includes('z-html')&&!html.includes('z-text'))return html;const temp=document.createElement('div');temp.innerHTML=html;temp.querySelectorAll('[z-html]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-html'));el.innerHTML=val!=null?String(val):'';el.removeAttribute('z-html');});temp.querySelectorAll('[z-text]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-text'));el.textContent=val!=null?String(val):'';el.removeAttribute('z-text');});return temp.innerHTML;}_processDirectives(){const ifEls=[...this._el.querySelectorAll('[z-if]')];for(const el of ifEls){if(!el.parentNode||el.closest('[z-pre]'))continue;const show=!!this._evalExpr(el.getAttribute('z-if'));const chain=[{el,show}];let sib=el.nextElementSibling;while(sib){if(sib.hasAttribute('z-else-if')){chain.push({el:sib,show:!!this._evalExpr(sib.getAttribute('z-else-if'))});sib=sib.nextElementSibling;}else if(sib.hasAttribute('z-else')){chain.push({el:sib,show:true});break;}else{break;}}let found=false;for(const item of chain){if(!found&&item.show){found=true;item.el.removeAttribute('z-if');item.el.removeAttribute('z-else-if');item.el.removeAttribute('z-else');}else{item.el.remove();}}}this._el.querySelectorAll('[z-show]').forEach(el=>{if(el.closest('[z-pre]'))return;const show=!!this._evalExpr(el.getAttribute('z-show'));el.style.display=show?'':'none';el.removeAttribute('z-show');});const walker=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(n){return n.hasAttribute('z-pre')?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const attrs=node.attributes;for(let i=attrs.length-1;i>=0;i--){const attr=attrs[i];let attrName;if(attr.name.startsWith('z-bind:'))attrName=attr.name.slice(7);else if(attr.name.charCodeAt(0)===58&&attr.name.charCodeAt(1)!==58)attrName=attr.name.slice(1);else continue;const val=this._evalExpr(attr.value);node.removeAttribute(attr.name);if(val===false||val===null||val===undefined){node.removeAttribute(attrName);}else if(val===true){node.setAttribute(attrName,'');}else{node.setAttribute(attrName,String(val));}}}this._el.querySelectorAll('[z-class]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-class'));if(typeof val==='string'){val.split(/\s+/).filter(Boolean).forEach(c=>el.classList.add(c));}else if(Array.isArray(val)){val.filter(Boolean).forEach(c=>el.classList.add(String(c)));}else if(val&&typeof val==='object'){for(const[cls,active]of Object.entries(val)){el.classList.toggle(cls,!!active);}}el.removeAttribute('z-class');});this._el.querySelectorAll('[z-style]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-style'));if(typeof val==='string'){el.style.cssText+=';'+val;}else if(val&&typeof val==='object'){for(const[prop,v]of Object.entries(val)){el.style[prop]=v;}}el.removeAttribute('z-style');});this._el.querySelectorAll('[z-cloak]').forEach(el=>{el.removeAttribute('z-cloak');});}setState(partial){if(partial&&Object.keys(partial).length>0){Object.assign(this.state,partial);}else{this._scheduleUpdate();}}emit(name,detail){this._el.dispatchEvent(new CustomEvent(name,{detail,bubbles:true,cancelable:true}));}destroy(){if(this._destroyed)return;this._destroyed=true;if(this._def.destroyed){try{this._def.destroyed.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},err);}}this._listeners.forEach(({event,handler})=>this._el.removeEventListener(event,handler));this._listeners=[];this._delegatedEvents=null;this._eventBindings=null;if(this._styleEl)this._styleEl.remove();_instances.delete(this._el);this._el.innerHTML='';}}const _reservedKeys=new Set(['state','render','styles','init','mounted','updated','destroyed','props','templateUrl','styleUrl','templates','base','computed','watch']);function component(name,definition){if(!name||typeof name!=='string'){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,'Component name must be a non-empty string');}if(!name.includes('-')){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,`Component name "${name}" must contain a hyphen (Web Component convention)`);}definition._name=name;if(definition.base!==undefined){definition._base=definition.base;}else{definition._base=_detectCallerBase();}_registry.set(name,definition);}function mount(target,componentName,props={}){const el=typeof target==='string'?document.querySelector(target):target;if(!el)throw new ZQueryError(ErrorCode.COMP_MOUNT_TARGET,`Mount target "${target}" not found`,{target});const def=_registry.get(componentName);if(!def)throw new ZQueryError(ErrorCode.COMP_NOT_FOUND,`Component "${componentName}" not registered`,{component:componentName});if(_instances.has(el))_instances.get(el).destroy();const instance=new Component(el,def,props);_instances.set(el,instance);instance._render();return instance;}function mountAll(root=document.body){for(const[name,def]of _registry){const tags=root.querySelectorAll(name);tags.forEach(tag=>{if(_instances.has(tag))return;const props={};let parentInstance=null;let ancestor=tag.parentElement;while(ancestor){if(_instances.has(ancestor)){parentInstance=_instances.get(ancestor);break;}ancestor=ancestor.parentElement;}[...tag.attributes].forEach(attr=>{if(attr.name.startsWith('@')||attr.name.startsWith('z-'))return;if(attr.name.startsWith(':')){const propName=attr.name.slice(1);if(parentInstance){props[propName]=safeEval(attr.value,[parentInstance.state.__raw||parentInstance.state,{props:parentInstance.props,refs:parentInstance.refs,computed:parentInstance.computed,$:typeof window!=='undefined'?window.$:undefined}]);}else{try{props[propName]=JSON.parse(attr.value);}catch{props[propName]=attr.value;}}return;}try{props[attr.name]=JSON.parse(attr.value);}catch{props[attr.name]=attr.value;}});const instance=new Component(tag,def,props);_instances.set(tag,instance);instance._render();});}}function getInstance(target){const el=typeof target==='string'?document.querySelector(target):target;return _instances.get(el)||null;}function destroy(target){const el=typeof target==='string'?document.querySelector(target):target;const inst=_instances.get(el);if(inst)inst.destroy();}function getRegistry(){return Object.fromEntries(_registry);}async function prefetch(name){const def=_registry.get(name);if(!def)return;if((def.templateUrl&&!def._templateLoaded)||(def.styleUrl&&!def._styleLoaded)){await Component.prototype._loadExternals.call({_def:def});}}const _globalStyles=new Map();function style(urls,opts={}){const callerBase=_detectCallerBase();const list=Array.isArray(urls)?urls:[urls];const elements=[];const loadPromises=[];let _criticalStyle=null;if(opts.critical!==false){_criticalStyle=document.createElement('style');_criticalStyle.setAttribute('data-zq-critical','');_criticalStyle.textContent=`html{visibility:hidden!important;background:${opts.bg || '#0d1117'}}`;document.head.insertBefore(_criticalStyle,document.head.firstChild);}for(let url of list){if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){url=_resolveUrl(url,callerBase);}if(_globalStyles.has(url)){elements.push(_globalStyles.get(url));continue;}const link=document.createElement('link');link.rel='stylesheet';link.href=url;link.setAttribute('data-zq-style','');const p=new Promise(resolve=>{link.onload=resolve;link.onerror=resolve;});loadPromises.push(p);document.head.appendChild(link);_globalStyles.set(url,link);elements.push(link);}const ready=Promise.all(loadPromises).then(()=>{if(_criticalStyle){_criticalStyle.remove();}});return{ready,remove(){for(const el of elements){el.remove();for(const[k,v]of _globalStyles){if(v===el){_globalStyles.delete(k);break;}}}}};}const _ZQ_STATE_KEY='__zq';class Router{constructor(config={}){this._el=null;const isFile=typeof location!=='undefined'&&location.protocol==='file:';this._mode=isFile?'hash':(config.mode||'history');let rawBase=config.base;if(rawBase==null){rawBase=(typeof window!=='undefined'&&window.__ZQ_BASE)||'';if(!rawBase&&typeof document!=='undefined'){const baseEl=document.querySelector('base');if(baseEl){try{rawBase=new URL(baseEl.href).pathname;}catch{rawBase=baseEl.getAttribute('href')||'';}if(rawBase==='/')rawBase='';}}}this._base=String(rawBase).replace(/\/+$/,'');if(this._base&&!this._base.startsWith('/'))this._base='/'+this._base;this._routes=[];this._fallback=config.fallback||null;this._current=null;this._guards={before:[],after:[]};this._listeners=new Set();this._instance=null;this._resolving=false;this._substateListeners=[];this._inSubstate=false;if(config.el){this._el=typeof config.el==='string'?document.querySelector(config.el):config.el;}if(config.routes){config.routes.forEach(r=>this.add(r));}if(this._mode==='hash'){window.addEventListener('hashchange',()=>this._resolve());}else{window.addEventListener('popstate',(e)=>{const st=e.state;if(st&&st[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(st.key,st.data,'pop');if(handled)return;}else if(this._inSubstate){this._inSubstate=false;this._fireSubstate(null,null,'reset');}this._resolve();});}document.addEventListener('click',(e)=>{if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const link=e.target.closest('[z-link]');if(!link)return;if(link.getAttribute('target')==='_blank')return;e.preventDefault();let href=link.getAttribute('z-link');const paramsAttr=link.getAttribute('z-link-params');if(paramsAttr){try{const params=JSON.parse(paramsAttr);href=this._interpolateParams(href,params);}catch{}}this.navigate(href);if(link.hasAttribute('z-to-top')){const scrollBehavior=link.getAttribute('z-to-top')||'instant';window.scrollTo({top:0,behavior:scrollBehavior});}});if(this._el){queueMicrotask(()=>this._resolve());}}add(route){const keys=[];const pattern=route.path.replace(/:(\w+)/g,(_,key)=>{keys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const regex=new RegExp(`^${pattern}$`);this._routes.push({...route,_regex:regex,_keys:keys});if(route.fallback){const fbKeys=[];const fbPattern=route.fallback.replace(/:(\w+)/g,(_,key)=>{fbKeys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const fbRegex=new RegExp(`^${fbPattern}$`);this._routes.push({...route,path:route.fallback,_regex:fbRegex,_keys:fbKeys});}return this;}remove(path){this._routes=this._routes.filter(r=>r.path!==path);return this;}_interpolateParams(path,params){if(!params||typeof params!=='object')return path;return path.replace(/:([\w]+)/g,(_,key)=>{const val=params[key];return val!=null?encodeURIComponent(String(val)):':'+key;});}_currentURL(){if(this._mode==='hash'){return window.location.hash.slice(1)||'/';}const pathname=window.location.pathname||'/';const hash=window.location.hash||'';return pathname+hash;}navigate(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;const targetHash='#'+normalized;if(window.location.hash===targetHash&&!options.force)return this;window.location.hash=targetHash;}else{const targetURL=this._base+normalized+hash;const currentURL=(window.location.pathname||'/')+(window.location.hash||'');if(targetURL===currentURL&&!options.force){if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}const targetPathOnly=this._base+normalized;const currentPathOnly=window.location.pathname||'/';if(targetPathOnly===currentPathOnly&&hash&&!options.force){window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}window.history.pushState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);this._resolve();}return this;}replace(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;window.location.replace('#'+normalized);}else{window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',this._base+normalized+hash);this._resolve();}return this;}_normalizePath(path){let p=path&&path.startsWith('/')?path:(path?`/${path}`:'/');if(this._base){if(p===this._base)return'/';if(p.startsWith(this._base+'/'))p=p.slice(this._base.length)||'/';}return p;}resolve(path){const normalized=path&&path.startsWith('/')?path:(path?`/${path}`:'/');return this._base+normalized;}back(){window.history.back();return this;}forward(){window.history.forward();return this;}go(n){window.history.go(n);return this;}beforeEach(fn){this._guards.before.push(fn);return this;}afterEach(fn){this._guards.after.push(fn);return this;}onChange(fn){this._listeners.add(fn);return()=>this._listeners.delete(fn);}pushSubstate(key,data){this._inSubstate=true;if(this._mode==='hash'){const current=window.location.hash||'#/';window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}else{window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}return this;}onSubstate(fn){this._substateListeners.push(fn);return()=>{this._substateListeners=this._substateListeners.filter(f=>f!==fn);};}_fireSubstate(key,data,action){for(const fn of this._substateListeners){try{if(fn(key,data,action)===true)return true;}catch(err){reportError(ErrorCode.ROUTER_GUARD,'onSubstate listener threw',{key,data},err);}}return false;}get current(){return this._current;}get base(){return this._base;}get path(){if(this._mode==='hash'){const raw=window.location.hash.slice(1)||'/';if(raw&&!raw.startsWith('/')){window.__zqScrollTarget=raw;const fallbackPath=(this._current&&this._current.path)||'/';window.location.replace('#'+fallbackPath);return fallbackPath;}return raw;}let pathname=window.location.pathname||'/';if(pathname.length>1&&pathname.endsWith('/')){pathname=pathname.slice(0,-1);}if(this._base){if(pathname===this._base)return'/';if(pathname.startsWith(this._base+'/')){return pathname.slice(this._base.length)||'/';}}return pathname;}get query(){const search=this._mode==='hash'?(window.location.hash.split('?')[1]||''):window.location.search.slice(1);return Object.fromEntries(new URLSearchParams(search));}async _resolve(){if(this._resolving)return;this._resolving=true;this._redirectCount=0;try{await this.__resolve();}finally{this._resolving=false;}}async __resolve(){const histState=window.history.state;if(histState&&histState[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(histState.key,histState.data,'resolve');if(handled)return;}const fullPath=this.path;const[pathPart,queryString]=fullPath.split('?');const path=pathPart||'/';const query=Object.fromEntries(new URLSearchParams(queryString||''));let matched=null;let params={};for(const route of this._routes){const m=path.match(route._regex);if(m){matched=route;route._keys.forEach((key,i)=>{params[key]=m[i+1];});break;}}if(!matched&&this._fallback){matched={component:this._fallback,path:'*',_keys:[],_regex:/.*/};}if(!matched)return;const to={route:matched,params,query,path};const from=this._current;if(from&&this._instance&&matched.component===from.route.component){const sameParams=JSON.stringify(params)===JSON.stringify(from.params);const sameQuery=JSON.stringify(query)===JSON.stringify(from.query);if(sameParams&&sameQuery){return;}}for(const guard of this._guards.before){try{const result=await guard(to,from);if(result===false)return;if(typeof result==='string'){if(++this._redirectCount>10){reportError(ErrorCode.ROUTER_GUARD,'Too many guard redirects (possible loop)',{to},null);return;}const[rPath,rFrag]=result.split('#');const rNorm=this._normalizePath(rPath||'/');const rHash=rFrag?'#'+rFrag:'';if(this._mode==='hash'){if(rFrag)window.__zqScrollTarget=rFrag;window.location.replace('#'+rNorm);}else{window.history.replaceState({[_ZQ_STATE_KEY]:'route'},'',this._base+rNorm+rHash);}return this.__resolve();}}catch(err){reportError(ErrorCode.ROUTER_GUARD,'Before-guard threw',{to,from},err);return;}}if(matched.load){try{await matched.load();}catch(err){reportError(ErrorCode.ROUTER_LOAD,`Failed to load module for route "${matched.path}"`,{path:matched.path},err);return;}}this._current=to;if(this._el&&matched.component){if(typeof matched.component==='string'){await prefetch(matched.component);}if(this._instance){this._instance.destroy();this._instance=null;}const _routeStart=typeof window!=='undefined'&&window.__zqRenderHook?performance.now():0;this._el.innerHTML='';const props={...params,$route:to,$query:query,$params:params};if(typeof matched.component==='string'){const container=document.createElement(matched.component);this._el.appendChild(container);this._instance=mount(container,matched.component,props);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',matched.component);}else if(typeof matched.component==='function'){this._el.innerHTML=matched.component(to);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',to);}}for(const guard of this._guards.after){await guard(to,from);}this._listeners.forEach(fn=>fn(to,from));}destroy(){if(this._instance)this._instance.destroy();this._listeners.clear();this._substateListeners=[];this._inSubstate=false;this._routes=[];this._guards={before:[],after:[]};}}let _activeRouter=null;function createRouter(config){_activeRouter=new Router(config);return _activeRouter;}function getRouter(){return _activeRouter;}class Store{constructor(config={}){this._subscribers=new Map();this._wildcards=new Set();this._actions=config.actions||{};this._getters=config.getters||{};this._middleware=[];this._history=[];this._debug=config.debug||false;const initial=typeof config.state==='function'?config.state():{...(config.state||{})};this.state=reactive(initial,(key,value,old)=>{const subs=this._subscribers.get(key);if(subs)subs.forEach(fn=>{try{fn(value,old,key);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,`Subscriber for "${key}" threw`,{key},err);}});this._wildcards.forEach(fn=>{try{fn(key,value,old);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,'Wildcard subscriber threw',{key},err);}});});this.getters={};for(const[name,fn]of Object.entries(this._getters)){Object.defineProperty(this.getters,name,{get:()=>fn(this.state.__raw||this.state),enumerable:true});}}dispatch(name,...args){const action=this._actions[name];if(!action){reportError(ErrorCode.STORE_ACTION,`Unknown action "${name}"`,{action:name,args});return;}for(const mw of this._middleware){try{const result=mw(name,args,this.state);if(result===false)return;}catch(err){reportError(ErrorCode.STORE_MIDDLEWARE,`Middleware threw during "${name}"`,{action:name},err);return;}}if(this._debug){console.log(`%c[Store] ${name}`,'color: #4CAF50; font-weight: bold;',...args);}try{const result=action(this.state,...args);this._history.push({action:name,args,timestamp:Date.now()});return result;}catch(err){reportError(ErrorCode.STORE_ACTION,`Action "${name}" threw`,{action:name,args},err);}}subscribe(keyOrFn,fn){if(typeof keyOrFn==='function'){this._wildcards.add(keyOrFn);return()=>this._wildcards.delete(keyOrFn);}if(!this._subscribers.has(keyOrFn)){this._subscribers.set(keyOrFn,new Set());}this._subscribers.get(keyOrFn).add(fn);return()=>this._subscribers.get(keyOrFn)?.delete(fn);}snapshot(){return JSON.parse(JSON.stringify(this.state.__raw||this.state));}replaceState(newState){const raw=this.state.__raw||this.state;for(const key of Object.keys(raw)){delete this.state[key];}Object.assign(this.state,newState);}use(fn){this._middleware.push(fn);return this;}get history(){return[...this._history];}reset(initialState){this.replaceState(initialState);this._history=[];}}let _stores=new Map();function createStore(name,config){if(typeof name==='object'){config=name;name='default';}const store=new Store(config);_stores.set(name,store);return store;}function getStore(name='default'){return _stores.get(name)||null;}const _config={baseURL:'',headers:{'Content-Type':'application/json'},timeout:30000,};const _interceptors={request:[],response:[],};async function request(method,url,data,options={}){if(!url||typeof url!=='string'){throw new Error(`HTTP request requires a URL string, got ${typeof url}`);}let fullURL=url.startsWith('http')?url:_config.baseURL+url;let headers={..._config.headers,...options.headers};let body=undefined;const fetchOpts={method:method.toUpperCase(),headers,...options,};if(data!==undefined&&method!=='GET'&&method!=='HEAD'){if(data instanceof FormData){body=data;delete fetchOpts.headers['Content-Type'];}else if(typeof data==='object'){body=JSON.stringify(data);}else{body=data;}fetchOpts.body=body;}if(data&&(method==='GET'||method==='HEAD')&&typeof data==='object'){const params=new URLSearchParams(data).toString();fullURL+=(fullURL.includes('?')?'&':'?')+params;}const controller=new AbortController();fetchOpts.signal=options.signal||controller.signal;const timeout=options.timeout??_config.timeout;let timer;if(timeout>0){timer=setTimeout(()=>controller.abort(),timeout);}for(const interceptor of _interceptors.request){const result=await interceptor(fetchOpts,fullURL);if(result===false)throw new Error('Request blocked by interceptor');if(result?.url)fullURL=result.url;if(result?.options)Object.assign(fetchOpts,result.options);}try{const response=await fetch(fullURL,fetchOpts);if(timer)clearTimeout(timer);const contentType=response.headers.get('Content-Type')||'';let responseData;try{if(contentType.includes('application/json')){responseData=await response.json();}else if(contentType.includes('text/')){responseData=await response.text();}else if(contentType.includes('application/octet-stream')||contentType.includes('image/')){responseData=await response.blob();}else{const text=await response.text();try{responseData=JSON.parse(text);}catch{responseData=text;}}}catch(parseErr){responseData=null;console.warn(`[zQuery HTTP] Failed to parse response body from ${method} ${fullURL}:`,parseErr.message);}const result={ok:response.ok,status:response.status,statusText:response.statusText,headers:Object.fromEntries(response.headers.entries()),data:responseData,response,};for(const interceptor of _interceptors.response){await interceptor(result);}if(!response.ok){const err=new Error(`HTTP ${response.status}: ${response.statusText}`);err.response=result;throw err;}return result;}catch(err){if(timer)clearTimeout(timer);if(err.name==='AbortError'){throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);}throw err;}}const http={get:(url,params,opts)=>request('GET',url,params,opts),post:(url,data,opts)=>request('POST',url,data,opts),put:(url,data,opts)=>request('PUT',url,data,opts),patch:(url,data,opts)=>request('PATCH',url,data,opts),delete:(url,data,opts)=>request('DELETE',url,data,opts),configure(opts){if(opts.baseURL!==undefined)_config.baseURL=opts.baseURL;if(opts.headers)Object.assign(_config.headers,opts.headers);if(opts.timeout!==undefined)_config.timeout=opts.timeout;},onRequest(fn){_interceptors.request.push(fn);},onResponse(fn){_interceptors.response.push(fn);},createAbort(){return new AbortController();},raw:(url,opts)=>fetch(url,opts),};function debounce(fn,ms=250){let timer;const debounced=(...args)=>{clearTimeout(timer);timer=setTimeout(()=>fn(...args),ms);};debounced.cancel=()=>clearTimeout(timer);return debounced;}function throttle(fn,ms=250){let last=0;let timer;return(...args)=>{const now=Date.now();const remaining=ms-(now-last);clearTimeout(timer);if(remaining<=0){last=now;fn(...args);}else{timer=setTimeout(()=>{last=Date.now();fn(...args);},remaining);}};}function pipe(...fns){return(input)=>fns.reduce((val,fn)=>fn(val),input);}function once(fn){let called=false,result;return(...args)=>{if(!called){called=true;result=fn(...args);}return result;};}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms));}function escapeHtml(str){const map={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};return String(str).replace(/[&<>"']/g,c=>map[c]);}function html(strings,...values){return strings.reduce((result,str,i)=>{const val=values[i-1];const escaped=(val instanceof TrustedHTML)?val.toString():escapeHtml(val??'');return result+escaped+str;});}class TrustedHTML{constructor(html){this._html=html;}toString(){return this._html;}}function trust(htmlStr){return new TrustedHTML(htmlStr);}function uuid(){return crypto?.randomUUID?.()||'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const r=Math.random()*16|0;return(c==='x'?r:(r&0x3|0x8)).toString(16);});}function camelCase(str){return str.replace(/-([a-z])/g,(_,c)=>c.toUpperCase());}function kebabCase(str){return str.replace(/([a-z])([A-Z])/g,'$1-$2').toLowerCase();}function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);return JSON.parse(JSON.stringify(obj));}function deepMerge(target,...sources){for(const source of sources){for(const key of Object.keys(source)){if(source[key]&&typeof source[key]==='object'&&!Array.isArray(source[key])){if(!target[key]||typeof target[key]!=='object')target[key]={};deepMerge(target[key],source[key]);}else{target[key]=source[key];}}}return target;}function isEqual(a,b){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;return keysA.every(k=>isEqual(a[k],b[k]));}function param(obj){return new URLSearchParams(obj).toString();}function parseQuery(str){return Object.fromEntries(new URLSearchParams(str));}const storage={get(key,fallback=null){try{const raw=localStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){localStorage.setItem(key,JSON.stringify(value));},remove(key){localStorage.removeItem(key);},clear(){localStorage.clear();},};const session={get(key,fallback=null){try{const raw=sessionStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){sessionStorage.setItem(key,JSON.stringify(value));},remove(key){sessionStorage.removeItem(key);},clear(){sessionStorage.clear();},};class EventBus{constructor(){this._handlers=new Map();}on(event,fn){if(!this._handlers.has(event))this._handlers.set(event,new Set());this._handlers.get(event).add(fn);return()=>this.off(event,fn);}off(event,fn){this._handlers.get(event)?.delete(fn);}emit(event,...args){this._handlers.get(event)?.forEach(fn=>fn(...args));}once(event,fn){const wrapper=(...args)=>{fn(...args);this.off(event,wrapper);};return this.on(event,wrapper);}clear(){this._handlers.clear();}}const bus=new EventBus();function $(selector,context){if(typeof selector==='function'){query.ready(selector);return;}return query(selector,context);}$.id=query.id;$.class=query.class;$.classes=query.classes;$.tag=query.tag;Object.defineProperty($,'name',{value:query.name,writable:true,configurable:true});$.children=query.children;$.all=function(selector,context){return queryAll(selector,context);};$.create=query.create;$.ready=query.ready;$.on=query.on;$.off=query.off;$.fn=query.fn;$.reactive=reactive;$.Signal=Signal;$.signal=signal;$.computed=computed;$.effect=effect;$.component=component;$.mount=mount;$.mountAll=mountAll;$.getInstance=getInstance;$.destroy=destroy;$.components=getRegistry;$.prefetch=prefetch;$.style=style;$.morph=morph;$.morphElement=morphElement;$.safeEval=safeEval;$.router=createRouter;$.getRouter=getRouter;$.store=createStore;$.getStore=getStore;$.http=http;$.get=http.get;$.post=http.post;$.put=http.put;$.patch=http.patch;$.delete=http.delete;$.debounce=debounce;$.throttle=throttle;$.pipe=pipe;$.once=once;$.sleep=sleep;$.escapeHtml=escapeHtml;$.html=html;$.trust=trust;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.bus=bus;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.validate=validate;$.version='0.9.0';$.libSize='~89 KB';$.meta={};$.noConflict=()=>{if(typeof window!=='undefined'&&window.$===$){delete window.$;}return $;};if(typeof window!=='undefined'){window.$=$;window.zQuery=$;}$;})(typeof window!=='undefined'?window:globalThis);
7
+ (function(global){'use strict';const ErrorCode=Object.freeze({REACTIVE_CALLBACK:'ZQ_REACTIVE_CALLBACK',SIGNAL_CALLBACK:'ZQ_SIGNAL_CALLBACK',EFFECT_EXEC:'ZQ_EFFECT_EXEC',EXPR_PARSE:'ZQ_EXPR_PARSE',EXPR_EVAL:'ZQ_EXPR_EVAL',EXPR_UNSAFE_ACCESS:'ZQ_EXPR_UNSAFE_ACCESS',COMP_INVALID_NAME:'ZQ_COMP_INVALID_NAME',COMP_NOT_FOUND:'ZQ_COMP_NOT_FOUND',COMP_MOUNT_TARGET:'ZQ_COMP_MOUNT_TARGET',COMP_RENDER:'ZQ_COMP_RENDER',COMP_LIFECYCLE:'ZQ_COMP_LIFECYCLE',COMP_RESOURCE:'ZQ_COMP_RESOURCE',COMP_DIRECTIVE:'ZQ_COMP_DIRECTIVE',ROUTER_LOAD:'ZQ_ROUTER_LOAD',ROUTER_GUARD:'ZQ_ROUTER_GUARD',ROUTER_RESOLVE:'ZQ_ROUTER_RESOLVE',STORE_ACTION:'ZQ_STORE_ACTION',STORE_MIDDLEWARE:'ZQ_STORE_MIDDLEWARE',STORE_SUBSCRIBE:'ZQ_STORE_SUBSCRIBE',HTTP_REQUEST:'ZQ_HTTP_REQUEST',HTTP_TIMEOUT:'ZQ_HTTP_TIMEOUT',HTTP_INTERCEPTOR:'ZQ_HTTP_INTERCEPTOR',HTTP_PARSE:'ZQ_HTTP_PARSE',INVALID_ARGUMENT:'ZQ_INVALID_ARGUMENT',});class ZQueryError extends Error{constructor(code,message,context={},cause){super(message);this.name='ZQueryError';this.code=code;this.context=context;if(cause)this.cause=cause;}}let _errorHandler=null;function onError(handler){_errorHandler=typeof handler==='function'?handler:null;}function reportError(code,message,context={},cause){const err=cause instanceof ZQueryError?cause:new ZQueryError(code,message,context,cause);if(_errorHandler){try{_errorHandler(err);}catch{}}console.error(`[zQuery ${code}] ${message}`,context,cause||'');}function guardCallback(fn,code,context={}){return(...args)=>{try{return fn(...args);}catch(err){reportError(code,err.message||'Callback error',context,err);}};}function validate(value,name,expectedType){if(value===undefined||value===null){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" is required but got ${value}`);}if(expectedType&&typeof value!==expectedType){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" must be a ${expectedType}, got ${typeof value}`);}}function reactive(target,onChange,_path=''){if(typeof target!=='object'||target===null)return target;if(typeof onChange!=='function'){reportError(ErrorCode.REACTIVE_CALLBACK,'reactive() onChange must be a function',{received:typeof onChange});onChange=()=>{};}const proxyCache=new WeakMap();const handler={get(obj,key){if(key==='__isReactive')return true;if(key==='__raw')return obj;const value=obj[key];if(typeof value==='object'&&value!==null){if(proxyCache.has(value))return proxyCache.get(value);const childProxy=new Proxy(value,handler);proxyCache.set(value,childProxy);return childProxy;}return value;},set(obj,key,value){const old=obj[key];if(old===value)return true;obj[key]=value;if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,value,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,value,old},err);}return true;},deleteProperty(obj,key){const old=obj[key];delete obj[key];if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,undefined,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,old},err);}return true;}};return new Proxy(target,handler);}class Signal{constructor(value){this._value=value;this._subscribers=new Set();}get value(){if(Signal._activeEffect){this._subscribers.add(Signal._activeEffect);if(Signal._activeEffect._deps){Signal._activeEffect._deps.add(this);}}return this._value;}set value(newVal){if(this._value===newVal)return;this._value=newVal;this._notify();}peek(){return this._value;}_notify(){const subs=[...this._subscribers];for(let i=0;i<subs.length;i++){try{subs[i]();}catch(err){reportError(ErrorCode.SIGNAL_CALLBACK,'Signal subscriber threw',{signal:this},err);}}}subscribe(fn){this._subscribers.add(fn);return()=>this._subscribers.delete(fn);}toString(){return String(this._value);}}Signal._activeEffect=null;function signal(initial){return new Signal(initial);}function computed(fn){const s=new Signal(undefined);effect(()=>{const v=fn();if(v!==s._value){s._value=v;s._notify();}});return s;}function effect(fn){const execute=()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=execute;try{fn();}catch(err){reportError(ErrorCode.EFFECT_EXEC,'Effect function threw',{},err);}finally{Signal._activeEffect=null;}};execute._deps=new Set();execute();return()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}};}class ZQueryCollection{constructor(elements){this.elements=Array.isArray(elements)?elements:(elements?[elements]:[]);this.length=this.elements.length;this.elements.forEach((el,i)=>{this[i]=el;});}each(fn){this.elements.forEach((el,i)=>fn.call(el,i,el));return this;}map(fn){return this.elements.map((el,i)=>fn.call(el,i,el));}forEach(fn){this.elements.forEach((el,i)=>fn(el,i,this.elements));return this;}first(){return this.elements[0]||null;}last(){return this.elements[this.length-1]||null;}eq(i){return new ZQueryCollection(this.elements[i]?[this.elements[i]]:[]);}toArray(){return[...this.elements];}[Symbol.iterator](){return this.elements[Symbol.iterator]();}find(selector){const found=[];this.elements.forEach(el=>found.push(...el.querySelectorAll(selector)));return new ZQueryCollection(found);}parent(){const parents=[...new Set(this.elements.map(el=>el.parentElement).filter(Boolean))];return new ZQueryCollection(parents);}closest(selector){return new ZQueryCollection(this.elements.map(el=>el.closest(selector)).filter(Boolean));}children(selector){const kids=[];this.elements.forEach(el=>{kids.push(...(selector?el.querySelectorAll(`:scope > ${selector}`):el.children));});return new ZQueryCollection([...kids]);}siblings(selector){const sibs=[];this.elements.forEach(el=>{if(!el.parentElement)return;const all=[...el.parentElement.children].filter(c=>c!==el);sibs.push(...(selector?all.filter(c=>c.matches(selector)):all));});return new ZQueryCollection(sibs);}next(selector){const els=this.elements.map(el=>el.nextElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}prev(selector){const els=this.elements.map(el=>el.previousElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}nextAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}nextUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}prevAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}prevUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}parents(selector){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(!selector||parent.matches(selector))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}parentsUntil(selector,filter){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(selector&&parent.matches(selector))break;if(!filter||parent.matches(filter))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}contents(){const result=[];this.elements.forEach(el=>result.push(...el.childNodes));return new ZQueryCollection(result);}filter(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter(selector));}return new ZQueryCollection(this.elements.filter(el=>el.matches(selector)));}not(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter((el,i)=>!selector.call(el,i,el)));}return new ZQueryCollection(this.elements.filter(el=>!el.matches(selector)));}has(selector){return new ZQueryCollection(this.elements.filter(el=>el.querySelector(selector)));}is(selector){if(typeof selector==='function'){return this.elements.some((el,i)=>selector.call(el,i,el));}return this.elements.some(el=>el.matches(selector));}slice(start,end){return new ZQueryCollection(this.elements.slice(start,end));}add(selector,context){const toAdd=(selector instanceof ZQueryCollection)?selector.elements:(selector instanceof Node)?[selector]:Array.from((context||document).querySelectorAll(selector));return new ZQueryCollection([...this.elements,...toAdd]);}get(index){if(index===undefined)return[...this.elements];return index<0?this.elements[this.length+index]:this.elements[index];}index(selector){if(selector===undefined){const el=this.first();if(!el||!el.parentElement)return-1;return Array.from(el.parentElement.children).indexOf(el);}const target=(typeof selector==='string')?document.querySelector(selector):selector;return this.elements.indexOf(target);}addClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(...classes);return this;}removeClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(...classes);return this;}toggleClass(...args){const force=typeof args[args.length-1]==='boolean'?args.pop():undefined;if(args.length===1&&args[0].indexOf(' ')===-1){const c=args[0];for(let i=0;i<this.elements.length;i++){force!==undefined?this.elements[i].classList.toggle(c,force):this.elements[i].classList.toggle(c);}return this;}const classes=args.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++){const el=this.elements[i];for(let j=0;j<classes.length;j++){force!==undefined?el.classList.toggle(classes[j],force):el.classList.toggle(classes[j]);}}return this;}hasClass(name){return this.first()?.classList.contains(name)||false;}attr(name,value){if(typeof name==='object'&&name!==null){return this.each((_,el)=>{for(const[k,v]of Object.entries(name))el.setAttribute(k,v);});}if(value===undefined)return this.first()?.getAttribute(name);return this.each((_,el)=>el.setAttribute(name,value));}removeAttr(name){return this.each((_,el)=>el.removeAttribute(name));}prop(name,value){if(value===undefined)return this.first()?.[name];return this.each((_,el)=>{el[name]=value;});}data(key,value){if(value===undefined){if(key===undefined)return this.first()?.dataset;const raw=this.first()?.dataset[key];try{return JSON.parse(raw);}catch{return raw;}}return this.each((_,el)=>{el.dataset[key]=typeof value==='object'?JSON.stringify(value):value;});}css(props,value){if(typeof props==='string'&&value!==undefined){return this.each((_,el)=>{el.style[props]=value;});}if(typeof props==='string'){const el=this.first();return el?getComputedStyle(el)[props]:undefined;}return this.each((_,el)=>Object.assign(el.style,props));}width(){return this.first()?.getBoundingClientRect().width;}height(){return this.first()?.getBoundingClientRect().height;}offset(){const r=this.first()?.getBoundingClientRect();return r?{top:r.top+window.scrollY,left:r.left+window.scrollX,width:r.width,height:r.height}:null;}position(){const el=this.first();return el?{top:el.offsetTop,left:el.offsetLeft}:null;}scrollTop(value){if(value===undefined){const el=this.first();return el===window?window.scrollY:el?.scrollTop;}return this.each((_,el)=>{if(el===window)window.scrollTo(window.scrollX,value);else el.scrollTop=value;});}scrollLeft(value){if(value===undefined){const el=this.first();return el===window?window.scrollX:el?.scrollLeft;}return this.each((_,el)=>{if(el===window)window.scrollTo(value,window.scrollY);else el.scrollLeft=value;});}innerWidth(){const el=this.first();return el?.clientWidth;}innerHeight(){const el=this.first();return el?.clientHeight;}outerWidth(includeMargin=false){const el=this.first();if(!el)return undefined;let w=el.offsetWidth;if(includeMargin){const style=getComputedStyle(el);w+=parseFloat(style.marginLeft)+parseFloat(style.marginRight);}return w;}outerHeight(includeMargin=false){const el=this.first();if(!el)return undefined;let h=el.offsetHeight;if(includeMargin){const style=getComputedStyle(el);h+=parseFloat(style.marginTop)+parseFloat(style.marginBottom);}return h;}html(content){if(content===undefined)return this.first()?.innerHTML;return this.each((_,el)=>{if(el.childNodes.length>0){_morph(el,content);}else{el.innerHTML=content;}});}morph(content){return this.each((_,el)=>{_morph(el,content);});}text(content){if(content===undefined)return this.first()?.textContent;return this.each((_,el)=>{el.textContent=content;});}val(value){if(value===undefined)return this.first()?.value;return this.each((_,el)=>{el.value=value;});}append(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforeend',content);else if(content instanceof ZQueryCollection)content.each((__,c)=>el.appendChild(c));else if(content instanceof Node)el.appendChild(content);});}prepend(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterbegin',content);else if(content instanceof Node)el.insertBefore(content,el.firstChild);});}after(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterend',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el.nextSibling);});}before(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforebegin',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el);});}wrap(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);if(!w||!el.parentNode)return;el.parentNode.insertBefore(w,el);w.appendChild(el);});}remove(){return this.each((_,el)=>el.remove());}empty(){return this.each((_,el)=>{el.textContent='';});}clone(deep=true){return new ZQueryCollection(this.elements.map(el=>el.cloneNode(deep)));}replaceWith(content){return this.each((_,el)=>{if(typeof content==='string'){_morphElement(el,content);}else if(content instanceof Node){el.parentNode.replaceChild(content,el);}});}appendTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.appendChild(el));return this;}prependTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.insertBefore(el,dest.firstChild));return this;}insertAfter(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref.nextSibling));return this;}insertBefore(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref));return this;}replaceAll(target){const targets=typeof target==='string'?Array.from(document.querySelectorAll(target)):target instanceof ZQueryCollection?target.elements:[target];targets.forEach((t,i)=>{const nodes=i===0?this.elements:this.elements.map(el=>el.cloneNode(true));nodes.forEach(el=>t.parentNode.insertBefore(el,t));t.remove();});return this;}unwrap(selector){this.elements.forEach(el=>{const parent=el.parentElement;if(!parent||parent===document.body)return;if(selector&&!parent.matches(selector))return;parent.replaceWith(...parent.childNodes);});return this;}wrapAll(wrapper){const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);const first=this.first();if(!first)return this;first.parentNode.insertBefore(w,first);this.each((_,el)=>w.appendChild(el));return this;}wrapInner(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);while(el.firstChild)w.appendChild(el.firstChild);el.appendChild(w);});}detach(){return this.each((_,el)=>el.remove());}show(display=''){return this.each((_,el)=>{el.style.display=display;});}hide(){return this.each((_,el)=>{el.style.display='none';});}toggle(display=''){return this.each((_,el)=>{const hidden=el.style.display==='none'||(el.style.display!==''?false:getComputedStyle(el).display==='none');el.style.display=hidden?display:'none';});}on(event,selectorOrHandler,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{if(typeof selectorOrHandler==='function'){el.addEventListener(evt,selectorOrHandler);}else if(typeof selectorOrHandler==='string'){const wrapper=(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target&&el.contains(target))handler.call(target,e);};wrapper._zqOriginal=handler;wrapper._zqSelector=selectorOrHandler;el.addEventListener(evt,wrapper);if(!el._zqDelegated)el._zqDelegated=[];el._zqDelegated.push({evt,wrapper});}});});}off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{el.removeEventListener(evt,handler);if(el._zqDelegated){el._zqDelegated=el._zqDelegated.filter(d=>{if(d.evt===evt&&d.wrapper._zqOriginal===handler){el.removeEventListener(evt,d.wrapper);return false;}return true;});}});});}one(event,handler){return this.each((_,el)=>{el.addEventListener(event,handler,{once:true});});}trigger(event,detail){return this.each((_,el)=>{el.dispatchEvent(new CustomEvent(event,{detail,bubbles:true,cancelable:true}));});}click(fn){return fn?this.on('click',fn):this.trigger('click');}submit(fn){return fn?this.on('submit',fn):this.trigger('submit');}focus(){this.first()?.focus();return this;}blur(){this.first()?.blur();return this;}hover(enterFn,leaveFn){this.on('mouseenter',enterFn);return this.on('mouseleave',leaveFn||enterFn);}animate(props,duration=300,easing='ease'){if(this.length===0)return Promise.resolve(this);return new Promise(resolve=>{let resolved=false;const count={done:0};const listeners=[];this.each((_,el)=>{el.style.transition=`all ${duration}ms ${easing}`;requestAnimationFrame(()=>{Object.assign(el.style,props);const onEnd=()=>{el.removeEventListener('transitionend',onEnd);el.style.transition='';if(!resolved&&++count.done>=this.length){resolved=true;resolve(this);}};el.addEventListener('transitionend',onEnd);listeners.push({el,onEnd});});});setTimeout(()=>{if(!resolved){resolved=true;for(const{el,onEnd}of listeners){el.removeEventListener('transitionend',onEnd);el.style.transition='';}resolve(this);}},duration+50);});}fadeIn(duration=300){return this.css({opacity:'0',display:''}).animate({opacity:'1'},duration);}fadeOut(duration=300){return this.animate({opacity:'0'},duration).then(col=>col.hide());}fadeToggle(duration=300){return Promise.all(this.elements.map(el=>{const cs=getComputedStyle(el);const visible=cs.opacity!=='0'&&cs.display!=='none';const col=new ZQueryCollection([el]);return visible?col.fadeOut(duration):col.fadeIn(duration);})).then(()=>this);}fadeTo(duration,opacity){return this.animate({opacity:String(opacity)},duration);}slideDown(duration=300){return this.each((_,el)=>{el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideUp(duration=300){return this.each((_,el)=>{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideToggle(duration=300){return this.each((_,el)=>{if(el.style.display==='none'||getComputedStyle(el).display==='none'){el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}else{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}});}serialize(){const form=this.first();if(!form||form.tagName!=='FORM')return'';return new URLSearchParams(new FormData(form)).toString();}serializeObject(){const form=this.first();if(!form||form.tagName!=='FORM')return{};const obj={};new FormData(form).forEach((v,k)=>{if(obj[k]!==undefined){if(!Array.isArray(obj[k]))obj[k]=[obj[k]];obj[k].push(v);}else{obj[k]=v;}});return obj;}}function createFragment(html){const tpl=document.createElement('template');tpl.innerHTML=html.trim();return tpl.content;}function query(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}function queryAll(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}query.id=(id)=>document.getElementById(id);query.class=(name)=>document.querySelector(`.${name}`);query.classes=(name)=>new ZQueryCollection(Array.from(document.getElementsByClassName(name)));query.tag=(name)=>new ZQueryCollection(Array.from(document.getElementsByTagName(name)));Object.defineProperty(query,'name',{value:(name)=>new ZQueryCollection(Array.from(document.getElementsByName(name))),writable:true,configurable:true});query.children=(parentId)=>{const p=document.getElementById(parentId);return new ZQueryCollection(p?Array.from(p.children):[]);};query.create=(tag,attrs={},...children)=>{const el=document.createElement(tag);for(const[k,v]of Object.entries(attrs)){if(k==='class')el.className=v;else if(k==='style'&&typeof v==='object')Object.assign(el.style,v);else if(k.startsWith('on')&&typeof v==='function')el.addEventListener(k.slice(2),v);else if(k==='data'&&typeof v==='object')Object.entries(v).forEach(([dk,dv])=>{el.dataset[dk]=dv;});else el.setAttribute(k,v);}children.flat().forEach(child=>{if(typeof child==='string')el.appendChild(document.createTextNode(child));else if(child instanceof Node)el.appendChild(child);});return new ZQueryCollection(el);};query.ready=(fn)=>{if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);};query.on=(event,selectorOrHandler,handler)=>{if(typeof selectorOrHandler==='function'){document.addEventListener(event,selectorOrHandler);return;}if(typeof selectorOrHandler==='object'&&typeof selectorOrHandler.addEventListener==='function'){selectorOrHandler.addEventListener(event,handler);return;}document.addEventListener(event,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target)handler.call(target,e);});};query.off=(event,handler)=>{document.removeEventListener(event,handler);};query.fn=ZQueryCollection.prototype;const T={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7};const PREC={'??':2,'||':3,'&&':4,'==':8,'!=':8,'===':8,'!==':8,'<':9,'>':9,'<=':9,'>=':9,'instanceof':9,'in':9,'+':11,'-':11,'*':12,'/':12,'%':12,};const KEYWORDS=new Set(['true','false','null','undefined','typeof','instanceof','in','new','void']);function tokenize(expr){const tokens=[];let i=0;const len=expr.length;while(i<len){const ch=expr[i];if(ch===' '||ch==='\t'||ch==='\n'||ch==='\r'){i++;continue;}if((ch>='0'&&ch<='9')||(ch==='.'&&i+1<len&&expr[i+1]>='0'&&expr[i+1]<='9')){let num='';if(ch==='0'&&i+1<len&&(expr[i+1]==='x'||expr[i+1]==='X')){num='0x';i+=2;while(i<len&&/[0-9a-fA-F]/.test(expr[i]))num+=expr[i++];}else{while(i<len&&((expr[i]>='0'&&expr[i]<='9')||expr[i]==='.'))num+=expr[i++];if(i<len&&(expr[i]==='e'||expr[i]==='E')){num+=expr[i++];if(i<len&&(expr[i]==='+'||expr[i]==='-'))num+=expr[i++];while(i<len&&expr[i]>='0'&&expr[i]<='9')num+=expr[i++];}}tokens.push({t:T.NUM,v:Number(num)});continue;}if(ch==="'"||ch==='"'){const quote=ch;let str='';i++;while(i<len&&expr[i]!==quote){if(expr[i]==='\\'&&i+1<len){const esc=expr[++i];if(esc==='n')str+='\n';else if(esc==='t')str+='\t';else if(esc==='r')str+='\r';else if(esc==='\\')str+='\\';else if(esc===quote)str+=quote;else str+=esc;}else{str+=expr[i];}i++;}i++;tokens.push({t:T.STR,v:str});continue;}if(ch==='`'){const parts=[];let str='';i++;while(i<len&&expr[i]!=='`'){if(expr[i]==='$'&&i+1<len&&expr[i+1]==='{'){parts.push(str);str='';i+=2;let depth=1;let inner='';while(i<len&&depth>0){if(expr[i]==='{')depth++;else if(expr[i]==='}'){depth--;if(depth===0)break;}inner+=expr[i++];}i++;parts.push({expr:inner});}else{if(expr[i]==='\\'&&i+1<len){str+=expr[++i];}else str+=expr[i];i++;}}i++;parts.push(str);tokens.push({t:T.TMPL,v:parts});continue;}if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||ch==='_'||ch==='$'){let ident='';while(i<len&&/[\w$]/.test(expr[i]))ident+=expr[i++];tokens.push({t:T.IDENT,v:ident});continue;}const two=expr.slice(i,i+3);if(two==='==='||two==='!=='||two==='?.'){if(two==='?.'){tokens.push({t:T.OP,v:'?.'});i+=2;}else{tokens.push({t:T.OP,v:two});i+=3;}continue;}const pair=expr.slice(i,i+2);if(pair==='=='||pair==='!='||pair==='<='||pair==='>='||pair==='&&'||pair==='||'||pair==='??'||pair==='?.'||pair==='=>'){tokens.push({t:T.OP,v:pair});i+=2;continue;}if('+-*/%'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('<>=!'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('()[]{},.?:'.includes(ch)){tokens.push({t:T.PUNC,v:ch});i++;continue;}i++;}tokens.push({t:T.EOF,v:null});return tokens;}class Parser{constructor(tokens,scope){this.tokens=tokens;this.pos=0;this.scope=scope;}peek(){return this.tokens[this.pos];}next(){return this.tokens[this.pos++];}expect(type,val){const t=this.next();if(t.t!==type||(val!==undefined&&t.v!==val)){throw new Error(`Expected ${val || type} but got ${t.v}`);}return t;}match(type,val){const t=this.peek();if(t.t===type&&(val===undefined||t.v===val)){return this.next();}return null;}parse(){const result=this.parseExpression(0);return result;}parseExpression(minPrec){let left=this.parseUnary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='?'){if(this.tokens[this.pos+1]?.v!=='.'){if(1<=minPrec)break;this.next();const truthy=this.parseExpression(0);this.expect(T.PUNC,':');const falsy=this.parseExpression(1);left={type:'ternary',cond:left,truthy,falsy};continue;}}if(tok.t===T.OP&&tok.v in PREC){const prec=PREC[tok.v];if(prec<=minPrec)break;this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}if(tok.t===T.IDENT&&(tok.v==='instanceof'||tok.v==='in')&&PREC[tok.v]>minPrec){const prec=PREC[tok.v];this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}break;}return left;}parseUnary(){const tok=this.peek();if(tok.t===T.IDENT&&tok.v==='typeof'){this.next();const arg=this.parseUnary();return{type:'typeof',arg};}if(tok.t===T.IDENT&&tok.v==='void'){this.next();this.parseUnary();return{type:'literal',value:undefined};}if(tok.t===T.OP&&tok.v==='!'){this.next();const arg=this.parseUnary();return{type:'not',arg};}if(tok.t===T.OP&&(tok.v==='-'||tok.v==='+')){this.next();const arg=this.parseUnary();return{type:'unary',op:tok.v,arg};}return this.parsePostfix();}parsePostfix(){let left=this.parsePrimary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='.'){this.next();const prop=this.next();left={type:'member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.OP&&tok.v==='?.'){this.next();const next=this.peek();if(next.t===T.PUNC&&next.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'optional_member',obj:left,prop,computed:true};}else if(next.t===T.PUNC&&next.v==='('){left={type:'optional_call',callee:left,args:this._parseArgs()};}else{const prop=this.next();left={type:'optional_member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}}continue;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'member',obj:left,prop,computed:true};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.PUNC&&tok.v==='('){left=this._parseCall(left);continue;}break;}return left;}_parseCall(callee){const args=this._parseArgs();return{type:'call',callee,args};}_parseArgs(){this.expect(T.PUNC,'(');const args=[];while(!(this.peek().t===T.PUNC&&this.peek().v===')')&&this.peek().t!==T.EOF){args.push(this.parseExpression(0));if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,')');return args;}parsePrimary(){const tok=this.peek();if(tok.t===T.NUM){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.STR){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.TMPL){this.next();return{type:'template',parts:tok.v};}if(tok.t===T.PUNC&&tok.v==='('){const savedPos=this.pos;this.next();const params=[];let couldBeArrow=true;if(this.peek().t===T.PUNC&&this.peek().v===')'){}else{while(couldBeArrow){const p=this.peek();if(p.t===T.IDENT&&!KEYWORDS.has(p.v)){params.push(this.next().v);if(this.peek().t===T.PUNC&&this.peek().v===','){this.next();}else{break;}}else{couldBeArrow=false;}}}if(couldBeArrow&&this.peek().t===T.PUNC&&this.peek().v===')'){this.next();if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params,body};}}this.pos=savedPos;this.next();const expr=this.parseExpression(0);this.expect(T.PUNC,')');return expr;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const elements=[];while(!(this.peek().t===T.PUNC&&this.peek().v===']')&&this.peek().t!==T.EOF){elements.push(this.parseExpression(0));if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,']');return{type:'array',elements};}if(tok.t===T.PUNC&&tok.v==='{'){this.next();const properties=[];while(!(this.peek().t===T.PUNC&&this.peek().v==='}')&&this.peek().t!==T.EOF){const keyTok=this.next();let key;if(keyTok.t===T.IDENT||keyTok.t===T.STR)key=keyTok.v;else if(keyTok.t===T.NUM)key=String(keyTok.v);else throw new Error('Invalid object key: '+keyTok.v);if(this.peek().t===T.PUNC&&(this.peek().v===','||this.peek().v==='}')){properties.push({key,value:{type:'ident',name:key}});}else{this.expect(T.PUNC,':');properties.push({key,value:this.parseExpression(0)});}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,'}');return{type:'object',properties};}if(tok.t===T.IDENT){this.next();if(tok.v==='true')return{type:'literal',value:true};if(tok.v==='false')return{type:'literal',value:false};if(tok.v==='null')return{type:'literal',value:null};if(tok.v==='undefined')return{type:'literal',value:undefined};if(tok.v==='new'){const classExpr=this.parsePostfix();let args=[];if(this.peek().t===T.PUNC&&this.peek().v==='('){args=this._parseArgs();}return{type:'new',callee:classExpr,args};}if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params:[tok.v],body};}return{type:'ident',name:tok.v};}this.next();return{type:'literal',value:undefined};}}const SAFE_ARRAY_METHODS=new Set(['length','map','filter','find','findIndex','some','every','reduce','reduceRight','forEach','includes','indexOf','lastIndexOf','join','slice','concat','flat','flatMap','reverse','sort','fill','keys','values','entries','at','toString',]);const SAFE_STRING_METHODS=new Set(['length','charAt','charCodeAt','includes','indexOf','lastIndexOf','slice','substring','trim','trimStart','trimEnd','toLowerCase','toUpperCase','split','replace','replaceAll','match','search','startsWith','endsWith','padStart','padEnd','repeat','at','toString','valueOf',]);const SAFE_NUMBER_METHODS=new Set(['toFixed','toPrecision','toString','valueOf',]);const SAFE_OBJECT_METHODS=new Set(['hasOwnProperty','toString','valueOf',]);const SAFE_MATH_PROPS=new Set(['PI','E','LN2','LN10','LOG2E','LOG10E','SQRT2','SQRT1_2','abs','ceil','floor','round','trunc','max','min','pow','sqrt','sign','random','log','log2','log10',]);const SAFE_JSON_PROPS=new Set(['parse','stringify']);function _isSafeAccess(obj,prop){const BLOCKED=new Set(['constructor','__proto__','prototype','__defineGetter__','__defineSetter__','__lookupGetter__','__lookupSetter__','call','apply','bind',]);if(typeof prop==='string'&&BLOCKED.has(prop))return false;if(obj!==null&&obj!==undefined&&(typeof obj==='object'||typeof obj==='function'))return true;if(typeof obj==='string')return SAFE_STRING_METHODS.has(prop);if(typeof obj==='number')return SAFE_NUMBER_METHODS.has(prop);return false;}function evaluate(node,scope){if(!node)return undefined;switch(node.type){case'literal':return node.value;case'ident':{const name=node.name;for(const layer of scope){if(layer&&typeof layer==='object'&&name in layer){return layer[name];}}if(name==='Math')return Math;if(name==='JSON')return JSON;if(name==='Date')return Date;if(name==='Array')return Array;if(name==='Object')return Object;if(name==='String')return String;if(name==='Number')return Number;if(name==='Boolean')return Boolean;if(name==='parseInt')return parseInt;if(name==='parseFloat')return parseFloat;if(name==='isNaN')return isNaN;if(name==='isFinite')return isFinite;if(name==='Infinity')return Infinity;if(name==='NaN')return NaN;if(name==='encodeURIComponent')return encodeURIComponent;if(name==='decodeURIComponent')return decodeURIComponent;if(name==='console')return console;return undefined;}case'template':{let result='';for(const part of node.parts){if(typeof part==='string'){result+=part;}else if(part&&part.expr){result+=String(safeEval(part.expr,scope)??'');}}return result;}case'member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'optional_member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'call':{const result=_resolveCall(node,scope,false);return result;}case'optional_call':{const callee=evaluate(node.callee,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;const args=node.args.map(a=>evaluate(a,scope));return callee(...args);}case'new':{const Ctor=evaluate(node.callee,scope);if(typeof Ctor!=='function')return undefined;if(Ctor===Date||Ctor===Array||Ctor===Map||Ctor===Set||Ctor===RegExp||Ctor===Error||Ctor===URL||Ctor===URLSearchParams){const args=node.args.map(a=>evaluate(a,scope));return new Ctor(...args);}return undefined;}case'binary':return _evalBinary(node,scope);case'unary':{const val=evaluate(node.arg,scope);return node.op==='-'?-val:+val;}case'not':return!evaluate(node.arg,scope);case'typeof':{try{return typeof evaluate(node.arg,scope);}catch{return'undefined';}}case'ternary':{const cond=evaluate(node.cond,scope);return cond?evaluate(node.truthy,scope):evaluate(node.falsy,scope);}case'array':return node.elements.map(e=>evaluate(e,scope));case'object':{const obj={};for(const{key,value}of node.properties){obj[key]=evaluate(value,scope);}return obj;}case'arrow':{const paramNames=node.params;const bodyNode=node.body;const closedScope=scope;return function(...args){const arrowScope={};paramNames.forEach((name,i)=>{arrowScope[name]=args[i];});return evaluate(bodyNode,[arrowScope,...closedScope]);};}default:return undefined;}}function _resolveCall(node,scope){const callee=node.callee;const args=node.args.map(a=>evaluate(a,scope));if(callee.type==='member'||callee.type==='optional_member'){const obj=evaluate(callee.obj,scope);if(obj==null)return undefined;const prop=callee.computed?evaluate(callee.prop,scope):callee.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}const fn=evaluate(callee,scope);if(typeof fn!=='function')return undefined;return fn(...args);}function _evalBinary(node,scope){if(node.op==='&&'){const left=evaluate(node.left,scope);return left?evaluate(node.right,scope):left;}if(node.op==='||'){const left=evaluate(node.left,scope);return left?left:evaluate(node.right,scope);}if(node.op==='??'){const left=evaluate(node.left,scope);return left!=null?left:evaluate(node.right,scope);}const left=evaluate(node.left,scope);const right=evaluate(node.right,scope);switch(node.op){case'+':return left+right;case'-':return left-right;case'*':return left*right;case'/':return left/right;case'%':return left%right;case'==':return left==right;case'!=':return left!=right;case'===':return left===right;case'!==':return left!==right;case'<':return left<right;case'>':return left>right;case'<=':return left<=right;case'>=':return left>=right;case'instanceof':return left instanceof right;case'in':return left in right;default:return undefined;}}const _astCache=new Map();const _AST_CACHE_MAX=512;function safeEval(expr,scope){try{const trimmed=expr.trim();if(!trimmed)return undefined;if(/^[a-zA-Z_$][\w$]*$/.test(trimmed)){for(const layer of scope){if(layer&&typeof layer==='object'&&trimmed in layer){return layer[trimmed];}}}let ast=_astCache.get(trimmed);if(!ast){const tokens=tokenize(trimmed);const parser=new Parser(tokens,scope);ast=parser.parse();if(_astCache.size>=_AST_CACHE_MAX){const first=_astCache.keys().next().value;_astCache.delete(first);}_astCache.set(trimmed,ast);}return evaluate(ast,scope);}catch(err){if(typeof console!=='undefined'&&console.debug){console.debug(`[zQuery EXPR_EVAL] Failed to evaluate: "${expr}"`,err.message);}return undefined;}}let _tpl=null;function _getTemplate(){if(!_tpl)_tpl=document.createElement('template');return _tpl;}function morph(rootEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newRoot=tpl.content;const tempDiv=document.createElement('div');while(newRoot.firstChild)tempDiv.appendChild(newRoot.firstChild);_morphChildren(rootEl,tempDiv);if(start)window.__zqMorphHook(rootEl,performance.now()-start);}function morphElement(oldEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newEl=tpl.content.firstElementChild;if(!newEl)return oldEl;if(oldEl.nodeName===newEl.nodeName){_morphAttributes(oldEl,newEl);_morphChildren(oldEl,newEl);if(start)window.__zqMorphHook(oldEl,performance.now()-start);return oldEl;}const clone=newEl.cloneNode(true);oldEl.parentNode.replaceChild(clone,oldEl);if(start)window.__zqMorphHook(clone,performance.now()-start);return clone;}function _morphChildren(oldParent,newParent){const oldCN=oldParent.childNodes;const newCN=newParent.childNodes;const oldLen=oldCN.length;const newLen=newCN.length;const oldChildren=new Array(oldLen);const newChildren=new Array(newLen);for(let i=0;i<oldLen;i++)oldChildren[i]=oldCN[i];for(let i=0;i<newLen;i++)newChildren[i]=newCN[i];let hasKeys=false;let oldKeyMap,newKeyMap;for(let i=0;i<oldLen;i++){if(_getKey(oldChildren[i])!=null){hasKeys=true;break;}}if(!hasKeys){for(let i=0;i<newLen;i++){if(_getKey(newChildren[i])!=null){hasKeys=true;break;}}}if(hasKeys){oldKeyMap=new Map();newKeyMap=new Map();for(let i=0;i<oldLen;i++){const key=_getKey(oldChildren[i]);if(key!=null)oldKeyMap.set(key,i);}for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null)newKeyMap.set(key,i);}_morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap);}else{_morphChildrenUnkeyed(oldParent,oldChildren,newChildren);}}function _morphChildrenUnkeyed(oldParent,oldChildren,newChildren){const oldLen=oldChildren.length;const newLen=newChildren.length;const minLen=oldLen<newLen?oldLen:newLen;for(let i=0;i<minLen;i++){_morphNode(oldParent,oldChildren[i],newChildren[i]);}if(newLen>oldLen){for(let i=oldLen;i<newLen;i++){oldParent.appendChild(newChildren[i].cloneNode(true));}}if(oldLen>newLen){for(let i=oldLen-1;i>=newLen;i--){oldParent.removeChild(oldChildren[i]);}}}function _morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap){const consumed=new Set();const newLen=newChildren.length;const matched=new Array(newLen);for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null&&oldKeyMap.has(key)){const oldIdx=oldKeyMap.get(key);matched[i]=oldChildren[oldIdx];consumed.add(oldIdx);}else{matched[i]=null;}}for(let i=oldChildren.length-1;i>=0;i--){if(!consumed.has(i)){const key=_getKey(oldChildren[i]);if(key!=null&&!newKeyMap.has(key)){oldParent.removeChild(oldChildren[i]);}}}const oldIndices=[];for(let i=0;i<newLen;i++){if(matched[i]){const key=_getKey(newChildren[i]);oldIndices.push(oldKeyMap.get(key));}else{oldIndices.push(-1);}}const lisSet=_lis(oldIndices);let cursor=oldParent.firstChild;const unkeyedOld=[];for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)&&_getKey(oldChildren[i])==null){unkeyedOld.push(oldChildren[i]);}}let unkeyedIdx=0;for(let i=0;i<newLen;i++){const newNode=newChildren[i];const newKey=_getKey(newNode);let oldNode=matched[i];if(!oldNode&&newKey==null){oldNode=unkeyedOld[unkeyedIdx++]||null;}if(oldNode){if(!lisSet.has(i)){oldParent.insertBefore(oldNode,cursor);}const nextSib=oldNode.nextSibling;_morphNode(oldParent,oldNode,newNode);cursor=nextSib;}else{const clone=newNode.cloneNode(true);if(cursor){oldParent.insertBefore(clone,cursor);}else{oldParent.appendChild(clone);}}}while(unkeyedIdx<unkeyedOld.length){const leftover=unkeyedOld[unkeyedIdx++];if(leftover.parentNode===oldParent){oldParent.removeChild(leftover);}}for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)){const node=oldChildren[i];if(node.parentNode===oldParent&&_getKey(node)!=null&&!newKeyMap.has(_getKey(node))){oldParent.removeChild(node);}}}}function _lis(arr){const len=arr.length;const result=new Set();if(len===0)return result;const tails=[];const prev=new Array(len).fill(-1);const tailIndices=[];for(let i=0;i<len;i++){if(arr[i]===-1)continue;const val=arr[i];let lo=0,hi=tails.length;while(lo<hi){const mid=(lo+hi)>>1;if(tails[mid]<val)lo=mid+1;else hi=mid;}tails[lo]=val;tailIndices[lo]=i;prev[i]=lo>0?tailIndices[lo-1]:-1;}let k=tailIndices[tails.length-1];for(let i=tails.length-1;i>=0;i--){result.add(k);k=prev[k];}return result;}function _morphNode(parent,oldNode,newNode){if(oldNode.nodeType===3||oldNode.nodeType===8){if(newNode.nodeType===oldNode.nodeType){if(oldNode.nodeValue!==newNode.nodeValue){oldNode.nodeValue=newNode.nodeValue;}return;}parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType!==newNode.nodeType||oldNode.nodeName!==newNode.nodeName){parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType===1){if(oldNode.hasAttribute('z-skip'))return;if(oldNode.isEqualNode(newNode))return;_morphAttributes(oldNode,newNode);const tag=oldNode.nodeName;if(tag==='INPUT'){_syncInputValue(oldNode,newNode);return;}if(tag==='TEXTAREA'){if(oldNode.value!==newNode.textContent){oldNode.value=newNode.textContent||'';}return;}if(tag==='SELECT'){_morphChildren(oldNode,newNode);if(oldNode.value!==newNode.value){oldNode.value=newNode.value;}return;}_morphChildren(oldNode,newNode);}}function _morphAttributes(oldEl,newEl){const newAttrs=newEl.attributes;const oldAttrs=oldEl.attributes;const newLen=newAttrs.length;const oldLen=oldAttrs.length;if(newLen===oldLen){let same=true;for(let i=0;i<newLen;i++){const na=newAttrs[i];if(oldEl.getAttribute(na.name)!==na.value){same=false;break;}}if(same){for(let i=0;i<oldLen;i++){if(!newEl.hasAttribute(oldAttrs[i].name)){same=false;break;}}}if(same)return;}const newNames=new Set();for(let i=0;i<newLen;i++){const attr=newAttrs[i];newNames.add(attr.name);if(oldEl.getAttribute(attr.name)!==attr.value){oldEl.setAttribute(attr.name,attr.value);}}const oldNames=new Array(oldLen);for(let i=0;i<oldLen;i++)oldNames[i]=oldAttrs[i].name;for(let i=oldNames.length-1;i>=0;i--){if(!newNames.has(oldNames[i])){oldEl.removeAttribute(oldNames[i]);}}}function _syncInputValue(oldEl,newEl){const type=(oldEl.type||'').toLowerCase();if(type==='checkbox'||type==='radio'){if(oldEl.checked!==newEl.checked)oldEl.checked=newEl.checked;}else{if(oldEl.value!==(newEl.getAttribute('value')||'')){oldEl.value=newEl.getAttribute('value')||'';}}if(oldEl.disabled!==newEl.disabled)oldEl.disabled=newEl.disabled;}function _getKey(node){if(node.nodeType!==1)return null;const zk=node.getAttribute('z-key');if(zk)return zk;if(node.id)return'\0id:'+node.id;const ds=node.dataset;if(ds){if(ds.id)return'\0data-id:'+ds.id;if(ds.key)return'\0data-key:'+ds.key;}return null;}const _registry=new Map();const _instances=new Map();const _resourceCache=new Map();let _uid=0;if(typeof document!=='undefined'&&!document.querySelector('[data-zq-cloak]')){const _s=document.createElement('style');_s.textContent='[z-cloak]{display:none!important}*,*::before,*::after{-webkit-tap-highlight-color:transparent}';_s.setAttribute('data-zq-cloak','');document.head.appendChild(_s);}const _debounceTimers=new WeakMap();const _throttleTimers=new WeakMap();function _fetchResource(url){if(_resourceCache.has(url))return _resourceCache.get(url);if(typeof window!=='undefined'&&window.__zqInline){for(const[path,content]of Object.entries(window.__zqInline)){if(url===path||url.endsWith('/'+path)||url.endsWith('\\'+path)){const resolved=Promise.resolve(content);_resourceCache.set(url,resolved);return resolved;}}}let resolvedUrl=url;if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){try{const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');resolvedUrl=new URL(url,root).href;}catch{}}const promise=fetch(resolvedUrl).then(res=>{if(!res.ok)throw new Error(`zQuery: Failed to load resource "${url}" (${res.status})`);return res.text();});_resourceCache.set(url,promise);return promise;}function _resolveUrl(url,base){if(!base||!url||typeof url!=='string')return url;if(url.startsWith('/')||url.includes('://')||url.startsWith('//'))return url;try{if(base.includes('://')){return new URL(url,base).href;}const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');const absBase=new URL(base.endsWith('/')?base:base+'/',root).href;return new URL(url,absBase).href;}catch{return url;}}let _ownScriptUrl;try{if(typeof document!=='undefined'&&document.currentScript&&document.currentScript.src){_ownScriptUrl=document.currentScript.src.replace(/[?#].*$/,'');}}catch{}function _detectCallerBase(){try{const stack=new Error().stack||'';const urls=stack.match(/(?:https?|file):\/\/[^\s\)]+/g)||[];for(const raw of urls){const url=raw.replace(/:\d+:\d+$/,'').replace(/:\d+$/,'');if(/zquery(\.min)?\.js$/i.test(url))continue;if(_ownScriptUrl&&url.replace(/[?#].*$/,'')===_ownScriptUrl)continue;return url.replace(/\/[^/]*$/,'/');}}catch{}return undefined;}function _getPath(obj,path){return path.split('.').reduce((o,k)=>o?.[k],obj);}function _setPath(obj,path,value){const keys=path.split('.');const last=keys.pop();const target=keys.reduce((o,k)=>(o&&typeof o==='object')?o[k]:undefined,obj);if(target&&typeof target==='object')target[last]=value;}class Component{constructor(el,definition,props={}){this._uid=++_uid;this._el=el;this._def=definition;this._mounted=false;this._destroyed=false;this._updateQueued=false;this._listeners=[];this._watchCleanups=[];this.refs={};this._slotContent={};const defaultSlotNodes=[];[...el.childNodes].forEach(node=>{if(node.nodeType===1&&node.hasAttribute('slot')){const slotName=node.getAttribute('slot');if(!this._slotContent[slotName])this._slotContent[slotName]='';this._slotContent[slotName]+=node.outerHTML;}else if(node.nodeType===1||(node.nodeType===3&&node.textContent.trim())){defaultSlotNodes.push(node.nodeType===1?node.outerHTML:node.textContent);}});if(defaultSlotNodes.length){this._slotContent['default']=defaultSlotNodes.join('');}this.props=Object.freeze({...props});const initialState=typeof definition.state==='function'?definition.state():{...(definition.state||{})};this.state=reactive(initialState,(key,value,old)=>{if(!this._destroyed){this._runWatchers(key,value,old);this._scheduleUpdate();}});this.computed={};if(definition.computed){for(const[name,fn]of Object.entries(definition.computed)){Object.defineProperty(this.computed,name,{get:()=>fn.call(this,this.state.__raw||this.state),enumerable:true});}}for(const[key,val]of Object.entries(definition)){if(typeof val==='function'&&!_reservedKeys.has(key)){this[key]=val.bind(this);}}if(definition.init){try{definition.init.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${definition._name}" init() threw`,{component:definition._name},err);}}if(definition.watch){this._prevWatchValues={};for(const key of Object.keys(definition.watch)){this._prevWatchValues[key]=_getPath(this.state.__raw||this.state,key);}}}_runWatchers(changedKey,value,old){const watchers=this._def.watch;if(!watchers)return;for(const[key,handler]of Object.entries(watchers)){if(changedKey===key||key.startsWith(changedKey+'.')||changedKey.startsWith(key+'.')){const currentVal=_getPath(this.state.__raw||this.state,key);const prevVal=this._prevWatchValues?.[key];if(currentVal!==prevVal){const fn=typeof handler==='function'?handler:handler.handler;if(typeof fn==='function')fn.call(this,currentVal,prevVal);if(this._prevWatchValues)this._prevWatchValues[key]=currentVal;}}}}_scheduleUpdate(){if(this._updateQueued)return;this._updateQueued=true;queueMicrotask(()=>{try{if(!this._destroyed)this._render();}finally{this._updateQueued=false;}});}async _loadExternals(){const def=this._def;const base=def._base;if(def.templateUrl&&!def._templateLoaded){const tu=def.templateUrl;if(typeof tu==='string'){def._externalTemplate=await _fetchResource(_resolveUrl(tu,base));}else if(Array.isArray(tu)){const urls=tu.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalTemplates={};results.forEach((html,i)=>{def._externalTemplates[i]=html;});}else if(typeof tu==='object'){const entries=Object.entries(tu);const results=await Promise.all(entries.map(([,url])=>_fetchResource(_resolveUrl(url,base))));def._externalTemplates={};entries.forEach(([key],i)=>{def._externalTemplates[key]=results[i];});}def._templateLoaded=true;}if(def.styleUrl&&!def._styleLoaded){const su=def.styleUrl;if(typeof su==='string'){const resolved=_resolveUrl(su,base);def._externalStyles=await _fetchResource(resolved);def._resolvedStyleUrls=[resolved];}else if(Array.isArray(su)){const urls=su.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalStyles=results.join('\n');def._resolvedStyleUrls=urls;}def._styleLoaded=true;}}_render(){if((this._def.templateUrl&&!this._def._templateLoaded)||(this._def.styleUrl&&!this._def._styleLoaded)){this._loadExternals().then(()=>{if(!this._destroyed)this._render();});return;}if(this._def._externalTemplates){this.templates=this._def._externalTemplates;}let html;if(this._def.render){html=this._def.render.call(this);html=this._expandZFor(html);}else if(this._def._externalTemplate){html=this._expandZFor(this._def._externalTemplate);html=html.replace(/\{\{(.+?)\}\}/g,(_,expr)=>{try{const result=safeEval(expr.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});}else{html='';}html=this._expandContentDirectives(html);if(html.includes('<slot')){html=html.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(_,name,fallback)=>{const slotName=name||'default';return this._slotContent[slotName]||fallback||'';});}const combinedStyles=[this._def.styles||'',this._def._externalStyles||''].filter(Boolean).join('\n');if(!this._mounted&&combinedStyles){const scopeAttr=`z-s${this._uid}`;this._el.setAttribute(scopeAttr,'');let noScopeDepth=0;let braceDepth=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(noScopeDepth>0&&braceDepth<=noScopeDepth)noScopeDepth=0;braceDepth--;return match;}braceDepth++;const trimmed=selector.trim();if(trimmed.startsWith('@')){if(/^@(keyframes|font-face)\b/.test(trimmed)){noScopeDepth=braceDepth;}return match;}if(noScopeDepth>0&&braceDepth>noScopeDepth){return match;}return selector.split(',').map(s=>`[${scopeAttr}] ${s.trim()}`).join(', ')+' {';});const styleEl=document.createElement('style');styleEl.textContent=scoped;styleEl.setAttribute('data-zq-component',this._def._name||'');styleEl.setAttribute('data-zq-scope',scopeAttr);if(this._def._resolvedStyleUrls){styleEl.setAttribute('data-zq-style-urls',this._def._resolvedStyleUrls.join(' '));if(this._def.styles){styleEl.setAttribute('data-zq-inline',this._def.styles);}}document.head.appendChild(styleEl);this._styleEl=styleEl;}let _focusInfo=null;const _active=document.activeElement;if(_active&&this._el.contains(_active)){const modelKey=_active.getAttribute?.('z-model');const refKey=_active.getAttribute?.('z-ref');let selector=null;if(modelKey){selector=`[z-model="${modelKey}"]`;}else if(refKey){selector=`[z-ref="${refKey}"]`;}else{const tag=_active.tagName.toLowerCase();if(tag==='input'||tag==='textarea'||tag==='select'){let s=tag;if(_active.type)s+=`[type="${_active.type}"]`;if(_active.name)s+=`[name="${_active.name}"]`;if(_active.placeholder)s+=`[placeholder="${CSS.escape(_active.placeholder)}"]`;selector=s;}}if(selector){_focusInfo={selector,start:_active.selectionStart,end:_active.selectionEnd,dir:_active.selectionDirection,};}}const _renderStart=typeof window!=='undefined'&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(!this._mounted){this._el.innerHTML=html;if(_renderStart&&window.__zqRenderHook)window.__zqRenderHook(this._el,performance.now()-_renderStart,'mount',this._def._name);}else{morph(this._el,html);}this._processDirectives();this._bindEvents();this._bindRefs();this._bindModels();if(_focusInfo){const el=this._el.querySelector(_focusInfo.selector);if(el&&el!==document.activeElement){el.focus();try{if(_focusInfo.start!==null&&_focusInfo.start!==undefined){el.setSelectionRange(_focusInfo.start,_focusInfo.end,_focusInfo.dir);}}catch(_){}}}mountAll(this._el);if(!this._mounted){this._mounted=true;if(this._def.mounted){try{this._def.mounted.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" mounted() threw`,{component:this._def._name},err);}}}else{if(this._def.updated){try{this._def.updated.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" updated() threw`,{component:this._def._name},err);}}}}_bindEvents(){const eventMap=new Map();const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{if(child.closest('[z-pre]'))return;const attrs=child.attributes;for(let a=0;a<attrs.length;a++){const attr=attrs[a];let raw;if(attr.name.charCodeAt(0)===64){raw=attr.name.slice(1);}else if(attr.name.startsWith('z-on:')){raw=attr.name.slice(5);}else{continue;}const parts=raw.split('.');const event=parts[0];const modifiers=parts.slice(1);const methodExpr=attr.value;if(!child.dataset.zqEid){child.dataset.zqEid=String(++_uid);}const selector=`[data-zq-eid="${child.dataset.zqEid}"]`;if(!eventMap.has(event))eventMap.set(event,[]);eventMap.get(event).push({selector,methodExpr,modifiers,el:child});}});this._eventBindings=eventMap;if(this._delegatedEvents){for(const event of eventMap.keys()){if(!this._delegatedEvents.has(event)){this._attachDelegatedEvent(event,eventMap.get(event));}}for(const event of this._delegatedEvents.keys()){if(!eventMap.has(event)){const{handler,opts}=this._delegatedEvents.get(event);this._el.removeEventListener(event,handler,opts);this._delegatedEvents.delete(event);this._listeners=this._listeners.filter(l=>l.event!==event);}}return;}this._delegatedEvents=new Map();for(const[event,bindings]of eventMap){this._attachDelegatedEvent(event,bindings);}}_attachDelegatedEvent(event,bindings){const needsCapture=bindings.some(b=>b.modifiers.includes('capture'));const needsPassive=bindings.some(b=>b.modifiers.includes('passive'));const listenerOpts=(needsCapture||needsPassive)?{capture:needsCapture,passive:needsPassive}:false;const handler=(e)=>{const currentBindings=this._eventBindings?.get(event)||[];for(const{selector,methodExpr,modifiers,el}of currentBindings){if(!e.target.closest(selector))continue;if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop'))e.stopPropagation();const invoke=(evt)=>{const match=methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const methodName=match[1];const fn=this[methodName];if(typeof fn!=='function')return;if(match[2]!==undefined){const args=match[2].split(',').map(a=>{a=a.trim();if(a==='')return undefined;if(a==='$event')return evt;if(a==='true')return true;if(a==='false')return false;if(a==='null')return null;if(/^-?\d+(\.\d+)?$/.test(a))return Number(a);if((a.startsWith("'")&&a.endsWith("'"))||(a.startsWith('"')&&a.endsWith('"')))return a.slice(1,-1);if(a.startsWith('state.'))return _getPath(this.state,a.slice(6));return a;}).filter(a=>a!==undefined);fn(...args);}else{fn(evt);}};const debounceIdx=modifiers.indexOf('debounce');if(debounceIdx!==-1){const ms=parseInt(modifiers[debounceIdx+1],10)||250;const timers=_debounceTimers.get(el)||{};clearTimeout(timers[event]);timers[event]=setTimeout(()=>invoke(e),ms);_debounceTimers.set(el,timers);continue;}const throttleIdx=modifiers.indexOf('throttle');if(throttleIdx!==-1){const ms=parseInt(modifiers[throttleIdx+1],10)||250;const timers=_throttleTimers.get(el)||{};if(timers[event])continue;invoke(e);timers[event]=setTimeout(()=>{timers[event]=null;},ms);_throttleTimers.set(el,timers);continue;}if(modifiers.includes('once')){if(el.dataset.zqOnce===event)continue;el.dataset.zqOnce=event;}invoke(e);}};this._el.addEventListener(event,handler,listenerOpts);this._listeners.push({event,handler});this._delegatedEvents.set(event,{handler,opts:listenerOpts});}_bindRefs(){this.refs={};this._el.querySelectorAll('[z-ref]').forEach(el=>{this.refs[el.getAttribute('z-ref')]=el;});}_bindModels(){this._el.querySelectorAll('[z-model]').forEach(el=>{const key=el.getAttribute('z-model');const tag=el.tagName.toLowerCase();const type=(el.type||'').toLowerCase();const isEditable=el.hasAttribute('contenteditable');const isLazy=el.hasAttribute('z-lazy');const isTrim=el.hasAttribute('z-trim');const isNum=el.hasAttribute('z-number');const currentVal=_getPath(this.state,key);if(tag==='input'&&type==='checkbox'){el.checked=!!currentVal;}else if(tag==='input'&&type==='radio'){el.checked=el.value===String(currentVal);}else if(tag==='select'&&el.multiple){const vals=Array.isArray(currentVal)?currentVal.map(String):[];[...el.options].forEach(opt=>{opt.selected=vals.includes(opt.value);});}else if(isEditable){if(el.textContent!==String(currentVal??'')){el.textContent=currentVal??'';}}else{el.value=currentVal??'';}const event=isLazy||tag==='select'||type==='checkbox'||type==='radio'?'change':isEditable?'input':'input';if(el._zqModelBound)return;el._zqModelBound=true;const handler=()=>{let val;if(type==='checkbox')val=el.checked;else if(tag==='select'&&el.multiple)val=[...el.selectedOptions].map(o=>o.value);else if(isEditable)val=el.textContent;else val=el.value;if(isTrim&&typeof val==='string')val=val.trim();if(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};el.addEventListener(event,handler);});}_evalExpr(expr){return safeEval(expr,[this.state.__raw||this.state,{props:this.props,refs:this.refs,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);}_expandZFor(html){if(!html.includes('z-for'))return html;const temp=document.createElement('div');temp.innerHTML=html;const _recurse=(root)=>{let forEls=[...root.querySelectorAll('[z-for]')].filter(el=>!el.querySelector('[z-for]'));if(!forEls.length)return;for(const el of forEls){if(!el.parentNode)continue;const expr=el.getAttribute('z-for');const m=expr.match(/^\s*(?:\(\s*(\w+)(?:\s*,\s*(\w+))?\s*\)|(\w+))\s+in\s+(.+)\s*$/);if(!m){el.removeAttribute('z-for');continue;}const itemVar=m[1]||m[3];const indexVar=m[2]||'$index';const listExpr=m[4].trim();let list=this._evalExpr(listExpr);if(list==null){el.remove();continue;}if(typeof list==='number'){list=Array.from({length:list},(_,i)=>i+1);}if(!Array.isArray(list)&&typeof list==='object'&&typeof list[Symbol.iterator]!=='function'){list=Object.entries(list).map(([k,v])=>({key:k,value:v}));}if(!Array.isArray(list)&&typeof list[Symbol.iterator]==='function'){list=[...list];}if(!Array.isArray(list)){el.remove();continue;}const parent=el.parentNode;const tplEl=el.cloneNode(true);tplEl.removeAttribute('z-for');const tplOuter=tplEl.outerHTML;const fragment=document.createDocumentFragment();const evalReplace=(str,item,index)=>str.replace(/\{\{(.+?)\}\}/g,(_,inner)=>{try{const loopScope={};loopScope[itemVar]=item;loopScope[indexVar]=index;const result=safeEval(inner.trim(),[loopScope,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});for(let i=0;i<list.length;i++){const processed=evalReplace(tplOuter,list[i],i);const wrapper=document.createElement('div');wrapper.innerHTML=processed;while(wrapper.firstChild)fragment.appendChild(wrapper.firstChild);}parent.replaceChild(fragment,el);}if(root.querySelector('[z-for]'))_recurse(root);};_recurse(temp);return temp.innerHTML;}_expandContentDirectives(html){if(!html.includes('z-html')&&!html.includes('z-text'))return html;const temp=document.createElement('div');temp.innerHTML=html;temp.querySelectorAll('[z-html]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-html'));el.innerHTML=val!=null?String(val):'';el.removeAttribute('z-html');});temp.querySelectorAll('[z-text]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-text'));el.textContent=val!=null?String(val):'';el.removeAttribute('z-text');});return temp.innerHTML;}_processDirectives(){const ifEls=[...this._el.querySelectorAll('[z-if]')];for(const el of ifEls){if(!el.parentNode||el.closest('[z-pre]'))continue;const show=!!this._evalExpr(el.getAttribute('z-if'));const chain=[{el,show}];let sib=el.nextElementSibling;while(sib){if(sib.hasAttribute('z-else-if')){chain.push({el:sib,show:!!this._evalExpr(sib.getAttribute('z-else-if'))});sib=sib.nextElementSibling;}else if(sib.hasAttribute('z-else')){chain.push({el:sib,show:true});break;}else{break;}}let found=false;for(const item of chain){if(!found&&item.show){found=true;item.el.removeAttribute('z-if');item.el.removeAttribute('z-else-if');item.el.removeAttribute('z-else');}else{item.el.remove();}}}this._el.querySelectorAll('[z-show]').forEach(el=>{if(el.closest('[z-pre]'))return;const show=!!this._evalExpr(el.getAttribute('z-show'));el.style.display=show?'':'none';el.removeAttribute('z-show');});const walker=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(n){return n.hasAttribute('z-pre')?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const attrs=node.attributes;for(let i=attrs.length-1;i>=0;i--){const attr=attrs[i];let attrName;if(attr.name.startsWith('z-bind:'))attrName=attr.name.slice(7);else if(attr.name.charCodeAt(0)===58&&attr.name.charCodeAt(1)!==58)attrName=attr.name.slice(1);else continue;const val=this._evalExpr(attr.value);node.removeAttribute(attr.name);if(val===false||val===null||val===undefined){node.removeAttribute(attrName);}else if(val===true){node.setAttribute(attrName,'');}else{node.setAttribute(attrName,String(val));}}}this._el.querySelectorAll('[z-class]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-class'));if(typeof val==='string'){val.split(/\s+/).filter(Boolean).forEach(c=>el.classList.add(c));}else if(Array.isArray(val)){val.filter(Boolean).forEach(c=>el.classList.add(String(c)));}else if(val&&typeof val==='object'){for(const[cls,active]of Object.entries(val)){el.classList.toggle(cls,!!active);}}el.removeAttribute('z-class');});this._el.querySelectorAll('[z-style]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-style'));if(typeof val==='string'){el.style.cssText+=';'+val;}else if(val&&typeof val==='object'){for(const[prop,v]of Object.entries(val)){el.style[prop]=v;}}el.removeAttribute('z-style');});this._el.querySelectorAll('[z-cloak]').forEach(el=>{el.removeAttribute('z-cloak');});}setState(partial){if(partial&&Object.keys(partial).length>0){Object.assign(this.state,partial);}else{this._scheduleUpdate();}}emit(name,detail){this._el.dispatchEvent(new CustomEvent(name,{detail,bubbles:true,cancelable:true}));}destroy(){if(this._destroyed)return;this._destroyed=true;if(this._def.destroyed){try{this._def.destroyed.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},err);}}this._listeners.forEach(({event,handler})=>this._el.removeEventListener(event,handler));this._listeners=[];this._delegatedEvents=null;this._eventBindings=null;const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{const dTimers=_debounceTimers.get(child);if(dTimers){for(const key in dTimers)clearTimeout(dTimers[key]);_debounceTimers.delete(child);}const tTimers=_throttleTimers.get(child);if(tTimers){for(const key in tTimers)clearTimeout(tTimers[key]);_throttleTimers.delete(child);}});if(this._styleEl)this._styleEl.remove();_instances.delete(this._el);this._el.innerHTML='';}}const _reservedKeys=new Set(['state','render','styles','init','mounted','updated','destroyed','props','templateUrl','styleUrl','templates','base','computed','watch']);function component(name,definition){if(!name||typeof name!=='string'){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,'Component name must be a non-empty string');}if(!name.includes('-')){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,`Component name "${name}" must contain a hyphen (Web Component convention)`);}definition._name=name;if(definition.base!==undefined){definition._base=definition.base;}else{definition._base=_detectCallerBase();}_registry.set(name,definition);}function mount(target,componentName,props={}){const el=typeof target==='string'?document.querySelector(target):target;if(!el)throw new ZQueryError(ErrorCode.COMP_MOUNT_TARGET,`Mount target "${target}" not found`,{target});const def=_registry.get(componentName);if(!def)throw new ZQueryError(ErrorCode.COMP_NOT_FOUND,`Component "${componentName}" not registered`,{component:componentName});if(_instances.has(el))_instances.get(el).destroy();const instance=new Component(el,def,props);_instances.set(el,instance);instance._render();return instance;}function mountAll(root=document.body){for(const[name,def]of _registry){const tags=root.querySelectorAll(name);tags.forEach(tag=>{if(_instances.has(tag))return;const props={};let parentInstance=null;let ancestor=tag.parentElement;while(ancestor){if(_instances.has(ancestor)){parentInstance=_instances.get(ancestor);break;}ancestor=ancestor.parentElement;}[...tag.attributes].forEach(attr=>{if(attr.name.startsWith('@')||attr.name.startsWith('z-'))return;if(attr.name.startsWith(':')){const propName=attr.name.slice(1);if(parentInstance){props[propName]=safeEval(attr.value,[parentInstance.state.__raw||parentInstance.state,{props:parentInstance.props,refs:parentInstance.refs,computed:parentInstance.computed,$:typeof window!=='undefined'?window.$:undefined}]);}else{try{props[propName]=JSON.parse(attr.value);}catch{props[propName]=attr.value;}}return;}try{props[attr.name]=JSON.parse(attr.value);}catch{props[attr.name]=attr.value;}});const instance=new Component(tag,def,props);_instances.set(tag,instance);instance._render();});}}function getInstance(target){const el=typeof target==='string'?document.querySelector(target):target;return _instances.get(el)||null;}function destroy(target){const el=typeof target==='string'?document.querySelector(target):target;const inst=_instances.get(el);if(inst)inst.destroy();}function getRegistry(){return Object.fromEntries(_registry);}async function prefetch(name){const def=_registry.get(name);if(!def)return;if((def.templateUrl&&!def._templateLoaded)||(def.styleUrl&&!def._styleLoaded)){await Component.prototype._loadExternals.call({_def:def});}}const _globalStyles=new Map();function style(urls,opts={}){const callerBase=_detectCallerBase();const list=Array.isArray(urls)?urls:[urls];const elements=[];const loadPromises=[];let _criticalStyle=null;if(opts.critical!==false){_criticalStyle=document.createElement('style');_criticalStyle.setAttribute('data-zq-critical','');_criticalStyle.textContent=`html{visibility:hidden!important;background:${opts.bg || '#0d1117'}}`;document.head.insertBefore(_criticalStyle,document.head.firstChild);}for(let url of list){if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){url=_resolveUrl(url,callerBase);}if(_globalStyles.has(url)){elements.push(_globalStyles.get(url));continue;}const link=document.createElement('link');link.rel='stylesheet';link.href=url;link.setAttribute('data-zq-style','');const p=new Promise(resolve=>{link.onload=resolve;link.onerror=resolve;});loadPromises.push(p);document.head.appendChild(link);_globalStyles.set(url,link);elements.push(link);}const ready=Promise.all(loadPromises).then(()=>{if(_criticalStyle){_criticalStyle.remove();}});return{ready,remove(){for(const el of elements){el.remove();for(const[k,v]of _globalStyles){if(v===el){_globalStyles.delete(k);break;}}}}};}const _ZQ_STATE_KEY='__zq';function _shallowEqual(a,b){if(a===b)return true;if(!a||!b)return false;const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;for(let i=0;i<keysA.length;i++){const k=keysA[i];if(a[k]!==b[k])return false;}return true;}class Router{constructor(config={}){this._el=null;const isFile=typeof location!=='undefined'&&location.protocol==='file:';this._mode=isFile?'hash':(config.mode||'history');let rawBase=config.base;if(rawBase==null){rawBase=(typeof window!=='undefined'&&window.__ZQ_BASE)||'';if(!rawBase&&typeof document!=='undefined'){const baseEl=document.querySelector('base');if(baseEl){try{rawBase=new URL(baseEl.href).pathname;}catch{rawBase=baseEl.getAttribute('href')||'';}if(rawBase==='/')rawBase='';}}}this._base=String(rawBase).replace(/\/+$/,'');if(this._base&&!this._base.startsWith('/'))this._base='/'+this._base;this._routes=[];this._fallback=config.fallback||null;this._current=null;this._guards={before:[],after:[]};this._listeners=new Set();this._instance=null;this._resolving=false;this._substateListeners=[];this._inSubstate=false;if(config.el){this._el=typeof config.el==='string'?document.querySelector(config.el):config.el;}if(config.routes){config.routes.forEach(r=>this.add(r));}if(this._mode==='hash'){this._onNavEvent=()=>this._resolve();window.addEventListener('hashchange',this._onNavEvent);}else{this._onNavEvent=(e)=>{const st=e.state;if(st&&st[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(st.key,st.data,'pop');if(handled)return;}else if(this._inSubstate){this._inSubstate=false;this._fireSubstate(null,null,'reset');}this._resolve();};window.addEventListener('popstate',this._onNavEvent);}this._onLinkClick=(e)=>{if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const link=e.target.closest('[z-link]');if(!link)return;if(link.getAttribute('target')==='_blank')return;e.preventDefault();let href=link.getAttribute('z-link');const paramsAttr=link.getAttribute('z-link-params');if(paramsAttr){try{const params=JSON.parse(paramsAttr);href=this._interpolateParams(href,params);}catch{}}this.navigate(href);if(link.hasAttribute('z-to-top')){const scrollBehavior=link.getAttribute('z-to-top')||'instant';window.scrollTo({top:0,behavior:scrollBehavior});}};document.addEventListener('click',this._onLinkClick);if(this._el){queueMicrotask(()=>this._resolve());}}add(route){const keys=[];const pattern=route.path.replace(/:(\w+)/g,(_,key)=>{keys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const regex=new RegExp(`^${pattern}$`);this._routes.push({...route,_regex:regex,_keys:keys});if(route.fallback){const fbKeys=[];const fbPattern=route.fallback.replace(/:(\w+)/g,(_,key)=>{fbKeys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const fbRegex=new RegExp(`^${fbPattern}$`);this._routes.push({...route,path:route.fallback,_regex:fbRegex,_keys:fbKeys});}return this;}remove(path){this._routes=this._routes.filter(r=>r.path!==path);return this;}_interpolateParams(path,params){if(!params||typeof params!=='object')return path;return path.replace(/:([\w]+)/g,(_,key)=>{const val=params[key];return val!=null?encodeURIComponent(String(val)):':'+key;});}_currentURL(){if(this._mode==='hash'){return window.location.hash.slice(1)||'/';}const pathname=window.location.pathname||'/';const hash=window.location.hash||'';return pathname+hash;}navigate(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;const targetHash='#'+normalized;if(window.location.hash===targetHash&&!options.force)return this;window.location.hash=targetHash;}else{const targetURL=this._base+normalized+hash;const currentURL=(window.location.pathname||'/')+(window.location.hash||'');if(targetURL===currentURL&&!options.force){if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}const targetPathOnly=this._base+normalized;const currentPathOnly=window.location.pathname||'/';if(targetPathOnly===currentPathOnly&&hash&&!options.force){window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}window.history.pushState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);this._resolve();}return this;}replace(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;window.location.replace('#'+normalized);}else{window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',this._base+normalized+hash);this._resolve();}return this;}_normalizePath(path){let p=path&&path.startsWith('/')?path:(path?`/${path}`:'/');if(this._base){if(p===this._base)return'/';if(p.startsWith(this._base+'/'))p=p.slice(this._base.length)||'/';}return p;}resolve(path){const normalized=path&&path.startsWith('/')?path:(path?`/${path}`:'/');return this._base+normalized;}back(){window.history.back();return this;}forward(){window.history.forward();return this;}go(n){window.history.go(n);return this;}beforeEach(fn){this._guards.before.push(fn);return this;}afterEach(fn){this._guards.after.push(fn);return this;}onChange(fn){this._listeners.add(fn);return()=>this._listeners.delete(fn);}pushSubstate(key,data){this._inSubstate=true;if(this._mode==='hash'){const current=window.location.hash||'#/';window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}else{window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}return this;}onSubstate(fn){this._substateListeners.push(fn);return()=>{this._substateListeners=this._substateListeners.filter(f=>f!==fn);};}_fireSubstate(key,data,action){for(const fn of this._substateListeners){try{if(fn(key,data,action)===true)return true;}catch(err){reportError(ErrorCode.ROUTER_GUARD,'onSubstate listener threw',{key,data},err);}}return false;}get current(){return this._current;}get base(){return this._base;}get path(){if(this._mode==='hash'){const raw=window.location.hash.slice(1)||'/';if(raw&&!raw.startsWith('/')){window.__zqScrollTarget=raw;const fallbackPath=(this._current&&this._current.path)||'/';window.location.replace('#'+fallbackPath);return fallbackPath;}return raw;}let pathname=window.location.pathname||'/';if(pathname.length>1&&pathname.endsWith('/')){pathname=pathname.slice(0,-1);}if(this._base){if(pathname===this._base)return'/';if(pathname.startsWith(this._base+'/')){return pathname.slice(this._base.length)||'/';}}return pathname;}get query(){const search=this._mode==='hash'?(window.location.hash.split('?')[1]||''):window.location.search.slice(1);return Object.fromEntries(new URLSearchParams(search));}async _resolve(){if(this._resolving)return;this._resolving=true;this._redirectCount=0;try{await this.__resolve();}finally{this._resolving=false;}}async __resolve(){const histState=window.history.state;if(histState&&histState[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(histState.key,histState.data,'resolve');if(handled)return;}const fullPath=this.path;const[pathPart,queryString]=fullPath.split('?');const path=pathPart||'/';const query=Object.fromEntries(new URLSearchParams(queryString||''));let matched=null;let params={};for(const route of this._routes){const m=path.match(route._regex);if(m){matched=route;route._keys.forEach((key,i)=>{params[key]=m[i+1];});break;}}if(!matched&&this._fallback){matched={component:this._fallback,path:'*',_keys:[],_regex:/.*/};}if(!matched)return;const to={route:matched,params,query,path};const from=this._current;if(from&&this._instance&&matched.component===from.route.component){const sameParams=_shallowEqual(params,from.params);const sameQuery=_shallowEqual(query,from.query);if(sameParams&&sameQuery){return;}}for(const guard of this._guards.before){try{const result=await guard(to,from);if(result===false)return;if(typeof result==='string'){if(++this._redirectCount>10){reportError(ErrorCode.ROUTER_GUARD,'Too many guard redirects (possible loop)',{to},null);return;}const[rPath,rFrag]=result.split('#');const rNorm=this._normalizePath(rPath||'/');const rHash=rFrag?'#'+rFrag:'';if(this._mode==='hash'){if(rFrag)window.__zqScrollTarget=rFrag;window.location.replace('#'+rNorm);}else{window.history.replaceState({[_ZQ_STATE_KEY]:'route'},'',this._base+rNorm+rHash);}return this.__resolve();}}catch(err){reportError(ErrorCode.ROUTER_GUARD,'Before-guard threw',{to,from},err);return;}}if(matched.load){try{await matched.load();}catch(err){reportError(ErrorCode.ROUTER_LOAD,`Failed to load module for route "${matched.path}"`,{path:matched.path},err);return;}}this._current=to;if(this._el&&matched.component){if(typeof matched.component==='string'){await prefetch(matched.component);}if(this._instance){this._instance.destroy();this._instance=null;}const _routeStart=typeof window!=='undefined'&&window.__zqRenderHook?performance.now():0;this._el.innerHTML='';const props={...params,$route:to,$query:query,$params:params};if(typeof matched.component==='string'){const container=document.createElement(matched.component);this._el.appendChild(container);this._instance=mount(container,matched.component,props);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',matched.component);}else if(typeof matched.component==='function'){this._el.innerHTML=matched.component(to);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',to);}}for(const guard of this._guards.after){await guard(to,from);}this._listeners.forEach(fn=>fn(to,from));}destroy(){if(this._onNavEvent){window.removeEventListener(this._mode==='hash'?'hashchange':'popstate',this._onNavEvent);this._onNavEvent=null;}if(this._onLinkClick){document.removeEventListener('click',this._onLinkClick);this._onLinkClick=null;}if(this._instance)this._instance.destroy();this._listeners.clear();this._substateListeners=[];this._inSubstate=false;this._routes=[];this._guards={before:[],after:[]};}}let _activeRouter=null;function createRouter(config){_activeRouter=new Router(config);return _activeRouter;}function getRouter(){return _activeRouter;}class Store{constructor(config={}){this._subscribers=new Map();this._wildcards=new Set();this._actions=config.actions||{};this._getters=config.getters||{};this._middleware=[];this._history=[];this._maxHistory=config.maxHistory||1000;this._debug=config.debug||false;const initial=typeof config.state==='function'?config.state():{...(config.state||{})};this.state=reactive(initial,(key,value,old)=>{const subs=this._subscribers.get(key);if(subs)subs.forEach(fn=>{try{fn(value,old,key);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,`Subscriber for "${key}" threw`,{key},err);}});this._wildcards.forEach(fn=>{try{fn(key,value,old);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,'Wildcard subscriber threw',{key},err);}});});this.getters={};for(const[name,fn]of Object.entries(this._getters)){Object.defineProperty(this.getters,name,{get:()=>fn(this.state.__raw||this.state),enumerable:true});}}dispatch(name,...args){const action=this._actions[name];if(!action){reportError(ErrorCode.STORE_ACTION,`Unknown action "${name}"`,{action:name,args});return;}for(const mw of this._middleware){try{const result=mw(name,args,this.state);if(result===false)return;}catch(err){reportError(ErrorCode.STORE_MIDDLEWARE,`Middleware threw during "${name}"`,{action:name},err);return;}}if(this._debug){console.log(`%c[Store] ${name}`,'color: #4CAF50; font-weight: bold;',...args);}try{const result=action(this.state,...args);this._history.push({action:name,args,timestamp:Date.now()});if(this._history.length>this._maxHistory){this._history.splice(0,this._history.length-this._maxHistory);}return result;}catch(err){reportError(ErrorCode.STORE_ACTION,`Action "${name}" threw`,{action:name,args},err);}}subscribe(keyOrFn,fn){if(typeof keyOrFn==='function'){this._wildcards.add(keyOrFn);return()=>this._wildcards.delete(keyOrFn);}if(!this._subscribers.has(keyOrFn)){this._subscribers.set(keyOrFn,new Set());}this._subscribers.get(keyOrFn).add(fn);return()=>this._subscribers.get(keyOrFn)?.delete(fn);}snapshot(){return JSON.parse(JSON.stringify(this.state.__raw||this.state));}replaceState(newState){const raw=this.state.__raw||this.state;for(const key of Object.keys(raw)){delete this.state[key];}Object.assign(this.state,newState);}use(fn){this._middleware.push(fn);return this;}get history(){return[...this._history];}reset(initialState){this.replaceState(initialState);this._history=[];}}let _stores=new Map();function createStore(name,config){if(typeof name==='object'){config=name;name='default';}const store=new Store(config);_stores.set(name,store);return store;}function getStore(name='default'){return _stores.get(name)||null;}const _config={baseURL:'',headers:{'Content-Type':'application/json'},timeout:30000,};const _interceptors={request:[],response:[],};async function request(method,url,data,options={}){if(!url||typeof url!=='string'){throw new Error(`HTTP request requires a URL string, got ${typeof url}`);}let fullURL=url.startsWith('http')?url:_config.baseURL+url;let headers={..._config.headers,...options.headers};let body=undefined;const fetchOpts={method:method.toUpperCase(),headers,...options,};if(data!==undefined&&method!=='GET'&&method!=='HEAD'){if(data instanceof FormData){body=data;delete fetchOpts.headers['Content-Type'];}else if(typeof data==='object'){body=JSON.stringify(data);}else{body=data;}fetchOpts.body=body;}if(data&&(method==='GET'||method==='HEAD')&&typeof data==='object'){const params=new URLSearchParams(data).toString();fullURL+=(fullURL.includes('?')?'&':'?')+params;}const controller=new AbortController();const timeout=options.timeout??_config.timeout;let timer;if(options.signal){if(typeof AbortSignal.any==='function'){fetchOpts.signal=AbortSignal.any([options.signal,controller.signal]);}else{fetchOpts.signal=controller.signal;if(options.signal.aborted){controller.abort(options.signal.reason);}else{options.signal.addEventListener('abort',()=>controller.abort(options.signal.reason),{once:true});}}}else{fetchOpts.signal=controller.signal;}if(timeout>0){timer=setTimeout(()=>controller.abort(),timeout);}for(const interceptor of _interceptors.request){const result=await interceptor(fetchOpts,fullURL);if(result===false)throw new Error('Request blocked by interceptor');if(result?.url)fullURL=result.url;if(result?.options)Object.assign(fetchOpts,result.options);}try{const response=await fetch(fullURL,fetchOpts);if(timer)clearTimeout(timer);const contentType=response.headers.get('Content-Type')||'';let responseData;try{if(contentType.includes('application/json')){responseData=await response.json();}else if(contentType.includes('text/')){responseData=await response.text();}else if(contentType.includes('application/octet-stream')||contentType.includes('image/')){responseData=await response.blob();}else{const text=await response.text();try{responseData=JSON.parse(text);}catch{responseData=text;}}}catch(parseErr){responseData=null;console.warn(`[zQuery HTTP] Failed to parse response body from ${method} ${fullURL}:`,parseErr.message);}const result={ok:response.ok,status:response.status,statusText:response.statusText,headers:Object.fromEntries(response.headers.entries()),data:responseData,response,};for(const interceptor of _interceptors.response){await interceptor(result);}if(!response.ok){const err=new Error(`HTTP ${response.status}: ${response.statusText}`);err.response=result;throw err;}return result;}catch(err){if(timer)clearTimeout(timer);if(err.name==='AbortError'){throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);}throw err;}}const http={get:(url,params,opts)=>request('GET',url,params,opts),post:(url,data,opts)=>request('POST',url,data,opts),put:(url,data,opts)=>request('PUT',url,data,opts),patch:(url,data,opts)=>request('PATCH',url,data,opts),delete:(url,data,opts)=>request('DELETE',url,data,opts),configure(opts){if(opts.baseURL!==undefined)_config.baseURL=opts.baseURL;if(opts.headers)Object.assign(_config.headers,opts.headers);if(opts.timeout!==undefined)_config.timeout=opts.timeout;},onRequest(fn){_interceptors.request.push(fn);},onResponse(fn){_interceptors.response.push(fn);},createAbort(){return new AbortController();},raw:(url,opts)=>fetch(url,opts),};function debounce(fn,ms=250){let timer;const debounced=(...args)=>{clearTimeout(timer);timer=setTimeout(()=>fn(...args),ms);};debounced.cancel=()=>clearTimeout(timer);return debounced;}function throttle(fn,ms=250){let last=0;let timer;return(...args)=>{const now=Date.now();const remaining=ms-(now-last);clearTimeout(timer);if(remaining<=0){last=now;fn(...args);}else{timer=setTimeout(()=>{last=Date.now();fn(...args);},remaining);}};}function pipe(...fns){return(input)=>fns.reduce((val,fn)=>fn(val),input);}function once(fn){let called=false,result;return(...args)=>{if(!called){called=true;result=fn(...args);}return result;};}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms));}function escapeHtml(str){const map={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};return String(str).replace(/[&<>"']/g,c=>map[c]);}function html(strings,...values){return strings.reduce((result,str,i)=>{const val=values[i-1];const escaped=(val instanceof TrustedHTML)?val.toString():escapeHtml(val??'');return result+escaped+str;});}class TrustedHTML{constructor(html){this._html=html;}toString(){return this._html;}}function trust(htmlStr){return new TrustedHTML(htmlStr);}function uuid(){return crypto?.randomUUID?.()||'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const r=Math.random()*16|0;return(c==='x'?r:(r&0x3|0x8)).toString(16);});}function camelCase(str){return str.replace(/-([a-z])/g,(_,c)=>c.toUpperCase());}function kebabCase(str){return str.replace(/([a-z])([A-Z])/g,'$1-$2').toLowerCase();}function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);return JSON.parse(JSON.stringify(obj));}function deepMerge(target,...sources){const seen=new WeakSet();function merge(tgt,src){if(seen.has(src))return tgt;seen.add(src);for(const key of Object.keys(src)){if(src[key]&&typeof src[key]==='object'&&!Array.isArray(src[key])){if(!tgt[key]||typeof tgt[key]!=='object')tgt[key]={};merge(tgt[key],src[key]);}else{tgt[key]=src[key];}}return tgt;}for(const source of sources)merge(target,source);return target;}function isEqual(a,b){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;if(Array.isArray(a)!==Array.isArray(b))return false;const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;return keysA.every(k=>isEqual(a[k],b[k]));}function param(obj){return new URLSearchParams(obj).toString();}function parseQuery(str){return Object.fromEntries(new URLSearchParams(str));}const storage={get(key,fallback=null){try{const raw=localStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){localStorage.setItem(key,JSON.stringify(value));},remove(key){localStorage.removeItem(key);},clear(){localStorage.clear();},};const session={get(key,fallback=null){try{const raw=sessionStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){sessionStorage.setItem(key,JSON.stringify(value));},remove(key){sessionStorage.removeItem(key);},clear(){sessionStorage.clear();},};class EventBus{constructor(){this._handlers=new Map();}on(event,fn){if(!this._handlers.has(event))this._handlers.set(event,new Set());this._handlers.get(event).add(fn);return()=>this.off(event,fn);}off(event,fn){this._handlers.get(event)?.delete(fn);}emit(event,...args){this._handlers.get(event)?.forEach(fn=>fn(...args));}once(event,fn){const wrapper=(...args)=>{fn(...args);this.off(event,wrapper);};return this.on(event,wrapper);}clear(){this._handlers.clear();}}const bus=new EventBus();function $(selector,context){if(typeof selector==='function'){query.ready(selector);return;}return query(selector,context);}$.id=query.id;$.class=query.class;$.classes=query.classes;$.tag=query.tag;Object.defineProperty($,'name',{value:query.name,writable:true,configurable:true});$.children=query.children;$.all=function(selector,context){return queryAll(selector,context);};$.create=query.create;$.ready=query.ready;$.on=query.on;$.off=query.off;$.fn=query.fn;$.reactive=reactive;$.Signal=Signal;$.signal=signal;$.computed=computed;$.effect=effect;$.component=component;$.mount=mount;$.mountAll=mountAll;$.getInstance=getInstance;$.destroy=destroy;$.components=getRegistry;$.prefetch=prefetch;$.style=style;$.morph=morph;$.morphElement=morphElement;$.safeEval=safeEval;$.router=createRouter;$.getRouter=getRouter;$.store=createStore;$.getStore=getStore;$.http=http;$.get=http.get;$.post=http.post;$.put=http.put;$.patch=http.patch;$.delete=http.delete;$.debounce=debounce;$.throttle=throttle;$.pipe=pipe;$.once=once;$.sleep=sleep;$.escapeHtml=escapeHtml;$.html=html;$.trust=trust;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.bus=bus;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.validate=validate;$.version='0.9.1';$.libSize='~92 KB';$.meta={};$.noConflict=()=>{if(typeof window!=='undefined'&&window.$===$){delete window.$;}return $;};if(typeof window!=='undefined'){window.$=$;window.zQuery=$;}$;})(typeof window!=='undefined'?window:globalThis);
package/index.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Lightweight modern frontend library — jQuery-like selectors, reactive
5
5
  * components, SPA router, state management, HTTP client & utilities.
6
6
  *
7
- * @version 0.9.0
7
+ * @version 0.9.1
8
8
  * @license MIT
9
9
  * @see https://z-query.com/docs
10
10
  */
@@ -126,7 +126,7 @@ import type {
126
126
  deepClone, deepMerge, isEqual, param, parseQuery,
127
127
  StorageWrapper, EventBus,
128
128
  } from './types/utils';
129
- import type { onError, ZQueryError, ErrorCode } from './types/errors';
129
+ import type { onError, ZQueryError, ErrorCode, guardCallback, validate } from './types/errors';
130
130
  import type { morph, morphElement, safeEval } from './types/misc';
131
131
 
132
132
  /**
@@ -245,6 +245,10 @@ interface ZQueryStatic {
245
245
  ZQueryError: typeof ZQueryError;
246
246
  /** Frozen map of all error code constants. */
247
247
  ErrorCode: typeof ErrorCode;
248
+ /** Wrap a callback so thrown errors are caught and reported via the global handler. */
249
+ guardCallback: typeof guardCallback;
250
+ /** Validate a required value is defined and of the expected type. */
251
+ validate: typeof validate;
248
252
 
249
253
  // -- Utilities -----------------------------------------------------------
250
254
  debounce: typeof debounce;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zero-query",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "Lightweight modern frontend library — jQuery-like selectors, reactive components, SPA router, and state management with zero dependencies.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
package/src/component.js CHANGED
@@ -264,7 +264,7 @@ class Component {
264
264
  if (!watchers) return;
265
265
  for (const [key, handler] of Object.entries(watchers)) {
266
266
  // Match exact key or parent key (e.g. watcher on 'user' fires when 'user.name' changes)
267
- if (changedKey === key || key.startsWith(changedKey + '.') || changedKey.startsWith(key + '.') || changedKey === key) {
267
+ if (changedKey === key || key.startsWith(changedKey + '.') || changedKey.startsWith(key + '.')) {
268
268
  const currentVal = _getPath(this.state.__raw || this.state, key);
269
269
  const prevVal = this._prevWatchValues?.[key];
270
270
  if (currentVal !== prevVal) {
@@ -413,20 +413,26 @@ class Component {
413
413
  if (!this._mounted && combinedStyles) {
414
414
  const scopeAttr = `z-s${this._uid}`;
415
415
  this._el.setAttribute(scopeAttr, '');
416
- let inAtBlock = 0;
416
+ let noScopeDepth = 0; // brace depth at which a no-scope @-rule started (0 = none active)
417
+ let braceDepth = 0; // overall brace depth
417
418
  const scoped = combinedStyles.replace(/([^{}]+)\{|\}/g, (match, selector) => {
418
419
  if (match === '}') {
419
- if (inAtBlock > 0) inAtBlock--;
420
+ if (noScopeDepth > 0 && braceDepth <= noScopeDepth) noScopeDepth = 0;
421
+ braceDepth--;
420
422
  return match;
421
423
  }
424
+ braceDepth++;
422
425
  const trimmed = selector.trim();
423
- // Don't scope @-rules (@media, @keyframes, @supports, @container, @layer, @font-face, etc.)
426
+ // Don't scope @-rules themselves
424
427
  if (trimmed.startsWith('@')) {
425
- inAtBlock++;
428
+ // @keyframes and @font-face contain non-selector content — skip scoping inside them
429
+ if (/^@(keyframes|font-face)\b/.test(trimmed)) {
430
+ noScopeDepth = braceDepth;
431
+ }
426
432
  return match;
427
433
  }
428
- // Don't scope keyframe stops (from, to, 0%, 50%, etc.)
429
- if (inAtBlock > 0 && /^[\d%\s,fromto]+$/.test(trimmed.replace(/\s/g, ''))) {
434
+ // Inside @keyframes or @font-face don't scope inner rules
435
+ if (noScopeDepth > 0 && braceDepth > noScopeDepth) {
430
436
  return match;
431
437
  }
432
438
  return selector.split(',').map(s => `[${scopeAttr}] ${s.trim()}`).join(', ') + ' {';
@@ -1054,6 +1060,21 @@ class Component {
1054
1060
  this._listeners = [];
1055
1061
  this._delegatedEvents = null;
1056
1062
  this._eventBindings = null;
1063
+ // Clear any pending debounce/throttle timers to prevent stale closures.
1064
+ // Timers are keyed by individual child elements, so iterate all descendants.
1065
+ const allEls = this._el.querySelectorAll('*');
1066
+ allEls.forEach(child => {
1067
+ const dTimers = _debounceTimers.get(child);
1068
+ if (dTimers) {
1069
+ for (const key in dTimers) clearTimeout(dTimers[key]);
1070
+ _debounceTimers.delete(child);
1071
+ }
1072
+ const tTimers = _throttleTimers.get(child);
1073
+ if (tTimers) {
1074
+ for (const key in tTimers) clearTimeout(tTimers[key]);
1075
+ _throttleTimers.delete(child);
1076
+ }
1077
+ });
1057
1078
  if (this._styleEl) this._styleEl.remove();
1058
1079
  _instances.delete(this._el);
1059
1080
  this._el.innerHTML = '';