wcstack 1.33.0 → 2.0.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.
package/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n,s=".",r="*",i=128,a="@",l="|",c="prevent",d="stop",u="ro",h="init",f="sync",p="else",m="...",g="on",b="eventToken",y="command",_="class",w="attr",v="style",N={};for(let t=0;t<128;t++)N[`$${t+1}`]=t;const S=Object.freeze(N),I="$connectedCallback",P="$disconnectedCallback",x="$updatedCallback",$="$stateReadyCallback",E="$bindables",C="$commands",A="$commandTokens",k="$command",T="$eventTokens",M="$on",L="$streams",O="$watch",R="$listKeys",j="$streamStatus",D="$streamError",B="data-wc-definition",W=new WeakMap,F=new WeakSet;let z=0;async function H(t){const e=function(t){let e,n=W.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++z,promise:o,resolve:e},W.set(t,n),F.has(t)&&n.resolve(),n}(t);await e.promise}function U(t){const e=W.get(t);void 0===e?F.add(t):e.resolve()}const q=new Map;let G=0;function V(t){let e=q.get(t);return void 0!==e||(e=Object.freeze(new K(t)),q.set(t,e)),e}let K=class{id=++G;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:V(e),n=t.split("."),o=[],s=[],i=[],a={},l=[],c=[],d=[],u=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===r&&(i.push(h),a[h]=p,l.push(e(h)),c.push(f),d.push(e(f)),u.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=i.length>0?i[i.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=i,this.wildcardPathSet=new Set(i),this.indexByWildcardPath=a,this.wildcardPathInfos=l,this.wildcardPathInfoSet=new Set(l),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}};const J=new WeakMap;function Q(t){const e=J.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{J.set(t,n)}}function X(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Y(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return X(e);if(void 0!==n)return X(n)}return X(globalThis.customElements)}function Z(t,e){t.upgrade?.(e)}function tt(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=st(s.properties,et);if(null===r)return null;const i=void 0===s.inputs?new Map:st(s.inputs,nt);if(null===i)return null;const a=void 0===s.commands?new Map:st(s.commands,ot);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function et(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function nt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function ot(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function st(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function rt(t){throw new Error(`[@wcstack/state] ${t}`)}function it(t,e,n){const o="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:o,statePathInfo:V(o),stateName:n,inFilters:[],outFilters:[],bindingType:"prop"}}function at(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function lt(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&rt("Spread binding requires an element node.");const e=t,o=Q(e);null===o&&rt(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Y(e);if(null===a&&rt(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||rt(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Z(a,e);const l=tt(e);null===l&&rt(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=n.stateName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=it(t,c,d);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=it(t,c,d);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=at(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=at(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function ct(t,e){let n=t;if(0===e.length)return n;for(let t=0;t<e.length&&(n=n?.childNodes[e[t]]??null,null!==n);t++);return n}const dt=new WeakMap;function ut(t){return dt.get(t)||null}function ht(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function ft(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=ht(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const pt=" Validate statically: npx @wcstack/lint <file>.",mt=new Set(["if","elseif","else","for"]);function gt(t){rt(`filter ${t} requires at least one option`)}function bt(t){rt(`filter ${t} requires a number as option`)}function yt(t){rt(`filter ${t} requires a number value`)}function _t(t){rt(`filter ${t} requires a date value`)}function wt(t){return!(!t||isNaN(Number(t)))}const vt={eq:t=>{const e=t?.[0]??gt("eq");return t=>"number"==typeof t?(wt(e)||bt("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??gt("ne");return t=>"number"==typeof t?(wt(e)||bt("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&rt("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??gt("lt");return wt(e)||bt("lt"),t=>("number"!=typeof t&&yt("lt"),t<Number(e))},le:t=>{const e=t?.[0]??gt("le");return wt(e)||bt("le"),t=>("number"!=typeof t&&yt("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??gt("gt");return wt(e)||bt("gt"),t=>("number"!=typeof t&&yt("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??gt("ge");return wt(e)||bt("ge"),t=>("number"!=typeof t&&yt("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??gt("inc");return wt(e)||bt("inc"),t=>("number"!=typeof t&&yt("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??gt("dec");return wt(e)||bt("dec"),t=>("number"!=typeof t&&yt("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??gt("mul");return wt(e)||bt("mul"),t=>("number"!=typeof t&&yt("mul"),t*Number(e))},div:t=>{const e=t?.[0]??gt("div");return wt(e)||bt("div"),t=>("number"!=typeof t&&yt("div"),t/Number(e))},mod:t=>{const e=t?.[0]??gt("mod");return wt(e)||bt("mod"),t=>("number"!=typeof t&&yt("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&yt("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??gt("clamp");wt(e)||bt("clamp");const n=t?.[1]??gt("clamp");wt(n)||bt("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&yt("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return wt(e)||bt("fix"),t=>("number"!=typeof t&&yt("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&yt("locale"),t.toLocaleString(e??o.locale))},uc:t=>t=>String(t).toUpperCase(),lc:t=>t=>String(t).toLowerCase(),cap:t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)},trim:t=>t=>String(t).trim(),slice:t=>{const e=[],n=t?.[0]??gt("slice");wt(n)||bt("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(wt(o)||bt("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??gt("substr");wt(e)||bt("substr");const n=t?.[1]??gt("substr");return wt(n)||bt("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??gt("pad");wt(e)||bt("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??gt("rep");return wt(e)||bt("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??gt("truncate");wt(e)||bt("truncate");const n=Number(e),o=t?.[1]??"…";return t=>{const e=String(t);return e.length<=n?e:e.slice(0,n)+o}},join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||rt("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=t?.[0]??"0";return wt(e)||bt("round"),t=>{"number"!=typeof t&&yt("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return wt(e)||bt("floor"),t=>{"number"!=typeof t&&yt("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return wt(e)||bt("ceil"),t=>{"number"!=typeof t&&yt("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return wt(e)||bt("percent"),t=>("number"!=typeof t&&yt("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??gt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||_t("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||_t("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||_t("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||_t("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||_t("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!1===t||null==t||0===t||""===t||Number.isNaN(t),truthy:t=>t=>!1!==t&&null!=t&&0!==t&&""!==t&&!Number.isNaN(t),defaults:t=>{const e=t?.[0]??gt("defaults");return t=>!1===t||null==t||0===t||""===t||Number.isNaN(t)?e:t},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),null:t=>t=>""===t?null:t},Nt=vt,St={input:vt,output:Nt},It=(t,e)=>n=>{const o=n[t];return o||rt(`[wcs/filter-unknown] filter not found: ${t}.${ft(t,Object.keys(n))}${pt}`),o(e)};function Pt(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const xt=new Map;function $t(t,e){const n=St[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&rt(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&rt(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=xt.get(s);return void 0===r&&(r=It(o,[])(n),xt.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=t.substring(o+1,s),i=t.substring(0,o).trim(),a=function(t){const e=[];let n="",o=null,s=!1,r=-1,i=-1;const a=()=>{e.push(Pt(n,r,i)),n="",s=!1,r=-1,i=-1};for(let e=0;e<t.length;e++){const l=t[e];o?l===o?o=null:(-1===r&&(r=n.length),n+=l,i=n.length):'"'===l||"'"===l?(o=l,s=!0):","===l?a():n+=l}const l=Pt(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=xt.get(l);return void 0===c&&(c=It(i,a)(n),xt.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const Et=t=>t.trim(),Ct=new Map,At=new Set;function kt(t,e){if(!o.debug)return;const n=`${t}:${e}`;if(At.has(n))return;At.add(n);const s="attribute"===t?`<wcs-state name="${e}"> will be removed in v2. Mount the state onto the root tree with <wcs-state mount="${e}"> and read it as "${e}.<path>".`:`"${e}" uses the "@name" state selector, which will be removed in v2. Read the mounted tree as "<name>.<path>" instead.`;console.warn(`[@wcstack/state] [wcs/named-state-deprecated] ${s} See docs/state-mount-design.md §9.`)}const Tt=new Map;function Mt(t){const e=t.indexOf(l);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Tt.has(s)?r=Tt.get(s):(o=s.split(l).map(Et),r=$t(o,"output"),Tt.set(s,r))):n=t.trim(),-1!==n.indexOf(a)&&kt("path",n);const[i,c="default"]=n.split(a).map(Et);return{stateName:c,statePathName:i,statePathInfo:V(i),outFilters:r}}function Lt(t){const[...e]=t.split(";").map(Et).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&rt(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===p){const t=V("#else");return{propName:p,propSegments:[p],propModifiers:[],statePathName:"#else",statePathInfo:t,stateName:"",inFilters:[],outFilters:[],bindingType:"else"}}if(n===m){const e=Mt(o);return e.outFilters.length>0&&rt(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&rt(`Invalid spread binding "${t}": spread target path is required.`),{propName:m,propSegments:[m],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Mt(o),bindingType:n};{const t=Mt(o),e=function(t){const e=t.indexOf(l);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),Ct.has(r)?i=Ct.get(r):(o=r.split(l).map(Et),i=$t(o,"input"),Ct.set(r,i))):n=t.trim();const[a,c]=n.split("#").map(Et),d=a.split(s).map(Et);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map(Et):[],inFilters:i}}(n);return e.propSegments[0]===b||e.propSegments[0].startsWith(g)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>mt.has(t.bindingType))&&rt(`[wcs/template-syntax] Invalid bindText: "${t}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${pt}`),n}const Ot=new WeakMap,Rt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),jt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Dt(t){const e=Ot.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=jt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Rt.has(r)?(Ot.set(t,s[2]),s[2]):null}function Bt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Mt(t),bindingType:"text"}}const Wt=new Map;function Ft(t,e,n){if(null===n)Wt.delete(t);else{Wt.set(t,n);const o=n.parseBindTextResult,s=wi(e,o.stateName);null===s&&rt(`State element with name "${o.stateName}" not found for fragment info.`),s.setPathInfo(o.statePathName,o.bindingType);for(const t of n.nodeInfos)for(const n of t.parseBindTextResults){const t=wi(e,n.stateName);null===t&&rt(`State element with name "${n.stateName}" not found for fragment info node.`),t.setPathInfo(n.statePathName,n.bindingType)}}}function zt(t){return Wt.get(t)||null}function Ht(t){if(t.nodeType===Node.ELEMENT_NODE)return Lt(t.getAttribute(o.bindAttributeName)||"");if(t.nodeType===Node.COMMENT_NODE){const e=Dt(t);null===e&&rt("Comment node binding text not found.");const n=zt(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Bt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function Ut(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function qt(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Ut(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function Gt(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function Vt(t){const e=[],n=qt(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Dt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&Gt(t,n)||e.push(t)}return e}const Kt=new WeakSet;function Jt(t,e,n){const o=lt(t,e,{allowDeferred:n.allowDeferred});if(o.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Q(t):null;return null===n&&rt("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e}}}Kt.add(t);const s=function(t,e){const n=[];for(const o of e)if("text"!==o.bindingType)n.push({...o,node:t,replaceNode:t});else{const e=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,node:t,replaceNode:e})}return n}(t,o);return function(t,e){dt.set(t,e)}(t,s),U(t),{bindings:s,deferred:null}}function Qt(t){const e=Vt(t),n=[],o=[];for(const t of e){if(Kt.has(t))continue;const e=Jt(t,Ht(t),{allowDeferred:!0});null===e.deferred?n.push(...e.bindings):o.push(e.deferred)}return[e,n,o]}function Xt(t){Kt.add(t)}function Yt(t){const{node:e,parseResults:n}=t;return function(t){Kt.delete(t)}(e),Jt(e,n,{allowDeferred:!1}).bindings}const Zt=new WeakMap;function te(t){let e=t;for(;e;){const t=Zt.get(e);if(t)return t;e=e.parentNode}return null}function ee(t,e){null!==e?Zt.set(t,e):Zt.delete(t)}let ne=null;const oe=new WeakMap;function se(t){return oe.get(t)??[]}function re(t,e){oe.set(t,e)}const ie=Symbol("$$setLoopContext"),ae=Symbol("$$getByAddress"),le=Symbol("$$hasByAddress"),ce=Symbol("$$setByAddress"),de=Symbol("$$connectedCallback"),ue=Symbol("$$disconnectedCallback"),he=Symbol("$$updatedCallback"),fe=new WeakMap;function pe(t,e){if(fe.has(t)){const n=fe.get(t);if(n.has(e))return n.get(e)}else fe.set(t,new WeakMap);const n=Object.freeze(new me(t,e));return fe.get(t).set(e,n),n}class me{pathInfo;stateName;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateName=t.name,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=pe(t,e.parentPathInfo)}}const ge=new WeakMap,be=new WeakMap;class ye{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const t=this.absolutePathInfo.parentAbsolutePathInfo;if(null===t)return null;let e=null;return e=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=_e(t,e)}}function _e(t,e){if(null===e){let e=be.get(t);return void 0!==e||(e=new ye(t,null),be.set(t,e)),e}{let n=ge.get(e);void 0===n&&(n=new WeakMap,ge.set(e,n));let o=n.get(t);return void 0!==o||(o=new ye(t,e),n.set(t,o)),o}}const we=new WeakMap;function ve(t,e){null===e?we.delete(t):we.set(t,e)}function Ne(t){return we.get(t)||null}const Se=new Map;function Ie(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=Se.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Se.set(s,r)),r}function Pe(t,e,n){return e<0||e>=n?null:t.at(e-n)}function xe(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const $e=new WeakMap;function Ee(t){const e=te(t.node);if(null===e)return null;let n=$e.get(e);if(void 0===n)n=new WeakMap,$e.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Ie(e.pathInfo,t.statePathInfo);return n>0&&(o=Pe(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const Ce=new WeakMap;function Ae(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Ne(n);null===e?rt(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function ke(t,e){let n=null;if(n=Ce.get(t)||null,null!==n)return n;const o=Ae(t,e),s=Ee(t),r=wi(o,t.stateName);return null===r&&rt(`State element with name "${t.stateName}" not found for binding.`),n=_e(pe(r,t.statePathInfo),s),Ce.set(t,n),n}function Te(t){Ce.delete(t)}const Me=new WeakMap;function Le(t,e){const n=Me.get(t);void 0===n?Me.set(t,e):n instanceof Set?n.add(e):n!==e&&Me.set(t,new Set([n,e])),null!==ne&&ne({type:"state:binding-added",absoluteAddress:t,binding:e})}function Oe(t,e){const n=Me.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&Me.delete(t),null!==ne&&ne({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const Re=new WeakMap;function je(t,e,n){let o=Re.get(t);void 0===o&&(o=new WeakMap,Re.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==ne&&ne({type:"state:binding-added",absoluteAddress:_e(t,e),binding:n})}function De(t,e,n){const o=Re.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==ne&&ne({type:"state:binding-removed",absoluteAddress:_e(t,e),binding:n}))}function Be(t){const e=Me.get(t);return void 0!==e?e:null!==t.listIndex?Re.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const We=new WeakMap,Fe=new WeakMap;class ze{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=He(t,e)}}function He(t,e){if(null===e){let e=Fe.get(t);return void 0!==e||(e=new ze(t,null),Fe.set(t,e)),e}{let n=We.get(e);void 0===n&&(n=new WeakMap,We.set(e,n));let o=n.get(t);return void 0!==o||(o=new ze(t,e),n.set(t,o)),o}}const Ue=new WeakMap;function qe(t){let e=null;if(e=Ue.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=Ee(t);null===n&&rt(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=He(t.statePathInfo,n)}else e=He(t.statePathInfo,null);return Ue.set(t,e),e}function Ge(t){Ue.delete(t)}function Ve(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const Ke=new Map,Je=Ve();function Qe(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.statePathName}::${e}::${n}`}function Xe(t){let e="input";for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function Ye(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function Ze(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Ye(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class tn{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)e.push(n(...t));return e}}class en extends tn{_ownerStateName;constructor(t,e){super(t),this._ownerStateName=e??null}emit(...t){return null!==ne&&ne({type:"state:token-emit",kind:"event",stateName:this._ownerStateName,tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}const nn=new WeakMap;function on(t,e){let n=nn.get(t);void 0===n&&(n=new Map,nn.set(t,n));let o=n.get(e);return void 0===o&&(o=new en(e,t.name),n.set(e,o)),o}function sn(t){nn.delete(t)}const rn=new WeakMap;class an extends tn{_ownerStateName;constructor(t,e){super(t),this._ownerStateName=e??null}emit(...t){return null!==ne&&ne({type:"state:token-emit",kind:"command",stateName:this._ownerStateName,tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}function ln(t){return t instanceof an}const cn=new Map,dn=Ve();function un(t){const e=t.propModifiers.filter(t=>t===c||t===d).sort().join(",");return`${t.stateName}::${t.statePathName}::${e}`}function hn(t){if(!t.propName.startsWith(g))return!1;const e=un(t);let n=cn.get(e);void 0===n&&(n=((t,e,n,o)=>s=>{n.includes(c)&&s.preventDefault(),n.includes(d)&&s.stopPropagation();const r=s.target,i=wi(r.getRootNode(),t);null===i&&rt(`State element with name "${t}" not found for event handler.`);const a=te(r),l=e.startsWith(k+".");i.createStateAsync("writable",async n=>{Ze(n[ie](a,()=>{const r=null!==a?xe(a.listIndex,a.pathInfo.wildcardCount):[];if(l){const t=n[ae](He(o,null));return ln(t)||rt(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),t.emit(s,...r)}const i=n[e];return"function"!=typeof i&&rt(`Handler "${e}" is not a function on state "${t}".`),Reflect.apply(i,n,[s,...r])}),`"${e}" of state "${t}"`)})})(t.stateName,t.statePathName,t.propModifiers,t.statePathInfo),cn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),dn.add(e,t),!0}const fn=new Map,pn=Ve();function mn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.statePathName}::${e}::${n}`}function gn(t){let e="input";for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}const bn=new Set(["radio","checkbox"]),yn=new Set(["value","valueAsNumber","valueAsDate"]);function _n(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(bn.has(t)&&"checked"===e)return!0;if(yn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Q(n);if(null!==s){const t=Y(n)?.get(s);void 0===t&&rt(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=tt(n);if(o?.knownProperties.has(e))return!0}return!1}let wn=1,vn=1,Nn=1;const Sn=new WeakMap;function In(t,e,n,o){let s=Sn.get(t);void 0===s&&(s=new Map,Sn.set(t,s));const r=function(t,e,n){return`${e}::${n}::${t}`}(e,n,o);let i=s.get(r);return void 0===i&&(i=wn++,s.set(r,i)),i}function Pn(t,e){return"to-element"===e?2*t:2*t+1}const xn=new Set;function $n(t){return{transactionId:vn++,originBindingId:t,visitedEdges:xn,hop:0}}function En(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let Cn=null;function An(){return Cn}function kn(t,e){const n=Cn;Cn=t;try{return e()}finally{Cn=n}}const Tn=[];let Mn=!1;const Ln=new Map,On=Ve(),Rn=new WeakMap,jn=t=>t.detail;function Dn(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function Bn(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Q(t.node);if(null!==n){const o=Y(t.node)?.get(n);void 0===o&&rt(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=tt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function Wn(t){if(null!==Q(t.node)){const e=tt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??jn}return null}function Fn(t){if(null===Q(t.node))return!1;const e=tt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const zn=new WeakMap;function Hn(t,e){const n=zn.get(t);return n?n.get(e)??null:null}const Un=new WeakMap;function qn(t,e){Un.set(t,e)}function Gn(t){return Un.get(t)??null}function Vn(t){let e=t;for(;;){if(null==e||!0!==e.hasMappedComponentState)return null;const t=e.boundComponent;if(null==t)return null;const n=te(t)?.listIndex;if(null!=n)return n;e=Gn(t)}}function Kn(t){return Vn(t)?.length??0}function Jn(t,e){return e.wildcardCount+Kn(t)}function Qn(t,e){return e??Vn(t)}const Xn=new WeakMap,Yn=new WeakMap,Zn=new WeakMap,to=new WeakMap;function eo(t,e){const n=e.propSegments.slice(1).join(s);return{innerAbsPathInfo:pe(t,V(n)),outerAbsPathInfo:ke(e).absolutePathInfo,isRoot:0===n.length}}function no(t){return Zn.get(t)??null}function oo(t){const e=Zn.get(t);if(void 0===e)return!1;for(const t of e)if(t.isRoot)return!0;return!1}function so(t,e,n=!0){let r=Xn.get(t);if(void 0===r&&(r=new Map,Xn.set(t,r)),r.has(e))return r.get(e);let i=Yn.get(t);void 0===i&&(i=new Map,Yn.set(t,i));const a=Zn.get(t);if(void 0===a)return null;let l=null,c=-1;for(const t of a){if(t.isRoot){c<0&&(l=t,c=0);continue}if(!e.pathInfo.cumulativePathInfoSet.has(t.innerAbsPathInfo.pathInfo))continue;const n=t.innerAbsPathInfo.pathInfo.segments.length;n===e.pathInfo.segments.length&&rt("Duplicate mapping rule for web component."),n>c&&(l=t,c=n)}if(null===l)return null;const d=to.get(l);void 0===d&&rt("Binding not found for primary mapping rule on web component.");const u=e.pathInfo.segments.slice(c),h=V(l.outerAbsPathInfo.pathInfo.segments.concat(u).join(s)),f=wi(t.getRootNode(),d.stateName);null===f&&rt(`State element with name "${d.stateName}" not found for web component.`);const p=pe(f,h);if(!n)return p;r.set(e,p),i.set(p,e);const m=[d.propSegments[0],...e.pathInfo.segments],g={...d,propName:m.join(s),propSegments:m,statePathName:p.pathInfo.path,statePathInfo:p.pathInfo},b=e=>{o.debug&&console.warn(`parent→child notification for "${p.pathInfo.path}" is not registered: ${e}.`,{webComponent:t,primaryBinding:d})},y=Uo(d);return null===y?(b("no binding session for the primary mapping rule"),p):p.pathInfo.wildcardCount>0&&null===Ee(g)?(b("the derived outer path is a wildcard path but no list index resolves from the component"),p):(y.initialize([g],{registerAddress:!0}),p)}function ro(t,e){const n=io(t,e);return null===n||n.stateElement===t||Jn(t,e)!==Jn(n.stateElement,n.pathInfo)?null:n}function io(t,e){if(!0!==t.hasMappedComponentState)return null;const n=t.boundComponent;return null==n?null:so(n,pe(t,e),!1)}const ao=new WeakSet;function lo(t){ao.add(t)}function co(t){return!!ao.has(t)&&(ao.delete(t),!0)}const uo=new WeakSet;function ho(t){uo.add(t)}function fo(t){return!!uo.has(t)&&(uo.delete(t),!0)}let po=0;function mo(){po--}function go(){return po>0}class bo{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const yo=new WeakMap;function _o(t){let e=yo.get(t);return void 0===e&&(e=new bo(t),yo.set(t,e)),e}function wo(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==h&&s!==f&&rt(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&rt(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function vo(t){return t.propModifiers.some(t=>t.includes("="))}const No=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),So=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Io(t,e){return"state"===t&&"call"===e?No:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Po(t){if(!o.enableDirectionalInitialSync)return vo(t)&&rt("init=/sync= modifiers require enableDirectionalInitialSync."),No;const e=null===(n=wo(t,h))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:rt(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":rt(`Invalid sync modifier value "${t}".`)}(wo(t,f));if("event"===t.bindingType)return null!==e&&"none"!==e&&rt("Event bindings only allow init=none."),"call"===s?So:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===y)return Io("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&rt(`Binding type "${t.bindingType}" does not support init=${e}.`),Io(e??"state",s);const r=tt(t.node);if(null===r)return Io(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||rt(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||rt(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||rt(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let xo=0,$o=0;const Eo=new WeakMap,Co=new WeakMap,Ao=new WeakMap,ko=new WeakMap;function To(t,e){const n=ko.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):ko.set(t,new Set([n,e]))):ko.set(t,e)}function Mo(t){return ko.has(t)}function Lo(t,e){const n=ko.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Oo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Oo(n,e)}function Ro(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class jo{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(const o of t)e.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));const o=[];for(const t of e)co(t)||Oo(t,t=>{Lo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)fo(t)&&!go()||Oo(t,t=>{Lo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&xr(o)}}const Do=new WeakMap;function Bo(t){let e=Do.get(t);return void 0===e&&(e=new jo(t),Do.set(t,e)),e}function Wo(t){const e=t.inFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|"),n=t.outFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.bindingType,t.propName,t.propModifiers.join(","),t.stateName,t.statePathName,e,n,t.uuid??""].join("\0")}function Fo(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class zo{records=new Set;rowPlan=null;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=Eo.get(t);void 0===o||"disposed"===o.phase||"failed"===o.phase?(this.start(t,s,n),r.push(t)):(this.observe(o.anchor),s.registerAddress&&null===o.address&&null===o.patternListIndex&&(o.options.registerAddress=!0,this.registerAddress(o)),"active"===o.phase&&this.settleInitialRecord(o),this.settleConnectedSnapshot(o))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(Ro(e)&&Bo(e),null===this.rowPlan)for(const n of t){const t=Eo.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return vo(t)&&Po(t),!0;const e=Eo.get(t);return void 0===e||e.session!==this||!e.options.registerAddress||"waiting-definition"===e.phase||"failed"!==e.phase&&("active"===e.phase&&this.settleInitialRecord(e),e.initialApplyDone?"state"===e.resolvedAuthority||!e.outputOnlyMember&&!e.observationPending:(e.initialApplyDone=!0,"state"===e.resolvedAuthority))}getRecord(t){const e=Eo.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=Eo.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(Fo(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=Y(t);null===s&&rt(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),To(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=_o(s).wait(e,()=>{if(a())try{Z(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=Eo.get(t);void 0!==e&&e.session===this&&this.disposeRecord(e)}dispose(){for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.records)null!==t.address&&(Oe(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}observe(t){const e=function(t){const e=t.getRootNode();return Ro(e)?e:null}(t);null!==e&&Bo(e)}handleMutations(t,e,n){for(const n of e)Oo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Oo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&xr(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Eo.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=Ao.get(e);void 0===t&&(t=Wo(e),Ao.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;To(n,this);const o=this.knownMapFor(n);let s=Ao.get(t);void 0===s&&(s=Wo(t),Ao.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n={registerAddress:!1,registerPathInfo:!1,applyOnReconnect:!1},o=t.slots;for(let s=0;s<e.length;s++){const r=e[s],i=o[s],a=r.replaceNode;To(a,this),this.addKnownRowBinding(a,r,s),this.optionsByBinding.set(r,n);const l={id:++xo,info:r,generation:++$o,phase:"active",teardowns:null,session:this,anchor:a,options:n,address:null,patternPathInfo:null,patternListIndex:null,outerPatternPathInfo:null,outerPatternPathInfosRest:null,pendingDefinitions:0,initialPolicy:i.policy,resolvedAuthority:i.authority,initialSettled:!0,initialApplyDone:!1,outputOnlyMember:i.policy.outputOnly,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};if(Eo.set(r,l),this.records.add(l),i.isEvent){try{hn(r)}catch(t){throw l.phase="failed",this.runTeardowns(l),this.records.delete(l),t}l.eventAttached=!0}}}activatePlanRows(t,e,n){const o=t.slots;for(let s=0;s<e.length;s++){const r=e[s],i=Eo.get(r);if(void 0!==i&&i.session===this){if(i.options.registerAddress=!0,"disposed"===i.phase||"failed"===i.phase){const e=o[s];if(i.generation=++$o,i.phase="active",i.initialPolicy=e.policy,i.resolvedAuthority=e.authority,i.initialSettled=!0,i.initialApplyDone=!1,i.outputOnlyMember=e.policy.outputOnly,this.records.add(i),e.isEvent){try{hn(r)}catch(t){throw i.phase="failed",this.runTeardowns(i),this.records.delete(i),t}i.eventAttached=!0}this.registerAddress(i,n);continue}null===i.address&&null===i.patternListIndex&&this.registerAddress(i,n)}else this.initialize([r],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++xo,info:t,generation:++$o,phase:"discovered",teardowns:null,session:this,anchor:t.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,outerPatternPathInfo:null,outerPatternPathInfosRest:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Eo.set(t,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;hn(e)?t.eventAttached=!0:e.propSegments[0]!==b?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(u)){const s=gn(t),r=mn(t,s);let i=fn.get(r);return void 0===i&&(e=t.stateName,n=t.statePathName,o=t.inFilters,i=t=>{const s=t.target;if(null===s)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==s.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===s.checked)return;let r=s.value;for(const t of o)r=t.filterFn(r);const i=wi(s.getRootNode(),e);null===i&&rt(`State element with name "${e}" not found for two-way binding.`);const a=te(s);i.createState("writable",t=>{t[ie](a,()=>{t[n]=r})})},fn.set(r,i)),t.node.addEventListener(s,i),pn.add(r,t),!0}var e,n,o;return!1}(e)&&Fo(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(u)){const e=gn(t),n=mn(t,e),o=fn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==pn.countOf(n)&&(pn.remove(n,t)&&fn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(u)){const s=Xe(t),r=Qe(t,s);let i=Ke.get(r);return void 0===i&&(e=t.stateName,n=t.statePathName,o=t.inFilters,i=t=>{const s=t.target;if(null===s)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==s.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const r=s.checked;let i=s.value;for(const t of o)i=t.filterFn(i);const a=wi(s.getRootNode(),e);null===a&&rt(`State element with name "${e}" not found for two-way binding.`);const l=te(s);a.createState("writable",t=>{t[ie](l,()=>{let e=t[n];if(Array.isArray(e))if(r)-1===e.indexOf(i)&&(t[n]=e.concat(i));else{const o=e.indexOf(i);-1!==o&&(t[n]=e.toSpliced(o,1))}else t[n]=r?[i]:[]})})},Ke.set(r,i)),t.node.addEventListener(s,i),Je.add(r,t),!0}var e,n,o;return!1}(e)&&Fo(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(u)){const e=Xe(t),n=Qe(t,e),o=Ke.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Je.countOf(n)&&(Je.remove(n,t)&&Ke.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&_n(e.node,e.propName)&&-1===e.propModifiers.indexOf(u)){const n=function(t,e,n){let o=Rn.get(t);void 0===o&&(o=new Map,Rn.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&Rn.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});Fo(t,n)}!function(t){const e=Q(t.node);if(null!==e){const n=Y(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&rt(`CustomElementRegistry is unavailable for <${e}>.`))}if(_n(t.node,t.propName)&&-1===t.propModifiers.indexOf(u)){const e=Bn(t),n=Wn(t),s=Fn(t),r=Dn(t,e,null!==n,s);let i=Ln.get(r);void 0===i&&(i=((t,e,n,s,r,i)=>a=>{const l=a.target;if(null===l)return void console.warn("[@wcstack/state] event.target is null.");let c;if(null!==r)c=r(a);else{if(!(e in l))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);c=l[e]}let d=c;for(const t of s)d=t.filterFn(d);const u=Rn.get(l)?.get(e);if(void 0!==u)for(const t of u)t(d);let h=null;if(o.enablePropagationContext){const s=In(l,e,t,n),r=function(t,e){for(let n=Tn.length-1;n>=0;n--){const o=Tn[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(l,e);if(null!==r&&Object.is(r.writtenValue,c))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:l,propName:e,statePathName:n,transactionId:r.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===d||"object"!=typeof d)}),void(null!==ne&&ne({type:"propagation:suppressed",reason:"confirmation",transactionId:r.transactionId,edgeId:Pn(s,"to-state"),node:l,member:e}));const i=Pn(s,"to-state"),a=An();if(null!==a&&a.visitedEdges.has(i))return void(null!==ne&&ne({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:l,member:e}));h=En(a??$n(s),i)}const f=wi(l.getRootNode(),t);null===f&&rt(`State element with name "${t}" not found for two-way binding.`);const p=te(l),m=()=>{i&&(Mn=!0);try{f.createState("writable",t=>{t[ie](p,()=>{t[n]=d})})}finally{i&&(Mn=!1)}};null!==h?kn(h,m):m()})(t.stateName,t.propName,t.statePathName,t.inFilters,n,s),Ln.set(r,i)),t.node.addEventListener(e,i),On.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==b)return!1;const e=t.node,n=Q(e),o=Y(e);if(null!==n&&void 0===o?.get(n))return null===o&&rt(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(rn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||rt('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Q(t)?null:tt(t)}(e);null===r&&rt(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&rt(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${ft(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,u=t.stateName,h=t.propModifiers,f=t=>{h.includes(c)&&t.preventDefault(),h.includes(d)&&t.stopPropagation();const n=wi(e.getRootNode(),u);null===n&&rt(`State element with name "${u}" not found for eventToken handler.`),n.eventTokenNames.has(l)||rt(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens of state "${u}".${ft(l,n.eventTokenNames)}${pt}`);const o=te(e);n.createStateAsync("writable",async e=>{Ze(e[ie](o,()=>{const s=null!==o?xe(o.listIndex,o.pathInfo.wildcardCount):[];return on(n,l).emit(e,t,...s)}),`$on."${l}" of state "${u}"`)})};return e.addEventListener(a,f),rn.set(t,{eventName:a,handler:f}),!0})(e)&&Fo(t,()=>function(t){if(t.propSegments[0]!==b)return!1;const e=rn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),rn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Q(t.info.node);if(null===n)return void e();const o=Y(t.info.node);if(null===o&&rt(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=_o(o).wait(n,()=>{if(this.isAlive(t,s))try{Z(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});Fo(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Po(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=wi(t.replaceNode.getRootNode(),t.stateName);null===e&&rt(`State element with name "${t.stateName}" not found for binding.`);const n=qe(t);let o=!1;return e.createState("readonly",t=>{o=t[le](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void po++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,mo()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=wi(t.node.getRootNode(),t.stateName);null===o&&rt(`State element with name "${t.stateName}" not found for initial binding sync.`);const s=te(t.node);o.createState("writable",e=>{e[ie](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=Ee(n);if(null!==o){const i=wi(Ae(n,e),n.stateName);null===i&&rt(`State element with name "${n.stateName}" not found for binding.`);const a=pe(i,n.statePathInfo);je(a,o,n),t.patternPathInfo=a,t.patternListIndex=o;const l=(s=i,0===(r=n.statePathInfo).wildcardCount?null:ro(s,r));if(null!==l){je(l,o,n),t.outerPatternPathInfo=l;const e=function(t){let e=null,n=t.stateElement,o=t.pathInfo;for(;;){const t=ro(n,o);if(null===t)return e;(e??=[]).push(t),n=t.stateElement,o=t.pathInfo}}(l);if(null!==e){for(let t=0;t<e.length;t++)je(e[t],o,n);t.outerPatternPathInfosRest=e}}}else{const o=ke(n,e);Le(o,n),t.address=o}var s,r;if(!t.options.registerPathInfo)return;const i=wi(n.replaceNode.getRootNode(),n.stateName);null===i&&rt(`State element with name "${n.stateName}" not found for binding.`),"event"!==n.bindingType&&i.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Eo.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,mo());const e=t.info;if(null!==t.address)try{Oe(t.address,e),t.address=null,Ge(e),Te(e)}catch{}else if(null!==t.patternListIndex){if(null!==t.outerPatternPathInfo){try{De(t.outerPatternPathInfo,t.patternListIndex,e)}catch{}t.outerPatternPathInfo=null}if(null!==t.outerPatternPathInfosRest){const n=t.outerPatternPathInfosRest;for(let o=0;o<n.length;o++)try{De(n[o],t.patternListIndex,e)}catch{}t.outerPatternPathInfosRest=null}try{De(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,Ge(e),Te(e)}catch{}}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=Q(t.node);if(null!==e){const n=Y(t.node),o=n?.get(e);if(void 0===o)return}if(_n(t.node,t.propName)&&-1===t.propModifiers.indexOf(u)){const e=Bn(t),n=Dn(t,e,null!==Wn(t),Fn(t)),o=Ln.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),On.remove(n,t)&&Ln.delete(n)}}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{!function(t){if(!t.propName.startsWith(g))return!1;const e=un(t),n=cn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==dn.countOf(e)&&dn.remove(e,t)&&cn.delete(e)}(e)}catch{}}}}function Ho(t){let e=Co.get(t);return void 0===e&&(e=new zo(t),Co.set(t,e)),e}function Uo(t){return Eo.get(t)?.session??null}const qo=new WeakMap,Go=new WeakMap;function Vo(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const Ko=Object.freeze([]),Jo=new WeakMap,Qo=new WeakMap;function Xo(t){return Qo.get(t)??[]}function Yo(t,e){Qo.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let Zo=0;function ts(){return`u${(Zo++).toString(36)}`}let es=0;class ns{uuid=ts();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(t,e){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._index=e,this._version=es}get index(){return this._index}set index(t){this._index=t,this._version=++es,this.indexes[this.position]=t}get version(){return this._version}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=es),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0===this._listIndexes&&(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)]),this._listIndexes}get varName(){return`$${this.position+1}`}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function os(t,e){return new ns(t,e)}const ss=new WeakMap;function rs(t){return ss.get(t)||null}function is(t,e){null!==e?ss.set(t,e):ss.delete(t)}const as=new WeakMap,ls=Object.freeze([]),cs=new Set;function ds(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:ls,s=Array.isArray(n)&&n.length>0?n:ls,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:ls,o=Array.isArray(e)&&e.length>0?e:ls;let s=as.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=rs(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:cs,deleteIndexSet:new Set(i),addIndexSet:cs};let e=rs(s);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=os(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:cs,deleteIndexSet:cs,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return a={oldIndexes:i,newIndexes:i,changeIndexSet:cs,deleteIndexSet:cs,addIndexSet:cs};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,l=new Set;for(let o=0;o<s.length;o++){const a=s[o],c=n.get(a),d=c&&c.length>0?c.shift():void 0;if(void 0===d){const n=os(t,o);e.push(n),l.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(function(t,e,n){let o=as.get(t);o||(o=new WeakMap,as.set(t,o)),o.set(e,n)}(o,s,a),is(s,a.newIndexes))}}(t,e,n);return function(t){for(let e=0;e<t.length;e++)t[e].index!==e&&(t[e].index=e)}(o.newIndexes),o}const us=new WeakMap;function hs(t){return us.get(t)??[]}function fs(t,e){us.set(t,e)}const ps=new WeakMap;function ms(t){return ps.get(t)??null}function gs(t,e){ps.set(t,e)}const bs=new WeakMap;function ys(t){return bs.get(t)??[]}function _s(t,e){bs.set(t,e)}function ws(t,e){const n=ys(t);for(const t of n)ee(t,e)}function vs(t,e,n){ws(t,e);const o=hs(t),s=ms(t);null!==s&&s.activate(o,n.rootNode);for(const t of o)null===s&&Le(ke(t),t),(null===s||s.shouldApplyState(t))&&Ir(t,n)}function Ns(t){if(!t.mounted)return;const e=hs(t),n=ms(t);for(const t of e)null!==n?n.disposeBinding(t):Oe(ke(t),t);!function(t){const e=ys(t);for(const t of e)ee(t,null)}(t)}const Ss=new WeakMap,Is=Object.freeze(new Set);function Ps(t,e){const n=Ss.get(t);n?n.add(e):Ss.set(t,new Set([e]))}function xs(t){const e=Ss.get(t);return void 0!==e?e:Is}function $s(t,e){const n=Ss.get(t);n&&(n.delete(e),0===n.size&&Ss.delete(t))}const Es=new Set(["if","elseif","else","for"]);class Cs{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e,this._childNodeArray=Array.from(this._content.childNodes),this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(t){for(const e of this._childNodeArray)ho(e),t.appendChild(e);this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){ho(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=ms(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)lo(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=hs(this);for(const t of e)if(Es.has(t.bindingType)){const e=xs(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){ms(this)?.dispose();for(const t of this._childNodeArray)lo(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=hs(this);for(const e of t){if(Es.has(e.bindingType)){const t=xs(e.node);for(const e of t)e.unmount()}Ge(e),Te(e)}this._mounted=!1}}function As(t){const e=document.createDocumentFragment(),n=new Cs(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function ks(t){void 0!==t.uuid&&null!==t.uuid||rt("BindingInfo.uuid is null.");const n=zt(t.uuid);n||rt(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=ct(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===y||s===b)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Q(r))return null;if("prop"===o&&_n(r,t.propName))return null;let i;try{i=Po({...t,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;n.push({nodeIndex:e,template:t,isEvent:"event"===o,isIndexBinding:t.statePathName in S,policy:i,authority:i.authority})}}return{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=ct(o,s[t].nodePath);null===e&&rt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Xt(e),U(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e){const n=new zo;return n.initializeRow(t,e),n}(n,a),d=new Cs(o);return gs(d,c),fs(d,a),Yo(d,l),_s(d,r),Ps(t.node,d),d}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=ct(t,s.nodePath);if(null===e&&rt(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Kt.has(e))continue;const r=Jt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new zo;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new Cs(i,s);gs(l,a.bindingSession),fs(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in S&&c.push(t);return Yo(l,c),_s(l,a.nodes),Ps(t.node,l),l}const Ts=Symbol.for("wcstack.transition-runner");function Ms(t){const e=globalThis[Ts];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}const Ls=new WeakSet,Os=Symbol.for("wcstack.state.view-transition-naming");function Rs(){const t=Ms("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function js(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||Ls.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[Os]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(Ls.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const Ds=new WeakMap,Bs=new WeakMap,Ws=new WeakMap,Fs=new WeakMap;function zs(t,e,n){!function(t,e,n){let o=Bs.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Bs.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Hs(t,e){Ds.set(t,e)}function Us(t,e){let n=Ws.get(t.node);void 0===n&&(n=[],Ws.set(t.node,n)),n.length<1e3?n.push(e):$s(t.node,e)}function qs(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function Gs(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function Vs(t,n,s){const r=Boolean(s);let i;const a=xs(t.node);i=0===a.size?ks(t):a.values().next().value;const l=e(),c=t.uuid??"",d=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Gs(t)}`),Ns(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Gs(t)}`),l){const e=document.createComment(`@@wcs-${d}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);vs(i,te(t.node),n);const e=Rs();null!==e&&js(i,"branch",e)}}const Ks=new WeakMap,Js=new WeakMap,Qs=new WeakMap;function Xs(t){return Qs.get(t)??[]}const Ys=new Set,Zs={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}};function tr(t,n,s){if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const l=i[0],c=r[l];if(c!==s){null!==c&&"object"==typeof c&&null!==s&&"object"==typeof s&&null!==Q(r)&&function(t,e,n){let o=Ks.get(t);o||(o=new Map,Ks.set(t,o)),o.has(e)||o.set(e,n)}(r,l,c);const e=()=>{let t=!1;try{r[l]=s,t=!0}catch(t){o.debug&&console.warn(`Failed to set property '${l}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=Q(t);if(null===n)return null;const o=Y(t)?.get(n);if(void 0===o)return null;const s=tt(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,l);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&_n(r,l)){const o=In(r,l,t.stateName,t.statePathName),i=Pn(o,"to-element"),a=n?.propagationContextByBinding?.get(t)??An()??$n(o);if(a.visitedEdges.has(i))null!==ne&&ne({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:r,member:l});else{const t=En(a,i);kn(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Nn++,writtenValue:n};Tn.push({receipt:i,node:t});try{return r()}finally{Tn.pop()}}(r,l,s,o,t.transactionId,e))}}else e()}if(e()){const t=Zs[l];t?t(r,s):(function(t,e,n){let o=Qs.get(t);o||(o=[],Qs.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,l,s),a=r,Ys.add(a))}return}var a;const l=i[0];let c=r[l];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==c)return;c=c[e]}const d=i[i.length-1],u=c[d];if(u!==s){if(Object.isFrozen(c))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:u,newValue:s}));2!==i.length||"object"!=typeof c||null===c||d in c||null===Q(r)||function(t,e,n){let o=Js.get(t);o||(o=new Map,Js.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)}(r,l,d);try{c[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:u,newValue:s,error:t})}}}const er=new WeakSet;function nr(t){const e=t.boundPaths;if(void 0===e)return[];const n=new Set;for(const t of e){if("$"===t[0])continue;const e=t.indexOf(s);n.add(-1===e?t:t.slice(0,e))}return[...n]}function or(t,e,n){const r=t.node,i=t.propSegments,[a,...l]=i,c=Hn(r,a);if(null===c&&rt(`State element not bound to "${a}" on web component.`),!1!==c.hasRootNode){if(0===l.length){const t=nr(c);if(0===t.length)return;return void c.createState("readonly",e=>{for(const n of t)e.$postUpdate(n)})}c.createState("readonly",t=>{t.$postUpdate(l.join(s))})}else o.debug&&console.debug(`[@wcstack/state] skipped parent→child notification for a disconnected state element on <${r.tagName.toLowerCase()}>.`,{element:r,stateProp:a,path:l.join(s)})}const sr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),rr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function ir(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function ar(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),r=e.length>0?e+s:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(s)&&o.push(e)}return o}const lr={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},cr={binding:"Bound path",watch:"$watch path"};function dr(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${pt}`}function ur(t,e){return`$setAll("${t}") ${e}`}function hr(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${pt}`}const fr=new WeakMap;const pr=new WeakSet;function mr(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const gr=Object.freeze({[_]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&rt("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[w]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[v]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[y]:function(t,e,n){ln(n)||rt("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Jo.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||rt('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Q(t);if(null===e)return null;const n=Y(t)?.get(e);return void 0===n&&rt(`Custom element <${e}> is not defined for command binding.`),tt(t)}(r);null===a&&rt(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||rt(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ft(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Jo.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void Jo.delete(t);const o=n[i];return"function"!=typeof o&&rt(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),Jo.set(t,{token:o,unsubscribe:c,elementRef:l})}}),br={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!er.has(t.replaceNode)){er.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,i=Ee(t),a=ke(t),l=se(a),c=ds(Qn(n.stateElement,i),l,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);const d=Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0;if(d&&null!==t.node.parentNode){let e=Fs.get(t.node);if(void 0===e){const n=Ds.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(n.nodeType===Node.ELEMENT_NODE||n.nodeType===Node.TEXT_NODE&&""!==(n.textContent?.trim()??"")){s=!1;break}n=n.previousSibling}for(;null!==o;){if(o.nodeType===Node.ELEMENT_NODE||o.nodeType===Node.TEXT_NODE&&""!==(o.textContent?.trim()??"")){s=!1;break}o=o.nextSibling}return s}(t.node,n),Fs.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let u=Bs.get(t.node),h=d?1e3-function(t){return Ws.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==u){for(const e of c.deleteIndexSet){const n=u.get(e);void 0!==n&&(h<=0&&n.tryDestroy()?$s(t.node,n):(Ns(n),n.unmount(),Us(t,n),h-=1),d||u.delete(e))}d&&(Bs.delete(t.node),u=void 0)}let f=t.node;const p=V(s.path+"."+r),m=n.stateElement.loopContextStack,g=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const t of i)a.add(n[t]);return a}(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&f.isConnected&&(b=document.createDocumentFragment(),ve(b,n.rootNode));const y=e(),_=Rs(),w=t.uuid??"",v=Ws.get(t.node);for(const e of c.newIndexes){let o;if(c.addIndexSet.has(e)){const r=He(p,e);m.createLoopContext(r,r=>{if(o=void 0!==v?v.pop():void 0,void 0===o&&(o=ks(t)),null!==b)y&&b.appendChild(document.createComment(`@@wcs-for-start:${w}:${s.path}:${e.index}`)),o.appendTo(b),y&&b.appendChild(document.createComment(`@@wcs-for-end:${w}:${s.path}:${e.index}`));else{if(f.nextSibling!==o.firstNode){if(y){const t=document.createComment(`@@wcs-for-start:${w}:${s.path}:${e.index}`);f.parentNode.insertBefore(t,f.nextSibling),f=t}o.mountAfter(f)}if(y){const t=document.createComment(`@@wcs-for-end:${w}:${s.path}:${e.index}`),n=o.lastNode??f;n.parentNode.insertBefore(t,n.nextSibling)}}vs(o,r,n),null!==_&&js(o,"row",_)}),void 0===o&&rt(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=void 0!==u?u.get(e)??null:null,c.changeIndexSet.has(e)){const t=Xo(o);for(const e of t)Ir(e,n)}null===o&&rt(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==g&&g.has(e)&&qs(f,o.firstNode)||f.nextSibling===o.firstNode||o.mountAfter(f),t){const t=o,s=He(p,e);m.createLoopContext(s,e=>{vs(t,e,n)})}}f=o.lastNode||f,void 0===u&&(u=new WeakMap,Bs.set(t.node,u)),u.set(e,o)}Ds.set(t.node,f),null!==b&&(t.node.parentNode.insertBefore(b,t.node.nextSibling),ve(b,null))},if:Vs,else:Vs,elseif:Vs,radio:function(t,e,n){const o=t.node,s=Vo(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=Vo(o.value,t.inFilters),r=Array.isArray(n)?n:Ko;o.checked=r.includes(s)}},yr=new WeakMap,_r=new WeakMap,wr=new WeakMap;function vr(){}function Nr(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===qo.get(t)?.has(e)}(e,n)?or:1===t.propSegments.length&&function(t,e){return!0===Go.get(t)?.has(e)}(e,n)?vr:tr}function Sr(t,e){const n=Vo(function(t,e){const n=qe(e);if(n.pathInfo.path in S){const t=te(e.node);return null===t&&rt(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&rt("ListIndex not found for loopContext:");const n=S[e];void 0===n&&rt(`Invalid index name: ${e}`);const o=Pe(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&rt(hr(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[ae](n)}(e.state,t),t.outFilters);if(!0===_r.get(t))return void e.deferredSelectBindings.push({binding:t,value:n});let o=yr.get(t);if(void 0===o){if(yr.has(t))return o=Nr(t),o===or&&yr.set(t,o),void o(t,e,n);if(o=br[t.bindingType],void 0===o){const e=t.propSegments[0];o=gr[e],yr.set(t,o),void 0===o&&(Q(t.replaceNode)?(o=Nr(t),o===or&&yr.set(t,o)):(o=tr,yr.set(t,o)))}if(o===tr&&"SELECT"===t.node.tagName){const o=t.propSegments[0];if("value"===o||"selectedIndex"===o)return e.deferredSelectBindings.push({binding:t,value:n}),void _r.set(t,!0)}o(t,e,n)}else o(t,e,n)}function Ir(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=ke(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=Uo(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==wr.get(t)){const e=Q(t.replaceNode);if(e&&void 0===Y(t.replaceNode)?.get(e))return void function(t,e){if(pr.has(t))return;pr.add(t);const n=()=>{pr.delete(t);const e=Uo(t);(null===e||e.shouldApplyState(t))&&xr([t])},o=n=>{pr.delete(t),mr(e,n)},s=Uo(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{pr.delete(t),r()})||(pr.delete(t),r()))}const r=Y(t.replaceNode);if(null===r)return pr.delete(t),void mr(e,new Error("CustomElementRegistry is unavailable."));_o(r).wait(e,()=>{t.replaceNode.isConnected?n():pr.delete(t)},o)}(t,e);wr.set(t,!0)}if(!0===e.sameRootVerified&&t.stateName===e.stateName)return void Sr(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Ne(o),null===o&&rt("Root node for fragment not found for binding.")),t.stateName!==e.stateName||o!==e.rootNode){const n=wi(o,t.stateName);null===n&&rt(`State element with name "${t.stateName}" not found for binding.`),n.createState("readonly",s=>{const r={stateName:t.stateName,rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};Sr(t,r)})}else Sr(t,e)}function Pr(t,e){console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e}),null!==ne&&ne({type:"state:binding-apply-error",stateName:t.stateName,path:t.statePathName,bindingType:t.bindingType,error:e})}function xr(t,e){let n=0;const s=new Set,r=new Map,i=new Map,a=[];for(;n<t.length;){let l=t[n];const c=l.stateName;if(!1===l.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${l.bindingType} ${l.statePathName} on ${l.node.nodeName}`,l),n++;continue}let d=l.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Ne(d),null===d&&rt("Root node for fragment not found for binding."));const u=wi(d,c);null===u&&rt(`State element with name "${c}" not found for binding.`),u.createState("readonly",o=>{const h={rootNode:d,stateName:c,stateElement:u,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Ir(l,h)}catch(t){Pr(l,t)}n++;const e=t[n];if(!e)break;const o=e.replaceNode.getRootNode();if(e.stateName!==c||o!==h.rootNode)break;l=e}})}for(const{binding:t,value:n}of a)try{tr(t,{propagationContextByBinding:e},n)}catch(e){Pr(t,e)}for(const[t,e]of r.entries())re(t,e);for(const[t,e]of i.entries())t.createState("writable",t=>{t[he](Array.from(e))})}function $r(t,e){const[n,o,s]=Qt(t),r=Ho(t);for(const t of n)ee(t,e);xr(r.initialize(o)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=Yt(o);0!==t.length&&(ee(o.node,e),xr(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(s,e,r)}const Er=/\{\{\s*(.+?)\s*\}\}/g,Cr=new Set(["SCRIPT","STYLE"]);function Ar(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&Cr.has(t.parentElement.tagName)||kr(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),Ar(e.content)}else Ar(t.content)}function kr(t){const e=t.data;if(Er.lastIndex=0,!Er.test(e))return;Er.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Er.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}let Tr;function Mr(){if(Tr)return Tr;const t=[],e=It("not",t)(Nt);return Tr={filterName:"not",args:t,filterFn:e},Tr}const Lr=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Or(t,e){const n=e+s+r,o=t.indexOf("|"),i=t.indexOf("@");let a,l;if(-1!==o?(a=t.slice(0,o).trim(),l=t.slice(o)):-1!==i?(a=t.slice(0,i).trim(),l=t.slice(i)):(a=t.trim(),l=""),"."===a)a=n;else{if(!a.startsWith("."))return t;a=n+s+a.slice(1)}return l.length>0?a+l:a}function Rr(t,e){const n=Lr.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+Or(s,e)+r}function jr(t,e){const n=t.split(";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=n.indexOf(":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Or(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function Dr(t,e){return jr(t,e)}function Br(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=Rr(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=jr(r,e);t!==r&&o.setAttribute(n,t)}}}function Wr(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}function Fr(t){const e=[],n=Vt(t);for(const t of n){const n=Ht(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:Wr(o),parseBindTextResults:n})}return e}function zr(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const Hr=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Ur=Mr();function qr(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Ur],bindingType:t}}function Gr(t,e,n,o){return zr(e),"string"==typeof o&&Br(e,o),Vr(t,e,o),{fragment:e,parseBindTextResult:n,nodeInfos:Fr(e)}}function Vr(t,e,n){const s=o.commentElsePrefix,r=qt(e),i=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return r.length>0&&-1!==r.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let a=null;const l=[],c=[];for(;i.nextNode();){const t=i.currentNode;c.push(t)}for(const e of c){let r=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(r=Dr(r,n));let i=Lt(r)[0];const c=Hr.get(i.bindingType);if(void 0===c)continue;const d=i.bindingType,u=e.content,h=ts();let f=null;const p="for"===d?i.statePathName:n;if("else"===d){null===a&&rt("'else' binding found without preceding 'if' or 'elseif' binding."),i=qr("else",a.parseBindTextResult),f=Gr(t,u,i,p),Ft(h,t,f);const n=l.at(-1),o=document.createComment(`@@${c}:${h}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Wr(o),parseBindTextResults:Ht(o)})):e.replaceWith(o)}else if("elseif"===d){null===a&&rt("'elseif' binding found without preceding 'if' or 'elseif' binding."),f=Gr(t,u,i,p),Ft(h,t,f);const n=document.createComment(`@@${c}:${h}`),o=ts(),r={fragment:document.createDocumentFragment(),parseBindTextResult:qr("else",a.parseBindTextResult),nodeInfos:[]};r.fragment.appendChild(n),r.nodeInfos.push({nodePath:Wr(n),parseBindTextResults:Ht(n)}),Ft(o,t,r);const d=l.at(-1);l.push(r);const m=document.createComment(`@@${s}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(m),d.nodeInfos.push({nodePath:Wr(m),parseBindTextResults:Ht(m)})):e.replaceWith(m)}else{f=Gr(t,u,i,p),Ft(h,t,f);const n=document.createComment(`@@${c}:${h}`);e.replaceWith(n)}"if"===d?(l.length=0,a=f):"elseif"===d?a=f:"else"===d&&(a=null,l.length=0)}}async function Kr(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Y(t);null===s&&rt(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(Ut(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function Jr(t){if(t===document)await Kr(document),Ar(document),Vr(document,document),$r(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await H(e.host),await Kr(e),Ar(e),Vr(e,e),$r(e,null)}}const Qr="1.33.0",Xr="undefined"==typeof HTMLElement?class{}:HTMLElement,Yr=/^@@wcs-(?:for|if|elseif|else):[^-]/,Zr=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,ti=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,ei=/^@@wcs-text-start:(.+)$/;function ni(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class oi extends Xr{_stateData=null;_templates=null;_hydrateProps=null;get name(){return this.getAttribute("name")||"default"}get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=Qr.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static findByName(t,e){const n=o.tagNames.ssr,s=t instanceof Element?t:t instanceof Document?t.documentElement:null;return s?s.querySelector(`${n}[name="${e}"]`):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const[t,o]of Object.entries(e))t.startsWith("$")||"function"==typeof o||(n[t]=o);return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=ni(JSON.stringify(e)),t.appendChild(n);const s=Array.from(Wt.keys());for(const e of s){const n=zt(e);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",e);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),t.appendChild(s)}const r=Array.from(Ys);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=Xs(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const t of o)i[t.propName]=t.value;e[s]=i}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ni(JSON.stringify(e)),t.appendChild(n)}}Ys.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(Zr.test(t.data)||ti.test(t.data))&&n.push(t)}for(const t of n)t.remove()}static removeStructuralComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;Yr.test(t.data)&&n.push(t)}for(const t of n)t.remove()}static restoreTextBindings(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode,o=ei.exec(t.data);o&&n.push({comment:t,path:o[1]})}for(const{comment:t,path:e}of n){const n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}const r=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const t=r.currentNode;Zr.test(t.data)&&i.push(t)}for(const t of i){const e=Zr.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}oi.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(Yr.test(t.data)){const e=t.data.split(":")[1];l.push({comment:t,uuid:e})}}for(const{comment:t,uuid:e}of l){const n=s.get(e);if(n){const e=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&e.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)e.content.appendChild(r);else for(const t of Array.from(n.childNodes))e.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(e,t)}}const c=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of c)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const si=new Set(["for","if","elseif","else"]);function ri(t){const e=new zo;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i]=Qt(s),a=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:e}}function ii(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const t=i.currentNode;if(t.data===r)return t}return null}function ai(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Lt(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s?e={...s,outFilters:[...s.outFilters,Mr()],bindingType:"else"}:"elseif"===i&&s&&(e={...e,stateName:s.stateName}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;zr(a),"string"==typeof l&&Br(a,l),Vr(n,a,l),Ft(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:Fr(a)})}}const li=Symbol.for("wcstack.binder"),ci=Symbol.for("wcstack.binder.pending"),di=Symbol.for("wcstack.binder.taken");function ui(t){if(Mo(t))return!0;if(!hi(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Mo(e)}function hi(t){return 1===t.nodeType}function fi(t){if(ui(t))return;Ar(t),Vr(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);$r(e&&s?n:t,null)}const pi=[];function mi(){const t=pi.splice(0,pi.length);for(const e of t)fi(e);!function(){const t=function(){const t=globalThis[li];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[ci];return void 0===e&&(e=[],t[ci]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[di];return void 0===e&&(e=new WeakSet,t[di]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const gi={protocol:"wcs-binder",version:1,bind:function(t){var e;hi(t)&&!ui(t)&&(e=t.getRootNode(),Ni.has(e)?fi(t):pi.push(t))}},bi=new WeakMap,yi=new WeakMap,_i=new Set;function wi(t,e){let n=bi.get(t);return n&&n.get(e)||null}function vi(t){return yi.get(t)??Promise.resolve()}const Ni=new WeakSet;function Si(t){Ni.add(t)}function Ii(t,n,s){let i=bi.get(t);if(null===s){if(!i)return;const e=i.get(n);i.delete(n),0===i.size&&bi.delete(t),void 0!==e&&(_i.delete(e),null!==ne&&ne({type:"state:element-unregistered",name:n,rootNode:t,element:e})),o.debug&&console.debug(`State element unregistered: name="${n}"`)}else{if(!i){i=new Map,bi.set(t,i);const n=!e()&&s.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,s)=>{queueMicrotask(async()=>{try{n&&await async function(t){await Kr(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${Qr}". Falling back to full render.`),oi.cleanupDom(t),!1}for(const n of e)ai(t,n);const n=function(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const t of o){const n=Zr.exec(t.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let d=t.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body);!function(t,e){const n=new Map;for(const o of e){if(0===o.nodes.length)continue;const e=As(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=ri(o.nodes);gs(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");fs(e,s),_s(e,i);const l=[];for(const t of s)t.statePathName in S&&l.push(t);if(Yo(e,l),"for"===o.type&&null!==o.index){const i=ii(t,"for",o.uuid);if(i){const t=os(null,o.index);zs(i,t,e),Hs(i,o.nodes[o.nodes.length-1]),Ps(i,e),ws(e,He(V(o.path+"."+r),t)),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let l=n.get(o.uuid);l||(l=[],n.set(o.uuid,l)),l.push(t)}}else{const n=ii(t,o.type,o.uuid);n&&(Ps(n,e),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=ii(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=zt(e);if(!r)continue;const i=r.parseBindTextResult.stateName,a=r.parseBindTextResult.statePathName,l=wi(s,i);l&&l.createState("readonly",t=>{const e=t[a];Array.isArray(e)&&is(e,o)})}}(document.body,n),oi.removeBlockBoundaryComments(document.body);const s=[];for(const t of e)t.parentNode&&(s.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());oi.restoreTextBindings(document.body);const[i,a]=Qt(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(ee(t,null),e.setAttribute("data-wcs-completed",""))}else ee(t,null);const l=[],c=[],d=Ho(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(si.has(t.bindingType))c.push(t);else{if(t.statePathName.includes(r))continue;l.push(t)}for(const t of c)if("for"===t.bindingType){const e=ke(t),n=wi(t.replaceNode.getRootNode(),t.stateName);n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&re(e,o)})}xr(l);for(const{el:t,parent:e,next:n}of s)e.insertBefore(t,n);const u=t.querySelectorAll(o.tagNames.ssr);for(const e of u){const n=e.hydrateProps;for(const[e,o]of Object.entries(n)){const n=t.querySelector(`[data-wcs-ssr-id="${e}"]`);if(n)for(const[t,e]of Object.entries(o))n[t]=e}}const h=t.querySelectorAll("[data-wcs-completed]");for(const t of h)t.removeAttribute("data-wcs-completed");return!0}(t)||await Jr(t),Si(t),mi(),e()}catch(t){s(t)}})});yi.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await Jr(t),Si(t),mi(),e()}catch(t){n(t)}})});yi.set(t,e)}}i.has(n)&&rt(`State element with name "${n}" is already registered.`),i.set(n,s),_i.add(s),null!==ne&&ne({type:"state:element-registered",name:n,rootNode:t,element:s}),o.debug&&console.debug(`State element registered: name="${n}"`,s)}}let Pi=0,xi=0;const $i=[];function Ei(t,e=0){const n=$i.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?$i.push(o):$i.splice(n,0,o)}function Ci(t){queueMicrotask(()=>{throw t})}const Ai=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){Pi>xi&&(xi=Pi);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&queueMicrotask(()=>{const t=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(t)})}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t){const n=new Map;for(const e of t){const t=n.get(e.absoluteAddress);null!==ne&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&ne({type:"propagation:coalesced",absoluteAddress:e.absoluteAddress,droppedTransactionId:t.transactionId,winnerTransactionId:e.context.transactionId}),n.set(e.absoluteAddress,e.context)}const o=[],s=new Map;for(const[t,e]of n){if(null!==e&&e.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,stateName:t.absolutePathInfo.stateName,transactionId:e.transactionId,hop:e.hop,maxHops:32}),null!==ne&&ne({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=Be(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(o.push(t),null!==e&&s.set(t,e));else!1!==n.replaceNode.isConnected&&(o.push(n),null!==e&&s.set(n,e))}try{const t=()=>{s.size>0?xr(o,s):xr(o)};if(e()||0===o.length)t();else{const e=function(t,e){const n=Ms(t);if(null!==n)return n.run(e,{source:t,types:void 0});e()}("state",t);void 0!==e&&e.catch(Ci)}}finally{!function(t){for(const e of $i.slice())e.listener(t)}(new Set(n.keys()))}}};function ki(){return Ai}const Ti=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Mi(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,stateName:e.stateName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const Li="__WCSTACK_DEVTOOLS_HOOK__";const Oi=t=>{null!==ne&&ne({type:"state:update-batch",addresses:t})};function Ri(t){const e=null!==ne;!function(t){ne=t}(t);const n=null!==t;n&&!e?Ei(Oi,0):!n&&e&&function(t){const e=$i.findIndex(e=>e.listener===t);-1!==e&&$i.splice(e,1)}(Oi)}function ji(t){return{name:t.name,rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function Di(t,e){return wi(e,t)??rt(`devtools: state element not found: name="${t}"`)}let Bi=null;function Wi(){if(e())return;if(null!==Bi)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Qr,getStateElements(){const t=[];for(const e of _i)t.push(ji(e));return t},keys(t,e){const n=Di(t,e),o=[];return n.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}o.push(e)}}),o},read(t,e,n,o){let s;return Di(t,e).createState("readonly",t=>{s=t.$resolve(n,o??[])}),s},write(t,e,n,o,s){Di(t,e).createState("writable",t=>{void 0!==s&&s.length>0?t.$resolve(n,s,o):t[n]=o})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=[...t.inFilters,...t.outFilters].map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.stateName,t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=zt(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Mi(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=lt(e,Lt(n));for(const o of t)r(Mi(e,o,"attribute",n))}catch{}continue}const e=Ti.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=zt(s);if(null===a){if(n===o.commentTextPrefix)try{r(Mi(t,Bt(s),"comment",s))}catch{}}else r(Mi(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:Ri};Bi=t,function(){const t=globalThis,e=t[Li];if(void 0!==e)return 1!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 1. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:1,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[Li]=n,n}().register(t)}const Fi={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]`);for(const t of s){const e=t.getAttribute("name")||"default",o=t.previousElementSibling;if(null!==o&&o.tagName.toLowerCase()===n&&(o.getAttribute("name")||"default")===e)continue;const s=document.createElement(n);s.setAttribute("name",e),s.setAttribute("version",Qr),oi.buildContent(s,oi.extractStateData(t)),t.parentNode?.insertBefore(s,t)}}},zi="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Hi=0;async function Ui(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++Hi}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${zi}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${zi}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function qi(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){rt(`Failed to load script file: ${t}`)}}class Gi{_loopContextStack=Array(i).fill(void 0);_length=0;_getBaseDepth;constructor(t){this._getBaseDepth=t}createLoopContext(t,e){null===t.listIndex&&rt("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=i&&rt("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&rt("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&rt("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else if(n.listIndex.length!==n.pathInfo.wildcardCount){const t=this._getBaseDepth();n.listIndex.length!==n.pathInfo.wildcardCount+t&&rt(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}, base depth ${t}).`)}let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const Vi=new WeakMap;function Ki(t,e){let n=Vi.get(t);void 0===n&&(n=new Map,Vi.set(t,n));let o=n.get(e);return void 0===o&&(o=new an(e,t.name),n.set(e,o)),o}const Ji=new WeakMap;function Qi(t){const e=Ji.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return Ki(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Ki(t,n)}},set(){rt("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){rt("$command namespace is read-only; deleting from it is not allowed.")}});return Ji.set(t,n),n}const Xi=Symbol("wcs-stream-last-notified-uncertain"),Yi=new WeakMap;function Zi(t,e){const n=Yi.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function ta(t,e){const n=Yi.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Xi,error:Object.is(o.error,null)?null:Xi})}const ea=new Set;function na(t){ea.delete(t)}const oa=new WeakMap;function sa(t){return oa.get(t)??new Map}function ra(t){na(t);const e=oa.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,ta(t,n.name)}const ia=(t,e)=>e,aa=new Set;const la=new WeakMap,ca=new WeakMap;function da(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=sa(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&sa(t).has(n),ownKeys:()=>Array.from(sa(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=sa(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){rt(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){rt(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function ua(t){const e=la.get(t);if(void 0!==e)return e;const n=da(t,j,t=>t.status);return la.set(t,n),n}function ha(t){const e=ca.get(t);if(void 0!==e)return e;const n=da(t,D,t=>t.error);return ca.set(t,n),n}function fa(t){la.delete(t),ca.delete(t)}let pa=null;function ma(t){const e=sa(t);if(0!==e.size){!function(t){ea.add(t)}(t);for(const n of e.values())ga(t,n)}}function ga(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=pa,r=new Set;let i;pa=r;try{t.createState("readonly",t=>{i=n(t)})}finally{pa=o}i instanceof Promise&&rt(`${L} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${j}${s}${e.name}`,l=`${D}${s}${e.name}`;for(const n of r){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==a&&o.path!==l||rt(`${L} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&rt(`${L} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=r,i}(t,e);t.createState("writable",t=>{t[e.name]=e.definition.initial}),ba(t,e,"active",null);const r=e.definition,i={fold(n){t.createState("writable",t=>{t[e.name]=r.fold(t[e.name],n)})},done(){ba(t,e,"done",null)},fail(o){ba(t,e,"error",o),n.abort()}};!async function(t,e,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",i)}}(r.source,o,n.signal,i)}function ba(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return Yi.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),i=r.status!==n,a=!Object.is(r.error,o);(i||a)&&(function(t,e,n,o){let s=Yi.get(t);void 0===s&&(s=new Map,Yi.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${j}${s}${e.name}`),a&&t.$postUpdate(`${D}${s}${e.name}`)}))}Ei(function(t){const e=ea;if(0===e.size)return;const n=[];for(const o of e)for(const e of sa(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&sa(t).get(o.name)===o)try{ga(t,o)}catch(n){o.controller?.abort(),e.has(t)&&sa(t).get(o.name)===o&&ba(t,o,"error",n)}},20);const ya=new WeakMap,_a=new Set,wa=new Map;function va(t){return ya.get(t)??wa}const Na=new WeakMap;function Sa(t,e,n){let o=Na.get(t);void 0===o&&(o=new Map,Na.set(t,o)),o.set(e,n)}const Ia=new Map;function Pa(t){0!==va(t).size&&(function(t){_a.add(t)}(t),function(t){const e=[];for(const n of va(t).values())$a(t,n)&&e.push(n);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{Sa(t,xa(t,o),n[o.path])}catch(e){Ca(t,o.path,"prime",e)}})}(t))}function xa(t,e){return _e(pe(t,e.pathInfo),null)}function $a(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Ea={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Ca(t,e,n,o){console.error(`[@wcstack/state] $watch ${Ea[n]} "${e}" threw.`,o),null!==ne&&ne({type:"state:watch-error",phase:n,stateName:t.name,path:e,error:o})}function Aa(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function ka(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=$a(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void Ca(e,n.path,"evaluate",t)}const a=r?function(t,e){return Na.get(t)?.get(e)}(e,o):function(t){return Ia.get(t)}(o);r&&Sa(e,o,i),null!==ne&&ne({type:"state:watch-fired",stateName:e.name,path:n.path}),n.handler.call(t,i,a,...s)})}catch(t){Ca(e,n.path,"handler",t)}}function Ta(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function Ma(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function La(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function Oa(t){return t.startsWith("$")}function Ra(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}function ja(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function Da(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||rt(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||rt(`${e} entries must be non-empty strings.`),t.startsWith("$")&&rt(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&rt(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}Ei(function(t){const e=_a;try{if(0===e.size)return;const n=function(){const t=xi;return xi=0,t}();if(n>32){const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==ne&&ne({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=va(t).get(n.absolutePathInfo.pathInfo.path);if(void 0===s)continue;let r=[];if(s.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;r=xe(n.listIndex,s.pathInfo.wildcardCount)}o.push({stateElement:t,entry:s,absAddress:n,indexes:r})}if(0===o.length)return;o.sort(Aa),function(t){Pi=t+1}(n);try{for(const t of o)e.has(t.stateElement)&&va(t.stateElement).get(t.entry.path)===t.entry&&ka(t)}finally{Pi=0}}finally{Ia.clear()}},10);const Ba=new Map;class Wa{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=V(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Fa(t){let e;return Ba.get(t)??(Ba.set(t,e=new Wa(t)),e)}function za(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:Pe(n.listIndex,o,n.pathInfo.wildcardCount)}const Ha=new WeakMap;function Ua(t,e){null===e?Ha.delete(t):Ha.set(t,e)}function qa(t){const e=Ha.get(t);e&&(e.dirty=!0)}const Ga=[],Va=[];let Ka=0;function Ja(t,e){Ga[Ka]=t,Va[Ka]=e,Ka++}function Qa(){Ka--,Ga[Ka]=void 0,Va[Ka]=void 0}function Xa(t,e){return!0!==t.hasMappedComponentState&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Ya(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}function Za(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===k)return Ya(Qi(s),e.pathInfo.segments);if(i===j)return Ya(ua(s),e.pathInfo.segments);if(i===D)return Ya(ha(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){const i=e.parentAddress??rt(function(t,e,n,o){return`[${lr.binding}] Path "${e}" does not exist on state "${t}".${ft(e,ar(n,"",o))}${pt}`}(s.name,e.pathInfo.path,t,s.getterPaths)),a=tl(t,i,n,o);if(null==a)return;const l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??rt(hr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(a,t)}return Reflect.get(a,l)}if(s.getterPaths.has(e.pathInfo.path)){o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}else{if(!0!==s.hasMappedComponentState)return Reflect.get(t,e.pathInfo.path);Ja(s,e);try{return Reflect.get(t,e.pathInfo.path)}finally{Qa()}}}function tl(t,e,n,o){!function(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=Ie(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?Pe(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?Pe(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}(o,e),function(t,e){if(null===pa)return;const n=pe(t,e.pathInfo);pa.add(_e(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return Xa(s,e)?function(t,e,n,o,s){const r=_e(pe(s,e.pathInfo),e.listIndex),i=function(t){return Ha.get(t)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Za(t,e,n,o,s);return Ua(r,{value:a,dirty:!1}),a}(t,e,n,o,s):Za(t,e,n,o,s)}const el=new WeakMap;function nl(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const h=o[s]??null;if(null===h)return void u.push(d);const f=He(h,r),p=el.get(f),m=tl(t,f,e,n),g=ds(Qn(n.stateElement,r),p,m).newIndexes,b=l[c]??null;if(i.set(f,m),null===b)for(let t=0;t<g.length;t++){const e=g[t];a(o,s+1,e,l,c+1,d.concat(e.index),u)}else{const t=g[b]??rt(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,d.concat(t.index),u):u.push(d.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())el.set(t,e);return l}function ol(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=rs(tl(t,He(a,r),e,n));null==l&&rt(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??rt(`ListIndex not found at index ${c} of ${a.path}`)}return r}function sl(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}function rl(t,e,n,o){"object"==typeof t&&null!==t||rt(`${R} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&rt(`${R} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function il(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&rt(`${R} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function al(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];rl(a,n,o,i);const l=il(a,e,n,o,i);r.has(l)&&rt(`${R} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function ll(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function cl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=tl(t,s,n,o);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=e.pathInfo.lastSegment;if(a===r){const t=e.listIndex?.index;return"number"==typeof t&&t in i}return a in i}const dl=new WeakMap;function ul(t,e){null===e?dl.delete(t):dl.set(t,e)}function hl(t,e,n){const s=V(t.wildcardParentPaths[e]),r=pe(t.stateElement,s),i=He(s,n),a=se(_e(r,n)),l=t.stateProxy[ae](i),c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(ds(Qn(t.stateElement,i.listIndex),a,l),t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)hl(t,e+1,n)}const fl=[];function pl(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:fl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:fl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const ml=[];function gl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return ml;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=V(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??ml}function bl(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=V(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[ae](e),a=se(_e(pe(t.stateElement,e.pathInfo),e.listIndex)),l=pl(t,o,0,0,ds(Qn(t.stateElement,e.listIndex),a,r));for(const e of l.fullRows){const o=He(s,e);t.result.add(o),n.push(o)}if(null!==l.movedRows){const e=gl(t,i,s);if(null===e)for(const e of l.movedRows){const o=He(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of l.movedRows)for(const s of e){const e=He(s,o);t.result.add(e),n.push(e)}}}else{const o=He(s,e.listIndex);t.result.add(o),n.push(o)}}const i=t.dynamicMap.get(o);if(i)for(const o of i){const s=V(o),r=[];if(s.wildcardCount>0){const n=Ie(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&rt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=Pe(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateName:t.stateName,stateElement:t.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};hl(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&rt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=Pe(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=He(s,e);t.result.add(o),n.push(o)}}}function yl(t,e,n,o,s,r,i,a,l,c){const d=n.pathInfo.path;if(!o.has(d)&&!s.has(d))return l(n),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&rt(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(d,o,s),h={ranks:u,stateName:t,stateElement:e,staticMap:o,dynamicMap:s,result:new Set,listPathSet:r,visited:new Set,stateProxy:i,searchType:a,listExpansion:c?.listExpansion??"full",keyedMergePath:c?.keyedMergePath??null};return function(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,bl(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(h,n,l),Array.from(h.result)}function _l(t,e,n,o,s){const r=t.watchPaths;null!=r&&s&&r.has(e)&&function(t,e){Ia.has(t)||Ia.set(t,e)}(n,o)}function wl(t,e,n,s,r){const i=o.enablePropagationContext?An()??$n(-1):null,a=ki();a.enqueueAbsoluteAddress(e,i),yl(s.stateName,s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=_e(pe(s.stateElement,e.pathInfo),e.listIndex);qa(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function vl(t,e,n,o,s,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const a=tl(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??rt(hr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(a,t,o)}return Reflect.set(a,l,o)}if(i.stateElement.setterPaths.has(e.pathInfo.path)){i.pushAddress(e),i.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}else{if(!0!==i.stateElement.hasMappedComponentState)return Reflect.set(t,e.pathInfo.path,o);Ja(i.stateElement,e);try{return Reflect.set(t,e.pathInfo.path,o)}finally{Qa()}}}finally{wl(e,n,s,i,a)}}function Nl(t,e,n,o,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(n)){const l=a.get(e.pathInfo.path);if(void 0!==l){const a=tl(t,e,o,i),c=function(t,e,n,o){const s=al(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=al(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,l,a,n);if(null!==c)return function(t,e,n,o,i,a){const l=e.pathInfo.path,c=Qn(a.stateElement,e.listIndex);null===rs(o)&&ds(c,null,o);const d=ds(c,o,n.list),u=Sl(t,e,n.list,i,a,l),h=V(l+s+r);for(const e of n.matched){const n=ll(e.oldRow,e.newRow);if(0===n.length)continue;const o=d.newIndexes[e.position];for(const r of n)void 0!==o?Nl(t,He(V(h.path+s+r.field),o),r.value,i,a):e.oldRow[r.field]=r.value}return u}(t,e,c,a,o,i)}}return Sl(t,e,n,o,i,null)}function Sl(t,e,n,s,i,a){const l=i.stateElement,c=e.pathInfo.path,d=!!Mn&&(Mn=!1,!0);if(!(c in t)&&null!==e.parentAddress&&!l.elementPaths.has(c)){const u=tl(t,e.parentAddress,s,i);if("object"==typeof u&&null!==u){const t=e.pathInfo.lastSegment,h=t===r?e.listIndex?.index:t;let f,p=!1;if(!d&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==h&&h in u,e=void 0!==h?u[h]:void 0;if(t&&Object.is(e,n))return!0;f=e,p=!0}const m=Xa(l,e),g=_e(pe(l,e.pathInfo),e.listIndex);null!==ne&&ne({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:p}),_l(l,c,g,f,p);try{return void 0===h&&rt(hr(`path "${c}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),Reflect.set(u,h,n)}finally{wl(e,g,s,i,a),m&&Ua(g,{value:n,dirty:!1}),sl(l,e.pathInfo,{value:n})}}}let u,h=!1;if(!d&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=tl(t,e,s,i);if(cl(t,e,s,i)&&Object.is(o,n))return!0;u=o,h=!0}const f=l.elementPaths.has(e.pathInfo.path),p=Xa(l,e),m=_e(pe(l,e.pathInfo),e.listIndex);null!==ne&&ne({type:"state:write",absoluteAddress:m,value:n,oldValue:u,hasOldValue:h}),_l(l,c,m,u,h);try{return f?function(t,e,n,o,s,r,i){let a=e.parentAddress??rt(`address.parentAddress is undefined path: ${e.pathInfo.path}`),l=function(t){return dl.get(t)??null}(a);if(null===l){const e=tl(t,a,s,r)??[],n=rs(e)??[];l={value:[...e],listIndexes:[...n]},ul(a,l)}try{return vl(t,e,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=tl(t,a,s,r)??[],c=Array.isArray(i)?rs(i)??[]:[],d=e.listIndex.index,u=-1!==n?l.listIndexes[n]:os(a.listIndex,-1);if(c[d]=u,new Set(i).size===l.value.length){for(let t=0;t<c.length;t++)c[t].index=t;ul(a,null)}}}(t,e,m,n,s,i,a):vl(t,e,m,n,s,i,a)}finally{p&&Ua(m,{value:n,dirty:!1}),sl(l,e.pathInfo,{value:n})}}function Il(t,e,n,o){return(e,s,r)=>{const i=V(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&rt(dr("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=He(i,ol(t,n,o,i,s));if(void 0===r)return tl(t,a,n,o);Nl(t,a,r,n,o)}}function Pl(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return za(o,s.wildcardPaths.at(-1)??rt(`lastWildcardPath is null: ${e.pathInfo.path}`))??rt(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??rt(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=rs(tl(t,He(i,s),n,o))??rt(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??rt(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??rt(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":rt(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}const xl=`${j}${s}`,$l=`${D}${s}`,El=new WeakMap;class Cl{_stateElement;_stateName;_addressStack=Array(i).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e,n){this._stateName=e;const o=wi(t,this._stateName);null===o&&rt(`StateHandler: State element with name "${this._stateName}" not found.`),this._stateElement=o,this._mutability=n}get stateName(){return this._stateName}get stateElement(){return this._stateElement}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&rt("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=i&&rt(`Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_describeAddressCycle(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&rt(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return function(t,e,n,o){const s=S[e];if(void 0!==s){0===o.addressStackLength&&rt(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&rt(`ListIndex not found: ${e.toString()}`);const i=Pe(r,s,t.pathInfo.wildcardCount);return i?.index??rt(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>function(t,e,n,o){const s=Il(t,0,n,o);return(e,r)=>{const i=V(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&rt(dr("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=za(o,i.wildcardPaths[t]);if(e){r=xe(e,e.length-Kn(o.stateElement));break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length-Kn(o.stateElement)>0&&rt(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(e,t.pathInfo.path)),r=[]}}const a=nl(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>function(t,e,n,o){return(e,s,r,i)=>{const a=V(e);Array.isArray(s)||rt(ur(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&rt(dr("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&rt(ur(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&rt(ur(e,"requires an array as the value when { spread: true } is set."));const d=nl(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&rt(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,d.length,r.length));const u=[];for(let e=0;e<d.length;e++){const s=ol(t,n,o,a,d[e]);u.push(He(a,s))}let h=0;for(let e=0;e<u.length;e++){const s=u[e];let i;i=c?r(tl(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(Nl(t,s,i,n,o),h++)}return h}}(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=Fa(e),i=Pl(t,r,n,o),a=He(r.pathInfo,i),l=_e(pe(s,a.pathInfo),a.listIndex),c=ki();c.enqueueAbsoluteAddress(l),yl(o.stateName,o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=_e(pe(s,t.pathInfo),t.listIndex);qa(e),c.enqueueAbsoluteAddress(e)}),sl(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>Il(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{0===o.addressStackLength&&rt(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??rt("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(e.path)&&e.path!==t&&n.addDynamicDependency(t,e.path)}}(0,0,0,o)(t);case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case k:return Qi(o.stateElement);case j:return ua(o.stateElement);case D:return ha(o.stateElement)}if(!e.startsWith(xl)&&!e.startsWith($l))return}const s=Fa(e),r=Pl(t,s,n,o),i=He(s.pathInfo,r);return tl(t,i,n,o)}if("symbol"==typeof e){const s=function(t){let e=El.get(t);return void 0===e&&(e=new Map,El.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case ie:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&rt("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case ae:i=e=>tl(t,e,n,o);break;case le:i=e=>cl(t,e,n,o);break;case ce:i=(e,s)=>Nl(t,e,s,n,o);break;case de:i=()=>async function(t,e,n){const o=Reflect.get(t,I);"function"==typeof o&&await o.call(n)}(t,0,n);break;case ue:i=()=>function(t,e,n){const o=Reflect.get(t,P);"function"==typeof o&&o.call(n)}(t,0,n);break;case he:i=e=>function(t,e,n,o){const s=Reflect.get(t,x);if("function"==typeof s){const t=new Set,r={};for(const n of e){const e=n.absolutePathInfo.pathInfo;let s;if(s=n.absolutePathInfo.stateName===o.stateName?e.path:e.path+"@"+n.absolutePathInfo.stateName,t.add(s),e.wildcardCount>0){const t=xe(n.listIndex,e.wildcardCount),o=r[s];void 0===o?r[s]=[t]:o.push(t)}}return s.call(n,Array.from(t),r)}}(t,e,n,o);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&rt(`State "${this._stateName}" is readonly.`),function(t,e,n,o,s){if("string"==typeof e){const r=Fa(e),i=Pl(t,r,o,s);return Nl(t,He(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}}function Al(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}class kl{_webComponent;_innerStateElement;_rootMounted;_partialFirstSegments;constructor(t,e){if(this._webComponent=t,this._innerStateElement=Hn(t,e)??rt("State element not found for web component."),this._rootMounted=oo(t),this._partialFirstSegments=null,this._rootMounted){const e=no(t);for(const t of e??[])t.isRoot||(this._partialFirstSegments??=new Set).add(t.innerAbsPathInfo.pathInfo.segments[0])}}_isPrivateKey(t,e){if(!this._rootMounted)return!1;const n=e.indexOf(s),o=-1===n?e:e.slice(0,n);return!(!Object.prototype.hasOwnProperty.call(t,o)||null!==this._partialFirstSegments&&this._partialFirstSegments.has(o)||this._innerStateElement.getterPaths.has(o)||this._innerStateElement.setterPaths.has(o))}_outerLoopContext(t,e){const n=e.pathInfo.wildcardCount,o=Jn(e.stateElement,e.pathInfo),s=te(this._webComponent);if(null!==s&&s.listIndex.length===o)return s;if(n>0){const s=function(t,e){if(0===Ka)return null;const n=Ka-1,o=Va[n];return Ga[n]!==t||o?.pathInfo.path!==e?null:o}(this._innerStateElement,t.path),r=s?.listIndex??null;if(null!==r&&r.length===o)return He(V(e.pathInfo.wildcardPaths[n-1]),r)}return s}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e,n);{if("then"===e)return;if("$"===e[0])return;if(this._innerStateElement.getterPaths.has(e)&&e in t)return Reflect.get(t,e,n);if(this._isPrivateKey(t,e))return Reflect.get(t,e,n);const o=V(e),s=pe(this._innerStateElement,o),r=so(this._webComponent,s);if(null!==r){const t=this._outerLoopContext(o,r);let e;return r.stateElement.createState("readonly",n=>{n[ie](t,()=>{e=n[r.pathInfo.path]})}),e}if(e in t)return Reflect.get(t,e,n);rt(`Property "${e}" not found in inner state: no mapping rule and no local state property.`)}}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n,o);{if(this._innerStateElement.setterPaths.has(e)&&e in t)return Reflect.set(t,e,n,o);if(this._isPrivateKey(t,e))return Reflect.set(t,e,n,o);const s=V(e),r=pe(this._innerStateElement,s),i=so(this._webComponent,r);if(null!==i){const t=this._outerLoopContext(s,i);return i.stateElement.createState("writable",e=>{e[ie](t,()=>{e[i.pathInfo.path]=n})}),!0}if(e in t)return Reflect.set(t,e,n,o);rt(`Property "${e}" not found in inner state: no mapping rule and no local state property.`)}}has(t,e){if("string"==typeof e){if("$"===e[0])return!1;if((this._innerStateElement.getterPaths.has(e)||this._innerStateElement.setterPaths.has(e))&&e in t)return!0;if(this._isPrivateKey(t,e))return e in t;const n=V(e),o=pe(this._innerStateElement,n);return null!==so(this._webComponent,o)||e in t}return Reflect.has(t,e)}}class Tl{_innerStateElement;constructor(t,e){this._innerStateElement=Hn(t,e)??rt("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const Ml=new Set;function Ll(t,e){const n=e.outerAbsPathInfo,o=te(t);if(n.pathInfo.wildcardCount>0&&null===o)return;let s;return n.stateElement.createState("readonly",t=>{t[ie](o,()=>{s=t[n.pathInfo.path]})}),s}function Ol(t,e){Ml.has(t)||(Ml.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}const Rl=t=>()=>t;function jl(t,e,n,s){!function(t,e,n){let o=zn.get(t);o||(o=new Map,zn.set(t,o)),o.set(e,n)}(e,n,t);const r=e.hasAttribute(o.bindAttributeName)?(ut(e)??[]).filter(t=>t.propSegments[0]===n):[];r.length>0?(function(t,e,n){if(0===n.length)return;const o=Hn(t,e);null===o&&rt("State element not found for web component.");const s=new Map,r=new Map,i=new Set;for(const e of n){const n=eo(o,e),a=n.innerAbsPathInfo.pathInfo.path;i.has(a)&&rt("Duplicate mapping rule for web component."),i.add(a);let l=Zn.get(t);void 0===l?Zn.set(t,new Set([n])):l.add(n);const c=n.innerAbsPathInfo,d=n.outerAbsPathInfo;to.set(n,e),s.set(c,d),r.set(d,c),qn(t,d.stateElement)}Xn.set(t,s),Yn.set(t,r)}(e,n,r),function(t,e,n){const o=no(t);if(null===o)return;const s=function(t,e){const n=[];for(const o of Object.keys(t)){if(o.startsWith("$"))continue;if(void 0!==e&&e.has(o))continue;const s=Object.getOwnPropertyDescriptor(t,o);"function"!=typeof s.get&&"function"!=typeof s.set&&"function"!=typeof s.value&&n.push(o)}return n}(n,(r=t,i=e,Js.get(r)?.get(i)));var r,i;if(0===s.length)return;const a=t.tagName.toLowerCase();let l=null;const c=new Map;for(const t of o)t.isRoot?l=t:1===t.innerAbsPathInfo.pathInfo.segments.length&&c.set(t.innerAbsPathInfo.pathInfo.path,t);let d,u=!1;for(const n of s){const o=c.get(n);if(void 0!==o){Ol(`${a}|${e}|${n}|partial`,`<${a}>.${e}.${n} is an own key of the component and is also mapped from the host ("${e}.${n}: ${o.outerAbsPathInfo.pathInfo.path}"). Today the host value wins; in v2 the own key becomes private and hides the host value. Remove the default, or drop the mapping.`);continue}if(null===l)continue;if(u||(d=Ll(t,l),u=!0),"object"!=typeof d||null===d||!(n in d))continue;const s=l.outerAbsPathInfo.pathInfo.path;Ol(`${a}|${e}|${n}|root`,`<${a}>.${e}.${n} is private and hides the mounted tree key "${s}.${n}" (${e}: ${s}). Remove the default to read the tree, or rename it to keep it private.`)}}(e,n,s),t.markComponentStateMapped?.(),t.setInitialState(function(t,e){const n=new kl(t,e),o=Hn(t,e);null===o&&rt("State element not found for web component."),null===o.boundComponentStateProp&&rt("State element is not bound to any component state prop."),o.boundComponentStateProp in t||rt(`State element is not bound to a valid component state prop: ${o.boundComponentStateProp}`);const s=t[o.boundComponentStateProp];return"object"==typeof s&&null!==s||rt(`Invalid state object for component state prop: ${o.boundComponentStateProp}`),new Proxy(Al(s),n)}(e,n))):t.setInitialState(Al(s));const i=function(t,e){const n=new Tl(t,e);return new Proxy({},n)}(e,n);if(Object.defineProperty(e,n,{get:Rl(i),enumerable:!0,configurable:!0}),function(t,e){let n=qo.get(t);n||(n=new Set,qo.set(t,n)),n.add(e)}(e,n),$ in e){const t=e[$];"function"==typeof t?t.call(e,n).catch(t=>{rt(`Error in ${$}: ${t instanceof Error?t.message:String(t)}`)}):rt(`${$} is not a function.`)}}class Dl extends Xr{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return vi(t)}__state;_hasUpdatedCallback=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_name="default";_initialized=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(t=()=>0){return new Gi(t)}(()=>Kn(this));_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_watchPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMappedComponentState=!1;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_dcc=!1;_connectGeneration=0;_streamsStartedGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&rt(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){this._commandTokenNames=function(t){const e=new Set,n=t[A];if(void 0===n)return e;Array.isArray(n)||rt(`${A} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||rt(`${A} entries must be non-empty strings.`),t===k&&rt(`${A} entry "${t}" conflicts with the reserved namespace name "${k}".`),e.has(t)&&rt(`${A} entry "${t}" is duplicated.`),e.add(t);return e}(t),this._eventTokenNames=function(t){const e=new Set,n=t[T];if(void 0===n)return e;Array.isArray(n)||rt(`${T} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||rt(`${T} entries must be non-empty strings.`),e.has(t)&&rt(`${T} entry "${t}" is duplicated.`),e.add(t);return e}(t),this.__state=t,this._hasUpdatedCallback=x in t,sn(this),function(t,e,n){const o=e[M];if(void 0!==o){"object"==typeof o&&null!==o||rt(`${M} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||rt(`${M} entry "${e}" is not declared in $eventTokens.${ft(e,n)}`),"function"!=typeof s&&rt(`${M} entry "${e}" must be a function.`),on(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const n=function(t){const e=new Set,n=new Set,o=Ra(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of n.getterPaths)this._getterPaths.add(t);for(const t of n.setterPaths)this._setterPaths.add(t);fa(this),ra(this),na(this),oa.delete(this),function(t,e){const n=e[L];if(void 0===n)return void Zi(t,aa);"object"==typeof n&&null!==n||rt(`${L} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[i,a]of Object.entries(n)){0===i.length&&rt(`${L} entry name must be a non-empty string.`),i.includes(s)&&rt(`${L} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&rt(`${L} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&rt(`${L} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&rt(`${L} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&rt(`${L} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&rt(`${L} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||rt(`${L} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&rt(`${L} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&rt(`${L} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&rt(`${L} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&rt(`${L} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??ia,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};i in e||(e[i]=c.definition.initial),o.set(i,c)}!function(t,e){oa.set(t,e)}(t,o),Zi(t,new Set(o.keys()))}(this,t),this._listKeys=function(t){const e=t[R];if(void 0===e)return null;"object"==typeof e&&null!==e||rt(`${R} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&rt(`${R} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&rt(`${R} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&rt(`${R} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),"function"!=typeof o?("string"!=typeof o&&rt(`${R} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&rt(`${R} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&rt(`${R} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&rt(`${R} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t),function(t){_a.delete(t),ya.delete(t)}(this),function(t){Na.delete(t)}(this),this._watchPaths=function(t,e){const n=e[O];if(void 0===n)return null;"object"==typeof n&&null!==n||rt(`[wcs/watch-declaration-invalid] ${O} must be an object mapping state paths to handler functions.${pt}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${e}" must be a function.${pt}`),0===e.length&&rt(`[wcs/watch-declaration-invalid] ${O} entry name must be a non-empty state path.`),e.startsWith("$")&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${e}" must not start with "$" (reserved namespace).${pt}`),e.includes(a)&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${e}" must not target another state ("${a}" is not allowed); watch only paths of its own state.${pt}`),e in Object.prototype&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const n=V(e);for(const t of n.segments)0===t.length&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${e}" has an empty path segment.${pt}`);n.wildcardCount>128&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${e}" exceeds the maximum wildcard depth (128).`),o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){ya.set(t,e)}(t,o),s.size>0?s:null}(this,t),this._initialized&&null!==this._rootNode&&!e()&&(Pa(this),ma(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}get name(){return this._name}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const t=this.getAttribute("name")||"default",e=this.parentNode;if(!e)return null;const n=oi.findByName(e,t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null}async _initialize(){const t=e()?null:this._loadFromSsrElement();try{if(this.hasAttribute("state")){const t=this.getAttribute("state");this._state=function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){rt("Failed to parse JSON from script element:"+t)}return{}}(t)}else if(this.hasAttribute("src")){const t=this.getAttribute("src");t&&t.endsWith(".json")?this._state=await async function(t){try{const e=await fetch(t);return e.ok||rt(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t):t&&t.endsWith(".js")?this._state=await qi(t):rt(`Unsupported src file type: ${t}`)}else if(this.hasAttribute("json")){const t=this.getAttribute("json");this._state=JSON.parse(t)}else{const t=this.querySelector('script[type="module"]');if(t)this._state=await Ui(t,`${this._name}`);else{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element with name="${this._name}".`)},6e4);this._state=await this._setStatePromise,clearTimeout(t)}}}catch(t){rt(`Failed to initialize state: ${t}`)}if(null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}await this._loadingPromise,this._name=this.getAttribute("name")||"default",this.hasAttribute("name")&&!this.hasAttribute("bind-component")&&kt("attribute",this._name),Ii(this.rootNode,this._name,this)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const t=this.parentNode,e=t instanceof ShadowRoot?t.host:t instanceof Element?t:null,n=e?Q(e):null;null!==e&&null!==n||rt(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),t instanceof ShadowRoot||this.hasAttribute("name")||rt('"bind-component" in Light DOM requires a "name" attribute to avoid namespace conflicts with the parent scope.');const s=["state","src","json"].filter(t=>this.hasAttribute(t));null!==this.querySelector('script[type="module"]')&&s.push('<script type="module">'),s.length>0&&rt(`"bind-component" cannot be combined with ${s.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const r=this.getAttribute("bind-component");!function(t,e){let n=Go.get(t);n||(n=new Set,Go.set(t,n)),n.add(e)}(e,r);const i=Y(e);null===i&&rt(`CustomElementRegistry is unavailable for <${n}>.`),await i.whenDefined(n.toLowerCase()),e.hasAttribute(o.bindAttributeName)&&await H(e),r in e||rt(`Component does not have property "${r}" for state binding.`);let a=e[r];"object"==typeof a&&null!==a||rt(`Component property "${r}" is not an object for state binding.`);const l=function(t,e){const n=Ks.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(e,r);void 0!==l&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=ut(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(e,r)&&(e[r]=l,a=l),this._boundComponent=e,this._boundComponentStateProp=r,jl(this,this._boundComponent,this._boundComponentStateProp,a)}}_initializeLightDomComponentScope(){const t=this._boundComponent;null!==t&&this.parentNode===t&&t.hasAttribute(o.bindAttributeName)&&(Vr(this._rootNode,t),$r(t,null))}_reloadMappedPathsAfterReconnect(){if(!this._hasMappedComponentState||null===this._boundComponent)return;const t=function(t){const e=Zn.get(t);if(void 0===e)return[];const n=[];for(const t of e)t.isRoot||n.push(t.innerAbsPathInfo.pathInfo.path);return n}(this._boundComponent),e=oo(this._boundComponent)?nr(this):[];!function(t){const e=Zn.get(t);if(void 0===e)return;const n=new Map,o=new Map;for(const t of e)n.set(t.innerAbsPathInfo,t.outerAbsPathInfo),o.set(t.outerAbsPathInfo,t.innerAbsPathInfo);Xn.set(t,n),Yn.set(t,o)}(this._boundComponent),this.createState("readonly",n=>{for(const e of t)n.$postUpdate(e);for(const t of e)n.$postUpdate(t)})}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{I in t&&await t[de]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await qi(t):rt(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await Ui(e,t.tagName.toLowerCase()):rt(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){rt(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||rt(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Y(t);null!==r&&"function"==typeof r.define||rt(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&rt(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template");i.innerHTML=e.innerHTML;const a=e.mode,{bindables:l,commands:c,streamBackedBindables:d}=function(t){const e=Da(t,E)??[],n=Da(t,C)??[],o=Ra(t),s=function(t){const e=t[L];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}rt(`${E} entry "${t}" is not declared on the state.${ft(t,ja(o,"value"))}`)}"function"==typeof e.value&&rt(`${E} entry "${t}" is a method. Declare it in ${C} instead.`)}for(const t of n){const e=o[t];void 0===e&&rt(`${C} entry "${t}" is not declared on the state.${ft(t,ja(o,"method"))}`),"function"!=typeof e.value&&rt(`${C} entry "${t}" is not a method. Declare it in ${E} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),u=l.length>0||c.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,l,c):null,h=l.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,l):{},f=`${o.tagNames.state}:not([name])`,p=class extends HTMLElement{static template=i;static shadowRootMode=a;static wcBindable=u;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(B))return null;this._shadow=this.attachShadow({mode:p.shadowRootMode}),this._shadow.appendChild(p.template.content.cloneNode(!0));const t=Y(this._shadow);return null!==t&&Z(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(p.bindableEventMap).length>0){const e=t.querySelector(f);e?e.setBindableEventMap(p.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${E} but its template has no <${o.tagNames.state}> without a "name" attribute. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(f)??null}},m=Ra(n);for(const[t,e]of Object.entries(m)){if(Oa(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=La(t,o)}else n.get=Ta(t),n.set=Ma(t);Object.defineProperty(p.prototype,t,n)}for(const t of d)Object.defineProperty(p.prototype,t,{configurable:!0,enumerable:!0,get:Ta(t),set:Ma(t)});r.define(s,p)}(t,e,n),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",t=>{P in t&&t[ue]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized)this._dcc||wi(this._rootNode,this._name)===this||(Ii(this._rootNode,this._name,this),this._reloadMappedPathsAfterReconnect());else{const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(B))return this.hasAttribute("bind-component")&&rt(`"bind-component" cannot be used inside a [${B}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(t.host,t);await this._initializeBindWebComponent(),await this._initialize(),this._initialized=!0,this._initializeLightDomComponentScope(),this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await vi(this.rootNode);const t=this.getAttribute("name")||"default",e=oi.extractStateData(this),n=document.createElement(o.tagNames.ssr);n.setAttribute("name",t),n.setAttribute("version",Qr),oi.buildContent(n,e),this.parentNode?.insertBefore(n,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||Pa(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||ma(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(null!==this._rootNode)try{this._callStateDisconnectedCallback()}finally{Ii(this.rootNode,this._name,null),Vi.delete(this),function(t){Ji.delete(t)}(this),sn(this),ra(this),fa(this),function(t){_a.delete(t)}(this),this._rootNode=null}}get initialized(){return this._initialized}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get watchPaths(){return this._watchPaths}get elementPaths(){return this._elementPaths}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get rootNode(){return null===this._rootNode&&rt("State rootNode is not available."),this._rootNode}get hasRootNode(){return null!==this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get boundComponent(){return this._boundComponent}get hasMappedComponentState(){return this._hasMappedComponentState}get boundPaths(){return this._pathSet}markComponentStateMapped(){this._hasMappedComponentState=!0}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("for"===e){const e=!this._listPaths.has(t);this._listPaths.add(t),this._elementPaths.add(t+"."+r),e&&this._hasMappedComponentState&&function(t,e){const n=io(t,V(e));null!==n&&n.stateElement!==t&&n.stateElement.setPathInfo(n.pathInfo.path,"for","internal")}(this,t)}if(!this._pathSet.has(t)){const e=V(t);if(this._pathSet.add(t),function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(!0===t.hasMappedComponentState)return;const i=V(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=fr.get(t);return void 0===n&&(n=new Set,fr.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;const a=function(t,e,n){if(void 0!==ir(t,e))return rr;const o=V(e).segments;let i=t,a="";for(let e=0;e<o.length;e++){const l=o[e],c=a;if(a=0===e?l:a+s+l,e>0&&e<o.length-1&&void 0!==ir(t,a))return sr;if(Object(i)!==i)return sr;if(l===r){if(!Array.isArray(i)||0===i.length)return sr;i=i[0];continue}const d=ir(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:ar(i,c,n)};if("function"==typeof d.get)return e===o.length-1?rr:sr;i=d.value}return rr}(e,n,t.getterPaths);"missing"===a.existence&&(console.warn(`[@wcstack/state] [${lr[o]}] ${cr[o]} "${n}" does not resolve on state "${t.name}": "${a.missingSegment}" is not declared.${ft(a.missingSegment,a.candidates)} Updates to this path will be silently dropped.${pt}`),null!==ne&&ne({type:"state:path-unresolved",source:o,stateName:t.name,path:n,missingSegment:a.missingSegment}))}(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=V(t.parentPath)}}}_createState(t,e,n){try{const o=function(t,e,n,o){const s=new Cl(t,n,o);return new Proxy(e,s)}(t,this._state,this._name,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}bindProperty(t,e){Object.defineProperty(this._state,t,e),t===x&&(this._hasUpdatedCallback=!0)}setInitialState(t){this._initialized?this._state=t:this._resolveSetState?.(t)}}await function(){const e=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(void 0);var s;e&&((s=e).tagNames&&Object.assign(n.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(n.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(n.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(n.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(n.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(n.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(n.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(n.locale=s.locale),"boolean"==typeof s.debug&&(n.debug=s.debug),"boolean"==typeof s.enableMustache&&(n.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(n.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(n.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(n.sameValueGuard=s.sameValueGuard)),function(t=customElements){t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,oi),t.get(o.tagNames.state)||t.define(o.tagNames.state,Dl)}(void 0),function(){const t=globalThis;void 0===t[li]&&(t[li]=gi)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=Fi)}(),Wi()}();const Bl={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},Wl=!1,Fl=[".html"];function zl(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function Hl(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let Ul=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const ql={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}},Gl={static:2,param:1,"catch-all":0};let Vl=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&Hl(`${Bl.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&Hl(`${Bl.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=Gl[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(ql).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||Hl(`${Bl.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath;if(!await this._guardHandler(e,n))throw new Ul("Navigation cancelled by guard.",this._guardFallbackPath)}else if(this._hasGuard&&this._guardHandlerLoadFailed)throw new Ul("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath)}},Kl=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=zl();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new Vl(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||Hl(`${Bl.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):Hl(`${Bl.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&Hl(`${Bl.route} with fallback attribute must be a direct child of ${Bl.router}.`),t.fallbackRoute&&Hl(`${Bl.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const Jl=new Map;let Ql=class extends HTMLElement{_uuid=zl();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||Hl(`${Bl.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Jl.set(t,n),n}catch(e){Hl(`${Bl.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${Bl.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Jl.has(t)?n.innerHTML=Jl.get(t)||"":n.innerHTML=await this._loadTemplateFromSource(t)||"";else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=t:console.warn(`${Bl.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Wl}get name(){return this.getAttribute("name")||""}},Xl=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||Hl(`${Bl.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Wl}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Yl=new Set(["props","states","attr",""]);function Zl(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function tc(t,e){t.hasAttribute("data-bind")||Hl(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Yl.has(n)||Hl(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&Zl(t,e,o)}).catch(()=>{Hl(`Failed to define custom element: ${s}`)}):Zl(t,e,o)}let ec=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||Hl(`${Bl.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${Bl.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{tc(e,t)}),e.hasAttribute("data-bind")&&tc(e,t))}};function nc(){return document.createElement(Bl.layoutOutlet)}const oc="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function sc(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){Hl(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${oc}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${oc}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function rc(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function ic(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===Bl.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),rc(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===Bl.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&sc(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===Bl.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=nc();o.layout=n,i=o,a=e}}const c=await ic(t,a,n,o);a.innerHTML="",a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function ac(t){const e=new Map;return await ic(t,t.template.content,[],e)}function lc(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let d=!1;if("param"===e.type){const t=e.paramType||"any",n=ql[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),d=!0)}else d=null!==e.pattern.exec(c);if(!d){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)lc(s,e,n,o)}function cc(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)lc(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let dc=null,uc=null;function hc(){const t=Fl;return 0===t.length?null:(dc===t&&uc||(dc=t,uc=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),uc)}function fc(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=hc();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function pc(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function mc(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=hc();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function gc(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function bc(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{tc(e,t.typedParams)}),n.hasAttribute("data-bind")&&tc(n,t.typedParams),n.querySelectorAll(Bl.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===Bl.layoutOutlet&&n.assignParams(t.typedParams)}}function yc(t,e){bc(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const _c=Symbol.for("wcstack.transition-runner");const wc=Symbol.for("wcstack.binder");function vc(){const t=globalThis[wc];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const Nc=Symbol.for("wcstack.binder.pending"),Sc=Symbol.for("wcstack.binder.taken");function Ic(){const t=globalThis;let e=t[Sc];return void 0===e&&(e=new WeakSet,t[Sc]=e),e}function Pc(t){const e=vc();return null===e?(function(){const t=globalThis;let e=t[Nc];return void 0===e&&(e=[],t[Nc]=e),e}().push(t),!1):(Ic().add(t),e.bind(t),!0)}const xc=new WeakSet,$c="data-wcs";function Ec(t,e,n){!xc.has(t)&&function(t){return t.hasAttribute($c)||null!==t.querySelector(`[${$c}]`)}(t)&&(xc.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==vc()||(o=t,Ic().has(o))||console.warn(`[@wcstack/router] ${e} contains ${$c} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function Cc(t){for(const e of t.childNodeArray)1===e.nodeType&&(Pc(e)||Ec(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.'))}async function Ac(t,e){try{for(const t of e.routes)await t.guardCheck(e)}catch(e){if(e instanceof Ul)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function kc(t,e,n,o,s=""){const r=pc(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,search:s,path:r}),!0;let i=cc(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:Hl(`${Bl.router} No route matched for path: ${r}`)),i.lastPath=o;const a=e.lastRoutes,l=await async function(t,e,n){if(!await Ac(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||gc(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=yc(o,e),n.length>0&&!s.has(o)&&Cc(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[_c];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName))return t;const n=t.querySelector("h1,h2,h3,h4,h5,h6");if(null!==n)return n}return null}(e.routes[e.routes.length-1].childNodeArray);null!==t&&(t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus())}}(t,i),!0)}function Tc(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Mc(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}function Lc(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function Oc(t){return"?"===t?"":t}function Rc(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function jc(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Dc="data-wcs-ssr",Bc="data-wcs-ssr-link",Wc="@@wcs-route-ph:",Fc="@@wcs-route-start:",zc="@@wcs-route-end:",Hc=Object.freeze({});class Uc extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Hc;_typedParams=Hc;_searchParams=Hc;_routeName="";_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return this.getAttribute("focus")}get announcePolicy(){return this.getAttribute("announce")}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return fc(t)}_normalizeBasename(t){return mc(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(Bl.outlet))return t;const e=document.createElement(Bl.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||Hl(`${Bl.router} has no outlet.`),this._outlet}get template(){return this._template||Hl(`${Bl.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=function(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}(t.search),s=!Mc(this._params,e),r=this._routeName!==t.routeName,i=!Mc(this._searchParams,o),a=this._path!==t.path;s&&(this._params=e,this._typedParams=n),r&&(this._routeName=t.routeName),i&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,s&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),r&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${Bl.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${Bl.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=Lc(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Oc(n.search)+n.hash,r=Tc();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(pc(t,this._basename));await kc(this,this.outlet,t,this._path,Oc(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(pc(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await kc(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${Bl.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await kc(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=jc();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||Hl(`${Bl.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||Hl(`${Bl.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await ac(this),r=!t&&this._outlet.hasAttribute(Dc);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&Hl(`${Bl.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(Dc);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await kc(this,this.outlet,i,this._path,window.location.search||""),(r||null!==vc())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(Bl.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(Wc)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Fc)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith(zc)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const d=pc(t,this._basename);let u=cc(this,d);if(!u){if(null===this._fallbackRoute)return!1;u={routes:[this._fallbackRoute],params:{},typedParams:{},path:d,lastPath:this._path}}if(u.lastPath=this._path,u.routes.length!==r.size)return!1;for(const t of u.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of u.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of u.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(Fc)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===Bl.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(Dc);for(const t of u.routes)bc(t,u);return this.outlet.lastRoutes=u.routes,!await Ac(this,u)||(this.commitNavigation({params:u.params,typedParams:u.typedParams,routeName:u.routes[u.routes.length-1].name,search:window.location.search||"",path:d}),!0)}async _renderForSsr(t){const e=pc(t,this._basename),n=cc(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&Hl(`${Bl.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await kc(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${Wc}${t.absolutePath}`}),this.outlet.setAttribute(Dc,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${Fc}${t.absolutePath}`),s=document.createComment(`${zc}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&Pc(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Rc(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),jc()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Tc();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Tc()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const qc=["title","rel","target","download","hreflang"];class Gc extends HTMLElement{static get observedAttributes(){return["to",...qc]}_childNodeArray=[];_uuid=zl();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(Bl.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(Bl.router);if(n)return this._router=n;Hl(`${Bl.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return fc(t)}_joinInternalPath(t,e){const n=mc(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=Lc(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+Oc(o)+s}else try{t.href=new URL(e).toString()}catch{Hl(`[${Bl.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){jc()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Bc)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(Bc),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||qc.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,jc())return this._updateActiveState(),void n.setAttribute(Bc,"");Tc()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Tc()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Tc()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(qc.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=Lc(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Vc=[],Kc=new Map;let Jc=!1;const Qc=new WeakMap;class Xc extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Jc||(this._captureInitialHead(),Jc=!0),Vc.push(this),this._reapplyHead()}disconnectedCallback(){const t=Vc.indexOf(this);-1!==t&&Vc.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||Hl("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Qc.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Qc.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Kc.has(t)||Kc.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Vc)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Kc.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=Vc.length-1;e>=0;e--){const o=Vc[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Kc.has(n)&&(t=Kc.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),Pc(t)||Ec(t,`<${t.tagName.toLowerCase()}> inside <${Bl.head}>`,`<${Bl.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(Bl.layout)||t.define(Bl.layout,Ql),t.get(Bl.layoutOutlet)||t.define(Bl.layoutOutlet,ec),t.get(Bl.outlet)||t.define(Bl.outlet,Xl),t.get(Bl.route)||t.define(Bl.route,Kl),t.get(Bl.router)||t.define(Bl.router,Uc),t.get(Bl.link)||t.define(Bl.link,Gc),t.get(Bl.head)||t.define(Bl.head,Xc)}(void 0);const Yc="data-fetchtarget",Zc={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let td=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function ed(t,e){return e.every(e=>"available"===t.availability.get(e))}const nd=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let od=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new td("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return ed(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),d=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",u=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:d,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}(nd,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!ed(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:d="auto",timeout:u=0}=e;let h=null;u>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${u}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},u));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===d)s=await n.blob();else if("arrayBuffer"===d)s=await n.arrayBuffer();else if("text"===d)s=await n.text();else if("json"===d)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const u=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,u)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},sd=!1;function rd(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Yc}]`);if(!n)return;const o=n.getAttribute(Yc);if(!o)return;const s=customElements.get(Zc.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function id(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let ad=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...od.wcBindable,properties:[...od.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new od(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(Zc.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(Zc.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&(t.innerHTML=s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!id(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",sd||(sd=!0,document.addEventListener("click",rd)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}},ld=class extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}},cd=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}},dd=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof ad&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(Zc.fetch)||t.define(Zc.fetch,ad),t.get(Zc.fetchHeader)||t.define(Zc.fetchHeader,ld),t.get(Zc.fetchBody)||t.define(Zc.fetchBody,cd),t.get(Zc.infiniteScroll)||t.define(Zc.infiniteScroll,dd)}(void 0);const ud="data-storagetarget",hd={storage:"wcs-storage"},fd="wcs-storage:value-changed",pd="wcs-storage:loading-changed",md="wcs-storage:error",gd="wcs-storage:error-info-changed",bd="wcs-storage:trigger-changed";let yd=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:fd,semantics:"state",getter:t=>t.detail},{name:"loading",event:pd,semantics:"state"},{name:"error",event:md,semantics:"state"},{name:"errorInfo",event:gd,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(pd,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(md,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(gd,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(fd,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},_d=!1;function wd(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${ud}]`);if(!n)return;const o=n.getAttribute(ud);if(!o)return;const s=customElements.get(hd.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function vd(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let Nd=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...yd.wcBindable,properties:[...yd.wcBindable.properties,{name:"trigger",event:bd,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new yd(this),this._internals=this._initInternals(),this._wireStates({[pd]:t=>({loading:!0===t}),[md]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(bd,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!vd(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",_d||(_d=!0,document.addEventListener("click",wd)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(hd.storage)||t.define(hd.storage,Nd)}(void 0);const Sd="*",Id="vanilla",Pd={scanImportmap:!0,loaders:{[Id]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[Sd]:Id},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function xd(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function $d(t,e,n){let o;if(null===e||e===Sd||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===Sd)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[Sd],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const Ed=new Set,Cd=new Map;let Ad=new WeakMap;function kd(t){if(t===globalThis.customElements)return Cd;let e=Ad.get(t);return void 0===e&&(e=new Map,Ad.set(t,e)),e}const Td=new Map;async function Md(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of Td)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){Ed.has(e)||(console.error(`Failed to eager load component '${e}':`,t),Ed.add(e))}}function Ld(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function Od(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&Td.set(t,e)});const Rd=new WeakSet,jd=new WeakSet;async function Dd(t,e,n){t.shadowRoot&&(Rd.has(t)||await async function(t,e,n){Rd.add(t),await zd(t.shadowRoot,e,n)}(t,e,n))}async function Bd(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=kd(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=$d("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),Ed.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Wd(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=Od(t);void 0===o.get(s.name)?(jd.has(t)||(jd.add(t),o.whenDefined(s.name).then(async()=>{await Dd(t,e,n)})),a.has(s.name)||Ed.has(s.name)||(a.add(s.name),i.push(s))):await Dd(t,e,n)}let l=0;for(const t of i)await Bd(t,e,n,o),l++;return l}async function Fd(t,e,n,o){for(;await Wd(t,e,n,o)>0;);}async function zd(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return Ld(e)}return Ld(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Fd(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await Fd(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Hd extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Hd._instance)throw new Error(`${Pd.tagNames.autoloader} can only be instantiated once.`);Hd._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=xd(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=$d(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(Md(s,o,r))}await Promise.all(n)}(n,Pd.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await zd(document,Pd,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Hd._instance===this&&(Hd._instance=null)}}!function(t=customElements){t.get(Pd.tagNames.autoloader)||t.define(Pd.tagNames.autoloader,Hd)}(void 0);
1
+ const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n,s=".",r="*",i=128,a="|",l="prevent",c="stop",d="ro",u="init",h="sync",f="else",p="...",m="on",g="eventToken",y="command",b="class",w="attr",_="style",v={};for(let t=0;t<128;t++)v[`$${t+1}`]=t;const N=Object.freeze(v),S="$connectedCallback",I="$disconnectedCallback",$="$updatedCallback",x="$stateReadyCallback",P="$bindables",k="$commands",C="$commandTokens",E="$command",A="$eventTokens",T="$on",M="$streams",L="$watch",O="$listKeys",R="$streamStatus",j="$streamError",D="data-wc-definition",B=new WeakMap,W=new WeakSet;let z=0;async function F(t){const e=function(t){let e,n=B.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++z,promise:o,resolve:e},B.set(t,n),W.has(t)&&n.resolve(),n}(t);await e.promise}function H(t){const e=B.get(t);void 0===e?W.add(t):e.resolve()}const U=new Map;let q=0;function G(t){let e=U.get(t);return void 0!==e||(e=Object.freeze(new K(t)),U.set(t,e)),e}let K=class{id=++q;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:G(e),n=t.split("."),o=[],s=[],i=[],a={},l=[],c=[],d=[],u=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===r&&(i.push(h),a[h]=p,l.push(e(h)),c.push(f),d.push(e(f)),u.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=i.length>0?i[i.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=i,this.wildcardPathSet=new Set(i),this.indexByWildcardPath=a,this.wildcardPathInfos=l,this.wildcardPathInfoSet=new Set(l),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}};const V=new WeakMap;function J(t){const e=V.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{V.set(t,n)}}function Q(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function X(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Q(e);if(void 0!==n)return Q(n)}return Q(globalThis.customElements)}function Y(t,e){t.upgrade?.(e)}function Z(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=ot(s.properties,tt);if(null===r)return null;const i=void 0===s.inputs?new Map:ot(s.inputs,et);if(null===i)return null;const a=void 0===s.commands?new Map:ot(s.commands,nt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function tt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function et(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function nt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function ot(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function st(t){throw new Error(`[@wcstack/state] ${t}`)}function rt(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:G(n),inFilters:[],outFilters:[],bindingType:"prop"}}function it(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function at(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&st("Spread binding requires an element node.");const e=t,o=J(e);null===o&&st(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=X(e);if(null===a&&st(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||st(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Y(a,e);const l=Z(e);null===l&&st(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const t of l.knownProperties.keys()){if(d.has(t))continue;d.add(t);const e=rt(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(d.has(t))continue;d.add(t);const e=rt(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=it(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=it(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function lt(t,e){let n=t;if(0===e.length)return n;for(let t=0;t<e.length&&(n=n?.childNodes[e[t]]??null,null!==n);t++);return n}const ct=new WeakMap;function dt(t){return ct.get(t)||null}function ut(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function ht(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=ut(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const ft=" Validate statically: npx @wcstack/lint <file>.",pt=new Set(["if","elseif","else","for"]);function mt(t){st(`filter ${t} requires at least one option`)}function gt(t){st(`filter ${t} requires a number as option`)}function yt(t){st(`filter ${t} requires a number value`)}function bt(t){st(`filter ${t} requires a date value`)}function wt(t){return!(!t||isNaN(Number(t)))}const _t={eq:t=>{const e=t?.[0]??mt("eq");return t=>"number"==typeof t?(wt(e)||gt("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??mt("ne");return t=>"number"==typeof t?(wt(e)||gt("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&st("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??mt("lt");return wt(e)||gt("lt"),t=>("number"!=typeof t&&yt("lt"),t<Number(e))},le:t=>{const e=t?.[0]??mt("le");return wt(e)||gt("le"),t=>("number"!=typeof t&&yt("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??mt("gt");return wt(e)||gt("gt"),t=>("number"!=typeof t&&yt("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??mt("ge");return wt(e)||gt("ge"),t=>("number"!=typeof t&&yt("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??mt("inc");return wt(e)||gt("inc"),t=>("number"!=typeof t&&yt("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??mt("dec");return wt(e)||gt("dec"),t=>("number"!=typeof t&&yt("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??mt("mul");return wt(e)||gt("mul"),t=>("number"!=typeof t&&yt("mul"),t*Number(e))},div:t=>{const e=t?.[0]??mt("div");return wt(e)||gt("div"),t=>("number"!=typeof t&&yt("div"),t/Number(e))},mod:t=>{const e=t?.[0]??mt("mod");return wt(e)||gt("mod"),t=>("number"!=typeof t&&yt("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&yt("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??mt("clamp");wt(e)||gt("clamp");const n=t?.[1]??mt("clamp");wt(n)||gt("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&yt("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return wt(e)||gt("fix"),t=>("number"!=typeof t&&yt("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&yt("locale"),t.toLocaleString(e??o.locale))},uc:t=>t=>String(t).toUpperCase(),lc:t=>t=>String(t).toLowerCase(),cap:t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)},trim:t=>t=>String(t).trim(),slice:t=>{const e=[],n=t?.[0]??mt("slice");wt(n)||gt("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(wt(o)||gt("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??mt("substr");wt(e)||gt("substr");const n=t?.[1]??mt("substr");return wt(n)||gt("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??mt("pad");wt(e)||gt("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??mt("rep");return wt(e)||gt("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??mt("truncate");wt(e)||gt("truncate");const n=Number(e),o=t?.[1]??"…";return t=>{const e=String(t);return e.length<=n?e:e.slice(0,n)+o}},join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||st("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=t?.[0]??"0";return wt(e)||gt("round"),t=>{"number"!=typeof t&&yt("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return wt(e)||gt("floor"),t=>{"number"!=typeof t&&yt("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return wt(e)||gt("ceil"),t=>{"number"!=typeof t&&yt("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return wt(e)||gt("percent"),t=>("number"!=typeof t&&yt("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??mt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||bt("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||bt("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!1===t||null==t||0===t||""===t||Number.isNaN(t),truthy:t=>t=>!1!==t&&null!=t&&0!==t&&""!==t&&!Number.isNaN(t),defaults:t=>{const e=t?.[0]??mt("defaults");return t=>!1===t||null==t||0===t||""===t||Number.isNaN(t)?e:t},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),null:t=>t=>""===t?null:t},vt=_t,Nt={input:_t,output:vt},St=(t,e)=>n=>{const o=n[t];return o||st(`[wcs/filter-unknown] filter not found: ${t}.${ht(t,Object.keys(n))}${ft}`),o(e)};function It(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const $t=new Map;function xt(t,e){const n=Nt[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&st(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&st(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=$t.get(s);return void 0===r&&(r=St(o,[])(n),$t.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=t.substring(o+1,s),i=t.substring(0,o).trim(),a=function(t){const e=[];let n="",o=null,s=!1,r=-1,i=-1;const a=()=>{e.push(It(n,r,i)),n="",s=!1,r=-1,i=-1};for(let e=0;e<t.length;e++){const l=t[e];o?l===o?o=null:(-1===r&&(r=n.length),n+=l,i=n.length):'"'===l||"'"===l?(o=l,s=!0):","===l?a():n+=l}const l=It(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=$t.get(l);return void 0===c&&(c=St(i,a)(n),$t.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const Pt=t=>t.trim(),kt=new Map,Ct=new Map;function Et(t){const e=t.indexOf(a);let n="",o=[],s="",r=[];return-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Ct.has(s)?r=Ct.get(s):(o=s.split(a).map(Pt),r=xt(o,"output"),Ct.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&st(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`),{statePathName:n,statePathInfo:G(n),outFilters:r}}function At(t){const[...e]=t.split(";").map(Pt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&st(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===f){const t=G("#else");return{propName:f,propSegments:[f],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===p){const e=Et(o);return e.outFilters.length>0&&st(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&st(`Invalid spread binding "${t}": spread target path is required.`),{propName:p,propSegments:[p],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Et(o),bindingType:n};{const t=Et(o),e=function(t){const e=t.indexOf(a);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),kt.has(r)?i=kt.get(r):(o=r.split(a).map(Pt),i=xt(o,"input"),kt.set(r,i))):n=t.trim();const[l,c]=n.split("#").map(Pt),d=l.split(s).map(Pt);return{propName:l,propSegments:d,propModifiers:c?c.split(",").map(Pt):[],inFilters:i}}(n);return e.propSegments[0]===g||e.propSegments[0].startsWith(m)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>pt.has(t.bindingType))&&st(`[wcs/template-syntax] Invalid bindText: "${t}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${ft}`),n}const Tt=new WeakMap,Mt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Lt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Ot(t){const e=Tt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Lt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Mt.has(r)?(Tt.set(t,s[2]),s[2]):null}function Rt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Et(t),bindingType:"text"}}const jt=new Map;function Dt(t,e,n){if(null===n)jt.delete(t);else{jt.set(t,n);const o=Pi(e);null===o&&st("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function Bt(t){return jt.get(t)||null}function Wt(t){if(t.nodeType===Node.ELEMENT_NODE)return At(t.getAttribute(o.bindAttributeName)||"");if(t.nodeType===Node.COMMENT_NODE){const e=Ot(t);null===e&&st("Comment node binding text not found.");const n=Bt(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Rt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function zt(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function Ft(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!zt(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function Ht(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function Ut(t){const e=[],n=Ft(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Ot(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&Ht(t,n)||e.push(t)}return e}const qt=new WeakSet;function Gt(t,e,n,o){const s=at(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?J(t):null;return null===n&&st("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}qt.add(t);const r=function(t,e){const n=[];for(const o of e)if("text"!==o.bindingType)n.push({...o,node:t,replaceNode:t});else{const e=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,node:t,replaceNode:e})}return n}(t,function(t,e){return void 0===e?t:t.map(t=>null!=t.uuid?t:e(t))}(s,o));return function(t,e){ct.set(t,e)}(t,r),H(t),{bindings:r,deferred:null}}function Kt(t,e){const n=Ut(t),o=[],s=[];for(const t of n){if(qt.has(t))continue;const n=Gt(t,Wt(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Vt(t){qt.add(t)}function Jt(t){const{node:e,parseResults:n,transform:o}=t;return function(t){qt.delete(t)}(e),Gt(e,n,{allowDeferred:!1},o).bindings}let Qt=0;const Xt=["$watch","$streams","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on"],Yt=new Set;function Zt(t,e){const n=t.stateObject[e];if("function"==typeof n)try{const o=t.component[t.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function te(t){const e=t.indexOf(s);return-1===e?t:t.slice(0,e)}function ee(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function ne(t,e){for(const n of t.entries)if(ee(e,n.innerSegments)){const t=e.slice(n.innerSegments.length);return 0===t.length?n.outerPathInfo.path:n.outerPathInfo.path+s+t.join(s)}return null}function oe(t,e){return t.markerBasePath+s+e}function se(t,e,n,o){let r=t.accessorBySuffixByMarkerParent.get(e);void 0===r&&(r=new Map,t.accessorBySuffixByMarkerParent.set(e,r));const i=e+s+n;r.set(n,{accessorName:o,indexShift:G(i).wildcardCount-G(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(i),t.addedGetterPaths.add(i))}function re(t,e){return!t.injectedKeys.has(e)&&("function"==typeof t.stateObject[e]&&!t.getterKeys.has(e)||Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function ie(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(s)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${te(e)}: path") or declare the key on the component state.`}const ae=/^\$(\d+)$/;function le(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(s);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===r){o=t;break}if(-1===o)return se(t,t.markerBasePath,e,e),oe(t,e);if(re(t,n[0]))return se(t,t.markerBasePath,e,e),oe(t,e);const i=n.slice(0,o+1),a=n.slice(o+1),l=ne(t,i);null===l&&st(ie(t,e)),0===a.length&&st(`Wildcard-terminal accessor "${e}" on mounted <${t.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const c=l+s+t.marker;return se(t,c,a.join(s),e),c+s+a.join(s)}(t,e);const o=te(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return oe(t,e);if(re(t,o))return oe(t,e);const i=ne(t,e.split(s));if(null!==i)return i;st(ie(t,e))}function ce(t,e,n,o,s){if(void 0===o)return;const r=G(n).wildcardCount-G(e).wildcardCount;return 0===r?o:(s.length<r&&st(`Cannot resolve "${e}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const de=new WeakMap,ue=new WeakMap,he=new WeakMap,fe=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)});function pe(t){return de.get(t)??null}function me(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=he.get(t);if(void 0===o)return null;const r=e.indexOf(s,n),i=-1===r?e.slice(n):e.slice(n,r),a=o.get(i);if(void 0===a)return null;const l=a.deref();return void 0===l?(o.delete(i),null):l}const ge=new WeakMap;function ye(t){let e=t;for(;e;){const t=ge.get(e);if(t)return t;let n=e.parentNode;null===n&&e instanceof ShadowRoot&&null!==pe(e)&&(n=e.host),e=n}return null}function be(t,e){null!==e?ge.set(t,e):ge.delete(t)}let we=null;const _e=new WeakMap;function ve(t){return _e.get(t)??[]}function Ne(t,e){_e.set(t,e)}function Se(t){return _e.has(t)}const Ie=Symbol("$$setLoopContext"),$e=Symbol("$$getByAddress"),xe=Symbol("$$hasByAddress"),Pe=Symbol("$$setByAddress"),ke=Symbol("$$connectedCallback"),Ce=Symbol("$$disconnectedCallback"),Ee=Symbol("$$updatedCallback"),Ae=new WeakMap;function Te(t,e){if(Ae.has(t)){const n=Ae.get(t);if(n.has(e))return n.get(e)}else Ae.set(t,new WeakMap);const n=Object.freeze(new Me(t,e));return Ae.get(t).set(e,n),n}class Me{pathInfo;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Te(t,e.parentPathInfo)}}const Le=new WeakMap,Oe=new WeakMap;class Re{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const t=this.absolutePathInfo.parentAbsolutePathInfo;if(null===t)return null;let e=null;return e=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=je(t,e)}}function je(t,e){if(null===e){let e=Oe.get(t);return void 0!==e||(e=new Re(t,null),Oe.set(t,e)),e}{let n=Le.get(e);void 0===n&&(n=new WeakMap,Le.set(e,n));let o=n.get(t);return void 0!==o||(o=new Re(t,e),n.set(t,o)),o}}const De=new WeakMap;function Be(t,e){null===e?De.delete(t):De.set(t,e)}function We(t){return De.get(t)||null}const ze=new Map;function Fe(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=ze.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,ze.set(s,r)),r}function He(t,e,n){return e<0||e>=n?null:t.at(e-n)}function Ue(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const qe=new WeakMap;function Ge(t){const e=ye(t.node);if(null===e)return null;let n=qe.get(e);if(void 0===n)n=new WeakMap,qe.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Fe(e.pathInfo,t.statePathInfo);return n>0&&(o=He(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const Ke=new WeakMap;function Ve(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=We(n);null===e?st(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function Je(t,e){let n=null;if(n=Ke.get(t)||null,null!==n)return n;const o=Ve(t,e),s=Ge(t),r=Pi(o);return null===r&&st("No state tree found on this root for binding."),n=je(Te(r,t.statePathInfo),s),Ke.set(t,n),n}function Qe(t){Ke.delete(t)}const Xe=new WeakMap;function Ye(t,e){const n=Xe.get(t);void 0===n?Xe.set(t,e):n instanceof Set?n.add(e):n!==e&&Xe.set(t,new Set([n,e])),null!==we&&we({type:"state:binding-added",absoluteAddress:t,binding:e})}function Ze(t,e){const n=Xe.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&Xe.delete(t),null!==we&&we({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const tn=new WeakMap;function en(t,e,n){const o=tn.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==we&&we({type:"state:binding-removed",absoluteAddress:je(t,e),binding:n}))}function nn(t){const e=Xe.get(t);return void 0!==e?e:null!==t.listIndex?tn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const on=new WeakMap,sn=new WeakMap;class rn{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=an(t,e)}}function an(t,e){if(null===e){let e=sn.get(t);return void 0!==e||(e=new rn(t,null),sn.set(t,e)),e}{let n=on.get(e);void 0===n&&(n=new WeakMap,on.set(e,n));let o=n.get(t);return void 0!==o||(o=new rn(t,e),n.set(t,o)),o}}const ln=new WeakMap;function cn(t){let e=null;if(e=ln.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=Ge(t);null===n&&st(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=an(t.statePathInfo,n)}else e=an(t.statePathInfo,null);return ln.set(t,e),e}function dn(t){ln.delete(t)}function un(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const hn=new Map,fn=un();function pn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function mn(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function gn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function yn(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)gn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class bn{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)e.push(n(...t));return e}}class wn extends bn{constructor(t){super(t)}emit(...t){return null!==we&&we({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}const _n=new WeakMap;function vn(t,e){let n=_n.get(t);void 0===n&&(n=new Map,_n.set(t,n));let o=n.get(e);return void 0===o&&(o=new wn(e),n.set(e,o)),o}function Nn(t){_n.delete(t)}const Sn=new WeakMap;class In extends bn{constructor(t){super(t)}emit(...t){return null!==we&&we({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}function $n(t){return t instanceof In}const xn=new Map,Pn=un();function kn(t){const e=t.propModifiers.filter(t=>t===l||t===c).sort().join(",");return`${t.statePathName}::${e}`}function Cn(t){if(!t.propName.startsWith(m))return!1;const e=kn(t);let n=xn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(l)&&o.preventDefault(),e.includes(c)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Pi(r);null===i&&st("No state tree found on this root for event handler.");const a=ye(s),d=t.startsWith(E+".");i.createStateAsync("writable",async e=>{const l=e[Ie](a,()=>{let l=null!==a?a.pathInfo.wildcardCount:0;if(null!==a&&!0===i.hasMounts){const t=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=de.get(n);if(void 0!==t)return t;n=n.parentNode}return de.get(e)??null}(s,r);if(null!==t){const e=t.indexShiftByLoopElementPath.get(a.pathInfo.path);l=void 0!==e?l-e:0}}const c=null!==a?Ue(a.listIndex,l):[];if(d){const s=e[$e](an(n,null));return $n(s)||st(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...c)}const u=e[t];return"function"!=typeof u&&st(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(u,e,[o,...c])});yn(l,`"${t}"`)})})(t.statePathName,t.propModifiers,t.statePathInfo),xn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Pn.add(e,t),!0}const En=new Map,An=un();function Tn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Mn(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}const Ln=new Set(["radio","checkbox"]),On=new Set(["value","valueAsNumber","valueAsDate"]);function Rn(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(Ln.has(t)&&"checked"===e)return!0;if(On.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=J(n);if(null!==s){const t=X(n)?.get(s);void 0===t&&st(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Z(n);if(o?.knownProperties.has(e))return!0}return!1}let jn=1,Dn=1,Bn=1;const Wn=new WeakMap;function zn(t,e,n){let o=Wn.get(t);void 0===o&&(o=new Map,Wn.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=jn++,o.set(s,r)),r}function Fn(t,e){return"to-element"===e?2*t:2*t+1}const Hn=new Set;function Un(t){return{transactionId:Dn++,originBindingId:t,visitedEdges:Hn,hop:0}}function qn(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let Gn=null;function Kn(){return Gn}function Vn(t,e){const n=Gn;Gn=t;try{return e()}finally{Gn=n}}const Jn=[];let Qn=!1;const Xn=new Map,Yn=un(),Zn=new WeakMap,to=t=>t.detail;function eo(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function no(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=J(t.node);if(null!==n){const o=X(t.node)?.get(n);void 0===o&&st(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Z(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function oo(t){if(null!==J(t.node)){const e=Z(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??to}return null}function so(t){if(null===J(t.node))return!1;const e=Z(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const ro=new WeakSet;function io(t){ro.add(t)}function ao(t){return!!ro.has(t)&&(ro.delete(t),!0)}const lo=new WeakSet;function co(t){lo.add(t)}function uo(t){return!!lo.has(t)&&(lo.delete(t),!0)}let ho=0;function fo(){ho--}function po(){return ho>0}class mo{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const go=new WeakMap;function yo(t){let e=go.get(t);return void 0===e&&(e=new mo(t),go.set(t,e)),e}function bo(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==u&&s!==h&&st(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&st(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function wo(t){return t.propModifiers.some(t=>t.includes("="))}const _o=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),vo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function No(t,e){return"state"===t&&"call"===e?_o:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function So(t){if(!o.enableDirectionalInitialSync)return wo(t)&&st("init=/sync= modifiers require enableDirectionalInitialSync."),_o;const e=null===(n=bo(t,u))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:st(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":st(`Invalid sync modifier value "${t}".`)}(bo(t,h));if("event"===t.bindingType)return null!==e&&"none"!==e&&st("Event bindings only allow init=none."),"call"===s?vo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===y)return No("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&st(`Binding type "${t.bindingType}" does not support init=${e}.`),No(e??"state",s);const r=Z(t.node);if(null===r)return No(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||st(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||st(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||st(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let Io=0,$o=0;const xo=new WeakMap,Po=new WeakMap,ko=new WeakMap,Co=new WeakMap;function Eo(t,e){const n=Co.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Co.set(t,new Set([n,e]))):Co.set(t,e)}function Ao(t){return Co.has(t)}function To(t,e){const n=Co.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Mo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Mo(n,e)}function Lo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class Oo{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(const o of t)e.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));const o=[];for(const t of e)ao(t)||Mo(t,t=>{To(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)uo(t)&&!po()||Mo(t,t=>{To(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&Mr(o)}}const Ro=new WeakMap;function jo(t){let e=Ro.get(t);return void 0===e&&(e=new Oo(t),Ro.set(t,e)),e}function Do(t){const e=t.inFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|"),n=t.outFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function Bo(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class Wo{records=new Set;rowPlan=null;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=xo.get(t);void 0===o||"disposed"===o.phase||"failed"===o.phase?(this.start(t,s,n),r.push(t)):(this.observe(o.anchor),s.registerAddress&&null===o.address&&null===o.patternListIndex&&(o.options.registerAddress=!0,this.registerAddress(o)),"active"===o.phase&&this.settleInitialRecord(o),this.settleConnectedSnapshot(o))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(Lo(e)&&jo(e),null===this.rowPlan)for(const n of t){const t=xo.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return wo(t)&&So(t),!0;const e=xo.get(t);return void 0===e||e.session!==this||!e.options.registerAddress||"waiting-definition"===e.phase||"failed"!==e.phase&&("active"===e.phase&&this.settleInitialRecord(e),e.initialApplyDone?"state"===e.resolvedAuthority||!e.outputOnlyMember&&!e.observationPending:(e.initialApplyDone=!0,"state"===e.resolvedAuthority))}getRecord(t){const e=xo.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=xo.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(Bo(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=X(t);null===s&&st(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Eo(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=yo(s).wait(e,()=>{if(a())try{Y(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=xo.get(t);void 0!==e&&e.session===this&&this.disposeRecord(e)}dispose(){for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.records)null!==t.address&&(Ze(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];for(const e of this.records){if("active"!==e.phase)continue;const n=e.info;if(null===e.address&&null===e.patternListIndex)continue;const o="for"===n.bindingType?Je(n):null;if(null!==e.address?(Ze(e.address,n),e.address=null):(en(e.patternPathInfo,e.patternListIndex,n),e.patternPathInfo=null,e.patternListIndex=null),dn(n),Qe(n),this.registerAddress(e),null!==o){const t=Je(n);t!==o&&Se(o)&&Ne(t,ve(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return Lo(e)?e:null}(t);null!==e&&jo(e)}handleMutations(t,e,n){for(const n of e)Mo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Mo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&Mr(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=xo.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=ko.get(e);void 0===t&&(t=Do(e),ko.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Eo(n,this);const o=this.knownMapFor(n);let s=ko.get(t);void 0===s&&(s=Do(t),ko.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n={registerAddress:!1,registerPathInfo:!1,applyOnReconnect:!1},o=t.slots;for(let s=0;s<e.length;s++){const r=e[s],i=o[s],a=r.replaceNode;Eo(a,this),this.addKnownRowBinding(a,r,s),this.optionsByBinding.set(r,n);const l={id:++Io,info:r,generation:++$o,phase:"active",teardowns:null,session:this,anchor:a,options:n,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:i.policy,resolvedAuthority:i.authority,initialSettled:!0,initialApplyDone:!1,outputOnlyMember:i.policy.outputOnly,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};if(xo.set(r,l),this.records.add(l),i.isEvent){try{Cn(r)}catch(t){throw l.phase="failed",this.runTeardowns(l),this.records.delete(l),t}l.eventAttached=!0}}}activatePlanRows(t,e,n){const o=t.slots;for(let s=0;s<e.length;s++){const r=e[s],i=xo.get(r);if(void 0!==i&&i.session===this){if(i.options.registerAddress=!0,"disposed"===i.phase||"failed"===i.phase){const e=o[s];if(i.generation=++$o,i.phase="active",i.initialPolicy=e.policy,i.resolvedAuthority=e.authority,i.initialSettled=!0,i.initialApplyDone=!1,i.outputOnlyMember=e.policy.outputOnly,this.records.add(i),e.isEvent){try{Cn(r)}catch(t){throw i.phase="failed",this.runTeardowns(i),this.records.delete(i),t}i.eventAttached=!0}this.registerAddress(i,n);continue}null===i.address&&null===i.patternListIndex&&this.registerAddress(i,n)}else this.initialize([r],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++Io,info:t,generation:++$o,phase:"discovered",teardowns:null,session:this,anchor:t.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};xo.set(t,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;Cn(e)?t.eventAttached=!0:e.propSegments[0]!==g?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=Mn(t),s=Tn(t,o);let r=En.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const t of n)s=t.filterFn(s);const r=Pi(o.getRootNode());null===r&&st("No state tree found on this root for two-way binding.");const i=ye(o);r.createState("writable",t=>{t[Ie](i,()=>{t[e]=s})})},En.set(s,r)),t.node.addEventListener(o,r),An.add(s,t),!0}var e,n;return!1}(e)&&Bo(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=Mn(t),n=Tn(t,e),o=En.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==An.countOf(n)&&(An.remove(n,t)&&En.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=mn(t),s=pn(t,o);let r=hn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const t of n)r=t.filterFn(r);const i=Pi(o.getRootNode());null===i&&st("No state tree found on this root for two-way binding.");const a=ye(o);i.createState("writable",t=>{t[Ie](a,()=>{let n=t[e];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(t[e]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(t[e]=n.toSpliced(o,1))}else t[e]=s?[r]:[]})})},hn.set(s,r)),t.node.addEventListener(o,r),fn.add(s,t),!0}var e,n;return!1}(e)&&Bo(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=mn(t),n=pn(t,e),o=hn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==fn.countOf(n)&&(fn.remove(n,t)&&hn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Rn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const n=function(t,e,n){let o=Zn.get(t);void 0===o&&(o=new Map,Zn.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&Zn.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});Bo(t,n)}!function(t){const e=J(t.node);if(null!==e){const n=X(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&st(`CustomElementRegistry is unavailable for <${e}>.`))}if(Rn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=no(t),n=oo(t),s=so(t),r=eo(t,e,null!==n,s);let i=Xn.get(r);void 0===i&&(i=((t,e,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const t of n)c=t.filterFn(c);const d=Zn.get(a)?.get(t);if(void 0!==d)for(const t of d)t(c);let u=null;if(o.enablePropagationContext){const n=zn(a,t,e),s=function(t,e){for(let n=Jn.length-1;n>=0;n--){const o=Jn[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==we&&we({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Fn(n,"to-state"),node:a,member:t}));const r=Fn(n,"to-state"),i=Kn();if(null!==i&&i.visitedEdges.has(r))return void(null!==we&&we({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));u=qn(i??Un(n),r)}const h=Pi(a.getRootNode());null===h&&st("No state tree found on this root for two-way binding.");const f=ye(a),p=()=>{r&&(Qn=!0);try{h.createState("writable",t=>{t[Ie](f,()=>{t[e]=c})})}finally{r&&(Qn=!1)}};null!==u?Vn(u,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),Xn.set(r,i)),t.node.addEventListener(e,i),Yn.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==g)return!1;const e=t.node,n=J(e),o=X(e);if(null!==n&&void 0===o?.get(n))return null===o&&st(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Sn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||st('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===J(t)?null:Z(t)}(e);null===r&&st(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&st(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${ht(s,r.knownProperties.keys())}`);const a=i.event,d=t.statePathName,u=t.propModifiers,h=t=>{u.includes(l)&&t.preventDefault(),u.includes(c)&&t.stopPropagation();const n=Pi(e.getRootNode());null===n&&st("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(d)||st(`[wcs/token-undeclared] eventToken "${d}" is not declared in $eventTokens.${ht(d,n.eventTokenNames)}${ft}`);const o=ye(e);n.createStateAsync("writable",async e=>{yn(e[Ie](o,()=>{const s=null!==o?Ue(o.listIndex,o.pathInfo.wildcardCount):[];return vn(n,d).emit(e,t,...s)}),`$on."${d}"`)})};return e.addEventListener(a,h),Sn.set(t,{eventName:a,handler:h}),!0})(e)&&Bo(t,()=>function(t){if(t.propSegments[0]!==g)return!1;const e=Sn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),Sn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=J(t.info.node);if(null===n)return void e();const o=X(t.info.node);if(null===o&&st(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=yo(o).wait(n,()=>{if(this.isAlive(t,s))try{Y(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});Bo(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=So(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=Pi(t.replaceNode.getRootNode());null===e&&st("No state tree found on this root for binding.");const n=cn(t);let o=!1;return e.createState("readonly",t=>{o=t[xe](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void ho++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,fo()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=Pi(t.node.getRootNode());null===o&&st("No state tree found on this root for initial binding sync.");const s=ye(t.node);o.createState("writable",e=>{e[Ie](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=Ge(n);if(null!==o){const s=Pi(Ve(n,e));null===s&&st("No state tree found on this root for binding.");const r=Te(s,n.statePathInfo);!function(t,e,n){let o=tn.get(t);void 0===o&&(o=new WeakMap,tn.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==we&&we({type:"state:binding-added",absoluteAddress:je(t,e),binding:n})}(r,o,n),t.patternPathInfo=r,t.patternListIndex=o}else{const o=Je(n,e);Ye(o,n),t.address=o}if(!t.options.registerPathInfo)return;const s=Pi(n.replaceNode.getRootNode());null===s&&st("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&xo.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,fo());const e=t.info;if(null!==t.address)try{Ze(t.address,e),t.address=null,dn(e),Qe(e)}catch{}else if(null!==t.patternListIndex)try{en(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,dn(e),Qe(e)}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=J(t.node);if(null!==e){const n=X(t.node),o=n?.get(e);if(void 0===o)return}if(Rn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=no(t),n=eo(t,e,null!==oo(t),so(t)),o=Xn.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),Yn.remove(n,t)&&Xn.delete(n)}}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{!function(t){if(!t.propName.startsWith(m))return!1;const e=kn(t),n=xn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==Pn.countOf(e)&&Pn.remove(e,t)&&xn.delete(e)}(e)}catch{}}}}function zo(t){let e=Po.get(t);return void 0===e&&(e=new Wo(t),Po.set(t,e)),e}function Fo(t){return xo.get(t)?.session??null}const Ho=new WeakMap;function Uo(t,e){let n=Ho.get(t);n||(n=new Set,Ho.set(t,n)),n.add(e)}const qo=new WeakMap;function Go(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const Ko=Object.freeze([]),Vo=new WeakMap,Jo=new WeakMap;function Qo(t){return Jo.get(t)??[]}function Xo(t,e){Jo.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let Yo=0;function Zo(){return`u${(Yo++).toString(36)}`}let ts=0;class es{uuid=Zo();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(t,e){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._index=e,this._version=ts}get index(){return this._index}set index(t){this._index=t,this._version=++ts,this.indexes[this.position]=t}get version(){return this._version}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=ts),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0===this._listIndexes&&(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)]),this._listIndexes}get varName(){return`$${this.position+1}`}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function ns(t,e){return new es(t,e)}const os=new WeakMap;function ss(t){return os.get(t)||null}function rs(t,e){null!==e?os.set(t,e):os.delete(t)}const is=new WeakMap,as=Object.freeze([]),ls=new Set;function cs(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:as,s=Array.isArray(n)&&n.length>0?n:as,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:as,o=Array.isArray(e)&&e.length>0?e:as;let s=is.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=ss(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:ls,deleteIndexSet:new Set(i),addIndexSet:ls};let e=ss(s);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=ns(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:ls,deleteIndexSet:ls,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return a={oldIndexes:i,newIndexes:i,changeIndexSet:ls,deleteIndexSet:ls,addIndexSet:ls};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,l=new Set;for(let o=0;o<s.length;o++){const a=s[o],c=n.get(a),d=c&&c.length>0?c.shift():void 0;if(void 0===d){const n=ns(t,o);e.push(n),l.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(function(t,e,n){let o=is.get(t);o||(o=new WeakMap,is.set(t,o)),o.set(e,n)}(o,s,a),rs(s,a.newIndexes))}}(t,e,n);return function(t){for(let e=0;e<t.length;e++)t[e].index!==e&&(t[e].index=e)}(o.newIndexes),o}const ds=new WeakMap;function us(t){return ds.get(t)??[]}function hs(t,e){ds.set(t,e)}const fs=new WeakMap;function ps(t){return fs.get(t)??null}function ms(t,e){fs.set(t,e)}const gs=new WeakMap;function ys(t){return gs.get(t)??[]}function bs(t,e){gs.set(t,e)}function ws(t,e){const n=ys(t);for(const t of n)be(t,e)}function _s(t,e,n){ws(t,e);const o=us(t),s=ps(t);null!==s&&s.activate(o,n.rootNode);for(const t of o)null===s&&Ye(Je(t),t),(null===s||s.shouldApplyState(t))&&Ar(t,n)}function vs(t){if(!t.mounted)return;const e=us(t),n=ps(t);for(const t of e)null!==n?n.disposeBinding(t):Ze(Je(t),t);!function(t){const e=ys(t);for(const t of e)be(t,null)}(t)}const Ns=new WeakMap,Ss=Object.freeze(new Set);function Is(t,e){const n=Ns.get(t);n?n.add(e):Ns.set(t,new Set([e]))}function $s(t){const e=Ns.get(t);return void 0!==e?e:Ss}function xs(t,e){const n=Ns.get(t);n&&(n.delete(e),0===n.size&&Ns.delete(t))}const Ps=new Set(["if","elseif","else","for"]);class ks{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e,this._childNodeArray=Array.from(this._content.childNodes),this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(t){for(const e of this._childNodeArray)co(e),t.appendChild(e);this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){co(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=ps(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)io(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=us(this);for(const t of e)if(Ps.has(t.bindingType)){const e=$s(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){ps(this)?.dispose();for(const t of this._childNodeArray)io(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=us(this);for(const e of t){if(Ps.has(e.bindingType)){const t=$s(e.node);for(const e of t)e.unmount()}dn(e),Qe(e)}this._mounted=!1}}function Cs(t){const e=document.createDocumentFragment(),n=new ks(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function Es(t){void 0!==t.uuid&&null!==t.uuid||st("BindingInfo.uuid is null.");const n=Bt(t.uuid);n||st(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=lt(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===y||s===g)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==J(r))return null;if("prop"===o&&Rn(r,t.propName))return null;let i;try{i=So({...t,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;n.push({nodeIndex:e,template:t,isEvent:"event"===o,isIndexBinding:t.statePathName in N,policy:i,authority:i.authority})}}return{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=lt(o,s[t].nodePath);null===e&&st(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Vt(e),H(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e){const n=new Wo;return n.initializeRow(t,e),n}(n,a),d=new ks(o);return ms(d,c),hs(d,a),Xo(d,l),bs(d,r),Is(t.node,d),d}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=lt(t,s.nodePath);if(null===e&&st(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),qt.has(e))continue;const r=Gt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new Wo;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new ks(i,s);ms(l,a.bindingSession),hs(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in N&&c.push(t);return Xo(l,c),bs(l,a.nodes),Is(t.node,l),l}const As=Symbol.for("wcstack.transition-runner");function Ts(t){const e=globalThis[As];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}const Ms=new WeakSet,Ls=Symbol.for("wcstack.state.view-transition-naming");function Os(){const t=Ts("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Rs(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||Ms.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[Ls]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(Ms.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const js=new WeakMap,Ds=new WeakMap,Bs=new WeakMap,Ws=new WeakMap;function zs(t,e,n){!function(t,e,n){let o=Ds.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Ds.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Fs(t,e){js.set(t,e)}function Hs(t,e){let n=Bs.get(t.node);void 0===n&&(n=[],Bs.set(t.node,n)),n.length<1e3?n.push(e):xs(t.node,e)}function Us(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function qs(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function Gs(t,n,s){const r=Boolean(s);let i;const a=$s(t.node);i=0===a.size?Es(t):a.values().next().value;const l=e(),c=t.uuid??"",d=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${qs(t)}`),vs(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${qs(t)}`),l){const e=document.createComment(`@@wcs-${d}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);_s(i,ye(t.node),n);const e=Os();null!==e&&Rs(i,"branch",e)}}const Ks=new WeakMap,Vs=new WeakMap,Js=new WeakMap,Qs=new WeakMap;function Xs(t){return Qs.get(t)??[]}const Ys=new Set,Zs={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}};function tr(t,n,s){if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const l=i[0],c=r[l];if(c!==s){null!==c&&"object"==typeof c&&null!==s&&"object"==typeof s&&null!==J(r)&&function(t,e,n){let o=Ks.get(t);o||(o=new Map,Ks.set(t,o)),o.has(e)||o.set(e,n)}(r,l,c);const e=()=>{let t=!1;try{r[l]=s,t=!0}catch(t){o.debug&&console.warn(`Failed to set property '${l}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=J(t);if(null===n)return null;const o=X(t)?.get(n);if(void 0===o)return null;const s=Z(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,l);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&Rn(r,l)){const o=zn(r,l,t.statePathName),i=Fn(o,"to-element"),a=n?.propagationContextByBinding?.get(t)??Kn()??Un(o);if(a.visitedEdges.has(i))null!==we&&we({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:r,member:l});else{const t=qn(a,i);Vn(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Bn++,writtenValue:n};Jn.push({receipt:i,node:t});try{return r()}finally{Jn.pop()}}(r,l,s,o,t.transactionId,e))}}else e()}if(e()){const t=Zs[l];t?t(r,s):(function(t,e,n){let o=Qs.get(t);o||(o=[],Qs.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,l,s),a=r,Ys.add(a))}return}var a;const l=i[0];let c=r[l];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==c)return;c=c[e]}const d=i[i.length-1],u=c[d];if(u!==s){if(Object.isFrozen(c))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:u,newValue:s}));2===i.length&&"object"==typeof c&&null!==c&&null!==J(r)&&(d in c?function(t,e,n,o){let s=Js.get(t);s||(s=new Map,Js.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}(r,l,d,c[d]):function(t,e,n){let o=Vs.get(t);o||(o=new Map,Vs.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)}(r,l,d));try{c[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:u,newValue:s,error:t})}}}const er=new WeakSet;function nr(t,e,n){}const or=new WeakMap;function sr(t,e){if(null===t)return!1;const n=or.get(t);if(void 0===n||0===n.size)return!1;for(const t of n)if(e===t||e.startsWith(t+s)||t.startsWith(e+s))return!0;return!1}const rr=new WeakMap;function ir(t,e){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{e.$postUpdate(t+s+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...r)=>e[n](t+s+o,...r)}return e[o]}return e[t+s+o]}},set:(n,o,r)=>("string"!=typeof o||(e[t+s+o]=r),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const ar=new WeakMap,lr=[],cr=new WeakMap;let dr=null;const ur=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),hr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function fr(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function pr(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),r=e.length>0?e+s:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(s)&&o.push(e)}return o}const mr={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},gr={binding:"Bound path",watch:"$watch path"};function yr(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${ft}`}function br(t,e){return`$setAll("${t}") ${e}`}function wr(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${ft}`}const _r=new WeakMap;const vr=new WeakSet;function Nr(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Sr=Object.freeze({[b]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&st("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[w]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[_]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[y]:function(t,e,n){$n(n)||st("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Vo.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||st('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=J(t);if(null===e)return null;const n=X(t)?.get(e);return void 0===n&&st(`Custom element <${e}> is not defined for command binding.`),Z(t)}(r);null===a&&st(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||st(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ht(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Vo.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void Vo.delete(t);const o=n[i];return"function"!=typeof o&&st(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),Vo.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Ir={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!er.has(t.replaceNode)){er.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,i=Ge(t),a=Je(t),l=ve(a),c=l.length>0&&!Ds.has(t.node)?[]:l,d=cs(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);const u=Array.isArray(c)&&c.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(u&&null!==t.node.parentNode){let e=Ws.get(t.node);if(void 0===e){const n=js.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(n.nodeType===Node.ELEMENT_NODE||n.nodeType===Node.TEXT_NODE&&""!==(n.textContent?.trim()??"")){s=!1;break}n=n.previousSibling}for(;null!==o;){if(o.nodeType===Node.ELEMENT_NODE||o.nodeType===Node.TEXT_NODE&&""!==(o.textContent?.trim()??"")){s=!1;break}o=o.nextSibling}return s}(t.node,n),Ws.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let h=Ds.get(t.node),f=u?1e3-function(t){return Bs.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==h){for(const e of d.deleteIndexSet){const n=h.get(e);void 0!==n&&(f<=0&&n.tryDestroy()?xs(t.node,n):(vs(n),n.unmount(),Hs(t,n),f-=1),u||h.delete(e))}u&&(Ds.delete(t.node),h=void 0)}let p=t.node;const m=G(s.path+"."+r),g=n.stateElement.loopContextStack,y=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const t of i)a.add(n[t]);return a}(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&p.isConnected&&(b=document.createDocumentFragment(),Be(b,n.rootNode));const w=e(),_=Os(),v=t.uuid??"",N=Bs.get(t.node);for(const e of d.newIndexes){let o;if(d.addIndexSet.has(e)){const r=an(m,e);g.createLoopContext(r,r=>{if(o=void 0!==N?N.pop():void 0,void 0===o&&(o=Es(t)),null!==b)w&&b.appendChild(document.createComment(`@@wcs-for-start:${v}:${s.path}:${e.index}`)),o.appendTo(b),w&&b.appendChild(document.createComment(`@@wcs-for-end:${v}:${s.path}:${e.index}`));else{if(p.nextSibling!==o.firstNode){if(w){const t=document.createComment(`@@wcs-for-start:${v}:${s.path}:${e.index}`);p.parentNode.insertBefore(t,p.nextSibling),p=t}o.mountAfter(p)}if(w){const t=document.createComment(`@@wcs-for-end:${v}:${s.path}:${e.index}`),n=o.lastNode??p;n.parentNode.insertBefore(t,n.nextSibling)}}_s(o,r,n),null!==_&&Rs(o,"row",_)}),void 0===o&&st(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=void 0!==h?h.get(e)??null:null,d.changeIndexSet.has(e)){const t=Qo(o);for(const e of t)Ar(e,n)}null===o&&st(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==y&&y.has(e)&&Us(p,o.firstNode)||p.nextSibling===o.firstNode||o.mountAfter(p),t){const t=o,s=an(m,e);g.createLoopContext(s,e=>{_s(t,e,n)})}}p=o.lastNode||p,void 0===h&&(h=new WeakMap,Ds.set(t.node,h)),h.set(e,o)}js.set(t.node,p),null!==b&&(t.node.parentNode.insertBefore(b,t.node.nextSibling),Be(b,null))},if:Gs,else:Gs,elseif:Gs,radio:function(t,e,n){const o=t.node,s=Go(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=Go(o.value,t.inFilters),r=Array.isArray(n)?n:Ko;o.checked=r.includes(s)}},$r=new WeakMap,xr=new WeakMap,Pr=new WeakMap;function kr(){}function Cr(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===Ho.get(t)?.has(e)}(e,n)?nr:function(t,e){return!0===qo.get(t)?.has(e)}(e,n)?kr:tr}function Er(t,e){const n=Go(function(t,e){const n=cn(e);if(n.pathInfo.path in N){const t=ye(e.node);return null===t&&st(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&st("ListIndex not found for loopContext:");const n=N[e];void 0===n&&st(`Invalid index name: ${e}`);const o=He(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&st(wr(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[$e](n)}(e.state,t),t.outFilters);if(!0===xr.get(t))return void e.deferredSelectBindings.push({binding:t,value:n});let o=$r.get(t);if(void 0===o){if($r.has(t))return o=Cr(t),o===nr&&$r.set(t,o),void o(t,e,n);if(o=Ir[t.bindingType],void 0===o){const e=t.propSegments[0];o=Sr[e],$r.set(t,o),void 0===o&&(J(t.replaceNode)?(o=Cr(t),o===nr&&$r.set(t,o)):(o=tr,$r.set(t,o)))}if(o===tr&&"SELECT"===t.node.tagName){const o=t.propSegments[0];if("value"===o||"selectedIndex"===o)return e.deferredSelectBindings.push({binding:t,value:n}),void xr.set(t,!0)}o(t,e,n)}else o(t,e,n)}function Ar(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=Je(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=Fo(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Pr.get(t)){const e=J(t.replaceNode);if(e&&void 0===X(t.replaceNode)?.get(e))return void function(t,e){if(vr.has(t))return;vr.add(t);const n=()=>{vr.delete(t);const e=Fo(t);(null===e||e.shouldApplyState(t))&&Mr([t])},o=n=>{vr.delete(t),Nr(e,n)},s=Fo(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{vr.delete(t),r()})||(vr.delete(t),r()))}const r=X(t.replaceNode);if(null===r)return vr.delete(t),void Nr(e,new Error("CustomElementRegistry is unavailable."));yo(r).wait(e,()=>{t.replaceNode.isConnected?n():vr.delete(t)},o)}(t,e);Pr.set(t,!0)}if(!0===e.sameRootVerified)return void Er(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=We(o),null===o&&st("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Pi(o);null===n&&st("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};Er(t,r)})}else Er(t,e)}function Tr(t,e){console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e}),null!==we&&we({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function Mr(t,e){let n=0;const s=new Set,r=new Map,i=new Map,a=[];for(;n<t.length;){let l=t[n];if(!1===l.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${l.bindingType} ${l.statePathName} on ${l.node.nodeName}`,l),n++;continue}let c=l.replaceNode.getRootNode();c instanceof DocumentFragment&&!(c instanceof ShadowRoot)&&(c=We(c),null===c&&st("Root node for fragment not found for binding."));const d=Pi(c);null===d&&st("No state tree found on this root for binding."),d.createState("readonly",o=>{const u={rootNode:c,stateElement:d,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Ar(l,u)}catch(t){Tr(l,t)}n++;const e=t[n];if(!e)break;if(e.replaceNode.getRootNode()!==u.rootNode)break;l=e}})}for(const{binding:t,value:n}of a)try{tr(t,{propagationContextByBinding:e},n)}catch(e){Tr(t,e)}for(const[t,e]of r.entries())Ne(t,e);for(const[t,e]of i.entries())t.createState("writable",t=>{t[Ee](Array.from(e))})}function Lr(t,e,n){const[o,s,r]=Kt(t,n),i=zo(t);for(const t of o)be(t,e);Mr(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=Jt(o);0!==t.length&&(be(o.node,e),Mr(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const Or=/\{\{\s*(.+?)\s*\}\}/g,Rr=new Set(["SCRIPT","STYLE"]);function jr(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&Rr.has(t.parentElement.tagName)||Dr(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),jr(e.content)}else jr(t.content)}function Dr(t){const e=t.data;if(Or.lastIndex=0,!Or.test(e))return;Or.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Or.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}let Br;function Wr(){if(Br)return Br;const t=[],e=St("not",t)(vt);return Br={filterName:"not",args:t,filterFn:e},Br}const zr=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Fr(t,e){const n=e+s+r,o=t.indexOf("|");let i,a;if(-1!==o?(i=t.slice(0,o).trim(),a=t.slice(o)):(i=t.trim(),a=""),"."===i)i=n;else{if(!i.startsWith("."))return t;i=n+s+i.slice(1)}return a.length>0?i+a:i}function Hr(t,e){const n=zr.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+Fr(s,e)+r}function Ur(t,e){const n=t.split(";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=n.indexOf(":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Fr(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function qr(t,e){return Ur(t,e)}function Gr(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=Hr(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=Ur(r,e);t!==r&&o.setAttribute(n,t)}}}function Kr(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}function Vr(t){const e=[],n=Ut(t);for(const t of n){const n=Wt(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:Kr(o),parseBindTextResults:n})}return e}function Jr(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const Qr=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Xr=Wr();function Yr(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Xr],bindingType:t}}function Zr(t,e,n,o,s,r=!0){Jr(e),"string"==typeof o&&Gr(e,o),ti(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Vr(e)};return void 0!==s&&function(t,e,n){for(const o of t)for(let t=0;t<o.parseBindTextResults.length;t++){const s=o.parseBindTextResults[t];null==s.uuid&&(o.parseBindTextResults[t]=e(s,n))}}(i.nodeInfos,s,o),i}function ti(t,e,n,s){const r=o.commentElsePrefix,i=Ft(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const t=a.currentNode;d.push(t)}for(const e of d){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=qr(i,n));let a=At(i)[0];const d=Qr.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,h=e.content,f=Zo();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&st("'else' binding found without preceding 'if' or 'elseif' binding."),a=Yr("else",l.parseBindTextResult),p=Zr(t,h,a,m,s,!1),Dt(f,t,p);const n=c.at(-1),o=document.createComment(`@@${d}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Kr(o),parseBindTextResults:Wt(o)})):e.replaceWith(o)}else if("elseif"===u){null===l&&st("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Zr(t,h,a,m,s),Dt(f,t,p);const n=document.createComment(`@@${d}:${f}`),o=Zo(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Yr("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Kr(n),parseBindTextResults:Wt(n)}),Dt(o,t,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(e.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:Kr(g),parseBindTextResults:Wt(g)})):e.replaceWith(g)}else{p=Zr(t,h,a,m,s),Dt(f,t,p);const n=document.createComment(`@@${d}:${f}`);e.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}async function ei(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=X(t);null===s&&st(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(zt(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function ni(t){if(t===document)await ei(document),jr(document),ti(document,document),Lr(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await F(e.host),await ei(e),jr(e),ti(e,e),Lr(e,null)}}const oi="2.0.0",si="undefined"==typeof HTMLElement?class{}:HTMLElement,ri=/^@@wcs-(?:for|if|elseif|else):[^-]/,ii=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,ai=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,li=/^@@wcs-text-start:(.+)$/;function ci(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class di extends si{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=oi.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=o.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const[t,o]of Object.entries(e))t.startsWith("$")||"function"==typeof o||(n[t]=o);return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=ci(JSON.stringify(e)),t.appendChild(n);const s=Array.from(jt.keys());for(const e of s){const n=Bt(e);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",e);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),t.appendChild(s)}const r=Array.from(Ys);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=Xs(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const t of o)i[t.propName]=t.value;e[s]=i}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ci(JSON.stringify(e)),t.appendChild(n)}}Ys.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(ii.test(t.data)||ai.test(t.data))&&n.push(t)}for(const t of n)t.remove()}static removeStructuralComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;ri.test(t.data)&&n.push(t)}for(const t of n)t.remove()}static restoreTextBindings(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode,o=li.exec(t.data);o&&n.push({comment:t,path:o[1]})}for(const{comment:t,path:e}of n){const n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}const r=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const t=r.currentNode;ii.test(t.data)&&i.push(t)}for(const t of i){const e=ii.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}di.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(ri.test(t.data)){const e=t.data.split(":")[1];l.push({comment:t,uuid:e})}}for(const{comment:t,uuid:e}of l){const n=s.get(e);if(n){const e=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&e.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)e.content.appendChild(r);else for(const t of Array.from(n.childNodes))e.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(e,t)}}const c=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of c)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const ui=new Set(["for","if","elseif","else"]);function hi(t){const e=new Wo;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i]=Kt(s),a=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:e}}function fi(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const t=i.currentNode;if(t.data===r)return t}return null}function pi(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=At(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,Wr()],bindingType:"else"}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;Jr(a),"string"==typeof l&&Gr(a,l),ti(n,a,l),Dt(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:Vr(a)})}}const mi=Symbol.for("wcstack.binder"),gi=Symbol.for("wcstack.binder.pending"),yi=Symbol.for("wcstack.binder.taken");function bi(t){if(Ao(t))return!0;if(!wi(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Ao(e)}function wi(t){return 1===t.nodeType}function _i(t){if(bi(t))return;jr(t),ti(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Lr(e&&s?n:t,null)}const vi=[];function Ni(){const t=vi.splice(0,vi.length);for(const e of t)_i(e);!function(){const t=function(){const t=globalThis[mi];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[gi];return void 0===e&&(e=[],t[gi]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[yi];return void 0===e&&(e=new WeakSet,t[yi]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const Si={protocol:"wcs-binder",version:1,bind:function(t){var e;wi(t)&&!bi(t)&&(e=t.getRootNode(),Ci.has(e)?_i(t):vi.push(t))}},Ii=new WeakMap,$i=new WeakMap,xi=new Set;function Pi(t){return Ii.get(t)??null}function ki(t){return $i.get(t)??Promise.resolve()}const Ci=new WeakSet;function Ei(t){Ci.add(t)}function Ai(t,n){const s=Ii.get(t);if(null===n){if(void 0===s)return;Ii.delete(t),xi.delete(s),null!==we&&we({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{if(void 0===s){const s=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{s&&await async function(t){await ei(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${oi}". Falling back to full render.`),di.cleanupDom(t),!1}for(const n of e)pi(t,n);const n=function(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const t of o){const n=ii.exec(t.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let d=t.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body);!function(t,e){const n=new Map;for(const o of e){if(0===o.nodes.length)continue;const e=Cs(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=hi(o.nodes);ms(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");hs(e,s),bs(e,i);const l=[];for(const t of s)t.statePathName in N&&l.push(t);if(Xo(e,l),"for"===o.type&&null!==o.index){const i=fi(t,"for",o.uuid);if(i){const t=ns(null,o.index);zs(i,t,e),Fs(i,o.nodes[o.nodes.length-1]),Is(i,e),ws(e,an(G(o.path+"."+r),t)),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let l=n.get(o.uuid);l||(l=[],n.set(o.uuid,l)),l.push(t)}}else{const n=fi(t,o.type,o.uuid);n&&(Is(n,e),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=fi(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Bt(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Pi(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&rs(e,o)})}}(document.body,n),di.removeBlockBoundaryComments(document.body);const s=[];for(const t of e)t.parentNode&&(s.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());di.restoreTextBindings(document.body);const[i,a]=Kt(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(be(t,null),e.setAttribute("data-wcs-completed",""))}else be(t,null);const l=[],c=[],d=zo(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(ui.has(t.bindingType))c.push(t);else{if(t.statePathName.includes(r))continue;l.push(t)}for(const t of c)if("for"===t.bindingType){const e=Je(t),n=Pi(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&Ne(e,o)})}Mr(l);for(const{el:t,parent:e,next:n}of s)e.insertBefore(t,n);const u=t.querySelectorAll(o.tagNames.ssr);for(const e of u){const n=e.hydrateProps;for(const[e,o]of Object.entries(n)){const n=t.querySelector(`[data-wcs-ssr-id="${e}"]`);if(n)for(const[t,e]of Object.entries(o))n[t]=e}}const h=t.querySelectorAll("[data-wcs-completed]");for(const t of h)t.removeAttribute("data-wcs-completed");return!0}(t)||await ni(t),Ei(t),Ni(),e()}catch(t){n(t)}})});$i.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await ni(t),Ei(t),Ni(),e()}catch(t){n(t)}})});$i.set(t,e)}}void 0!==s&&st('A state tree is already registered on this root — one <wcs-state> per root in v2. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Ii.set(t,n),xi.add(n),function(t,e){const n=cr.get(t);if(void 0===n||0===n.length||null===dr)return;cr.delete(t);const o=dr;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,n),null!==we&&we({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}let Ti=0,Mi=0;const Li=[];function Oi(t,e=0){const n=Li.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Li.push(o):Li.splice(n,0,o)}function Ri(t){queueMicrotask(()=>{throw t})}const ji=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){Ti>Mi&&(Mi=Ti);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&queueMicrotask(()=>{const t=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(t)})}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t){const n=new Map;for(const e of t){const t=n.get(e.absoluteAddress);null!==we&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&we({type:"propagation:coalesced",absoluteAddress:e.absoluteAddress,droppedTransactionId:t.transactionId,winnerTransactionId:e.context.transactionId}),n.set(e.absoluteAddress,e.context)}const o=[],s=new Map;for(const[t,e]of n){if(null!==e&&e.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),null!==we&&we({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=nn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(o.push(t),null!==e&&s.set(t,e));else!1!==n.replaceNode.isConnected&&(o.push(n),null!==e&&s.set(n,e))}try{const t=()=>{s.size>0?Mr(o,s):Mr(o)};if(e()||0===o.length)t();else{const e=function(t,e){const n=Ts(t);if(null!==n)return n.run(e,{source:t,types:void 0});e()}("state",t);void 0!==e&&e.catch(Ri)}}finally{!function(t){for(const e of Li.slice())e.listener(t)}(new Set(n.keys()))}}};function Di(){return ji}const Bi=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Wi(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const zi="__WCSTACK_DEVTOOLS_HOOK__";const Fi=t=>{null!==we&&we({type:"state:update-batch",addresses:t})};function Hi(t){const e=null!==we;!function(t){we=t}(t);const n=null!==t;n&&!e?Oi(Fi,0):!n&&e&&function(t){const e=Li.findIndex(e=>e.listener===t);-1!==e&&Li.splice(e,1)}(Fi)}function Ui(t){return{rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function qi(t){return Pi(t)??st("devtools: no state tree on this root")}let Gi=null;function Ki(){if(e())return;if(null!==Gi)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:oi,getStateElements(){const t=[];for(const e of xi)t.push(Ui(e));return t},overlays:t=>function(t){const e=he.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}(qi(t)).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join("."),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys]})),keys(t){const e=qi(t),n=[];return e.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}n.push(e)}}),n},read(t,e,n){let o;return qi(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){qi(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=[...t.inFilters,...t.outFilters].map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=Bt(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Wi(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=at(e,At(n));for(const o of t)r(Wi(e,o,"attribute",n))}catch{}continue}const e=Bi.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=Bt(s);if(null===a){if(n===o.commentTextPrefix)try{r(Wi(t,Rt(s),"comment",s))}catch{}}else r(Wi(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:Hi};Gi=t,function(){const t=globalThis,e=t[zi];if(void 0!==e)return 2!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 2. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:2,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[zi]=n,n}().register(t)}const Vi={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of s){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",oi),di.buildContent(o,di.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}},Ji="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Qi=0;async function Xi(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++Qi}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${Ji}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${Ji}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Yi(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){st(`Failed to load script file: ${t}`)}}class Zi{_loopContextStack=Array(i).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&st("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=i&&st("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&st("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&st("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&st(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const ta=new WeakMap;function ea(t,e){let n=ta.get(t);void 0===n&&(n=new Map,ta.set(t,n));let o=n.get(e);return void 0===o&&(o=new In(e),n.set(e,o)),o}const na=new WeakMap;function oa(t){const e=na.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return ea(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:ea(t,n)}},set(){st("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){st("$command namespace is read-only; deleting from it is not allowed.")}});return na.set(t,n),n}const sa=Symbol("wcs-stream-last-notified-uncertain"),ra=new WeakMap;function ia(t,e){const n=ra.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function aa(t,e){const n=ra.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:sa,error:Object.is(o.error,null)?null:sa})}const la=new Set;function ca(t){la.delete(t)}const da=new WeakMap;function ua(t){return da.get(t)??new Map}function ha(t){ca(t);const e=da.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,aa(t,n.name)}const fa=(t,e)=>e,pa=new Set;const ma=new WeakMap,ga=new WeakMap;function ya(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=ua(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&ua(t).has(n),ownKeys:()=>Array.from(ua(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=ua(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){st(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){st(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function ba(t){const e=ma.get(t);if(void 0!==e)return e;const n=ya(t,R,t=>t.status);return ma.set(t,n),n}function wa(t){const e=ga.get(t);if(void 0!==e)return e;const n=ya(t,j,t=>t.error);return ga.set(t,n),n}function _a(t){ma.delete(t),ga.delete(t)}let va=null;function Na(t){const e=ua(t);if(0!==e.size){!function(t){la.add(t)}(t);for(const n of e.values())Sa(t,n)}}function Sa(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=va,r=new Set;let i;va=r;try{t.createState("readonly",t=>{i=n(t)})}finally{va=o}i instanceof Promise&&st(`${M} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${R}${s}${e.name}`,l=`${j}${s}${e.name}`;for(const n of r){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==a&&o.path!==l||st(`${M} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&st(`${M} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=r,i}(t,e);t.createState("writable",t=>{t[e.name]=e.definition.initial}),Ia(t,e,"active",null);const r=e.definition,i={fold(n){t.createState("writable",t=>{t[e.name]=r.fold(t[e.name],n)})},done(){Ia(t,e,"done",null)},fail(o){Ia(t,e,"error",o),n.abort()}};!async function(t,e,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",i)}}(r.source,o,n.signal,i)}function Ia(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return ra.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),i=r.status!==n,a=!Object.is(r.error,o);(i||a)&&(function(t,e,n,o){let s=ra.get(t);void 0===s&&(s=new Map,ra.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${R}${s}${e.name}`),a&&t.$postUpdate(`${j}${s}${e.name}`)}))}Oi(function(t){const e=la;if(0===e.size)return;const n=[];for(const o of e)for(const e of ua(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&ua(t).get(o.name)===o)try{Sa(t,o)}catch(n){o.controller?.abort(),e.has(t)&&ua(t).get(o.name)===o&&Ia(t,o,"error",n)}},20);const $a=new WeakMap,xa=new WeakMap,Pa=new Set,ka=new Map;function Ca(t){return $a.get(t)??ka}const Ea=new Map;function Aa(t){return xa.get(t)??Ea}function Ta(t){0===t.length&&st(`[wcs/watch-declaration-invalid] ${L} entry name must be a non-empty state path.`),t.startsWith("$")&&st(`[wcs/watch-declaration-invalid] ${L} entry "${t}" must not start with "$" (reserved namespace).${ft}`),t.includes("@")&&st(`[wcs/watch-declaration-invalid] ${L} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ft}`),t in Object.prototype&&st(`[wcs/watch-declaration-invalid] ${L} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=G(t);for(const n of e.segments)0===n.length&&st(`[wcs/watch-declaration-invalid] ${L} entry "${t}" has an empty path segment.${ft}`);return e.wildcardCount>128&&st(`[wcs/watch-declaration-invalid] ${L} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const Ma=new WeakMap;function La(t,e,n){let o=Ma.get(t);void 0===o&&(o=new Map,Ma.set(t,o)),o.set(e,n)}const Oa=new Map;function Ra(t){0===Ca(t).size&&0===Aa(t).size||(function(t){Pa.add(t)}(t),function(t){const e=[];for(const n of Ca(t).values())Da(t,n)&&e.push(n);for(const n of Aa(t).values())for(const o of n)Da(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{La(t,ja(t,o),n[o.path])}catch(e){Wa(t,o.path,"prime",e)}})}(t))}function ja(t,e){return je(Te(t,e.pathInfo),null)}function Da(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Ba={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Wa(t,e,n,o){console.error(`[@wcstack/state] $watch ${Ba[n]} "${e}" threw.`,o),null!==we&&we({type:"state:watch-error",phase:n,path:e,error:o})}function za(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function Fa(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Da(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void Wa(0,n.path,"evaluate",t)}const a=r?function(t,e){return Ma.get(t)?.get(e)}(e,o):function(t){return Oa.get(t)}(o);r&&La(e,o,i),null!==we&&we({type:"state:watch-fired",path:n.path}),n.handler.call(t,i,a,...s)})}catch(t){Wa(0,n.path,"handler",t)}}function Ha(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function Ua(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function qa(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function Ga(t){return t.startsWith("$")}function Ka(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}function Va(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function Ja(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||st(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||st(`${e} entries must be non-empty strings.`),t.startsWith("$")&&st(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&st(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}Oi(function(t){const e=Pa;try{if(0===e.size)return;const n=function(){const t=Mi;return Mi=0,t}();if(n>32){const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==we&&we({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=Ca(t).get(s),i=Aa(t).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const e of a){let s=[];if(e.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=Ue(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(za),function(t){Ti=t+1}(n);try{for(const t of o){if(!e.has(t.stateElement))continue;const n=Ca(t.stateElement).get(t.entry.path)===t.entry,o=!0===Aa(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&Fa(t)}}finally{Ti=0}}finally{Oa.clear()}},10);const Qa=new Map;class Xa{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=G(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Ya(t){let e;return Qa.get(t)??(Qa.set(t,e=new Xa(t)),e)}function Za(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:He(n.listIndex,o,n.pathInfo.wildcardCount)}const tl=new WeakMap;function el(t,e){null===e?tl.delete(t):tl.set(t,e)}function nl(t){const e=tl.get(t);e&&(e.dirty=!0)}function ol(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=Fe(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?He(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?He(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}const sl=new WeakMap;class rl{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,s,r){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return an(G(this.markerParentPath+s+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(le(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,s,...r)=>{const i=le(t,e),a=ce(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a=le(t,e),l=ce(0,e,a,r,n);return o[s](a,l,...i)}}return this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return ol(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[le(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||st(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(t,e)?(t[e]=n,!0):(this.receiver[le(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return le(this.record,e),!0}catch{return!1}}}function il(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function al(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}function ll(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===E)return al(oa(s),e.pathInfo.segments);if(i===R)return al(ba(s),e.pathInfo.segments);if(i===j)return al(wa(s),e.pathInfo.segments);if(!0===s.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const t=me(s,e.pathInfo.path);if(null!==t)return function(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=sl.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},sl.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(i,new rl(t,s,e.listIndex,r,n,o))}(t,e,n,o)}if(!(e.pathInfo.path in t)){if(null===e.parentAddress&&sr(function(t){return t.rootNode??null}(s),e.pathInfo.path))return;const i=e.parentAddress??st(function(t,e,n){return`[${mr.binding}] Path "${t}" does not exist on the state tree.${ht(t,pr(e,"",n))}${ft}`}(e.pathInfo.path,t,s.getterPaths)),a=cl(t,i,n,o);if(null==a)return;const l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??st(wr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(a,t)}return Reflect.get(a,l)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}function cl(t,e,n,o){ol(o,e),function(t,e){if(null===va)return;const n=Te(t,e.pathInfo);va.add(je(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return il(s,e)?function(t,e,n,o,s){const r=je(Te(s,e.pathInfo),e.listIndex),i=function(t){return tl.get(t)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=ll(t,e,n,o,s);return el(r,{value:a,dirty:!1}),a}(t,e,n,o,s):ll(t,e,n,o,s)}const dl=new WeakMap;function ul(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const h=o[s]??null;if(null===h)return void u.push(d);const f=an(h,r),p=dl.get(f),m=cl(t,f,e,n),g=cs(r,p,m).newIndexes,y=l[c]??null;if(i.set(f,m),null===y)for(let t=0;t<g.length;t++){const e=g[t];a(o,s+1,e,l,c+1,d.concat(e.index),u)}else{const t=g[y]??st(`ListIndex not found at index ${y} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,d.concat(t.index),u):u.push(d.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())dl.set(t,e);return l}function hl(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=ss(cl(t,an(a,r),e,n));null==l&&st(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??st(`ListIndex not found at index ${c} of ${a.path}`)}return r}function fl(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}function pl(t,e,n,o){"object"==typeof t&&null!==t||st(`${O} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&st(`${O} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function ml(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&st(`${O} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function gl(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];pl(a,n,o,i);const l=ml(a,e,n,o,i);r.has(l)&&st(`${O} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function yl(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function bl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=cl(t,s,n,o);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=e.pathInfo.lastSegment;if(a===r){const t=e.listIndex?.index;return"number"==typeof t&&t in i}return a in i}const wl=new WeakMap;function _l(t,e){null===e?wl.delete(t):wl.set(t,e)}function vl(t,e,n){const s=G(t.wildcardParentPaths[e]),r=Te(t.stateElement,s),i=an(s,n),a=ve(je(r,n)),l=t.stateProxy[$e](i),c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(cs(i.listIndex,a,l),t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)vl(t,e+1,n)}const Nl=[];function Sl(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:Nl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Nl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Il=[];function $l(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Il;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=G(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??Il}function xl(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=G(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[$e](e),a=ve(je(Te(t.stateElement,e.pathInfo),e.listIndex)),l=Sl(t,o,0,0,cs(e.listIndex,a,r));for(const e of l.fullRows){const o=an(s,e);t.result.add(o),n.push(o)}if(null!==l.movedRows){const e=$l(t,i,s);if(null===e)for(const e of l.movedRows){const o=an(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of l.movedRows)for(const s of e){const e=an(s,o);t.result.add(e),n.push(e)}}}else{const o=an(s,e.listIndex);t.result.add(o),n.push(o)}}const i=t.dynamicMap.get(o);if(i)for(const o of i){const s=G(o),r=[];if(s.wildcardCount>0){const n=Fe(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&st(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=He(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};vl(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&st(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=He(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=an(s,e);t.result.add(o),n.push(o)}}}function Pl(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const d=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&st(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),u={ranks:d,stateElement:t,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};return function(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,xl(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(u,e,a),Array.from(u.result)}function kl(t,e,n,o,s){const r=t.watchPaths;null!=r&&s&&r.has(e)&&function(t,e){Oa.has(t)||Oa.set(t,e)}(n,o)}function Cl(t,e,n,s,r){const i=o.enablePropagationContext?Kn()??Un(-1):null,a=Di();a.enqueueAbsoluteAddress(e,i),Pl(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=je(Te(s.stateElement,e.pathInfo),e.listIndex);nl(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function El(t,e,n,o,s,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const a=cl(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??st(wr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(a,t,o)}return Reflect.set(a,l,o)}if(!i.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);i.pushAddress(e),i.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}finally{Cl(e,n,s,i,a)}}function Al(t,e,n,o,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(n)){const l=a.get(e.pathInfo.path);if(void 0!==l){const a=cl(t,e,o,i),c=function(t,e,n,o){const s=gl(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=gl(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,l,a,n);if(null!==c)return function(t,e,n,o,i,a){const l=e.pathInfo.path,c=e.listIndex;null===ss(o)&&cs(c,null,o);const d=cs(c,o,n.list),u=Tl(t,e,n.list,i,a,l),h=G(l+s+r);for(const e of n.matched){const n=yl(e.oldRow,e.newRow);if(0===n.length)continue;const o=d.newIndexes[e.position];for(const r of n)void 0!==o?Al(t,an(G(h.path+s+r.field),o),r.value,i,a):e.oldRow[r.field]=r.value}return u}(t,e,c,a,o,i)}}return Tl(t,e,n,o,i,null)}function Tl(t,e,n,i,a,l){const c=a.stateElement,d=e.pathInfo.path;if(!0===c.hasGraftedVolumes){const t=function(t,e){const n=rr.get(t);if(void 0===n||0===n.size)return null;const o=e+s;for(const t of n)if(t.startsWith(o))return t;return null}(c,d);null!==t&&st(`Cannot replace "${d}" wholesale: a volume is mounted at "${t}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${t}" itself, or individual fields inside "${d}", instead.`)}const u=!!Qn&&(Qn=!1,!0);if(!(d in t)&&null!==e.parentAddress&&!c.elementPaths.has(d)){const s=cl(t,e.parentAddress,i,a);if("object"==typeof s&&null!==s){const t=e.pathInfo.lastSegment,h=t===r?e.listIndex?.index:t;let f,p=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==h&&h in s,e=void 0!==h?s[h]:void 0;if(t&&Object.is(e,n))return!0;f=e,p=!0}const m=il(c,e),g=je(Te(c,e.pathInfo),e.listIndex);null!==we&&we({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:p}),kl(c,d,g,f,p);try{return void 0===h&&st(wr(`path "${d}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),Reflect.set(s,h,n)}finally{Cl(e,g,i,a,l),m&&el(g,{value:n,dirty:!1}),fl(c,e.pathInfo,{value:n})}}}let h,f=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=cl(t,e,i,a);if(bl(t,e,i,a)&&Object.is(o,n))return!0;h=o,f=!0}const p=c.elementPaths.has(e.pathInfo.path),m=il(c,e),g=je(Te(c,e.pathInfo),e.listIndex);null!==we&&we({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:f}),kl(c,d,g,h,f);try{return p?function(t,e,n,o,s,r,i){let a=e.parentAddress??st(`address.parentAddress is undefined path: ${e.pathInfo.path}`),l=function(t){return wl.get(t)??null}(a);if(null===l){const e=cl(t,a,s,r)??[],n=ss(e)??[];l={value:[...e],listIndexes:[...n]},_l(a,l)}try{return El(t,e,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=cl(t,a,s,r)??[],c=Array.isArray(i)?ss(i)??[]:[],d=e.listIndex.index,u=-1!==n?l.listIndexes[n]:ns(a.listIndex,-1);if(c[d]=u,new Set(i).size===l.value.length){for(let t=0;t<c.length;t++)c[t].index=t;_l(a,null)}}}(t,e,g,n,i,a,l):El(t,e,g,n,i,a,l)}finally{m&&el(g,{value:n,dirty:!1}),fl(c,e.pathInfo,{value:n})}}function Ml(t,e,n,o){return(e,s,r)=>{const i=G(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&st(yr("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=an(i,hl(t,n,o,i,s));if(void 0===r)return cl(t,a,n,o);Al(t,a,r,n,o)}}function Ll(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Za(o,s.wildcardPaths.at(-1)??st(`lastWildcardPath is null: ${e.pathInfo.path}`))??st(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??st(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=ss(cl(t,an(i,s),n,o))??st(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??st(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??st(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":st(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}const Ol=`${R}${s}`,Rl=`${j}${s}`,jl=new WeakMap;function Dl(t,e,n,o){const r=N[e];if(void 0!==r){0===o.addressStackLength&&st(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const i=t?.listIndex;null==i&&st(`ListIndex not found: ${e.toString()}`);let a=r;const l=t.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const t=me(o.stateElement,l.path);null!==t&&(a=r+function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(s,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const r=-1===o?e:e.slice(0,o),i=-1===o?"":e.slice(o+1),a=t.accessorBySuffixByMarkerParent.get(r)?.get(i);return void 0!==a?a.indexShift:t.delta}(t,l.path))}const c=He(i,a,l.wildcardCount);return c?.index??st(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>function(t,e,n,o){const s=Ml(t,0,n,o);return(e,r)=>{const i=G(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&st(yr("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Za(o,i.wildcardPaths[t]);if(e){r=Ue(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&st(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(e,t.pathInfo.path)),r=[]}}const a=ul(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>function(t,e,n,o){return(e,s,r,i)=>{const a=G(e);Array.isArray(s)||st(br(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&st(yr("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&st(br(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&st(br(e,"requires an array as the value when { spread: true } is set."));const d=ul(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&st(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,d.length,r.length));const u=[];for(let e=0;e<d.length;e++){const s=hl(t,n,o,a,d[e]);u.push(an(a,s))}let h=0;for(let e=0;e<u.length;e++){const s=u[e];let i;i=c?r(cl(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(Al(t,s,i,n,o),h++)}return h}}(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=Ya(e),i=Ll(t,r,n,o),a=an(r.pathInfo,i),l=je(Te(s,a.pathInfo),a.listIndex),c=Di();c.enqueueAbsoluteAddress(l),Pl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=je(Te(s,t.pathInfo),t.listIndex);nl(e),c.enqueueAbsoluteAddress(e)}),fl(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>Ml(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{0===o.addressStackLength&&st(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??st("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(e.path)&&e.path!==t&&n.addDynamicDependency(t,e.path)}}(0,0,0,o)(t);case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case E:return oa(o.stateElement);case R:return ba(o.stateElement);case j:return wa(o.stateElement)}if(!e.startsWith(Ol)&&!e.startsWith(Rl))return}const s=Ya(e),r=Ll(t,s,n,o),i=an(s.pathInfo,r);return cl(t,i,n,o)}if("symbol"==typeof e){const r=function(t){let e=jl.get(t);return void 0===e&&(e=new Map,jl.set(t,e)),e}(o),i=r.get(e);if(void 0!==i)return i;let a;switch(e){case Ie:a=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&st("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case $e:a=e=>cl(t,e,n,o);break;case xe:a=e=>bl(t,e,n,o);break;case Pe:a=(e,s)=>Al(t,e,s,n,o);break;case ke:a=()=>async function(t,e,n){const o=Reflect.get(t,S);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Ce:a=()=>function(t,e,n){const o=Reflect.get(t,I);"function"==typeof o&&o.call(n)}(t,0,n);break;case Ee:a=e=>function(t,e,n,o){const r=Reflect.get(t,$);let i;if("function"==typeof r){const t=new Set,s={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,r=e.path;if(t.add(r),e.wildcardCount>0){const t=Ue(n.listIndex,e.wildcardCount),o=s[r];void 0===o?s[r]=[t]:o.push(t)}}i=r.call(n,Array.from(t),s)}const a=o.stateElement?(l=o.stateElement,ar.get(l)??lr):[];var l;if(a.length>0)for(const t of a){const r=t.mountPath+s,i=new Set,a={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo.path;if(e!==t.mountPath&&!e.startsWith(r))continue;const s=e===t.mountPath?"":e.slice(r.length);if(""===s)continue;i.add(s);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const t=Ue(n.listIndex,l);(a[s]??=[]).push(t)}}if(i.size>0)try{t.callback.call(ir(t.mountPath,n),Array.from(i),a)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" $updatedCallback threw.`,e)}}return i}(t,e,n,o);break;default:return Reflect.get(t,e,n)}return r.set(e,a),a}}class Bl{_stateElement;_addressStack=Array(i).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Pi(t);null===n&&st("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&st("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=i&&st(`Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_describeAddressCycle(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&st(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return Dl(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&st("This state is readonly."),function(t,e,n,o,s){if("string"==typeof e){const r=Ya(e),i=Ll(t,r,o,s);return Al(t,an(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}}const Wl=new WeakMap;class zl{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=Wl.get(t);return n?n.get(e)??null:null}(t,e)??st("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const Fl=t=>()=>t;function Hl(t,e,n,o){!function(t,e,n){let o=Wl.get(t);o||(o=new Map,Wl.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(function(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}(o));const s=function(t,e){const n=new zl(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:Fl(s),enumerable:!0,configurable:!0}),Uo(e,n),Ul(e,n)}function Ul(t,e){if(x in t){const n=t[x];"function"==typeof n?n.call(t,e).catch(t=>{st(`Error in ${x}: ${t instanceof Error?t.message:String(t)}`)}):st(`${x} is not a function.`)}}function ql(t,e){const n=pe(e);var o,i;null!==n&&n.stateProp!==t.stateProp&&st(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&zo(e).dispose(),function(t,e){de.set(t,e);let n=he.get(e.parentStateElement);void 0===n&&(n=new Map,he.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=ue.get(e.component);void 0===o&&(o=new Map,ue.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&fe.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}(e,t),e instanceof ShadowRoot&&function(t,e){const n=Ii.get(t);if(void 0!==n){if(n===e)return;st("A state tree is already registered on this root.")}Ii.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const i=ae.exec(e.statePathName);if(null!==i){const s=function(t,e){return void 0===e?t.delta:G(le(t,e)).wildcardCount-G(e).wildcardCount}(t,n);o=0===s?e.statePathName:`$${Number(i[1])+s}`}else if(o=le(t,e.statePathName),"for"===e.bindingType){const n=G(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+s+r,n)}return o===e.statePathName?e:{...e,statePathName:o,statePathInfo:G(o)}}(t,e,n);jr(e);const o=ye(t.component);ti(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),Lr(e,o,n)}(t,e),o=e,i=Promise.resolve(),$i.set(o,i),i.then(()=>Ei(o),()=>{})}const Gl=new Set;function Kl(t,e){Gl.has(t)||(Gl.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Vl(t){const e=t.rootEntry,n=ye(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Ie](n,()=>{o=t[e.outerPathInfo.path]})}),o}function Jl(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(ir(t.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function Ql(t,e,n){!function(t,e,n){const o=n[L];if(void 0!==o){"object"==typeof o&&null!==o||st(`${L} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&st(`${L} entry "${t}" must be a function.`),Ta(t)}const r=n[O];if(void 0!==r){"object"==typeof r&&null!==r||st(`${O} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(r))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&st(`${O} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+s+n)&&st(`${O} entry "${e+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&st(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`)}(t,e,n);const{data:o,accessors:r}=function(t){const e={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(t)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(e[o]=s.value):n.set(o,s));return{data:e,accessors:n}}(n),i=G(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;st(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],r=""===n?o in t:void 0!==t[n+s+o];n=""===n?o:n+s+o,r||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(a)return;st(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=o}),function(t,e){let n=rr.get(t);void 0===n&&(n=new Set,rr.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,o]of r){const r=e+s+n,i=o.get,a=o.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(ir(e,this))}),"function"==typeof a&&(l.set=function(t){a.call(ir(e,this),t)}),t.defineTreeAccessor(r,l)}!function(t,e,n){const o=n[L];if(void 0!==o){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(o)){const o=e+s+a,c=function(t,n,...o){l.call(ir(e,this),t,n,...o)};n.push({path:o,pathInfo:G(o),handler:c,order:1e6+i++}),r.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(function(t,e){let n=xa.get(t);void 0===n&&(n=new Map,xa.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}(t,n),t.addVolumeWatchPaths?.(r),Ra(t))}const r=n[O];if(void 0!==r){const n=new Map;for(const[t,o]of Object.entries(r))n.set(e+s+t,o);t.mergeVolumeListKeys?.(n)}const i=n[$];"function"==typeof i&&(function(t,e){let n=ar.get(t);void 0===n&&(n=[],ar.set(t,n)),n.push(e)}(t,{mountPath:e,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}(t,e,n);const l=n.$connectedCallback;return"function"==typeof l&&t.createState("writable",t=>{const n=l.call(ir(e,t));n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function Xl(t,e){let n=null;try{n=Ql(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}dr=Xl;class Yl extends si{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return ki(t)}__state;_hasUpdatedCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_name="default";_initialized=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Zi}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_watchPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_volumeGraftInfo=null;_volumeInitializing=!1;_mountRecord=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_dcc=!1;_connectGeneration=0;_streamsStartedGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&st(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){this._commandTokenNames=function(t){const e=new Set,n=t[C];if(void 0===n)return e;Array.isArray(n)||st(`${C} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||st(`${C} entries must be non-empty strings.`),t===E&&st(`${C} entry "${t}" conflicts with the reserved namespace name "${E}".`),e.has(t)&&st(`${C} entry "${t}" is duplicated.`),e.add(t);return e}(t),this._eventTokenNames=function(t){const e=new Set,n=t[A];if(void 0===n)return e;Array.isArray(n)||st(`${A} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||st(`${A} entries must be non-empty strings.`),e.has(t)&&st(`${A} entry "${t}" is duplicated.`),e.add(t);return e}(t),this.__state=t,this._hasUpdatedCallback=$ in t,Nn(this),function(t,e,n){const o=e[T];if(void 0!==o){"object"==typeof o&&null!==o||st(`${T} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||st(`${T} entry "${e}" is not declared in $eventTokens.${ht(e,n)}`),"function"!=typeof s&&st(`${T} entry "${e}" must be a function.`),vn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const n=function(t){const e=new Set,n=new Set,o=Ka(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of n.getterPaths)this._getterPaths.add(t);for(const t of n.setterPaths)this._setterPaths.add(t);_a(this),ha(this),ca(this),da.delete(this),function(t,e){const n=e[M];if(void 0===n)return void ia(t,pa);"object"==typeof n&&null!==n||st(`${M} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[i,a]of Object.entries(n)){0===i.length&&st(`${M} entry name must be a non-empty string.`),i.includes(s)&&st(`${M} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&st(`${M} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&st(`${M} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&st(`${M} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&st(`${M} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&st(`${M} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||st(`${M} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&st(`${M} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&st(`${M} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&st(`${M} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&st(`${M} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??fa,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};i in e||(e[i]=c.definition.initial),o.set(i,c)}!function(t,e){da.set(t,e)}(t,o),ia(t,new Set(o.keys()))}(this,t),this._listKeys=function(t){const e=t[O];if(void 0===e)return null;"object"==typeof e&&null!==e||st(`${O} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&st(`${O} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&st(`${O} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&st(`${O} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),"function"!=typeof o?("string"!=typeof o&&st(`${O} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&st(`${O} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&st(`${O} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&st(`${O} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t),function(t){Pa.delete(t),$a.delete(t)}(this),function(t){Ma.delete(t)}(this),this._watchPaths=function(t,e){const n=e[L];if(void 0===n)return null;"object"==typeof n&&null!==n||st(`[wcs/watch-declaration-invalid] ${L} must be an object mapping state paths to handler functions.${ft}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&st(`[wcs/watch-declaration-invalid] ${L} entry "${e}" must be a function.${ft}`);const n=Ta(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){$a.set(t,e)}(t,o),s.size>0?s:null}(this,t),this._initialized&&null!==this._rootNode&&!e()&&(Ra(this),Na(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}get name(){return this._name}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const t=this.parentNode;if(!t)return null;const e=di.find(t);if(!e)return null;const n=e.stateData;return Object.keys(n).length>0?n:null}async _loadStateFromSource(){try{if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){st("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await Xi(t,`${this._name}`);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||st(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await Yi(t);st(`Unsupported src file type: ${t}`)}}catch(t){st(`Failed to initialize state: ${t}`)}}async _initializeVolume(){const t=this._rootNode,e=this.getAttribute("mount");try{!function(t){0===t.length&&st('"mount" requires a non-empty tree path.');const e=G(t);for(const n of e.segments)0===n.length&&st(`"mount" path "${t}" has an empty segment.`),n===r&&st(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&st(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(e),this.hasAttribute("bind-component")&&st('"mount" cannot be combined with "bind-component".'),this.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),function(t,e){let n=or.get(t);void 0===n&&(n=new Set,or.set(t,n)),n.has(e)&&st(`Volume slot "${e}" is already mounted on this tree.`),n.add(e)}(t,e)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}this._volumeInitializing=!0,null===Pi(t)&&function(t,e){const n=()=>{if(null!==Pi(t))return;const n=t.querySelectorAll(o.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=t.ownerDocument??t;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(t,e);const n=t=>{this._volumeGraftInfo=t,this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()};let s;try{s=await this._loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${e}" failed to load.`,t),void n(null)}null!==this._rootNode?function(t,e,n,o,s){null===e?function(t,e){let n=cr.get(t);void 0===n&&(n=[],cr.set(t,n)),n.push(e)}(t,{mountPath:n,volumeState:o,onGrafted:s}):Xl(e,{mountPath:n,volumeState:o,onGrafted:s})}(t,Pi(t),e,s,n):n(null)}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}await this._loadingPromise,Ai(this.rootNode,this)}_failInitialization(t){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),st(t)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const i=this.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?J(a):null;null!==a&&null!==l||st(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${this.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(t=>this.hasAttribute(t));null!==this.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&st(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const d=this.getAttribute("bind-component");!function(t,e){let n=qo.get(t);n||(n=new Set,qo.set(t,n)),n.add(e)}(a,d);const u=X(a);null===u&&st(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await F(a),d in a||st(`Component does not have property "${d}" for state binding.`);let h=a[d];"object"==typeof h&&null!==h||st(`Component property "${d}" is not an object for state binding.`);const f=function(t,e){const n=Ks.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,d);if(void 0!==f&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=dt(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,d)&&(a[d]=f,h=f),this._boundComponent=a,this._boundComponentStateProp=d,i instanceof ShadowRoot||(dt(a)??[]).some(t=>t.propSegments[0]===d)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(o.bindAttributeName)){const o=(dt(a)??[]).filter(t=>t.propSegments[0]===d);if(o.length>0){const c=Pi(a.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${l}>.`);let u=(n=a,r=d,ue.get(n)?.get(r)??null);const f=null!==u;if(null===u&&(function(t,e,n){const o=Js.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;Js.get(t).delete(e)}}(a,d,h),u=function(t,e,n,o,r,i=new Set){0===n.length&&st(`Cannot build a mount record without host bindings for "${e}".`);const a=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(s);l.has(n)&&st("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo};a.push(o),0===e.length&&(c=o)}a.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const d=++Qt,u=`#m${d}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(r),p={};for(const t of Object.keys(r))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof r[t]&&(i.has(t)||(p[t]=r[t]));return{id:d,marker:u,component:t,stateProp:e,parentStateElement:o,entries:a,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+s+u,stateObject:r,getterKeys:h,setterKeys:f,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set}}(a,d,o,c,h,(t=a,e=d,Vs.get(t)?.get(e))),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp,s=new Map;for(const e of t.entries)1===e.innerSegments.length&&s.set(e.innerSegments[0],e.outerPathInfo.path);let r,i=!1;for(const a of e){const e=s.get(a);if(void 0!==e){Kl(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted entry "${o}.${a}: ${e}" (the host value no longer reaches it). Remove the default to read the tree, or rename it to keep it private.`);continue}if(null===t.rootEntry)continue;if(i||(r=Vl(t),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=t.rootEntry.outerPathInfo.path;Kl(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted tree key "${l}.${a}" (${o}: ${l}). Remove the default to read the tree, or rename it to keep it private.`)}}(u)),this._mountRecord=u,this.parentNode!==i)return;try{ql(u,i instanceof ShadowRoot?i:a)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}if(!f){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=ye(t.component);let s;return e[Ie](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(t,e,n){const o=t.parentStateElement,s=(t,e)=>{let s;return o.createState(t,t=>{s=n(t,()=>e(t))}),s};return"$postUpdate"===e?e=>s("readonly",n=>n.$postUpdate(le(t,e))):(n,o,...r)=>{const i=le(t,n),a=ye(t.component)?.listIndex.indexes??[],l=ce(0,n,i,"$resolve"===e?o??[]:o,a),c="$setAll"===e||"$resolve"===e&&r.length>0?"writable":"readonly";return s(c,t=>t[e](i,l,...r))}}(t,s,n);let r;return e.createState("readonly",e=>{r=n(e,()=>e["$"===s[0]?s:le(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:le(t,s)]=r})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return le(t,n),!0}catch{return!1}}})}(u);Object.defineProperty(a,d,{get:()=>t,enumerable:!0,configurable:!0}),Uo(a,d)}return Ul(a,d),function(t){const e=Xt.filter(e=>void 0!==t.stateObject[e]);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Yt.has(n)||(Yt.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback). See docs/state-mount-design.md §4-6.`))}(u),void Zt(u,"$connectedCallback")}}Hl(this,this._boundComponent,this._boundComponentStateProp,h)}var t,e,n,r}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{S in t&&await t[ke]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await Yi(t):st(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await Xi(e,t.tagName.toLowerCase()):st(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){st(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||st(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=X(t);null!==r&&"function"==typeof r.define||st(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&st(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template");i.innerHTML=e.innerHTML;const a=e.mode,{bindables:l,commands:c,streamBackedBindables:d}=function(t){const e=Ja(t,P)??[],n=Ja(t,k)??[],o=Ka(t),s=function(t){const e=t[M];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}st(`${P} entry "${t}" is not declared on the state.${ht(t,Va(o,"value"))}`)}"function"==typeof e.value&&st(`${P} entry "${t}" is a method. Declare it in ${k} instead.`)}for(const t of n){const e=o[t];void 0===e&&st(`${k} entry "${t}" is not declared on the state.${ht(t,Va(o,"method"))}`),"function"!=typeof e.value&&st(`${k} entry "${t}" is not a method. Declare it in ${P} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),u=l.length>0||c.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,l,c):null,h=l.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,l):{},f=o.tagNames.state,p=class extends HTMLElement{static template=i;static shadowRootMode=a;static wcBindable=u;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(D))return null;this._shadow=this.attachShadow({mode:p.shadowRootMode}),this._shadow.appendChild(p.template.content.cloneNode(!0));const t=X(this._shadow);return null!==t&&Y(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(p.bindableEventMap).length>0){const e=t.querySelector(f);e?e.setBindableEventMap(p.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${P} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(f)??null}},m=Ka(n);for(const[t,e]of Object.entries(m)){if(Ga(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=qa(t,o)}else n.get=Ha(t),n.set=Ua(t);Object.defineProperty(p.prototype,t,n)}for(const t of d)Object.defineProperty(p.prototype,t,{configurable:!0,enumerable:!0,get:Ha(t),set:Ua(t)});r.define(s,p)}(t,e,n),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",t=>{I in t&&t[Ce]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Pi(this._rootNode)===this._volumeGraftInfo.rootStateElement&&Jl(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const t=this._mountRecord,e=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&function(t,e){const n=zo(e),o=ye(t.component);n.forEachActiveBindingNode(t=>be(t,o)),Mr(n.rebindAddresses())}(t,e)}),Zt(t,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||Pi(this._rootNode)===this||Ai(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(D))return this.hasAttribute("bind-component")&&st(`"bind-component" cannot be used inside a [${D}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(t.host,t);if(this.hasAttribute("mount")){if(this._volumeInitializing)return;return void await this._initializeVolume()}if(await this._initializeBindWebComponent(),null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await ki(this.rootNode);const t=di.extractStateData(this),e=document.createElement(o.tagNames.ssr);e.setAttribute("version",oi),di.buildContent(e,t),this.parentNode?.insertBefore(e,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||Ra(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||Na(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Jl(this._volumeGraftInfo,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._mountRecord)return Zt(this._mountRecord,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Ai(this.rootNode,null),ta.delete(this),function(t){na.delete(t)}(this),Nn(this),ha(this),_a(this),function(t){Pa.delete(t)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get watchPaths(){return this._watchPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&st(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get rootNode(){return null===this._rootNode&&st("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0}get hasGraftedVolumes(){return this._hasGraftedVolumes}markHasGraftedVolumes(){this._hasGraftedVolumes=!0}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+r)),!this._pathSet.has(t)){const e=G(t);if(this._pathSet.add(t),function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(sr(t.rootNode??null,n))return;const i=G(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=_r.get(t);return void 0===n&&(n=new Set,_r.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;const a=function(t,e,n){if(void 0!==fr(t,e))return hr;const o=G(e).segments;let i=t,a="";for(let e=0;e<o.length;e++){const l=o[e],c=a;if(a=0===e?l:a+s+l,e>0&&e<o.length-1&&void 0!==fr(t,a))return ur;if(Object(i)!==i)return ur;if(l===r){if(!Array.isArray(i)||0===i.length)return ur;i=i[0];continue}const d=fr(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:pr(i,c,n)};if("function"==typeof d.get)return e===o.length-1?hr:ur;i=d.value}return hr}(e,n,t.getterPaths);"missing"===a.existence&&(console.warn(`[@wcstack/state] [${mr[o]}] ${gr[o]} "${n}" does not resolve on the state tree: "${a.missingSegment}" is not declared.${ht(a.missingSegment,a.candidates)} Updates to this path will be silently dropped.${ft}`),null!==we&&we({type:"state:path-unresolved",source:o,path:n,missingSegment:a.missingSegment}))}(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=G(t.parentPath)}}}_createState(t,e,n){try{const o=function(t,e,n){const o=new Bl(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){this._initialized?((this._hasGraftedVolumes||this._hasMounts)&&st("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead."),this._state=t):this._resolveSetState?.(t)}}await function(){const e=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(void 0);var s;e&&((s=e).tagNames&&Object.assign(n.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(n.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(n.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(n.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(n.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(n.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(n.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(n.locale=s.locale),"boolean"==typeof s.debug&&(n.debug=s.debug),"boolean"==typeof s.enableMustache&&(n.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(n.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(n.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(n.sameValueGuard=s.sameValueGuard)),function(t=customElements){t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,di),t.get(o.tagNames.state)||t.define(o.tagNames.state,Yl)}(void 0),function(){const t=globalThis;void 0===t[mi]&&(t[mi]=Si)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=Vi)}(),Ki()}();const Zl={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},tc=!1,ec=[".html"];function nc(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function oc(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let sc=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const rc={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}},ic={static:2,param:1,"catch-all":0};let ac=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&oc(`${Zl.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&oc(`${Zl.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=ic[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(rc).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||oc(`${Zl.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath;if(!await this._guardHandler(e,n))throw new sc("Navigation cancelled by guard.",this._guardFallbackPath)}else if(this._hasGuard&&this._guardHandlerLoadFailed)throw new sc("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath)}},lc=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=nc();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new ac(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||oc(`${Zl.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):oc(`${Zl.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&oc(`${Zl.route} with fallback attribute must be a direct child of ${Zl.router}.`),t.fallbackRoute&&oc(`${Zl.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const cc=new Map;let dc=class extends HTMLElement{_uuid=nc();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||oc(`${Zl.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return cc.set(t,n),n}catch(e){oc(`${Zl.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${Zl.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)cc.has(t)?n.innerHTML=cc.get(t)||"":n.innerHTML=await this._loadTemplateFromSource(t)||"";else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=t:console.warn(`${Zl.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&tc}get name(){return this.getAttribute("name")||""}},uc=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||oc(`${Zl.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&tc}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const hc=new Set(["props","states","attr",""]);function fc(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function pc(t,e){t.hasAttribute("data-bind")||oc(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";hc.has(n)||oc(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&fc(t,e,o)}).catch(()=>{oc(`Failed to define custom element: ${s}`)}):fc(t,e,o)}let mc=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||oc(`${Zl.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${Zl.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{pc(e,t)}),e.hasAttribute("data-bind")&&pc(e,t))}};function gc(){return document.createElement(Zl.layoutOutlet)}const yc="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function bc(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){oc(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${yc}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${yc}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function wc(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function _c(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===Zl.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),wc(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===Zl.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&bc(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===Zl.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=gc();o.layout=n,i=o,a=e}}const c=await _c(t,a,n,o);a.innerHTML="",a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function vc(t){const e=new Map;return await _c(t,t.template.content,[],e)}function Nc(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let d=!1;if("param"===e.type){const t=e.paramType||"any",n=rc[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),d=!0)}else d=null!==e.pattern.exec(c);if(!d){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)Nc(s,e,n,o)}function Sc(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)Nc(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let Ic=null,$c=null;function xc(){const t=ec;return 0===t.length?null:(Ic===t&&$c||(Ic=t,$c=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),$c)}function Pc(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=xc();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function kc(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function Cc(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=xc();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function Ec(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function Ac(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{pc(e,t.typedParams)}),n.hasAttribute("data-bind")&&pc(n,t.typedParams),n.querySelectorAll(Zl.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===Zl.layoutOutlet&&n.assignParams(t.typedParams)}}function Tc(t,e){Ac(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const Mc=Symbol.for("wcstack.transition-runner");const Lc=Symbol.for("wcstack.binder");function Oc(){const t=globalThis[Lc];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const Rc=Symbol.for("wcstack.binder.pending"),jc=Symbol.for("wcstack.binder.taken");function Dc(){const t=globalThis;let e=t[jc];return void 0===e&&(e=new WeakSet,t[jc]=e),e}function Bc(t){const e=Oc();return null===e?(function(){const t=globalThis;let e=t[Rc];return void 0===e&&(e=[],t[Rc]=e),e}().push(t),!1):(Dc().add(t),e.bind(t),!0)}const Wc=new WeakSet,zc="data-wcs";function Fc(t,e,n){!Wc.has(t)&&function(t){return t.hasAttribute(zc)||null!==t.querySelector(`[${zc}]`)}(t)&&(Wc.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==Oc()||(o=t,Dc().has(o))||console.warn(`[@wcstack/router] ${e} contains ${zc} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function Hc(t){for(const e of t.childNodeArray)1===e.nodeType&&(Bc(e)||Fc(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.'))}async function Uc(t,e){try{for(const t of e.routes)await t.guardCheck(e)}catch(e){if(e instanceof sc)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function qc(t,e,n,o,s=""){const r=kc(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,search:s,path:r}),!0;let i=Sc(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:oc(`${Zl.router} No route matched for path: ${r}`)),i.lastPath=o;const a=e.lastRoutes,l=await async function(t,e,n){if(!await Uc(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||Ec(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=Tc(o,e),n.length>0&&!s.has(o)&&Hc(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[Mc];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName))return t;const n=t.querySelector("h1,h2,h3,h4,h5,h6");if(null!==n)return n}return null}(e.routes[e.routes.length-1].childNodeArray);null!==t&&(t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus())}}(t,i),!0)}function Gc(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Kc(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}function Vc(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function Jc(t){return"?"===t?"":t}function Qc(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function Xc(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Yc="data-wcs-ssr",Zc="data-wcs-ssr-link",td="@@wcs-route-ph:",ed="@@wcs-route-start:",nd="@@wcs-route-end:",od=Object.freeze({});class sd extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=od;_typedParams=od;_searchParams=od;_routeName="";_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return this.getAttribute("focus")}get announcePolicy(){return this.getAttribute("announce")}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return Pc(t)}_normalizeBasename(t){return Cc(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(Zl.outlet))return t;const e=document.createElement(Zl.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||oc(`${Zl.router} has no outlet.`),this._outlet}get template(){return this._template||oc(`${Zl.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=function(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}(t.search),s=!Kc(this._params,e),r=this._routeName!==t.routeName,i=!Kc(this._searchParams,o),a=this._path!==t.path;s&&(this._params=e,this._typedParams=n),r&&(this._routeName=t.routeName),i&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,s&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),r&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${Zl.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${Zl.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=Vc(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Jc(n.search)+n.hash,r=Gc();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(kc(t,this._basename));await qc(this,this.outlet,t,this._path,Jc(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(kc(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await qc(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${Zl.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await qc(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=Xc();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||oc(`${Zl.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||oc(`${Zl.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await vc(this),r=!t&&this._outlet.hasAttribute(Yc);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&oc(`${Zl.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(Yc);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await qc(this,this.outlet,i,this._path,window.location.search||""),(r||null!==Oc())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(Zl.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(td)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(ed)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith(nd)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const d=kc(t,this._basename);let u=Sc(this,d);if(!u){if(null===this._fallbackRoute)return!1;u={routes:[this._fallbackRoute],params:{},typedParams:{},path:d,lastPath:this._path}}if(u.lastPath=this._path,u.routes.length!==r.size)return!1;for(const t of u.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of u.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of u.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(ed)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===Zl.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(Yc);for(const t of u.routes)Ac(t,u);return this.outlet.lastRoutes=u.routes,!await Uc(this,u)||(this.commitNavigation({params:u.params,typedParams:u.typedParams,routeName:u.routes[u.routes.length-1].name,search:window.location.search||"",path:d}),!0)}async _renderForSsr(t){const e=kc(t,this._basename),n=Sc(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&oc(`${Zl.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await qc(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${td}${t.absolutePath}`}),this.outlet.setAttribute(Yc,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${ed}${t.absolutePath}`),s=document.createComment(`${nd}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&Bc(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Qc(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),Xc()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Gc();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Gc()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const rd=["title","rel","target","download","hreflang"];class id extends HTMLElement{static get observedAttributes(){return["to",...rd]}_childNodeArray=[];_uuid=nc();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(Zl.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(Zl.router);if(n)return this._router=n;oc(`${Zl.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return Pc(t)}_joinInternalPath(t,e){const n=Cc(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=Vc(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+Jc(o)+s}else try{t.href=new URL(e).toString()}catch{oc(`[${Zl.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){Xc()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Zc)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(Zc),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||rd.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,Xc())return this._updateActiveState(),void n.setAttribute(Zc,"");Gc()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Gc()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Gc()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(rd.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=Vc(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const ad=[],ld=new Map;let cd=!1;const dd=new WeakMap;class ud extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),cd||(this._captureInitialHead(),cd=!0),ad.push(this),this._reapplyHead()}disconnectedCallback(){const t=ad.indexOf(this);-1!==t&&ad.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||oc("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=dd.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return dd.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);ld.has(t)||ld.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of ad)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of ld.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=ad.length-1;e>=0;e--){const o=ad[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&ld.has(n)&&(t=ld.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),Bc(t)||Fc(t,`<${t.tagName.toLowerCase()}> inside <${Zl.head}>`,`<${Zl.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(Zl.layout)||t.define(Zl.layout,dc),t.get(Zl.layoutOutlet)||t.define(Zl.layoutOutlet,mc),t.get(Zl.outlet)||t.define(Zl.outlet,uc),t.get(Zl.route)||t.define(Zl.route,lc),t.get(Zl.router)||t.define(Zl.router,sd),t.get(Zl.link)||t.define(Zl.link,id),t.get(Zl.head)||t.define(Zl.head,ud)}(void 0);const hd="data-fetchtarget",fd={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let pd=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function md(t,e){return e.every(e=>"available"===t.availability.get(e))}const gd=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let yd=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new pd("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return md(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),d=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",u=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:d,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}(gd,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!md(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:d="auto",timeout:u=0}=e;let h=null;u>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${u}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},u));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===d)s=await n.blob();else if("arrayBuffer"===d)s=await n.arrayBuffer();else if("text"===d)s=await n.text();else if("json"===d)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const u=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,u)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},bd=!1;function wd(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${hd}]`);if(!n)return;const o=n.getAttribute(hd);if(!o)return;const s=customElements.get(fd.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function _d(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let vd=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...yd.wcBindable,properties:[...yd.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new yd(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(fd.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(fd.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&(t.innerHTML=s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!_d(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",bd||(bd=!0,document.addEventListener("click",wd)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}},Nd=class extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}},Sd=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}},Id=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof vd&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(fd.fetch)||t.define(fd.fetch,vd),t.get(fd.fetchHeader)||t.define(fd.fetchHeader,Nd),t.get(fd.fetchBody)||t.define(fd.fetchBody,Sd),t.get(fd.infiniteScroll)||t.define(fd.infiniteScroll,Id)}(void 0);const $d="data-storagetarget",xd={storage:"wcs-storage"},Pd="wcs-storage:value-changed",kd="wcs-storage:loading-changed",Cd="wcs-storage:error",Ed="wcs-storage:error-info-changed",Ad="wcs-storage:trigger-changed";let Td=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Pd,semantics:"state",getter:t=>t.detail},{name:"loading",event:kd,semantics:"state"},{name:"error",event:Cd,semantics:"state"},{name:"errorInfo",event:Ed,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(kd,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(Cd,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(Ed,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(Pd,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},Md=!1;function Ld(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${$d}]`);if(!n)return;const o=n.getAttribute($d);if(!o)return;const s=customElements.get(xd.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function Od(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let Rd=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Td.wcBindable,properties:[...Td.wcBindable.properties,{name:"trigger",event:Ad,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new Td(this),this._internals=this._initInternals(),this._wireStates({[kd]:t=>({loading:!0===t}),[Cd]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(Ad,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Od(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Md||(Md=!0,document.addEventListener("click",Ld)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(xd.storage)||t.define(xd.storage,Rd)}(void 0);const jd="*",Dd="vanilla",Bd={scanImportmap:!0,loaders:{[Dd]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[jd]:Dd},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function Wd(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function zd(t,e,n){let o;if(null===e||e===jd||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===jd)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[jd],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const Fd=new Set,Hd=new Map;let Ud=new WeakMap;function qd(t){if(t===globalThis.customElements)return Hd;let e=Ud.get(t);return void 0===e&&(e=new Map,Ud.set(t,e)),e}const Gd=new Map;async function Kd(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of Gd)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){Fd.has(e)||(console.error(`Failed to eager load component '${e}':`,t),Fd.add(e))}}function Vd(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function Jd(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&Gd.set(t,e)});const Qd=new WeakSet,Xd=new WeakSet;async function Yd(t,e,n){t.shadowRoot&&(Qd.has(t)||await async function(t,e,n){Qd.add(t),await nu(t.shadowRoot,e,n)}(t,e,n))}async function Zd(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=qd(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=zd("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),Fd.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function tu(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=Jd(t);void 0===o.get(s.name)?(Xd.has(t)||(Xd.add(t),o.whenDefined(s.name).then(async()=>{await Yd(t,e,n)})),a.has(s.name)||Fd.has(s.name)||(a.add(s.name),i.push(s))):await Yd(t,e,n)}let l=0;for(const t of i)await Zd(t,e,n,o),l++;return l}async function eu(t,e,n,o){for(;await tu(t,e,n,o)>0;);}async function nu(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return Vd(e)}return Vd(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await eu(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await eu(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class ou extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),ou._instance)throw new Error(`${Bd.tagNames.autoloader} can only be instantiated once.`);ou._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=Wd(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=zd(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(Kd(s,o,r))}await Promise.all(n)}(n,Bd.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await nu(document,Bd,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,ou._instance===this&&(ou._instance=null)}}!function(t=customElements){t.get(Bd.tagNames.autoloader)||t.define(Bd.tagNames.autoloader,ou)}(void 0);
2
2
  //# sourceMappingURL=auto.min.js.map