@jasonshimmy/custom-elements-runtime 0.0.9 → 0.0.10-beta.0

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,72 +1,2 @@
1
- (function(p,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(p=typeof globalThis<"u"?globalThis:p||self,g(p.CustomElementsRuntime={}))})(this,(function(p){"use strict";var g=typeof document<"u"?document.currentScript:null;function L(e){let t=new Proxy(e,{set:(i,a,c)=>(i[a]=c,s(),!0)});const n=[];function r(i){n.push(i),i(t)}function o(){return t}function s(){n.forEach(i=>i(t))}return{subscribe:r,getState:o}}class E extends EventTarget{handlers={};static instance;eventCounters=new Map;static getInstance(){return E.instance||(E.instance=new E),E.instance}emit(t,n){const r=Date.now(),o=this.eventCounters.get(t);if(!o||r-o.window>1e3)this.eventCounters.set(t,{count:1,window:r});else if(o.count++,o.count>50&&(console.error(`Event storm detected for "${t}": ${o.count} events in 1 second. Throttling...`),o.count>100)){console.warn(`Blocking further "${t}" events to prevent infinite loop`);return}this.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!1,cancelable:!0}));const s=this.handlers[t];s&&s.forEach(i=>{try{i(n)}catch(a){console.error(`Error in global event handler for "${t}":`,a)}})}on(t,n){return this.handlers[t]||(this.handlers[t]=new Set),this.handlers[t].add(n),()=>this.off(t,n)}off(t,n){const r=this.handlers[t];r&&r.delete(n)}offAll(t){delete this.handlers[t]}listen(t,n,r){return this.addEventListener(t,n,r),()=>this.removeEventListener(t,n)}once(t,n){return new Promise(r=>{const o=this.on(t,s=>{o(),n(s),r(s)})})}getActiveEvents(){return Object.keys(this.handlers).filter(t=>this.handlers[t]&&this.handlers[t].size>0)}clear(){this.handlers={}}getHandlerCount(t){return this.handlers[t]?.size||0}getEventStats(){const t={};for(const[n,r]of this.eventCounters.entries())t[n]={count:r.count,handlersCount:this.getHandlerCount(n)};return t}resetEventCounters(){this.eventCounters.clear()}}const C=E.getInstance(),tt=typeof window>"u"||typeof document>"u";function et(e){return{state:e,emit:()=>{},onGlobal:()=>()=>{},offGlobal:()=>{},emitGlobal:()=>{},render:()=>{}}}function F(e,t={}){tt||console.warn("[SSR] renderToString should only be used on the server");try{const n=e.state,r=et(n),o=e.template(n,r);let s="";t.includeStyles&&e.style&&(s=`<style>${typeof e.style=="function"?e.style(n):e.style}</style>`);const i=t.sanitizeAttributes?t.sanitizeAttributes(e.attrs||{}):e.attrs||{},a=Object.entries(i).map(([u,d])=>`${U(u)}="${U(d)}"`).join(" "),l=`${a?`<${e.tag} ${a}>`:`<${e.tag}>`}${s}${o}</${e.tag}>`;return t.prettyPrint?it(l):l}catch(n){return console.error(`[SSR] Error rendering ${e.tag}:`,n),`<${e.tag}><div style="color: red;">SSR Error: ${st(String(n))}</div></${e.tag}>`}}function nt(e,t={}){const n={components:new Map,styles:new Set},r=[];e.forEach(i=>{if(n.components.set(i.tag,i),i.style){const c=typeof i.style=="function"?i.style(i.state):i.style;n.styles.add(c)}const a=F(i,{...t,includeStyles:!1});r.push(a)});const o=Array.from(n.styles).join(`
2
- `);return{html:r.join(`
3
- `),styles:o,context:n}}function rt(e){const t=Array.from(e.components.entries()).map(([n,r])=>({tag:n,state:r.state}));return`
4
- <script type="module">
5
- // Hydration data from SSR
6
- window.__SSR_CONTEXT__ = ${JSON.stringify({components:t})};
7
-
8
- // Auto-hydrate when DOM is ready
9
- if (document.readyState === 'loading') {
10
- document.addEventListener('DOMContentLoaded', hydrate);
11
- } else {
12
- hydrate();
13
- }
14
-
15
- function hydrate() {
16
- const context = window.__SSR_CONTEXT__;
17
- if (!context?.components) return;
18
-
19
- context.components.forEach(({ tag, state }) => {
20
- const elements = document.querySelectorAll(tag);
21
- elements.forEach(el => {
22
- // Mark as hydrated to prevent re-initialization
23
- if (!el.hasAttribute('data-hydrated')) {
24
- el.setAttribute('data-hydrated', 'true');
25
- // Restore state if component supports it
26
- if (el._hydrateWithState) {
27
- el._hydrateWithState(state);
28
- }
29
- }
30
- });
31
- });
32
-
33
- // Clean up
34
- delete window.__SSR_CONTEXT__;
35
- }
36
- <\/script>`.trim()}const st=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),U=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),it=e=>e.replace(/></g,`>
37
- <`).split(`
38
- `).map(t=>{const n=(t.match(/^<[^\/]/g)||[]).length-(t.match(/<\//g)||[]).length;return" ".repeat(Math.max(0,n))+t.trim()}).join(`
39
- `);function K(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function M(e,t){if(typeof e!="string"||!t)return String(e);for(const n in t){if(typeof t[n]=="string"&&e===t[n])return K(e);if(Array.isArray(t[n])){for(const r of t[n])if(r&&typeof r=="object"){for(const o in r)if(typeof r[o]=="string"&&e===r[o])return K(e)}}}return String(e)}function T(e,...t){function n(r,o,s){if(Array.isArray(r)){const i=r.map(a=>n(a,o,s));return i.some(a=>a instanceof Promise)?Promise.all(i).then(a=>a.join("")):i.join("")}if(typeof r=="function"){const i=n(r(o,s),o,s);return i instanceof Promise,i}return r==null?"":r instanceof Promise?r:String(r)}return(r,o)=>{let s="",i=!1;const a=[];for(let c=0;c<e.length;c++)if(s+=e[c],c<t.length){let l=t[c];const u=e[c],d=/data-on-[a-z]+="?$/.test(u);l=n(l,r,o),l instanceof Promise?(i=!0,a.push(l)):/=\s*"?$/.test(u)&&typeof l=="string"&&!d?(l=l.replace(/"/g,"&quot;").replace(/'/g,"&#39;"),s+=l):!d&&!/=\s*"?$/.test(u)?s+=M(l,r):s+=l}return i?Promise.all(a).then(c=>{let l="",u=0;for(let d=0;d<e.length;d++)if(l+=e[d],d<t.length){let f=t[d];const h=e[d],y=/data-on-[a-z]+="?$/.test(h);f=n(f,r,o),f instanceof Promise?l+=c[u++]:/=\s*"?$/.test(h)&&typeof f=="string"&&!y?(f=f.replace(/"/g,"&quot;").replace(/'/g,"&#39;"),l+=f):!y&&!/=\s*"?$/.test(h)?l+=M(f,r):l+=f}return l}):s}}function ot(e,...t){const n="compiled-"+Math.random().toString(36).slice(2);function r(s,i,a){return Array.isArray(s)?s.map(c=>r(c,i,a)).join(""):typeof s=="function"?r(s(i,a),i,a):s==null?"":String(s)}const o=(s,i)=>{let a="";for(let c=0;c<e.length;c++)if(a+=e[c],c<t.length){let l=t[c];const u=e[c],d=/data-on-[a-z]+="?$/.test(u);l=r(l,s,i),/=\s*"?$/.test(u)&&typeof l=="string"&&!d?(l=l.replace(/"/g,"&quot;").replace(/'/g,"&#39;"),a+=l):!d&&!/=\s*"?$/.test(u)?a+=M(l,s):a+=l??""}return a};return o.id=n,o}function B(e,...t){let n="";for(let r=0;r<e.length;r++)n+=e[r],r<t.length&&(n+=t[r]??"");return n}function at(e){return Object.keys(e).filter(t=>e[t]).join(" ")}function ct(e){return Object.entries(e).map(([t,n])=>`${t}: ${n}`).join("; ")}function G(e,t,n){const[r,...o]=n.split("|").map(a=>a.trim());if(!r||r==="__proto__"||r==="constructor"||r==="prototype")return;function s(a,c,l){const u=c.split(".");let d=a;for(let f=0;f<u.length-1;f++)u[f]in d||(d[u[f]]={}),d=d[u[f]];d[u[u.length-1]]=l}const i=a=>{let c;if(e instanceof HTMLInputElement&&e.type==="checkbox"){c=e.value;const l=e.getAttribute("data-true-value"),u=e.getAttribute("data-false-value");let d=Array.isArray(t[r])?t[r]:void 0;if(d){if(e.checked)d.includes(c)||d.push(c);else{const f=d.indexOf(c);f!==-1&&d.splice(f,1)}s(t,r,[...d])}else l!==null||u!==null?e.checked?s(t,r,l):s(t,r,u!==null?u:!1):s(t,r,e.checked)}else e instanceof HTMLInputElement&&e.type==="radio"?(c=e.value,s(t,r,c),((e.form||e.closest("form")||e.getRootNode())instanceof Element?(e.form||e.closest("form")||e.getRootNode()).querySelectorAll(`input[type="radio"][name="${e.name}"][data-model="${n}"]`):[]).forEach(u=>{u.checked=u.value===String(c)})):(c=e.value,e instanceof HTMLInputElement&&e.type==="number"&&(c=Number(c)),o.includes("trim")&&typeof c=="string"&&(c=c.trim()),o.includes("number")&&(c=Number(c)),s(t,r,c));if("_vnode"in e&&typeof e._vnode=="object"&&e._vnode?.props&&(e._vnode.props.value=c),a.type==="input"&&(e._isDirty=!0),a.type==="keydown"&&a.key==="Enter"&&(e._isDirty=!1,e instanceof HTMLElement&&e.isConnected)){let l=e.parentElement;for(;l&&!(l instanceof HTMLElement&&l.shadowRoot);)l=l.parentElement;l&&typeof l=="object"&&l!==null&&"render"in l&&typeof l.render=="function"&&l.render()}a.type==="blur"&&(e._isDirty=!1)};e.addEventListener("input",i),e.addEventListener("change",i),e.addEventListener("keydown",i),e.addEventListener("blur",i)}const $=(()=>{try{if(typeof process<"u"&&process.env)return process.env.NODE_ENV==="development"}catch{}return typeof window<"u"?window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1":!1})();function lt(e,t={}){const{development:n=$,cache:r=!0,optimize:o=!0}=t,s=X(e);if(r&&N.has(s)){if(n){const i=S.get(s)||{compilationTime:0,renderTime:0,updateTime:0,cacheHits:0,cacheMisses:0};i.cacheHits++,S.set(s,i)}return N.get(s)}if(n){const i=S.get(s)||{compilationTime:0,renderTime:0,updateTime:0,cacheHits:0,cacheMisses:0};i.cacheMisses++,S.set(s,i)}try{const i=dt(e,{development:n,optimize:o});return r&&N.set(s,i),i}catch(i){return n&&(console.error("[Template Compiler] Error compiling template:",i),console.error("[Template Compiler] Template:",e)),{statics:[e],dynamics:[],fragment:null,id:s,hasDynamics:!1,render:()=>e}}}function ut(e,t){if(typeof document>"u")return[0];try{let n=function(a,c=[]){if(a.nodeType===Node.TEXT_NODE){if(a.textContent?.includes(t))return c}else if(a.nodeType===Node.ELEMENT_NODE){let l=0;for(let u=0;u<a.childNodes.length;u++){const d=a.childNodes[u],f=n(d,[...c,l]);if(f)return f;l++}}return null};const s=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html").body.firstElementChild;return n(s)||[0]}catch(n){return $&&console.warn("[Template Compiler] Error finding DOM path for placeholder:",t,n),[0]}}function dt(e,t){return new ft(e,t).compile()}class ft{template;options;dynamics=[];statics=[];constructor(t,n){this.template=t,this.options=n}compile(){this.parseTemplate();const t=this.createStaticFragment(),n=X(this.template),r=(o,s)=>{let i="";for(let a=0;a<this.statics.length;a++)if(i+=this.statics[a],a<this.dynamics.length){let c=this.dynamics[a].getValue(o,s);if(c instanceof Promise)return Promise.all(this.dynamics.map(l=>{const u=l.getValue(o,s);return u instanceof Promise?u:Promise.resolve(u)})).then(l=>{let u="";for(let d=0;d<this.statics.length;d++)u+=this.statics[d],d<l.length&&(u+=l[d]);return u});i+=c}return i};return{statics:this.statics,dynamics:this.dynamics,fragment:t,id:n,hasDynamics:this.dynamics.length>0,render:r}}parseTemplate(){const t=/\{\{([^}]+)\}\}/g;let n=0,r;for(;(r=t.exec(this.template))!==null;){const s=this.template.slice(n,r.index);this.statics.push(s);let i=s.match(/([a-zA-Z0-9_-]+)\s*=\s*"?$/),a=i?i[1]:void 0,c;if(s.endsWith('style="color:'))a="style",c="color";else if(a==="style"){const u=s.match(/style\s*=\s*"?([^:;]+):\s*$/);u&&(c=u[1].trim())}const l=r[1].trim();this.analyzeDynamicExpression(l,this.dynamics.length,a,c),n=r.index+r[0].length}const o=this.template.slice(n);this.statics.push(o)}analyzeDynamicExpression(t,n,r,o){let s="text",i;r?r==="class"?(s="class",i="class"):r==="style"?(s="style",i=o||"style"):r==="value"?(s="property",i="value"):(s="attribute",i=r):t.includes("class.")?(s="class",i=t.split(".")[1]):t.includes("style.")?(s="style",i=t.split(".")[1]):t.includes("@")?(s="event",i=t.split("@")[1]):t==="class"?(s="class",i="class"):t==="style"?(s="style",i="style"):t==="value"?(s="property",i="value"):t==="title"&&(s="attribute",i="title");const a=`__DYNAMIC_${n}__`,c=this.statics.join(a);let l=ut(c,a);this.statics.length===2&&s!=="text"?l=[0]:this.statics.length===2&&l.length===0&&(l=[0]),this.dynamics.push({path:l,type:s,target:i,getValue:this.createValueGetter(t)})}createValueGetter(t){return(n,r)=>{try{let o;if(t&&typeof t=="function")o=t(n);else if(typeof t=="string"&&t.startsWith("state.")){const s=t.slice(6);o=n[s]}else typeof t=="string"&&/^[a-zA-Z0-9_$]+$/.test(t)?o=n[t]:(typeof t=="string"&&t.includes("("),o="");return o}catch(o){return this.options.development&&console.warn(`[Template Compiler] Error evaluating expression: ${t}`,o),""}}}createStaticFragment(){if(typeof document>"u")return null;try{const t=this.statics.join("");if(!t.trim())return null;const r=new DOMParser().parseFromString(t,"text/html"),o=document.createDocumentFragment();for(;r.body.firstChild;)o.appendChild(r.body.firstChild);return o}catch(t){return this.options.development&&console.warn("[Template Compiler] Could not create static fragment:",t),null}}}function j(e,t){try{if(t.length===1&&t[0]===0&&e instanceof Element)return e;let n=e;for(let r=0;r<t.length;r++){const o=t[r];if(!n.childNodes||n.childNodes.length<=o)return null;n=n.childNodes[o]}return n}catch{return null}}function H(e,t,n){let r;return e.fragment&&!e.hasDynamics?r=e.fragment.cloneNode(!0):r=ht(e,t,n),r}function V(e,t,n,r,o){if(e.hasDynamics)for(const s of e.dynamics)try{const i=s.getValue(n,r);if(o!==void 0&&s.getValue(o,r)===i)continue;Z(t,s,i)}catch(i){console.warn("[Template Compiler] Error applying update:",i)}}function ht(e,t,n){let r="";for(let a=0;a<e.statics.length;a++)if(r+=e.statics[a],a<e.dynamics.length){const c=e.dynamics[a];if(c.type==="text"||c.type==="attribute"){const l=c.getValue(t,n);r+=String(l??"")}else(c.type==="property"||c.type==="class"||c.type==="style")&&(r+="")}if(typeof document>"u")return new DocumentFragment;const s=new DOMParser().parseFromString(r,"text/html"),i=document.createDocumentFragment();for(;s.body.firstChild;)i.appendChild(s.body.firstChild);for(const a of e.dynamics){const c=a.getValue(t,n),l=j(i,a.path);Z(l,a,c)}return i}function Z(e,t,n){try{if(t.type==="text"){const o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let s=!1,i;for(;i=o.nextNode();){const c=i.textContent||"";if(c.includes("Count: ")){const l=c.replace(/Count: \d+/,`Count: ${n}`);i.textContent=l,s=!0}}if(s)return;const a=j(e,t.path);a&&a.nodeType===Node.TEXT_NODE&&(a.textContent=n==null?"":String(n));return}const r=j(e,t.path);if(!r)return;switch(t.type){case"attribute":if(r.nodeType===Node.ELEMENT_NODE&&t.target){const o=r;n==null||n===""?o.removeAttribute(t.target):o.setAttribute(t.target,String(n))}break;case"property":r.nodeType===Node.ELEMENT_NODE&&t.target&&(r[t.target]=n??"",r.setAttribute(t.target,n==null?"":String(n)));break;case"class":if(r.nodeType===Node.ELEMENT_NODE&&t.target){const o=r;o.className=n==null?"":String(n),o.setAttribute("class",n==null?"":String(n))}break;case"style":if(r.nodeType===Node.ELEMENT_NODE&&t.target){const o=r;o.style[t.target]=n==null?"":String(n),o.setAttribute("style",n==null?`${t.target}:`:`${t.target}:${n}`)}break;default:throw new Error(`Unknown update type: ${t.type}`)}}catch(r){(typeof globalThis<"u"?globalThis.isDevelopment:$)&&console.warn("[Template Compiler] Error applying update:",t,r)}}const N=new Map,S=new Map;function X(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t=(t<<5)-t+r,t=t&t}return`tpl_${Math.abs(t).toString(36)}`}function x(e,t,n,r,o){return r&&o?`${t}.${e}[${n}]:${r}:${o}`:r?`${t}.${e}[${n}]:${r}`:`${t}.${e}[${n}]`}function D(e,t,n){if(!(!e||!(e instanceof Element))&&e.contains(n)&&n.parentNode===e)try{e.replaceChild(t,n)}catch(r){console.error("[VDOM] safeReplaceChild: error replacing child",r,{parent:e,newChild:t,oldChild:n,parentHTML:e.outerHTML,newChildHTML:t.outerHTML,oldChildHTML:n.outerHTML})}}function b(e){if(e.type==="#whitespace")return null;if(e.type==="#text"){const n=document.createTextNode(e.props.nodeValue??"");return e.dom=n,n}const t=document.createElement(e.type);for(const[n,r]of Object.entries(e.props))n==="value"&&t instanceof HTMLInputElement?t.type==="radio"?t.setAttribute("value",r):(t.type,t.value=r,t.setAttribute("value",r)):t.setAttribute(n,r);e.dom=t;for(const n of e.children){const r=b(n);r&&t.appendChild(r)}return t}function Y(e){const t=document.createElement("template");t.innerHTML=e.trim();const n=Array.from(t.content.childNodes);return n.length===1?w(n[0]):{type:"#fragment",key:void 0,props:{},children:n.map((o,s)=>w(o,"#fragment",s)),dom:void 0}}function w(e,t="",n=0){if(!e)return{type:"#unknown",key:void 0,props:{},children:[],dom:void 0};if(e.nodeType===Node.TEXT_NODE)return!e.nodeValue||/^\s*$/.test(e.nodeValue)?{type:"#whitespace",key:void 0,props:{},children:[],dom:void 0}:{type:"#text",key:x("#text",t,n),props:{nodeValue:e.nodeValue},children:[],dom:e};if(e.nodeType===Node.ELEMENT_NODE){const r=e,o={};Array.from(r.attributes).forEach(l=>{o[l.name]=l.value});const s=r.tagName.toLowerCase();let i;if((s==="input"||s==="select"||s==="textarea")&&r.hasAttribute("data-model")){const l=r.getAttribute("data-model"),u=r.getAttribute("type")??"";i=`${s}:${l}:${u}`,o["data-uid"]=i,r.setAttribute("data-uid",i);let d=r.getAttribute("value"),f=r.getAttribute("checked");d&&(o.value=d),f&&(o.checked=f)}else s==="input"||s==="textarea"||s==="select"||r.hasAttribute("contenteditable")?(i=`${s}:${t}:${n}`,o["data-uid"]=i,r.setAttribute("data-uid",i)):(i=x(s,t,n),s==="li"&&(o["data-uid"]=i,r.setAttribute("data-uid",i)));const a=Array.from(r.childNodes).map((l,u)=>w(l,i,u));return{type:s,key:i,props:o,children:a,dom:r}}return{type:"#unknown",key:void 0,props:{},children:[],dom:void 0}}function R(e,t,n){if(!t||!n)return;function r(c){return!!c&&c.type!=="#whitespace"&&!(c.type==="#text"&&(!c.props?.nodeValue||/^\s*$/.test(c.props.nodeValue)))}const o=Array.isArray(t.children)?t.children.filter(r):[],s=Array.isArray(n.children)?n.children.filter(r):[],i=n.type==="input"||n.type==="select"||n.type==="textarea";if(t.type!==n.type||t.key!==n.key){const c=b(n);if(c instanceof Node&&t.dom instanceof Node&&e.contains(t.dom)){if(D(e,c,t.dom),i&&n.props&&e.firstChild instanceof HTMLInputElement){const l=e.firstChild;l.type==="radio"||l.type,l.value=n.props.value,l.setAttribute("value",n.props.value),"checked"in n.props&&(l.checked=n.props.checked===!0||n.props.checked==="true")}}else if(c instanceof Node)if(c){if(e.appendChild(c),n.dom=c,i&&n.props&&e.firstChild instanceof HTMLInputElement){const l=e.firstChild;l.type==="radio"?l.setAttribute("value",n.props.value):(l.type,l.value=n.props.value,l.setAttribute("value",n.props.value)),"checked"in n.props&&(l.checked=n.props.checked===!0||n.props.checked==="true")}}else n.dom=void 0;else n.dom=void 0;return}if(i&&t.dom instanceof HTMLElement&&n.props){for(const[c,l]of Object.entries(n.props))if(c==="value"&&e.firstChild instanceof HTMLInputElement)e.firstChild.value=l;else if(c==="checked"&&e.firstChild instanceof HTMLInputElement)e.firstChild.checked=l===!0||l==="true";else if(c in t.dom)try{t.dom[c]=l}catch{}else t.dom.setAttribute(c,l);for(let c=n.children.length;c<o.length;c++)o[c]&&o[c].dom&&t.dom&&t.dom.contains(o[c].dom)&&t.dom.removeChild(o[c].dom);return}const a=t.dom;if(a&&a instanceof Element&&n.props){const c=a.tagName.toLowerCase()==="input"?a.getAttribute("type"):void 0,l=a.tagName.includes("-");for(const[u,d]of Object.entries(n.props))if(!(c==="radio"&&u==="value")){if(c==="checkbox"&&u==="value"){a.setAttribute("value",d);continue}a.setAttribute(u,d)}if(l)for(const[u,d]of Object.entries(n.props))a.setAttribute(u,d);for(const u of Array.from(a.attributes).map(d=>d.name))if(!(u in n.props)){if(c==="radio"&&u==="value"||c==="checkbox"&&u==="value")continue;a.removeAttribute(u)}}if(n.type==="#text"){if(a&&a.nodeType===Node.TEXT_NODE)a.nodeValue!==n.props.nodeValue&&(a.nodeValue=n.props.nodeValue),n.dom=a;else{const c=document.createTextNode(n.props.nodeValue??"");a&&e.contains(a)&&a.parentNode===e?D(e,c,a):e.appendChild(c),n.dom=c}return}if(a instanceof Element){const c=new Map;o.forEach(f=>f.key&&c.set(f.key,f));const l=new Set(s.map(f=>f.key));let u=[];for(let f=0;f<s.length;f++){const h=s[f],y=h.key?c.get(h.key):o[f];let m;const W=h.type==="input"||h.type==="select"||h.type==="textarea";if(y&&y.dom&&(!W||y.type===h.type&&y.key===h.key))R(a,y,h),m=y.dom;else{const O=b(h);if(m=O instanceof Node?O:void 0,m){if((m instanceof Element||m instanceof Node)&&m.contains(a))throw console.error("[VDOM] Attempted to insert a parent into its own child:",{parentTag:a.tagName,childTag:m.tagName,parentUid:a.getAttribute?.("data-uid"),childUid:m.getAttribute?.("data-uid"),parent:a,child:m}),new Error("VDOM patch error: Attempted to insert a parent into its own child");a.insertBefore(m,a.childNodes[f]||null)}}h.dom=m,m&&u.push(m)}for(o.forEach(f=>{!l.has(f.key)&&f.dom&&a.contains(f.dom)&&a.removeChild(f.dom)});a.childNodes.length>s.length;)a.removeChild(a.lastChild);for(let f=0;f<u.length;f++)if(a.childNodes[f]!==u[f]){if((u[f]instanceof Element||u[f]instanceof Node)&&u[f].contains(a))throw new Error("VDOM patch error: Attempted to insert a parent into its own child");a.insertBefore(u[f],a.childNodes[f]||null)}n.dom=a;const d=new Set(s.map(f=>f.key));Array.from(a.childNodes).forEach((f,h)=>{const y=f.getAttribute?.("data-uid");(y&&!d.has(y)||h>=s.length)&&a.removeChild(f)})}}const pt=e=>e?typeof URLSearchParams>"u"?{}:Object.fromEntries(new URLSearchParams(e)):{},v=(e,t)=>{for(const n of e){const r=[],o=n.path.replace(/:[^/]+/g,a=>(r.push(a.slice(1)),"([^/]+)")),s=new RegExp(`^${o}$`),i=t.match(s);if(i){const a={};return r.forEach((c,l)=>{a[c]=i[l+1]}),{route:n,params:a}}}return{route:null,params:{}}},I={};async function J(e){if(e.component)return e.component;if(e.load){if(I[e.path])return I[e.path];try{const t=await e.load();return I[e.path]=t.default,t.default}catch{throw new Error(`Failed to load component for route: ${e.path}`)}}throw new Error(`No component or loader defined for route: ${e.path}`)}function Q(e){const{routes:t,base:n=""}=e;let r,o,s,i,a,c,l;if(typeof window<"u"&&typeof document<"u"){r=()=>{const d=new URL(window.location.href),f=d.pathname.replace(n,"")||"/",h=pt(d.search);return{path:f,query:h}},o=r();const u=v(t,o.path);s=L({path:o.path,params:u.params,query:o.query}),i=()=>{const d=r(),f=v(t,d.path),h=s.getState();h.path=d.path,h.params=f.params,h.query=d.query},window.addEventListener("popstate",i),a=d=>{window.history.pushState({},"",n+d),i()},c=d=>{window.history.replaceState({},"",n+d),i()},l=()=>window.history.back()}else{r=()=>({path:"/",query:{}}),o=r();const u=v(t,o.path);s=L({path:o.path,params:u.params,query:o.query}),i=()=>{},a=()=>{},c=()=>{},l=()=>{}}return{store:s,push:a,replace:c,back:l,subscribe:s.subscribe,matchRoute:u=>v(t,u),getCurrent:()=>s.getState(),resolveRouteComponent:J}}function mt(e,t){return v(e,t)}function P(e,t){const n=[],r=t?Object.keys(t):[],o={...e};let s=null;function i(u){return n.push(u),()=>{const d=n.indexOf(u);d!==-1&&n.splice(d,1)}}function a(u){Object.assign(s,u),n.forEach(d=>d(s))}const c=new WeakMap;function l(u){if(c.has(u))return c.get(u);const d=new Proxy(u,{get(f,h,y){if(h==="subscribe")return i;if(h==="set")return a;if(t&&r.includes(h))return t[h](s);const m=Reflect.get(f,h,y);return typeof m=="object"&&m!==null?l(m):m},set(f,h,y,m){if(t&&r.includes(h))return!1;const W=f[h],O=Reflect.set(f,h,y,m);return W!==y&&n.forEach(bt=>bt(s)),O},deleteProperty(f,h){if(t&&r.includes(h))return!1;const y=Reflect.deleteProperty(f,h);return n.forEach(m=>m(s)),y}});return c.set(u,d),d}return s=l(o),s}const _=[];function yt(e){_.push(e)}function A(e,t=new WeakSet){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e))return e.map(o=>A(o,t));Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null&&Object.setPrototypeOf(e,null);const n=["__proto__","constructor","prototype"],r=Object.create(null);for(const o of Object.keys(e))n.includes(o)||(r[o]=A(e[o],t));return r}function k(e){return!!e&&typeof e.then=="function"}let q;typeof HTMLElement<"u"?q=class extends HTMLElement{syncStateToAttributes(){if(!this.stateObj||!this.config?.reflect||!Array.isArray(this.config.reflect))return;const e=["__proto__","constructor","prototype"];this.config.reflect.forEach(t=>{if(e.includes(t)){this.removeAttribute(t);return}const n=this.stateObj[t];["string","number","boolean"].includes(typeof n)?n==null?this.removeAttribute(t):this.setAttribute(t,String(n)):this.removeAttribute(t)})}setTemplate(e){const t=this.config;typeof e=="function"?t.template=e:t.template=()=>e,this.render()}_hasError=!1;_mountedCalled=!1;_unmountedCalled=!1;_autoWiredHandlers={};removeEventListener(e,t,n){super.removeEventListener(e,t,n),this._autoWiredHandlers[e]&&(this._autoWiredHandlers[e]=this._autoWiredHandlers[e].filter(r=>r===t?(super.removeEventListener(e,r,n),!1):!0),this._autoWiredHandlers[e].length===0&&delete this._autoWiredHandlers[e])}static get observedAttributes(){const e=this.stateObj||{};return Object.keys(e).filter(t=>["string","number","boolean"].includes(typeof e[t]))}attributeChangedCallback(e,t,n){if(e==="__proto__"||e==="constructor"||e==="prototype"||!this.stateObj)return;const r=e.replace(/-([a-z])/g,(s,i)=>i.toUpperCase()),o=e in this.stateObj?e:r in this.stateObj?r:null;if(o){const s=typeof this.config?.state?.[o];let i=n;if(n===null)i=void 0;else if(s==="number")if(i===void 0||i==="")i=this.config?.state?.[o];else{const a=Number(i);i=isNaN(a)?this.config?.state?.[o]:a}else s==="boolean"&&(i=i==="true");i=A(i),this.stateObj[o]!==i&&(this.config?.debug&&console.log("[runtime] state update:",{stateKey:o,value:i}),this.stateObj[o]=i,this.render())}}forceSyncControlledInputs(){this.shadowRoot&&(this.shadowRoot.querySelectorAll("input[data-model]").forEach(e=>{const t=e.getAttribute("data-model");if(!t||!this.stateObj||typeof this.stateObj[t]>"u")return;const n=e,r=String(this.stateObj[t]),o=document.activeElement===n;n._hasDirtyListener||(n.addEventListener("input",()=>{n._isDirty=!0}),n.addEventListener("blur",()=>{n._isDirty=!1}),n._hasDirtyListener=!0);const s=!!n._isDirty;o||s||n.type!=="radio"&&n.type!=="checkbox"&&n.value!==r&&(n.value=r)}),this.rebindEventListeners())}syncControlledInputsAndEvents(){this.shadowRoot&&(this.shadowRoot.querySelectorAll('input[type="radio"][data-model]').forEach(e=>{const t=e.getAttribute("data-model");if(!t||!this.stateObj||typeof this.stateObj[t]>"u")return;const n=e,r=String(this.stateObj[t]);n.checked=n.value===r}),this.shadowRoot.querySelectorAll("input[data-model]").forEach(e=>{const t=e.getAttribute("data-model");if(!t||!this.stateObj||typeof this.stateObj[t]>"u")return;const n=e,r=String(this.stateObj[t]);if(n.type==="checkbox"){const o=this.stateObj[t];if(Array.isArray(o))n.checked=o.includes(n.value);else{const s=n.getAttribute("data-true-value"),i=n.getAttribute("data-false-value");s!==null||i!==null?String(o)===s?n.checked=!0:String(o)===i?n.checked=!1:o===!0?n.checked=!0:n.checked=!1:n.checked=o===!0||o==="true"||o===1}}else n.type==="radio"||(n.value=r)}),this.shadowRoot.querySelectorAll("textarea[data-model]").forEach(e=>{const t=e.getAttribute("data-model");!t||!this.stateObj||typeof this.stateObj[t]>"u"||(e.value=String(this.stateObj[t]))}),this.shadowRoot.querySelectorAll("select[data-model]").forEach(e=>{const t=e.getAttribute("data-model");!t||!this.stateObj||typeof this.stateObj[t]>"u"||(e.value=String(this.stateObj[t]))}))}attachListItemModelListeners(){this.shadowRoot&&this.shadowRoot.querySelectorAll("input[data-bind]").forEach(e=>{const t=e.getAttribute("data-bind");if(!t)return;e._listItemModelListener&&(e.removeEventListener("input",e._listItemModelListener),e.removeEventListener("change",e._listItemModelListener),delete e._listItemModelListener);const n=t.match(/^([a-zA-Z0-9_]+)\[(\d+)\]\.([a-zA-Z0-9_]+)$/);if(n){const[,o,s,i]=n,a=parseInt(s,10),c=this.stateObj[o];e instanceof HTMLInputElement&&e.type==="checkbox"&&(e.checked=!!(Array.isArray(c)&&c[a]&&c[a][i]));const l=u=>{!Array.isArray(c)||!c[a]||(e instanceof HTMLInputElement&&e.type==="checkbox"?c[a][i]=e.checked:c[a][i]=e.value)};e.addEventListener("input",l),e.addEventListener("change",l),e._listItemModelListener=l;return}const r=t.match(/^([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)((?:\|[a-zA-Z0-9_]+)*)$/);if(r){const[,o,s,i]=r,a=this.stateObj[o],c=i?i.split("|").map(u=>u.trim()).filter(Boolean):[];e instanceof HTMLInputElement&&e.type==="checkbox"?e.checked=!!(a&&a[s]):e instanceof HTMLInputElement&&(e.value=a?String(a[s]??""):"");const l=u=>{if(!a)return;let d;e instanceof HTMLInputElement&&e.type==="checkbox"?d=e.checked:(d=e.value,c.includes("number")&&(d=Number(d)),c.includes("trim")&&typeof d=="string"&&(d=d.trim())),a[s]=d};e.addEventListener("input",l),e.addEventListener("change",l),e._listItemModelListener=l}})}attachControlledInputListeners(){const e=this.shadowRoot;e&&(e.querySelectorAll("[data-model]").forEach(t=>{const n=t.getAttribute("data-model");n&&(t._dataModelBound||(G(t,this.stateObj,n),t._dataModelBound=!0))}),e.querySelectorAll("[data-model]").forEach(t=>{const[n]=t.getAttribute("data-model")?.split("|").map(r=>r.trim())??[];if(!(!n||!(n in this.stateObj)))if(t instanceof HTMLInputElement)if(t.type==="checkbox"){const r=this.stateObj[n],o=t.getAttribute("data-true-value"),s=t.getAttribute("data-false-value");Array.isArray(r)?t.checked=r.includes(t.value):o!==null||s!==null?String(r)===o?t.checked=!0:String(r)===s?t.checked=!1:r===!0?t.checked=!0:t.checked=!1:t.checked=r===!0||r==="true"||r===1}else t.type==="radio"?t.checked=t.value===String(this.stateObj[n]):t.value=String(this.stateObj[n]??"");else(t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&(t.value=String(this.stateObj[n]??""))}))}config;stateObj;api;_globalUnsubscribes=[];unsubscribes=[];lastCompiledTemplate=null;lastState=null;rafId=null;constructor(){super()}initializeConfig(){if(this.config)return;const e=this.tagName.toLowerCase(),n=(window.__componentRegistry||{})[e];if(!n||typeof n!="object")throw new Error("Invalid component config: must be an object");if(!n.state||typeof n.state!="object")throw new Error("Invalid component config: state must be an object");this.config=n;const r=n.computed?P(n.state,n.computed):P(n.state);if(this.stateObj=r,typeof this.stateObj.subscribe=="function"&&this.unsubscribes.push(this.stateObj.subscribe(()=>{this.scheduleRender()})),this.api={state:this.stateObj,emit:(s,i)=>this.dispatchEvent(new CustomEvent(s,{detail:i,bubbles:!0})),onGlobal:(s,i)=>{const a=C.on(s,i);return this._globalUnsubscribes.push(a),a},offGlobal:(s,i)=>C.off(s,i),emitGlobal:(s,i)=>C.emit(s,i),render:()=>this.render()},Object.keys(this.config).forEach(s=>{if(s.startsWith("on")&&s.length>2&&typeof this.config[s]=="function"){const i=s.charAt(2).toLowerCase()+s.slice(3),a=c=>{const l=c.detail??c;this.config[s](l,this.api.state,this.api)};this.addEventListener(i,a),this._autoWiredHandlers[i]||(this._autoWiredHandlers[i]=[]),this._autoWiredHandlers[i].push(a)}}),this.attachShadow({mode:"open"}),n.style){const s=document.createElement("style");s.textContent=typeof n.style=="function"?n.style(this.stateObj):n.style,this.shadowRoot.appendChild(s)}if(typeof this.config.hydrate=="function"){const s=this.shadowRoot?.querySelectorAll("[data-hydrate]");try{s&&s.length>0?s.forEach(i=>{try{this.config.hydrate(i,this.stateObj,this.api)}catch(a){typeof this.config.onError=="function"&&this.config.onError(a instanceof Error?a:new Error(String(a)),this.api.state,this.api),this._handleRenderError(a)}}):this.config.hydrate(this.shadowRoot,this.stateObj,this.api)}catch(i){typeof this.config.onError=="function"&&this.config.onError(i instanceof Error?i:new Error(String(i)),this.api.state,this.api),this._handleRenderError(i)}}if(this.hasAttribute("data-hydrated")?this.processRefs():this.render(),!this._mountedCalled&&typeof this.config.onMounted=="function")try{const s=this.config.onMounted(this.api.state,this.api);k(s)?s.catch(i=>{typeof this.config.onError=="function"&&this.config.onError(i,this.api.state,this.api),this._handleRenderError(i)}).finally(()=>{this._mountedCalled=!0}):this._mountedCalled=!0}catch(s){typeof this.config.onError=="function"&&this.config.onError(s,this.api.state,this.api),this._handleRenderError(s),this._mountedCalled=!0}}connectedCallback(){if(this.initializeConfig(),this.stateObj)for(const e of this.getAttributeNames()){const n=e.replace(/-([a-z])/g,(r,o)=>o.toUpperCase());if(n in this.stateObj){const r=typeof this.config?.state?.[n];let o=this.getAttribute(e);r==="number"?o=Number(o):r==="boolean"&&(o=o==="true"),this.stateObj[n]=o===null?void 0:o}}if(!this._mountedCalled&&typeof this.config.onMounted=="function")try{const e=this.config.onMounted(this.api.state,this.api);k(e)?e.catch(t=>{typeof this.config.onError=="function"&&this.config.onError(t,this.api.state,this.api),this._handleRenderError(t)}).finally(()=>{this._mountedCalled=!0}):this._mountedCalled=!0}catch(e){typeof this.config.onError=="function"&&this.config.onError(e,this.api.state,this.api),this._handleRenderError(e),this._mountedCalled=!0}typeof this.render=="function"&&this.render()}disconnectedCallback(){if(Object.entries(this._autoWiredHandlers).forEach(([e,t])=>{t.forEach(n=>{super.removeEventListener(e,n)})}),this._autoWiredHandlers={},this.unsubscribes.forEach(e=>e()),this.unsubscribes=[],this._globalUnsubscribes.forEach(e=>e()),this._globalUnsubscribes=[],!this._unmountedCalled&&typeof this.config.onUnmounted=="function")try{const e=this.config.onUnmounted(this.api.state,this.api);k(e)?e.catch(t=>{typeof this.config.onError=="function"&&this.config.onError(t,this.api.state,this.api),this._handleRenderError(t)}).finally(()=>{this._unmountedCalled=!0}):this._unmountedCalled=!0}catch(e){typeof this.config.onError=="function"&&this.config.onError(e,this.api.state,this.api),this._handleRenderError(e),this._unmountedCalled=!0}this._mountedCalled=!1,this._unmountedCalled=!1}render(){this._hasError=!1,this.syncControlledInputsAndEvents(),setTimeout(()=>this.attachControlledInputListeners(),0);try{_.forEach(t=>{try{t.onRender?.(this.stateObj,this.api)}catch(n){this._handleRenderError(n)}}),this.config.computed&&Object.values(this.config.computed).forEach(t=>{try{t(this.stateObj)}catch(n){this._handleRenderError(n)}});const e=this.config.template(this.stateObj,this.api);e instanceof Promise?e.then(t=>{this._hasError||(this._renderTemplateResult(t),this.syncStateToAttributes(),setTimeout(()=>this.attachListItemModelListeners(),0))}).catch(t=>{this._handleRenderError(t)}):this._hasError||(this._renderTemplateResult(e),this.syncStateToAttributes(),setTimeout(()=>this.attachListItemModelListeners(),0))}catch(e){this._handleRenderError(e),this.renderError(e instanceof Error?e:new Error(String(e)))}}_prevVNode=null;rebindEventListeners(){if(!this.shadowRoot)return;["data-on-input","data-on-change","data-on-blur","data-on-click"].forEach(t=>{this.shadowRoot.querySelectorAll(`[${t}]`).forEach(n=>{const r=t.replace("data-on-",""),o=n.getAttribute(t);if(!o||typeof this.config[o]!="function")return;n._boundHandlers&&n._boundHandlers[r]&&n.removeEventListener(r,n._boundHandlers[r]);const s=this.config[o],i=a=>s.call(this,a,this.stateObj,this.api);n.addEventListener(r,i),n._boundHandlers||(n._boundHandlers={}),n._boundHandlers[r]=i})}),Array.from(this.shadowRoot.children).forEach(t=>{t instanceof HTMLElement&&typeof t.rebindEventListeners=="function"&&t.rebindEventListeners()})}_renderTemplateResult(e){if(!this._hasError)try{let t=function(n){const r=new WeakSet;function o(s){if(s===null||typeof s!="object"||r.has(s))return s;if(r.add(s),Array.isArray(s))return s.map(o);const i={};for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&(i[a]=o(s[a]));return i}return o(n)};if(typeof e=="string"){let n=function(c){return c.replace(/<([a-zA-Z0-9]+)([^>]*)>/g,(l,u,d)=>{const f=d.replace(/\s+on[a-zA-Z]+\s*=\s*(['"][^'"]*['"]|[^\s>]*)/gi,"");return`<${u}${f}>`})},r=function(c){c.children.forEach(r)};const o=n(e),s=Y(o);r(s);const i=this.shadowRoot;if(!i)return;let a=i.querySelector("style");if(a||(a=document.createElement("style"),i.appendChild(a)),this.config.style?a.textContent=typeof this.config.style=="function"?this.config.style(this.stateObj):this.config.style:a.textContent="",s.type==="#fragment"){const c=Array.from(i.childNodes).find(l=>l.nodeType===1&&l!==a);if(c){Array.from(c.childNodes).forEach(d=>{d.nodeType===1&&d.nodeName==="STYLE"||c.removeChild(d)});const l={type:"#fragment",dom:c,children:s.children,props:{},key:void 0},u=this._prevVNode&&this._prevVNode.type==="#fragment"?{...this._prevVNode,dom:c}:l;R(c,u,l)}else s.children.forEach(l=>{const u=b(l);u&&i.appendChild(u),l.dom=u??void 0})}else{let c=Array.from(this.shadowRoot.childNodes).find(l=>l!==a&&l.nodeType===1);if(c)if(this._prevVNode&&(this._prevVNode.type!==s.type||this._prevVNode.key!==s.key)){const l=b(s);l&&(this.shadowRoot.contains(c)&&this.shadowRoot.replaceChild(l,c),c=l)}else R(c,this._prevVNode,s);else c=b(s),c&&this.shadowRoot.appendChild(c);s.dom=c}this._prevVNode=s,this.forceSyncControlledInputs(),this.lastCompiledTemplate=null}else{const n=!this.shadowRoot.firstElementChild,r=this.lastCompiledTemplate?.id===e.id;if(n){const o=H(e,this.stateObj,this.api);this.shadowRoot.appendChild(o)}else if(r&&this.shadowRoot.firstElementChild){const o=this.lastState;V(e,this.shadowRoot.firstElementChild,this.stateObj,this.api,o||void 0)}else{const o=H(e,this.stateObj,this.api);let s=this.shadowRoot.querySelector("style");s||(s=document.createElement("style"),this.shadowRoot.insertBefore(s,this.shadowRoot.firstChild)),this.config.style?s.textContent=typeof this.config.style=="function"?this.config.style(this.stateObj):this.config.style:s.textContent="";let i=this.shadowRoot.querySelector("[data-root]");for(i||(i=document.createElement("div"),i.setAttribute("data-root",""),this.shadowRoot.appendChild(i));i.firstChild;)i.removeChild(i.firstChild);i.appendChild(o)}this.lastCompiledTemplate=e}this.lastState=t(this.stateObj),this.updateStyle(),this.processRefs(),this.bindEvents(),this.syncControlledInputsAndEvents()}catch(t){this._handleRenderError(t)}}_handleRenderError(e){if(this._hasError=!0,this.config.debug&&console.error(`[runtime] Render error in <${this.tagName.toLowerCase()}>:`,e),_.forEach(t=>t.onError?.(e instanceof Error?e:new Error(String(e)),this.stateObj,this.api)),"onError"in this.config&&typeof this.config.onError=="function")try{this.config.onError(e instanceof Error?e:new Error(String(e)),this.api.state,this.api)}catch(t){this.config.debug&&console.error("[runtime] Error in onError handler:",t)}this.renderError(e instanceof Error?e:new Error(String(e)))}scheduleRender(){this.rafId!==void 0&&this.rafId!==null&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>{this.render(),this.rafId=null})}updateStyle(){const e=this.shadowRoot.querySelector("style");if(!e||!this.config.style)return;const t=typeof this.config.style=="function"?this.config.style(this.api.state):this.config.style;e.textContent=t}processRefs(){if(!this.config.refs)return;const e=new WeakMap;Object.entries(this.config.refs).forEach(([t,n])=>{const r=this.shadowRoot.querySelector(`[data-ref="${t}"]`);if(r){e.has(r)||e.set(r,new Set);const o=e.get(r),s=r.addEventListener;r.addEventListener=function(i,a,c){const l=`${i}`;o.has(l)||(o.add(l),s.call(r,i,a,c))},r.setAttribute("data-refs-processed","true");try{n(r,this.api.state,this.api)}catch(i){this._handleRenderError(i)}}})}bindEvents(){if(!this.shadowRoot)return;const e=document.createTreeWalker(this.shadowRoot,NodeFilter.SHOW_ELEMENT);let t=e.nextNode();for(;t;){const n=t;Array.from(n.attributes).forEach(r=>{if(r.name.startsWith("data-on-")){const o=r.name.slice(8),s=r.value,i=this.config[s];if(typeof i=="function"){n._boundHandlers&&n._boundHandlers[o]&&n.removeEventListener(o,n._boundHandlers[o]);const a=c=>{i.call(this.config,c,this.api.state,this.api),this.syncControlledInputsAndEvents()};n.addEventListener(o,a),n._boundHandlers||(n._boundHandlers={}),n._boundHandlers[o]=a}else this.config.debug&&console.warn(`[runtime] Handler '${s}' not found on config for event '${o}'`,n)}}),t=e.nextNode()}}renderError(e){const t=this.config.style?typeof this.config.style=="function"?this.config.style(this.api.state):this.config.style:"";this.shadowRoot.innerHTML=`
40
- <style>${t}</style>
41
- <div style="color: red; border: 1px solid red; padding: 1rem; border-radius: 4px;">
42
- <h3>Error Boundary</h3>
43
- <div>Error: ${e.message}</div>
44
- </div>
45
- `}}:q=class{constructor(){}};function z(e,t){if(t=A(t),t.debug&&console.log(`[runtime] Debugging component: ${e}`,t),!e||!t.template){t&&typeof t.onError=="function"&&t.onError(new Error("Component requires tag and template"),t.state??{},{state:t.state??{},emit:()=>{},onGlobal:()=>()=>{},offGlobal:()=>{},emitGlobal:()=>{}}),t&&t.debug&&console.error("[runtime] Malformed config:",{tag:e,config:t});return}_.forEach(u=>{try{u.onInit?.(t)}catch(d){t&&typeof t.onError=="function"&&t.onError(d instanceof Error?d:new Error(String(d)),t.state,{state:t.state,emit:()=>{},onGlobal:()=>()=>{},offGlobal:()=>{},emitGlobal:()=>{}}),t&&t.debug&&console.error("[runtime] Plugin onInit error:",d)}});const r=typeof window<"u"&&window.VITE_DEV_HMR,o=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:g&&g.tagName.toUpperCase()==="SCRIPT"&&g.src||new URL("custom-elements-runtime.umd.js",document.baseURI).href}<"u"&&void 0;if((r||o)&&typeof customElements<"u"&&customElements.get(e))try{document.querySelectorAll(e).forEach(u=>u.remove()),window.customElements._definitions&&delete window.customElements._definitions[e]}catch{}if(typeof customElements<"u"&&customElements.get(e)){t.debug&&console.warn(`[runtime] Component "${e}" already registered`);return}const s=P(t.state??{},t.computed);t.state=s,t._subscribe=s.subscribe;const i=t.state??{},a=Object.keys(i).filter(u=>["string","number","boolean"].includes(typeof i[u]));class c extends q{static get observedAttributes(){return a}constructor(){super()}}const l=c;typeof customElements<"u"&&!customElements.get(e)&&(window.__componentRegistry=window.__componentRegistry||{},window.__componentRegistry[e]=t,customElements.define(e,l))}function gt(e){const t=Q(e);return z("router-view",{template:async()=>{if(!t)return"<div>Router not initialized.</div>";const n=t.getCurrent(),{path:r}=n,o=t.matchRoute(r);return o.route?(o.route.load&&await o.route.load(),`<${o.route.component}></${o.route.component}>`):"<div>Not found</div>"},onMounted(n,r){t&&typeof t.subscribe=="function"&&t.subscribe(()=>{r.render()})}}),z("router-link",{state:{to:"",tag:"a",replace:!1,exact:!1,activeClass:"active",exactActiveClass:"exact-active",ariaCurrentValue:"page",disabled:!1,external:!1,style:B`
46
- [aria-disabled="true"] {
47
- pointer-events: none;
48
- opacity: 0.5;
49
- }
50
- `},computed:{current(){return t.getCurrent()},isExactActive(n){return n.current.path===n.to},isActive(n){const r=n.current;return n.exact?n.isExactActive:r&&typeof r.path=="string"?r.path.startsWith(n.to):!1},className(n){return n.isExactActive?n.exactActiveClass:n.isActive?n.activeClass:""},ariaCurrent(n){return n.isExactActive?`aria-current="${n.ariaCurrentValue}"`:""},isButton(n){return n.tag==="button"},disabledAttr(n){return n.disabled?n.isButton?'disabled aria-disabled="true" tabindex="-1"':'aria-disabled="true" tabindex="-1"':""},externalAttr(n){return n.external&&(n.tag==="a"||!n.tag)?'target="_blank" rel="noopener noreferrer"':""}},reflect:["to","tag","replace","exact","activeClass","exactActiveClass","ariaCurrentValue","disabled","external","style"],style:n=>n.style,template:n=>T`
51
- ${n.isButton?T`
52
- <button
53
- part="button"
54
- class="${n.className}"
55
- ${n.ariaCurrent}
56
- ${n.disabledAttr}
57
- ${n.externalAttr}
58
- data-on-click="navigate"
59
- ><slot></slot></button>
60
- `(n):T`
61
- <a
62
- part="link"
63
- href="${n.to}"
64
- class="${n.className}"
65
- ${n.ariaCurrent}
66
- ${n.disabledAttr}
67
- ${n.externalAttr}
68
- data-on-click="navigate"
69
- ><slot></slot></a>
70
- `(n)}
71
- `(n),navigate:(n,r)=>{if(r.disabled){n.preventDefault();return}r.external&&(r.tag==="a"||!r.tag)||(n.preventDefault(),r.replace?t.replace(r.to):t.push(r.to))}}),t}p.Store=L,p.classes=at,p.compile=ot,p.compileTemplate=lt,p.component=z,p.createVNodeFromElement=w,p.css=B,p.deepSanitizeObject=A,p.eventBus=C,p.generateHydrationScript=rt,p.getVNodeKey=x,p.html=T,p.initRouter=gt,p.isPromise=k,p.matchRouteSSR=mt,p.mountVNode=b,p.parseVNodeFromHTML=Y,p.patchVNode=R,p.renderCompiledTemplate=H,p.renderComponentsToString=nt,p.renderToString=F,p.resolveRouteComponent=J,p.runtimePlugins=_,p.safeReplaceChild=D,p.styles=ct,p.updateCompiledTemplate=V,p.useDataModel=G,p.useRouter=Q,p.useRuntimePlugin=yt,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(v,D){typeof exports=="object"&&typeof module<"u"?D(exports):typeof define=="function"&&define.amd?define(["exports"],D):(v=typeof globalThis<"u"?globalThis:v||self,D(v.CustomElementsRuntime={}))})(this,(function(v){"use strict";function D(n){let e=new Proxy(n,{set:(o,l,f)=>(o[l]=f,i(),!0)});const t=[];function s(o){t.push(o),o(e)}function r(){return e}function i(){t.forEach(o=>o(e))}return{subscribe:s,getState:r}}class M extends EventTarget{handlers={};static instance;eventCounters=new Map;static getInstance(){return M.instance||(M.instance=new M),M.instance}emit(e,t){const s=Date.now(),r=this.eventCounters.get(e);if(!r||s-r.window>1e3)this.eventCounters.set(e,{count:1,window:s});else if(r.count++,r.count>50&&(console.error(`Event storm detected for "${e}": ${r.count} events in 1 second. Throttling...`),r.count>100)){console.warn(`Blocking further "${e}" events to prevent infinite loop`);return}this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!1,cancelable:!0}));const i=this.handlers[e];i&&i.forEach(o=>{try{o(t)}catch(l){console.error(`Error in global event handler for "${e}":`,l)}})}on(e,t){return this.handlers[e]||(this.handlers[e]=new Set),this.handlers[e].add(t),()=>this.off(e,t)}off(e,t){const s=this.handlers[e];s&&s.delete(t)}offAll(e){delete this.handlers[e]}listen(e,t,s){return this.addEventListener(e,t,s),()=>this.removeEventListener(e,t)}once(e,t){return new Promise(s=>{const r=this.on(e,i=>{r(),t(i),s(i)})})}getActiveEvents(){return Object.keys(this.handlers).filter(e=>this.handlers[e]&&this.handlers[e].size>0)}clear(){this.handlers={}}getHandlerCount(e){return this.handlers[e]?.size||0}getEventStats(){const e={};for(const[t,s]of this.eventCounters.entries())e[t]={count:s.count,handlersCount:this.getHandlerCount(t)};return e}resetEventCounters(){this.eventCounters.clear()}}const Y=M.getInstance();function z(n,e={},t,s){const r=s??e.key;return{tag:n,key:r,props:e,children:t}}function V(n){return!!n&&typeof n=="object"&&(n.type==="AnchorBlock"||n.tag==="#anchor")}function B(n){return typeof n=="object"&&n!==null&&"tag"in n&&!V(n)}function Q(n,e){return n.key!=null?n:{...n,key:e}}function G(n,e=[],t={}){const s={},r={},i={},o=/([:@#]?)([a-zA-Z0-9-:\.]+)=("([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)')/g;let l;for(;l=o.exec(n);){const f=l[1],c=l[2],h=(l[4]||l[6])??"",d=h.match(/^{{(\d+)}}$/);let a=d?e[Number(d[1])]??null:h;if(d||(a==="true"?a=!0:a==="false"?a=!1:a==="null"?a=null:isNaN(Number(a))||(a=Number(a))),f===":")typeof a=="boolean"?r[c]=a:a!=null&&(s[c]=a);else if(f==="@"){const _="on"+c.charAt(0).toUpperCase()+c.slice(1);s[_]=typeof a=="function"?a:typeof t[a]=="function"?t[a]:void 0}else if(f==="#"){const[_,...b]=c.split("."),T=[...b];let C=a,u=[...T];if(_==="model"&&typeof C=="string"&&C.includes(".")){const p=["trim","number","lazy"],m=C.split(".");let g=C;const y=[];for(let E=m.length-1;E>0&&p.includes(m[E]);E--)y.unshift(m[E]),g=m.slice(0,E).join(".");C=g,u.push(...y)}i[_]={value:C,modifiers:u}}else r[c]=a}return{props:s,attrs:r,directives:i}}function ee(n,e,t){function s(u,p){return z("#text",{},u,p)}let r="";for(let u=0;u<n.length;u++)r+=n[u],u<e.length&&(r+=`{{${u}}}`);const i=/<\/?([a-zA-Z0-9-]+)([^>]*)\/?>|{{(\d+)}}|([^<]+)/g,o=[];let l=null,f,c=[],h=null,d={},a,_=0,b=[];function T(u){!u||typeof u!="object"||V(u)||(u.props||u.attrs?(u.props&&(d.props||(d.props={}),Object.assign(d.props,u.props)),u.attrs&&(d.attrs||(d.attrs={}),Object.keys(u.attrs).forEach(p=>{if(p==="style"&&d.attrs.style){const m=d.attrs.style.replace(/;?\s*$/,""),g=u.attrs.style.replace(/^;?\s*/,"");d.attrs.style=m+"; "+g}else if(p==="class"&&d.attrs.class){const m=d.attrs.class.trim().split(/\s+/).filter(Boolean),g=u.attrs.class.trim().split(/\s+/).filter(Boolean),y=[...new Set([...m,...g])];d.attrs.class=y.join(" ")}else d.attrs[p]=u.attrs[p]}))):(d.props||(d.props={}),Object.assign(d.props,u)))}function C(u,p){const m=h?c:b;if(V(u)){const g=u.key??p;let y=u.children;m.push({...u,key:g,children:y});return}if(B(u)){m.push(Q(u,void 0));return}if(Array.isArray(u)){if(u.length===0)return;for(let g=0;g<u.length;g++){const y=u[g];V(y)||B(y)||Array.isArray(y)?C(y,`${p}-${g}`):y!==null&&typeof y=="object"?T(y):m.push(s(String(y),`${p}-${g}`))}return}if(u!==null&&typeof u=="object"){T(u);return}m.push(s(String(u),p))}for(;f=i.exec(r);)if(f[1]){const u=f[1],p=f[0][1]==="/",m=f[0][f[0].length-2]==="/",{props:g,attrs:y,directives:E}=G(f[2]||"",e,t),S={props:{},attrs:{}};for(const A in g)S.props[A]=g[A];for(const A in y)S.attrs[A]=y[A];for(const[A,w]of Object.entries(E))if(A==="bind")if(typeof w.value=="object"&&w.value!==null)for(const[x,$]of Object.entries(w.value))typeof $=="boolean"?S.attrs[x]=$:$!=null&&(S.attrs[x]=String($));else w.value!=null&&(S.attrs[A]=String(w.value));else if(A==="show"){const x=!!w.value;S.attrs.style=(S.attrs.style||"")+(x?"":"; display: none !important")}else if(A==="class"){const x=w.value;let $=[];if(typeof x=="string")$=x.split(/\s+/).filter(Boolean);else if(Array.isArray(x)){for(const O of x)if(typeof O=="string")$.push(...O.split(/\s+/).filter(Boolean));else if(O&&typeof O=="object")for(const[j,W]of Object.entries(O))W&&$.push(...j.split(/\s+/).filter(Boolean))}else if(x&&typeof x=="object")for(const[O,j]of Object.entries(x))j&&$.push(...O.split(/\s+/).filter(Boolean));const R=S.attrs.class||"",P=[...new Set([...R.split(/\s+/).filter(Boolean),...$])];S.attrs.class=P.join(" ")}else if(A==="style"){const x=w.value;let $="";if(typeof x=="string")$=x;else if(x&&typeof x=="object"){const P=[];for(const[O,j]of Object.entries(x))if(j!=null&&j!==""){const W=O.replace(/[A-Z]/g,xe=>`-${xe.toLowerCase()}`),we=["width","height","top","right","bottom","left","margin","margin-top","margin-right","margin-bottom","margin-left","padding","padding-top","padding-right","padding-bottom","padding-left","font-size","line-height","border-width","border-radius","min-width","max-width","min-height","max-height"];let X=String(j);typeof j=="number"&&we.includes(W)&&(X=`${j}px`),P.push(`${W}: ${X}`)}$=P.join("; ")+(P.length>0?";":"")}const R=S.attrs.style||"";S.attrs.style=R+(R&&!R.endsWith(";")?"; ":"")+$}const k={};for(const[A,w]of Object.entries(E))["bind","show","class","style"].includes(A)||(k[A]=w);if(Object.keys(k).length>0&&(S.directives=k),p){const A=z(h,d,c.length===1&&B(c[0])&&c[0].tag==="#text"?typeof c[0].children=="string"?c[0].children:"":c.length?c:void 0,a),w=o.pop();w?(h=w.tag,d=w.props,a=w.key,c=w.children,c.push(A)):l=A}else m?(h?c:b).push(z(u,S,void 0,void 0)):(h&&o.push({tag:h,props:d,children:c,key:a}),h=u,d=S,c=[])}else if(typeof f[3]<"u"){const u=Number(f[3]),p=e[u],m=`interp-${u}`;C(p,m)}else if(f[4]){const u=f[4],p=h?c:b,m=u.split(/({{\d+}})/);for(const g of m){if(!g)continue;const y=g.match(/^{{(\d+)}}$/);if(y){const E=Number(y[1]),S=e[E],k=`interp-${E}`;C(S,k)}else{const E=`text-${_++}`;p.push(s(g,E))}}}if(l)return B(l)&&Array.isArray(l.children)&&(l.children=l.children.filter(u=>B(u)?u.tag!=="#text"||typeof u.children=="string"&&u.children.trim()!=="":!0)),l;if(b.length>0){const u=b.filter(p=>B(p)?p.tag!=="#text"||typeof p.children=="string"&&p.children.trim()!=="":!0);return u.length===1?u[0]:u}return z("div",{},"","fallback-root")}function te(n,...e){const t=e[e.length-1],s=typeof t=="object"&&t&&!Array.isArray(t)?t:void 0;return ee(n,e,s)}function ne(n,e){return H(n?e:[],"when-block")}function se(n,e){return n.map((t,s)=>{const r=typeof t=="object"?t?.key??t?.id??`idx-${s}`:String(t);return H(e(t,s),`each-${r}`)})}function re(){const n=[];return{when(e,t){return n.push([e,t]),this},otherwise(e){return n.push([!0,e]),this},done(){return ie(...n)}}}function ie(...n){for(let e=0;e<n.length;e++){const[t,s]=n[e];if(t)return[H(s,`whenChain-branch-${e}`)]}return[H([],"whenChain-empty")]}function H(n,e){const t=n?Array.isArray(n)?n.filter(Boolean):[n].filter(Boolean):[];return{tag:"#anchor",key:e,children:t}}function L(n,e){return e.split(".").reduce((t,s)=>t?.[s],n)}function F(n,e,t){const s=e.split("."),r=s.pop();if(!r)return;const i=s.reduce((o,l)=>(l in o||(o[l]={}),o[l]),n);i[r]=t}function oe(n,e,t,s,r,i,o){if(!i)return;const l=e.includes("lazy"),f=e.includes("trim"),c=e.includes("number"),h=()=>{const C=i._state||i;return L(C,n)},d=h();let a="text";const _=s?.type;if(o instanceof HTMLInputElement?a=_||o.type||"text":o instanceof HTMLSelectElement?a="select":o instanceof HTMLTextAreaElement&&(a="textarea"),a==="checkbox")if(Array.isArray(d)){const C=o?.getAttribute("value")||s?.value||"",u=d.includes(C);o&&o.checked!==u&&(t.checked=u)}else{const C=o?.getAttribute("true-value")||!0,u=d===C;o&&o.checked!==u&&(t.checked=u)}else if(a==="radio"){const C=s?.value||"",u=d===C;o&&o.checked!==u&&(t.checked=u)}else if(a==="select")if(o&&o.hasAttribute("multiple")){const C=o,u=Array.isArray(d)?d:[];setTimeout(()=>{Array.from(C.options).forEach(p=>{const m=u.includes(p.value);p.selected!==m&&(p.selected=m)})},0)}else setTimeout(()=>{o instanceof HTMLSelectElement&&o.value!==String(d)&&(o.value=String(d))},0);else{const C=String(d??"");(!o||o.value!==C)&&(t.value=d)}const b=l||a==="checkbox"||a==="radio"||a==="select"?"change":"input",T=C=>{if(C.isComposing||r._isComposing||C.isTrusted===!1)return;const u=C.target;if(u._modelUpdating)return;const p=h();let m=u.value;if(a==="checkbox")if(Array.isArray(p)){const S=u.getAttribute("value")||"",k=[...p];if(u.checked)k.includes(S)||k.push(S);else{const A=k.indexOf(S);A>-1&&k.splice(A,1)}m=k}else{const S=u.getAttribute("true-value")||!0,k=u.getAttribute("false-value")||!1;m=u.checked?S:k}else if(a==="radio")m=u.getAttribute("value")||u.value;else if(a==="select"&&u.multiple){const S=u;m=Array.from(S.selectedOptions).map(k=>k.value)}else if(f&&(m=m.trim()),c){const S=Number(m);isNaN(S)||(m=S)}const g=i._state||i,y=L(g,n);if(Array.isArray(m)&&Array.isArray(y)?JSON.stringify([...m].sort())!==JSON.stringify([...y].sort()):m!==y){const S=C.target;S._modelUpdating=!0,F(g,n,m),setTimeout(()=>{S._modelUpdating=!1},0),i._requestRender&&i._requestRender()}};if(r[b]=T,a==="text"||a==="textarea"){const C=()=>{r._isComposing=!0},u=p=>{r._isComposing=!1;const m=p.target;setTimeout(()=>{if(m){let g=m.value;if(f&&(g=g.trim()),c){const k=Number(g);isNaN(k)||(g=k)}const y=i._state||i,E=L(y,n);(Array.isArray(g)&&Array.isArray(E)?JSON.stringify([...g].sort())!==JSON.stringify([...E].sort()):g!==E)&&(m&&(m._modelUpdating=!0,setTimeout(()=>{m._modelUpdating=!1},0)),F(y,n,g),i._requestRender&&i._requestRender())}},0)};r.compositionstart=C,r.compositionend=u}}function ce(n,e,t,s){if(s)try{const r=JSON.parse(n);if(typeof r=="object")for(const[i,o]of Object.entries(r))e[i]=o}catch{const r=L(s,n);t[n]=r}}function le(n,e,t){if(!t)return;const s=L(t,n),r=e.style||"",i=s?"":"none";if(r){const o=r.split(";").filter(Boolean),l=o.findIndex(f=>f.trim().startsWith("display:"));l>=0?o[l]=`display: ${i}`:o.push(`display: ${i}`),e.style=o.join("; ")}else e.style=`display: ${i}`}function ae(n,e,t){if(!t)return;const s=L(t,n);let r=[];typeof s=="string"?r=[s]:Array.isArray(s)?r=s.filter(Boolean):typeof s=="object"&&(r=Object.entries(s).filter(([,l])=>!!l).map(([l])=>l));const i=e.class||"",o=i?`${i} ${r.join(" ")}`.trim():r.join(" ");o&&(e.class=o)}function ue(n,e,t){let s;if(typeof n=="string"){if(!t)return;s=L(t,n)}else s=n;let r="";if(typeof s=="string")r=s;else if(s&&typeof s=="object"){const o=[];for(const[l,f]of Object.entries(s))if(f!=null&&f!==""){const c=l.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`),h=["width","height","top","right","bottom","left","margin","margin-top","margin-right","margin-bottom","margin-left","padding","padding-top","padding-right","padding-bottom","padding-left","font-size","line-height","border-width","border-radius","min-width","max-width","min-height","max-height"];let d=String(f);typeof f=="number"&&h.includes(c)&&(d=`${f}px`),o.push(`${c}: ${d}`)}r=o.join("; ")+(o.length>0?";":"")}const i=e.style||"";e.style=i+(i&&!i.endsWith(";")?"; ":"")+r}function J(n,e,t,s){const r={},i={...s||{}},o={};for(const[l,f]of Object.entries(n)){const{value:c,modifiers:h}=f;switch(l){case"model":oe(typeof c=="string"?c:String(c),h,r,i,o,e,t);break;case"bind":ce(c,r,i,e);break;case"show":le(c,i,e);break;case"class":ae(c,i,e);break;case"style":ue(c,i,e);break}}return{props:r,attrs:i,listeners:o}}function K(n,e){if(Array.isArray(n)){const i=new Set;return n.map(o=>{if(!o||typeof o!="object")return o;let l=o.props?.key??o.key;if(!l){const d=o.tag||"node",a=o.props?.attrs?.id??o.props?.attrs?.name??o.props?.attrs?.["data-key"]??"";l=a?`${e}:${d}:${a}`:`${e}:${d}`}let f=l,c=1;for(;i.has(f);)f=`${l}#${c++}`;i.add(f);let h=o.children;return Array.isArray(h)&&(h=K(h,f)),{...o,key:f,children:h}})}const t=n;let s=t.props?.key??t.key??e,r=t.children;return Array.isArray(r)&&(r=K(r,s)),{...t,key:s,children:r}}function fe(n,e,t,s){const r=t.directives??{},i=J(r,s,n,t.attrs),o={...e.props,...t.props,...i.props},l={...e.attrs,...t.attrs,...i.attrs},f=e.props??{},c=o;for(const a in{...f,...c}){const _=f[a],b=c[a];_!==b&&(a==="value"&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement)?n.value!==b&&(n.value=b??""):a==="checked"&&n instanceof HTMLInputElement?n.checked=!!b:a.startsWith("on")&&typeof b=="function"?(typeof _=="function"&&n.removeEventListener(a.slice(2).toLowerCase(),_),n.addEventListener(a.slice(2).toLowerCase(),b)):b==null||b===!1?n.removeAttribute(a):n.setAttribute(a,String(b)))}for(const[a,_]of Object.entries(i.listeners||{}))n.addEventListener(a,_);const h=e.attrs??{},d=l;for(const a in{...h,...d}){const _=h[a],b=d[a];_!==b&&(b==null||b===!1?n.removeAttribute(a):n.setAttribute(a,String(b)))}}function N(n,e){if(typeof n=="string")return document.createTextNode(n);if(n.tag==="#text"){const c=document.createTextNode(typeof n.children=="string"?n.children:"");return n.key!=null&&(c.key=n.key),c}if(n.tag==="#anchor"){const c=n,h=Array.isArray(c.children)?c.children:[],d=document.createTextNode(""),a=document.createTextNode("");c.key!=null&&(d.key=`${c.key}:start`,a.key=`${c.key}:end`),c._startNode=d,c._endNode=a;const _=document.createDocumentFragment();_.appendChild(d);for(const b of h)_.appendChild(N(b,e));return _.appendChild(a),_}const t=document.createElement(n.tag);n.key!=null&&(t.key=n.key);const{props:s={},attrs:r={},directives:i={}}=n.props??{},o=J(i,e,t,r),l={...s,...o.props},f={...r,...o.attrs};for(const c in f){const h=f[c];typeof h=="boolean"?h&&t.setAttribute(c,""):h!=null&&t.setAttribute(c,String(h))}for(const c in l){const h=l[c];if(c==="value"&&(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement))t.value=h??"";else if(c==="checked"&&t instanceof HTMLInputElement)t.checked=!!h;else if(c.startsWith("on")&&typeof h=="function")t.addEventListener(c.slice(2).toLowerCase(),h);else{if(c.startsWith("on")&&h===void 0)continue;h==null||h===!1?t.removeAttribute(c):t.setAttribute(c,String(h))}}for(const[c,h]of Object.entries(o.listeners||{}))t.addEventListener(c,h);if(Array.isArray(n.children))for(const c of n.children)t.appendChild(N(c,e));else typeof n.children=="string"&&(t.textContent=n.children);return t}function he(n,e,t,s){if(typeof t=="string"){n.textContent!==t&&(n.textContent=t);return}if(!Array.isArray(t))return;const r=Array.from(n.childNodes),i=Array.isArray(e)?e:[],o=new Map;for(const a of i)a&&a.key!=null&&o.set(a.key,a);const l=new Map;for(const a of r){const _=a.key;_!=null&&l.set(_,a)}const f=new Set;let c=n.firstChild;function h(a,_){let b=a;for(;b&&(f.add(b),b!==_);)b=b.nextSibling}function d(a,_,b,T){const C=[];let u=a.nextSibling;for(;u&&u!==_;)C.push(u),u=u.nextSibling;const p=Array.isArray(b)?b:[];if(T.some(g=>g&&g.key!=null)||p.some(g=>g&&g.key!=null)){const g=new Map,y=new Map;for(const k of p)k&&k.key!=null&&g.set(k.key,k);for(const k of C){const A=k.key;A!=null&&y.set(A,k)}const E=new Set;let S=a.nextSibling;for(const k of T){let A;if(k.key!=null&&y.has(k.key)){const w=g.get(k.key);A=I(y.get(k.key),w,k,s),E.add(A),A!==S&&n.contains(A)&&n.insertBefore(A,S)}else A=N(k,s),n.insertBefore(A,S),E.add(A);S=A.nextSibling}for(const k of C)!E.has(k)&&n.contains(k)&&n.removeChild(k)}else{const g=Math.min(p.length,T.length);for(let y=0;y<g;y++){const E=p[y],S=T[y],k=I(C[y],E,S,s);k!==C[y]&&(n.insertBefore(k,C[y]),n.removeChild(C[y]))}for(let y=g;y<T.length;y++)n.insertBefore(N(T[y],s),_);for(let y=g;y<C.length;y++)n.removeChild(C[y])}}for(const a of t){let _;if(a.tag==="#anchor"){const b=a.key,T=`${b}:start`,C=`${b}:end`;let u=l.get(T),p=l.get(C);const m=Array.isArray(a.children)?a.children:[];if(u||(u=document.createTextNode(""),u.key=T),p||(p=document.createTextNode(""),p.key=C),a._startNode=u,a._endNode=p,!n.contains(u)||!n.contains(p)){n.insertBefore(u,c);for(const g of m)n.insertBefore(N(g,s),c);n.insertBefore(p,c)}else d(u,p,o.get(b)?.children,m);h(u,p),c=p.nextSibling;continue}if(a.key!=null&&l.has(a.key)){const b=o.get(a.key);_=I(l.get(a.key),b,a,s),f.add(_),_!==c&&n.contains(_)&&(c&&!n.contains(c)&&(c=null),n.insertBefore(_,c))}else _=N(a,s),c&&!n.contains(c)&&(c=null),n.insertBefore(_,c),f.add(_);c=_.nextSibling}for(const a of r)!f.has(a)&&n.contains(a)&&n.removeChild(a)}function I(n,e,t,s){if(e===t)return n;if(typeof t=="string"){if(n.nodeType===Node.TEXT_NODE)return n.textContent!==t&&(n.textContent=t),n;{const i=document.createTextNode(t);return n.parentNode?.replaceChild(i,n),i}}if(t&&typeof t!="string"&&t.tag==="#anchor"){const i=t,o=Array.isArray(i.children)?i.children:[],l=i._startNode??document.createTextNode(""),f=i._endNode??document.createTextNode("");i.key!=null&&(l.key=`${i.key}:start`,f.key=`${i.key}:end`),i._startNode=l,i._endNode=f;const c=document.createDocumentFragment();c.appendChild(l);for(const h of o)c.appendChild(N(h,s));return c.appendChild(f),n.parentNode?.replaceChild(c,n),l}if(!t){const i=document.createComment("removed");return n.parentNode?.replaceChild(i,n),i}if(!e||typeof e=="string"){const i=N(t,s);return n.parentNode?.replaceChild(i,n),i}if(t.tag==="#anchor"){const i=Array.isArray(t.children)?t.children:[],o=t._startNode??document.createTextNode(""),l=t._endNode??document.createTextNode("");t.key!=null&&(o.key=`${t.key}:start`,l.key=`${t.key}:end`),t._startNode=o,t._endNode=l;const f=document.createDocumentFragment();f.appendChild(o);for(const c of i)f.appendChild(N(c,s));return f.appendChild(l),n.parentNode?.replaceChild(f,n),o}if(typeof e!="string"&&typeof t!="string"&&e.tag===t.tag&&e.key===t.key){const i=n;return fe(i,e.props||{},t.props||{},s),he(i,e.children,t.children,s),i}const r=N(t,s);return n.parentNode?.replaceChild(r,n),r}function de(n,e,t){const s=c=>c.key==null?{...c,key:"__root__"}:c;let r=Array.isArray(e)?{tag:"div",key:"__root__",children:e}:s(e);r=K(r,String(r.key??"root"));const i=n._prevVNode??null,o=n._prevDom??n.firstChild??null;let l;i&&o?typeof i!="string"&&typeof r!="string"&&i.tag===r.tag&&i.key===r.key?l=I(o,i,r,t):(l=N(r,t),n.replaceChild(l,o)):(l=N(r,t),n.firstChild?n.replaceChild(l,n.firstChild):n.appendChild(l));const f=[];for(let c=0;c<n.childNodes.length;c++){const h=n.childNodes[c];h!==l&&h.nodeName!=="STYLE"&&f.push(h)}f.forEach(c=>n.removeChild(c)),n._prevVNode=r,n._prevDom=l}class ye{cache=new Map;maxSize;accessOrder=new Map;accessCounter=0;constructor(e=100){this.maxSize=e}set(e,t,s=[]){this.cache.size>=this.maxSize&&this.evictOldest(),this.cache.set(e,{css:t,timestamp:Date.now(),dependencies:s}),this.accessOrder.set(e,++this.accessCounter)}get(e){const t=this.cache.get(e);return t?(this.accessOrder.set(e,++this.accessCounter),t.css):null}has(e){return this.cache.has(e)}invalidate(e){const t=[];for(const[s,r]of this.cache)r.dependencies.includes(e)&&t.push(s);t.forEach(s=>{this.cache.delete(s),this.accessOrder.delete(s)})}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}evictOldest(){let e="",t=1/0;for(const[s,r]of this.accessOrder)r<t&&(t=r,e=s);e&&(this.cache.delete(e),this.accessOrder.delete(e))}getStats(){return{size:this.cache.size,maxSize:this.maxSize,hitRate:this.accessCounter>0?this.cache.size/this.accessCounter:0}}}function pe(n){return n.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,>+~])\s*/g,"$1").replace(/;}/g,"}").trim()}function ge(n){try{return JSON.stringify(n,(e,t)=>{if(typeof t=="function")return t.toString();if(typeof t=="object"&&t!==null){if(t.__hashed)return"[Circular]";t.__hashed=!0;const s={...t};return delete s.__hashed,s}return t})}catch{return n.map(e=>String(e)).join("|")}}function me(n){const e=n.split("}").filter(r=>r.trim()),t=new Set,s=[];for(const r of e){const i=r.trim().replace(/\s+/g," ");i&&!t.has(i)&&(t.add(i),s.push(r+"}"))}return s.join("").replace(/}$/,"")}function _e(n,e){let t=null;const s=((...r)=>{t!==null&&clearTimeout(t),t=setTimeout(()=>{n(...r),t=null},e)});return s.cancel=()=>{t!==null&&(clearTimeout(t),t=null)},s}class be{metrics=new Map;startTimer(e){const t=performance.now();return()=>{const s=performance.now()-t;return this.recordMetric(e,s),s}}recordMetric(e,t){this.metrics.has(e)||this.metrics.set(e,[]);const s=this.metrics.get(e);s.push(t),s.length>100&&s.shift()}getStats(e){if(e){const s=this.metrics.get(e)||[];return s.length===0?null:{operation:e,count:s.length,average:s.reduce((r,i)=>r+i,0)/s.length,min:Math.min(...s),max:Math.max(...s)}}const t={};for(const[s,r]of this.metrics)r.length>0&&(t[s]={count:r.length,average:r.reduce((i,o)=>i+o,0)/r.length,min:Math.min(...r),max:Math.max(...r)});return t}reset(e){e?this.metrics.delete(e):this.metrics.clear()}}const Ce=new be,ke=new Map;function q(n){return n.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function U(n){return typeof n=="string"?n.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e]):n}function Se(n){return n.replace(/url\s*\(\s*['"]?javascript:[^)]*\)/gi,"").replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi,"").replace(/expression\s*\([^)]*\)/gi,"")}function Ae(n,...e){let t="";for(let s=0;s<n.length;s++)t+=n[s],s<e.length&&(t+=e[s]);return t}function Ee(n,e,t){let s=q(n);s.includes("-")||(s=`cer-${s}`);let r;typeof e=="function"?r={...t,render:e}:r=e,typeof r.onError!="function"&&(r.onError=(i,o)=>{console.error(`[${s}] Error:`,i,o)}),ke.set(s,r),typeof window<"u"&&!customElements.get(s)&&customElements.define(s,Z(r))}function Z(n){if(!n.render)throw new Error("Component must have a render function");return typeof window>"u"?class{constructor(){}}:class extends HTMLElement{context;_listeners=[];_watchers=new Map;_renderTimeoutId=null;_mounted=!1;_hasError=!1;_initializing=!0;_styleElement=null;_styleCache=new ye(100);_lastStyleHash="";_styleDependencies=new Set;_styleUpdateDebounced;_cfg;_lastRenderTime=0;_renderCount=0;_templateLoading=!1;_templateError=null;constructor(){super(),this.attachShadow({mode:"open"}),this._cfg=n;const e={debounceMs:16,...n.styleOptimizations};this._styleUpdateDebounced=_e(t=>this._applyStyle(t),e.debounceMs),this.context=this._initContext(n),Object.keys(n).forEach(t=>{const s=n[t];typeof s=="function"&&!t.startsWith("on")&&(this.context[t]=(...r)=>s(...r,this.context))}),this._applyProps(n),this._applyComputed(n),this._initializing=!1,this._initWatchers(n),this._render(n)}connectedCallback(){this._runLogicWithinErrorBoundary(n,()=>{n.onConnected&&!this._mounted&&(n.onConnected(this.context),this._mounted=!0)})}disconnectedCallback(){this._runLogicWithinErrorBoundary(n,()=>{n.onDisconnected&&n.onDisconnected(this.context),this._listeners.forEach(e=>e()),this._listeners=[],this._watchers.clear(),this._styleCache.clear(),this._styleDependencies.clear(),this._styleElement=null,this._lastStyleHash="",this._styleUpdateDebounced.cancel(),this._templateLoading=!1,this._templateError=null,this._mounted=!1})}attributeChangedCallback(e,t,s){this._runLogicWithinErrorBoundary(n,()=>{this._applyProps(n),n.onAttributeChanged&&n.onAttributeChanged(e,t,s,this.context)})}static get observedAttributes(){return n.props?Object.keys(n.props).map(q):[]}_applyComputed(e){this._runLogicWithinErrorBoundary(n,()=>{e.computed&&Object.entries(e.computed).forEach(([t,s])=>{Object.defineProperty(this.context,t,{get:()=>{const r=s(this.context);return U(r)},enumerable:!0})})})}_render(e){this._runLogicWithinErrorBoundary(e,()=>{if(!this.shadowRoot)return;if(this._styleDependencies.clear(),this._templateLoading&&e.loadingTemplate){this._renderOutput(e.loadingTemplate(this.context));return}if(this._templateError&&e.errorTemplate){this._renderOutput(e.errorTemplate(this._templateError,this.context));return}const t=e.render(this.context);if(t instanceof Promise){this._templateLoading=!0,t.then(s=>(this._templateLoading=!1,this._templateError=null,this._renderOutput(s),s)).catch(s=>{if(this._templateLoading=!1,this._templateError=s,e.errorTemplate){const r=e.errorTemplate(s,this.context);return this._renderOutput(r),r}throw s}),e.loadingTemplate&&this._renderOutput(e.loadingTemplate(this.context));return}this._renderOutput(t),this._applyStyle(e)})}_renderOutput(e){if(!this.shadowRoot)return;const t=new Proxy(this.context,{get:(s,r)=>r==="_requestRender"?()=>this._requestRender():r==="context"?s:typeof r=="string"&&r.includes(".")?r.split(".").reduce((i,o)=>i?.[o],s):s[r],set:(s,r,i)=>{if(typeof r=="string"&&r.includes(".")){const o=r.split("."),l=o.pop();if(!l)return!1;const f=o.reduce((c,h)=>(h in c||(c[h]={}),c[h]),s);return f[l]=i,!0}return s[r]=i,!0}});de(this.shadowRoot,Array.isArray(e)?e:[e],t),this._requestStyleUpdate()}_requestRender(){if(this._renderTimeoutId!==null&&clearTimeout(this._renderTimeoutId),Date.now()-this._lastRenderTime<16){if(this._renderCount++,this._renderCount>10){console.warn(`[${this.tagName}] Potential infinite render loop detected. Skipping render.`),this._renderTimeoutId=null;return}}else this._renderCount=0;this._renderTimeoutId=setTimeout(()=>{this._lastRenderTime=Date.now(),this._render(this._cfg),this._renderTimeoutId=null},0)}_requestStyleUpdate(){this._styleUpdateDebounced(this._cfg)}_applyStyle(e){this._runLogicWithinErrorBoundary(e,()=>{if(!this.shadowRoot)return;const t=Ce.startTimer("applyStyle");try{if(this._styleElement||(this._styleElement=this.shadowRoot.querySelector("style"),this._styleElement||typeof document<"u"&&(this._styleElement=document.createElement("style"),this.shadowRoot.prepend(this._styleElement))),!e.style){this._styleElement.textContent="";return}const s={enableCaching:!0,enableMinification:!1,enableDeduplication:!0,cacheSize:100,debounceMs:16,...e.styleOptimizations};let r;typeof e.style=="string"?r={css:e.style,cache:s.enableCaching}:typeof e.style=="function"?r={css:e.style,cache:s.enableCaching}:r={cache:s.enableCaching,...e.style};const i=r.dependencies||[],o=r.cache!==!1&&s.enableCaching;let l="";if(o&&i.length>0){const h=i.map(d=>this.context[d]);if(l=ge(h),this._lastStyleHash===l&&this._styleCache.has(l)){const d=this._styleCache.get(l);this._styleElement.textContent!==d&&(this._styleElement.textContent=d);return}}(!o||i.length===0)&&(l="no-deps-"+Date.now());const f=typeof r.css=="function"?r.css(this.context):r.css;let c=Se(f);s.enableMinification&&(c=pe(c)),s.enableDeduplication&&(c=me(c)),o&&i.length>0&&(this._styleCache.set(l,c,i.map(String)),this._lastStyleHash=l),this._styleElement.textContent!==c&&(this._styleElement.textContent=c)}finally{t()}})}_runLogicWithinErrorBoundary(e,t){this._hasError&&(this._hasError=!1);try{t()}catch(s){this._hasError=!0,e.onError&&e.onError(s,this.context),e.errorFallback&&this.shadowRoot&&(this.shadowRoot.innerHTML=e.errorFallback(s,this.context))}}_initContext(e){try{let t=function(r,i=""){return Array.isArray(r)?new Proxy(r,{get(o,l,f){const c=Reflect.get(o,l,f);return typeof c=="function"&&typeof l=="string"&&["push","pop","shift","unshift","splice","sort","reverse"].includes(l)?function(...d){const a=c.apply(o,d);if(!s._initializing){const _=i||"root";s._triggerWatchers(_,o),s._render(e)}return a}:c},set(o,l,f){if(o[l]=f,!s._initializing){const c=i?`${i}.${String(l)}`:String(l);s._styleDependencies.add(String(l)),s._styleCache.invalidate(String(l)),s._triggerWatchers(c,f);const h=e.style;let d=!1;if(h&&typeof h=="object"&&"dependencies"in h){const a=h.dependencies||[];d=a.includes(String(l))&&a.every(_=>!s._styleDependencies.has(String(_))||_===l)}d?s._requestStyleUpdate():s._render(e)}return!0},deleteProperty(o,l){if(delete o[l],!s._initializing){const f=i?`${i}.${String(l)}`:String(l);s._styleDependencies.add(String(l)),s._triggerWatchers(f,void 0),s._render(e)}return!0}}):r&&typeof r=="object"?(Object.keys(r).forEach(o=>{const l=i?`${i}.${o}`:o;r[o]=t(r[o],l)}),new Proxy(r,{set(o,l,f){const c=i?`${i}.${String(l)}`:String(l);return o[l]=t(f,c),s._initializing||(s._triggerWatchers(c,o[l]),s._render(e)),!0},get(o,l,f){return Reflect.get(o,l,f)}})):r};const s=this;return t({...e.state})}catch{return{}}}_initWatchers(e){if(e.watch)for(const[t,s]of Object.entries(e.watch)){let r,i={};if(Array.isArray(s)?(r=s[0],i=s[1]||{}):r=s,this._watchers.set(t,{callback:r,options:i,oldValue:this._getNestedValue(t)}),i.immediate)try{const o=this._getNestedValue(t);r(o,void 0,this.context)}catch(o){console.error(`Error in immediate watcher for "${t}":`,o)}}}_getNestedValue(e){return e.split(".").reduce((t,s)=>t?.[s],this.context)}_triggerWatchers(e,t){const s=(i,o)=>{if(i===o)return!0;if(typeof i!=typeof o||typeof i!="object"||i===null||o===null)return!1;if(Array.isArray(i)&&Array.isArray(o))return i.length!==o.length?!1:i.every((c,h)=>s(c,o[h]));const l=Object.keys(i),f=Object.keys(o);return l.length!==f.length?!1:l.every(c=>s(i[c],o[c]))},r=this._watchers.get(e);if(r&&!s(t,r.oldValue))try{r.callback(t,r.oldValue,this.context),r.oldValue=t}catch(i){console.error(`Error in watcher for "${e}":`,i)}for(const[i,o]of this._watchers.entries())if(o.options.deep&&e.startsWith(i+"."))try{const l=this._getNestedValue(i);s(l,o.oldValue)||(o.callback(l,o.oldValue,this.context),o.oldValue=l)}catch(l){console.error(`Error in deep watcher for "${i}":`,l)}}_applyProps(e){try{let t=function(s,r){return r===Boolean?s==="true":r===Number?Number(s):s};if(!e.props)return;Object.entries(e.props).forEach(([s,r])=>{const i=this.getAttribute(q(s));i!==null?this.context[s]=U(t(i,r.type)):"default"in r&&r.default!==void 0&&(this.context[s]=U(r.default))})}catch(t){this._hasError=!0,e.onError&&e.onError(t,this.context),e.errorFallback&&this.shadowRoot&&(this.shadowRoot.innerHTML=e.errorFallback(t,this.context))}}}}v.component=Ee,v.createElementClass=Z,v.createStore=D,v.css=Ae,v.each=se,v.eventBus=Y,v.html=te,v.match=re,v.when=ne,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})}));
72
2
  //# sourceMappingURL=custom-elements-runtime.umd.js.map