@wcstack/state 2.2.0 → 2.3.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 e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.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;const s=".",r="*",i=128,a="|",l="prevent",c="stop",d="ro",u="init",f="sync",h="else",p="...",m="on",g="eventToken",y="command",b="class",w="attr",v="style",$={};for(let e=0;e<128;e++)$[`$${e+1}`]=e;const S=Object.freeze($),x="$connectedCallback",N="$disconnectedCallback",I="$updatedCallback",P="$errorCallback",k="$stateReadyCallback",_="$bindables",A="$commands",C="$commandTokens",E="$command",M="$eventTokens",T="$on",O="$streams",R="$watch",L="$listKeys",j="$streamStatus",D="$streamError",W="data-wc-definition",B=new WeakMap,z=new WeakSet;let F=0;async function q(e){const t=function(e){let t,n=B.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++F,promise:o,resolve:t},B.set(e,n),z.has(e)&&n.resolve(),n}(e);await t.promise}function V(e){const t=B.get(e);void 0===t?z.add(e):t.resolve()}const U=new Map;let K=0;function G(e){let t=U.get(e);return void 0!==t||(t=Object.freeze(new H(e)),U.set(e,t)),t}class H{id=++K;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(e){const t=t=>e===t?this:G(t),n=e.split("."),o=[],s=[],i=[],a={},l=[],c=[],d=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===r&&(i.push(f),a[f]=p,l.push(t(f)),c.push(h),d.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const m=i.length>0?i[i.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=e,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?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=p}}const J=new WeakMap;function X(e){const t=J.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{J.set(e,n)}}function Y(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Q(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Y(t);if(void 0!==n)return Y(n)}return Y(globalThis.customElements)}function Z(e,t){e.upgrade?.(t)}function ee(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.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=se(s.properties,te);if(null===r)return null;const i=void 0===s.inputs?new Map:se(s.inputs,ne);if(null===i)return null;const a=void 0===s.commands?new Map:se(s.commands,oe);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function te(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function ne(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function oe(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function se(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function re(e){throw new Error(`[@wcstack/state] ${e}`)}function ie(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:G(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ae(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function le(e,t,n={}){const s=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&re("Spread binding requires an element node.");const t=e,o=X(t);null===o&&re(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Q(t);null===a&&re(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||re(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Z(a,t);const l=ee(t);null===l&&re(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=ie(e,c);i.add(t),r.push(t)}for(const e of l.declaredInputs.keys()){if(d.has(e))continue;d.add(e);const t=ie(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=ae(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=ae(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.debug&&i.has(r[t])){const o=r[a.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[t])}return l}function ce(e,t){let n=e;if(0===t.length)return n;for(let e=0;e<t.length&&(n=n?.childNodes[t[e]]??null,null!==n);e++);return n}const de=new WeakMap;function ue(e){return de.get(e)||null}function fe(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;const o=new Array(t.length+1),s=new Array(t.length+1);for(let e=0;e<=t.length;e++)o[e]=e;for(let n=1;n<=e.length;n++){s[0]=n;for(let r=1;r<=t.length;r++){const i=e[n-1]===t[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let e=0;e<=t.length;e++)o[e]=s[e]}return o[t.length]}function he(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=fe(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const pe=" Validate statically: npx @wcstack/lint <file>.",me=new Set(["if","elseif","else","for"]);function ge(e){re(`filter ${e} requires at least one option`)}function ye(e){re(`filter ${e} requires a number as option`)}function be(e){re(`filter ${e} requires a number value`)}function we(e){re(`filter ${e} requires a date value`)}function ve(e){return!(!e||isNaN(Number(e)))}const $e={eq:e=>{const t=e?.[0]??ge("eq");return e=>"number"==typeof e?(ve(t)||ye("eq"),e===Number(t)):e===t},ne:e=>{const t=e?.[0]??ge("ne");return e=>"number"==typeof e?(ve(t)||ye("ne"),e!==Number(t)):e!==t},not:e=>e=>("boolean"!=typeof e&&re(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??ge("lt");return ve(t)||ye("lt"),e=>("number"!=typeof e&&be("lt"),e<Number(t))},le:e=>{const t=e?.[0]??ge("le");return ve(t)||ye("le"),e=>("number"!=typeof e&&be("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??ge("gt");return ve(t)||ye("gt"),e=>("number"!=typeof e&&be("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??ge("ge");return ve(t)||ye("ge"),e=>("number"!=typeof e&&be("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??ge("inc");return ve(t)||ye("inc"),e=>("number"!=typeof e&&be("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??ge("dec");return ve(t)||ye("dec"),e=>("number"!=typeof e&&be("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??ge("mul");return ve(t)||ye("mul"),e=>("number"!=typeof e&&be("mul"),e*Number(t))},div:e=>{const t=e?.[0]??ge("div");return ve(t)||ye("div"),e=>("number"!=typeof e&&be("div"),e/Number(t))},mod:e=>{const t=e?.[0]??ge("mod");return ve(t)||ye("mod"),e=>("number"!=typeof e&&be("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&be("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??ge("clamp");ve(t)||ye("clamp");const n=e?.[1]??ge("clamp");ve(n)||ye("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&be("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return ve(t)||ye("fix"),e=>("number"!=typeof e&&be("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&be("locale"),e.toLocaleString(t??o.locale))},uc:e=>e=>String(e).toUpperCase(),lc:e=>e=>String(e).toLowerCase(),cap:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??ge("slice");ve(n)||ye("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(ve(o)||ye("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??ge("substr");ve(t)||ye("substr");const n=e?.[1]??ge("substr");return ve(n)||ye("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??ge("pad");ve(t)||ye("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??ge("rep");return ve(t)||ye("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??ge("truncate");ve(t)||ye("truncate");const n=Number(t),o=e?.[1]??"…";return e=>{const t=String(e);return t.length<=n?t:t.slice(0,n)+o}},join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||re(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=e?.[0]??"0";return ve(t)||ye("round"),e=>{"number"!=typeof e&&be("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return ve(t)||ye("floor"),e=>{"number"!=typeof e&&be("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return ve(t)||ye("ceil"),e=>{"number"!=typeof e&&be("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return ve(t)||ye("percent"),e=>("number"!=typeof e&&be("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??ge("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||we("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||we("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||we("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||we("ymd");const n=e.getFullYear().toString(),o=(e.getMonth()+1).toString().padStart(2,"0"),s=e.getDate().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},hms:e=>{const t=e?.[0]??":";return e=>{e instanceof Date||we("hms");const n=e.getHours().toString().padStart(2,"0"),o=e.getMinutes().toString().padStart(2,"0"),s=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!1===e||null==e||0===e||""===e||Number.isNaN(e),truthy:e=>e=>!1!==e&&null!=e&&0!==e&&""!==e&&!Number.isNaN(e),defaults:e=>{const t=e?.[0]??ge("defaults");return e=>!1===e||null==e||0===e||""===e||Number.isNaN(e)?t:e},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),null:e=>e=>""===e?null:e},Se=$e,xe={input:$e,output:Se},Ne=(e,t)=>n=>{const o=n[e];return o||re(`[wcs/filter-unknown] filter not found: ${e}.${he(e,Object.keys(n))}${pe}`),o(t)};function Ie(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const Pe=new Map;function ke(e,t){const n=xe[t];return e.map(e=>{const o=e.indexOf("("),s=e.lastIndexOf(")");if(-1!==o&&-1===s&&re(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==s&&-1===o&&re(`Invalid filter format: missing opening parenthesis in "${e}"`),-1===o){const o=e.trim(),s=`${o}():${t}`;let r=Pe.get(s);return void 0===r&&(r=Ne(o,[])(n),Pe.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=e.substring(o+1,s),i=e.substring(0,o).trim(),a=function(e){const t=[];let n="",o=null,s=!1,r=-1,i=-1;const a=()=>{t.push(Ie(n,r,i)),n="",s=!1,r=-1,i=-1};for(let t=0;t<e.length;t++){const l=e[t];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=Ie(n,r,i);return(l||s)&&t.push(l),t}(r),l=`${i}(${a.join(",")}):${t}`;let c=Pe.get(l);return void 0===c&&(c=Ne(i,a)(n),Pe.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const _e=e=>e.trim(),Ae=new Map;const Ce=new Map;function Ee(e){const t=e.indexOf(a);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ce.has(s)?r=Ce.get(s):(o=s.split(a).map(_e),r=ke(o,"output"),Ce.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&re(`"${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.`);return{statePathName:n,statePathInfo:G(n),outFilters:r}}function Me(e){const[...t]=e.split(";").map(_e).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&re(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim();if(n===h){const e=G("#else");return{propName:h,propSegments:[h],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===p){const t=Ee(o);return t.outFilters.length>0&&re(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&re(`Invalid spread binding "${e}": spread target path is required.`),{propName:p,propSegments:[p],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ee(o),bindingType:n}}{const e=Ee(o),t=function(e){const t=e.indexOf(a);let n="",o=[],r="",i=[];-1!==t?(n=e.slice(0,t).trim(),r=e.slice(t+1).trim(),Ae.has(r)?i=Ae.get(r):(o=r.split(a).map(_e),i=ke(o,"input"),Ae.set(r,i))):n=e.trim();const[l,c]=n.split("#").map(_e),d=l.split(s).map(_e);return{propName:l,propSegments:d,propModifiers:c?c.split(",").map(_e):[],inFilters:i}}(n);return t.propSegments[0]===g||t.propSegments[0].startsWith(m)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>me.has(e.bindingType))&&re(`[wcs/template-syntax] Invalid bindText: "${e}". '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">).${pe}`)}return n}const Te=new WeakMap,Oe=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Re=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Le(e){const t=Te.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=Re.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Oe.has(r)?(Te.set(e,s[2]),s[2]):null}function je(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ee(e),bindingType:"text"}}const De=new Map;function We(e,t,n){if(null===n)De.delete(e);else{De.set(e,n);const o=ta(t);null===o&&re("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const t of e.parseBindTextResults)o.setPathInfo(t.statePathName,t.bindingType)}}function Be(e){return De.get(e)||null}function ze(e){if(e.nodeType===Node.ELEMENT_NODE){return Me(e.getAttribute(o.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=Le(e);null===t&&re("Comment node binding text not found.");const n=Be(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=je(t),s=null):s=t,[{...o,uuid:s}]}return[]}function Fe(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function qe(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Fe(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function Ve(e,t){for(let n=0;n<t.length;n++){const o=t[n];if(o!==e&&o.contains(e))return!0}return!1}function Ue(e){const t=[],n=qe(e),s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==Le(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&Ve(e,n)||t.push(e)}return t}const Ke=new WeakSet;function Ge(e,t,n,o){const s=le(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?X(e):null;return null===n&&re("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}Ke.add(e);const r=function(e,t){const n=[];for(const o of t)if("text"!==o.bindingType)n.push({...o,node:e,replaceNode:e});else{const t=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,node:e,replaceNode:t})}return n}(e,function(e,t){return void 0===t?e:e.map(e=>null!=e.uuid?e:t(e))}(s,o));return function(e,t){de.set(e,t)}(e,r),V(e),{bindings:r,deferred:null}}function He(e,t){const n=Ue(e),o=[],s=[];for(const e of n){if(Ke.has(e))continue;const n=Ge(e,ze(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Je(e){Ke.add(e)}function Xe(e){const{node:t,parseResults:n,transform:o}=e;!function(e){Ke.delete(e)}(t);return Ge(t,n,{allowDeferred:!1},o).bindings}let Ye=0;const Qe=["$watch","$streams","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on"],Ze=new Set;function et(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function tt(e,t,n,o,r,i=new Set){0===n.length&&re(`Cannot build a mount record without host bindings for "${t}".`);const a=[],l=new Set;let c=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(s);l.has(n)&&re("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo};a.push(o),0===t.length&&(c=o)}a.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++Ye,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(r),p={};for(const e of Object.keys(r))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof r[e]&&(i.has(e)||(p[e]=r[e]));return{id:d,marker:u,component:e,stateProp:t,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:f,setterKeys:h,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function nt(e){const t=e.indexOf(s);return-1===t?e:e.slice(0,t)}function ot(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function st(e,t){for(const n of e.entries)if(ot(t,n.innerSegments)){const e=t.slice(n.innerSegments.length);return 0===e.length?n.outerPathInfo.path:n.outerPathInfo.path+s+e.join(s)}return null}function rt(e,t){return e.markerBasePath+s+t}function it(e,t,n,o){let r=e.accessorBySuffixByMarkerParent.get(t);void 0===r&&(r=new Map,e.accessorBySuffixByMarkerParent.set(t,r));const i=t+s+n;r.set(n,{accessorName:o,indexShift:G(i).wildcardCount-G(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(i),e.addedGetterPaths.add(i))}function at(e,t){return!e.injectedKeys.has(t)&&("function"==typeof e.stateObject[t]&&!e.getterKeys.has(t)||Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t))}function lt(e,t){return`Path "${t}" in <${e.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${e.entries.filter(e=>e.innerSegments.length>0).map(e=>e.innerSegments.join(s)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${nt(t)}: path") or declare the key on the component state.`}const ct=/^\$(\d+)$/;function dt(e,t){const n=t[0];if("$"===n||"#"===n)return t;if(e.getterKeys.has(t)||e.setterKeys.has(t))return function(e,t){const n=t.split(s);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===r){o=e;break}if(-1===o)return it(e,e.markerBasePath,t,t),rt(e,t);if(at(e,n[0]))return it(e,e.markerBasePath,t,t),rt(e,t);const i=n.slice(0,o+1),a=n.slice(o+1),l=st(e,i);null===l&&re(lt(e,t)),0===a.length&&re(`Wildcard-terminal accessor "${t}" on mounted <${e.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+e.marker;return it(e,c,a.join(s),t),c+s+a.join(s)}(e,t);const o=nt(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return rt(e,t);if(at(e,o))return rt(e,t);const i=st(e,t.split(s));if(null!==i)return i;re(lt(e,t))}function ut(e,t,n){let o;const i=ct.exec(t.statePathName);if(null!==i){const s=function(e,t){return void 0===t?e.delta:G(dt(e,t)).wildcardCount-G(t).wildcardCount}(e,n);o=0===s?t.statePathName:`$${Number(i[1])+s}`}else if(o=dt(e,t.statePathName),"for"===t.bindingType){const n=G(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+s+r,n)}return o===t.statePathName?t:{...t,statePathName:o,statePathInfo:G(o)}}function ft(e,t,n,o,s){if(void 0===o)return;const r=G(n).wildcardCount-G(t).wildcardCount;return 0===r?o:(s.length<r&&re(`Cannot resolve "${t}" 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 ht=new WeakMap,pt=new WeakMap;const mt=new WeakMap;const gt=new FinalizationRegistry(function(e){const t=e.byMarker.get(e.marker);if(void 0!==t&&void 0===t.deref()&&e.byMarker.delete(e.marker),void 0!==e.getterPaths)for(const t of e.addedGetterPaths)e.getterPaths.delete(t)});function yt(e){return ht.get(e)??null}function bt(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=mt.get(e);if(void 0===o)return null;const r=t.indexOf(s,n),i=-1===r?t.slice(n):t.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 wt=new WeakMap;function vt(e){let t=e;for(;t;){const e=wt.get(t);if(e)return e;let n=t.parentNode;null===n&&t instanceof ShadowRoot&&null!==yt(t)&&(n=t.host),t=n}return null}function $t(e,t){null!==t?wt.set(e,t):wt.delete(e)}let St=null;const xt=new WeakMap;function Nt(e){return xt.get(e)??[]}function It(e,t){xt.set(e,t)}function Pt(e){return xt.has(e)}const kt=Symbol("$$setLoopContext"),_t=Symbol("$$getByAddress"),At=Symbol("$$hasByAddress"),Ct=Symbol("$$setByAddress"),Et=Symbol("$$connectedCallback"),Mt=Symbol("$$disconnectedCallback"),Tt=Symbol("$$updatedCallback"),Ot=Symbol("$$errorCallback"),Rt=new WeakMap;function Lt(e,t){if(Rt.has(e)){const n=Rt.get(e);if(n.has(t))return n.get(t)}else Rt.set(e,new WeakMap);const n=Object.freeze(new jt(e,t));return Rt.get(e).set(t,n),n}class jt{pathInfo;stateElement;parentAbsolutePathInfo;constructor(e,t){this.pathInfo=t,this.stateElement=e,null===t.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Lt(e,t.parentPathInfo)}}const Dt=new WeakMap,Wt=new WeakMap;class Bt{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const e=this.absolutePathInfo.parentAbsolutePathInfo;if(null===e)return null;let t=null;return t=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=zt(e,t)}}function zt(e,t){if(null===t){let t=Wt.get(e);return void 0!==t||(t=new Bt(e,null),Wt.set(e,t)),t}{let n=Dt.get(t);void 0===n&&(n=new WeakMap,Dt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Bt(e,t),n.set(e,o)),o}}const Ft=new WeakMap;function qt(e,t){null===t?Ft.delete(e):Ft.set(e,t)}function Vt(e){return Ft.get(e)||null}const Ut=new Map;function Kt(e,t){let n,o;if(0===e.wildcardCount||0===t.wildcardCount)return 0;if(1===e.wildcardCount&&t.wildcardCount>0&&t.wildcardPathSet.has(e.path))return 1;e.id<t.id?(n=e,o=t):(n=t,o=e);const s=`${n.path}\t${o.path}`;let r=Ut.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Ut.set(s,r),r}function Gt(e,t,n){return t<0||t>=n?null:e.at(t-n)}function Ht(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const Jt=new WeakMap;function Xt(e){const t=vt(e.node);if(null===t)return null;let n=Jt.get(t);if(void 0===n)n=new WeakMap,Jt.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=Kt(t.pathInfo,e.statePathInfo);return n>0&&(o=Gt(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const Yt=new WeakMap;function Qt(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Vt(n);null===t?re(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function Zt(e,t){let n=null;if(n=Yt.get(e)||null,null!==n)return n;const o=Qt(e,t),s=Xt(e),r=ta(o);null===r&&re("No state tree found on this root for binding.");return n=zt(Lt(r,e.statePathInfo),s),Yt.set(e,n),n}function en(e){Yt.delete(e)}const tn=new WeakMap;function nn(e,t){const n=tn.get(e);void 0===n?tn.set(e,t):n instanceof Set?n.add(t):n!==t&&tn.set(e,new Set([n,t])),null!==St&&St({type:"state:binding-added",absoluteAddress:e,binding:t})}function on(e,t){const n=tn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&tn.delete(e),null!==St&&St({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const sn=new WeakMap;function rn(e,t,n){const o=sn.get(e);if(void 0===o)return;const s=o.get(t);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(t),null!==St&&St({type:"state:binding-removed",absoluteAddress:zt(e,t),binding:n}))}function an(e){const t=tn.get(e);return void 0!==t?t:null!==e.listIndex?sn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const ln=new WeakMap,cn=new WeakMap;class dn{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=un(e,t)}}function un(e,t){if(null===t){let t=cn.get(e);return void 0!==t||(t=new dn(e,null),cn.set(e,t)),t}{let n=ln.get(t);void 0===n&&(n=new WeakMap,ln.set(t,n));let o=n.get(e);return void 0!==o||(o=new dn(e,t),n.set(e,o)),o}}const fn=new WeakMap;function hn(e){let t=null;if(t=fn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=Xt(e);null===n&&re(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=un(e.statePathInfo,n)}else t=un(e.statePathInfo,null);return fn.set(e,t),t}function pn(e){fn.delete(e)}function mn(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const gn=new Map,yn=mn();function bn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function wn(e){let t="input";for(const n of e.propModifiers)n.startsWith(m)&&(t=n.slice(2));return t}function vn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(d)){const o=wn(e),s=bn(e,o);let r=gn.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.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 e of n)r=e.filterFn(r);const i=ta(o.getRootNode());null===i&&re("No state tree found on this root for two-way binding.");const a=vt(o);i.createState("writable",e=>{e[kt](a,()=>{let n=e[t];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(e[t]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(e[t]=n.toSpliced(o,1))}else e[t]=s?[r]:[]})})},gn.set(s,r)),e.node.addEventListener(o,r),yn.add(s,e),!0}var t,n;return!1}function $n(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Sn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)$n(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class xn{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)t.push(n(...e));return t}}class Nn extends xn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==St&&St({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const In=new WeakMap;function Pn(e,t){let n=In.get(e);void 0===n&&(n=new Map,In.set(e,n));let o=n.get(t);return void 0===o&&(o=new Nn(t,e),n.set(t,o)),o}function kn(e){In.delete(e)}const _n=new WeakMap;function An(e){if(e.propSegments[0]!==g)return!1;const t=e.node,n=X(t),o=Q(t);if(null!==n&&void 0===o?.get(n))return null===o&&re(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(_n.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||re('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===X(e)?null:ee(e)}(t);null===r&&re(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&re(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${he(s,r.knownProperties.keys())}`);const a=i.event,d=e.statePathName,u=e.propModifiers,f=e=>{u.includes(l)&&e.preventDefault(),u.includes(c)&&e.stopPropagation();const n=ta(t.getRootNode());null===n&&re("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(d)||re(`[wcs/token-undeclared] eventToken "${d}" is not declared in $eventTokens.${he(d,n.eventTokenNames)}${pe}`);const o=vt(t);n.createStateAsync("writable",async t=>{Sn(t[kt](o,()=>{const s=null!==o?Ht(o.listIndex,o.pathInfo.wildcardCount):[];return Pn(n,d).emit(t,e,...s)}),`$on."${d}"`)})};return t.addEventListener(a,f),_n.set(e,{eventName:a,handler:f}),!0}class Cn extends xn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==St&&St({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function En(e){return e instanceof Cn}const Mn=new Map,Tn=mn();function On(e){const t=e.propModifiers.filter(e=>e===l||e===c).sort().join(",");return`${e.statePathName}::${t}`}const Rn=(e,t,n)=>o=>{t.includes(l)&&o.preventDefault(),t.includes(c)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ta(r);null===i&&re("No state tree found on this root for event handler.");const a=vt(s),d=e.startsWith(E+".");i.createStateAsync("writable",async t=>{const l=t[kt](a,()=>{let l=null!==a?a.pathInfo.wildcardCount:0;if(null!==a&&!0===i.hasMounts){const e=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=ht.get(n);if(void 0!==e)return e;n=n.parentNode}return ht.get(t)??null}(s,r);if(null!==e){const t=e.indexShiftByLoopElementPath.get(a.pathInfo.path);l=void 0!==t?l-t:0}}const c=null!==a?Ht(a.listIndex,l):[];if(d){const s=t[_t](un(n,null));return En(s)||re(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...c)}const u=t[e];return"function"!=typeof u&&re(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...c])});Sn(l,`"${e}"`)})};function Ln(e){if(!e.propName.startsWith(m))return!1;const t=On(e);let n=Mn.get(t);void 0===n&&(n=Rn(e.statePathName,e.propModifiers,e.statePathInfo),Mn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Tn.add(t,e),!0}const jn=new Map,Dn=mn();function Wn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Bn(e){let t="input";for(const n of e.propModifiers)n.startsWith(m)&&(t=n.slice(2));return t}function zn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(d)){const o=Bn(e),s=Wn(e,o);let r=jn.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.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 e of n)s=e.filterFn(s);const r=ta(o.getRootNode());null===r&&re("No state tree found on this root for two-way binding.");const i=vt(o);r.createState("writable",e=>{e[kt](i,()=>{e[t]=s})})},jn.set(s,r)),e.node.addEventListener(o,r),Dn.add(s,e),!0}var t,n;return!1}const Fn=new Set(["radio","checkbox"]),qn=new Set(["value","valueAsNumber","valueAsDate"]);function Vn(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(Fn.has(e)&&"checked"===t)return!0;if(qn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=X(n);if(null!==s){const e=Q(n)?.get(s);void 0===e&&re(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=ee(n);if(o?.knownProperties.has(t))return!0}return!1}let Un=1,Kn=1,Gn=1;const Hn=new WeakMap;function Jn(e,t,n){let o=Hn.get(e);void 0===o&&(o=new Map,Hn.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=Un++,o.set(s,r)),r}function Xn(e,t){return"to-element"===t?2*e:2*e+1}const Yn=new Set;function Qn(e){return{transactionId:Kn++,originBindingId:e,visitedEdges:Yn,hop:0}}function Zn(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let eo=null;function to(){return eo}function no(e,t){const n=eo;eo=e;try{return t()}finally{eo=n}}const oo=[];let so=!1;const ro=new Map,io=mn(),ao=new WeakMap,lo=e=>e.detail,co=new WeakMap;function uo(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function fo(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=X(e.node);if(null!==n){const o=Q(e.node)?.get(n);void 0===o&&re(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=ee(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(m)&&(t=n.slice(2));return t}function ho(e){if(null!==X(e.node)){const t=ee(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??lo}return null}function po(e){if(null===X(e.node))return!1;const t=ee(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const mo=(e,t,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),s!==lo||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=co.get(e);void 0===r&&(r=new Set,co.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=ao.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=Jn(a,e,t),s=function(e,t){for(let n=oo.length-1;n>=0;n--){const o=oo[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==St&&St({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Xn(n,"to-state"),node:a,member:e}));const r=Xn(n,"to-state"),i=to();if(null!==i&&i.visitedEdges.has(r))return void(null!==St&&St({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=Zn(i??Qn(n),r)}const f=ta(a.getRootNode());null===f&&re("No state tree found on this root for two-way binding.");const h=vt(a),p=()=>{r&&(so=!0);try{f.createState("writable",e=>{e[kt](h,()=>{e[t]=c})})}finally{r&&(so=!1)}};null!==u?no(u,p):p()};const go=new WeakSet;function yo(e){go.add(e)}function bo(e){return!!go.has(e)&&(go.delete(e),!0)}const wo=new WeakSet;function vo(e){wo.add(e)}function $o(e){return!!wo.has(e)&&(wo.delete(e),!0)}let So=0;function xo(){So--}function No(){return So>0}class Io{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.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),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const Po=new WeakMap;function ko(e){let t=Po.get(e);return void 0===t&&(t=new Io(e),Po.set(e,t)),t}function _o(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==u&&s!==f&&re(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&re(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Ao(e){return e.propModifiers.some(e=>e.includes("="))}const Co=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Eo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Mo(e,t){return"state"===e&&"call"===t?Co:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function To(e){if(!o.enableDirectionalInitialSync)return Ao(e)&&re("init=/sync= modifiers require enableDirectionalInitialSync."),Co;const t=null===(n=_o(e,u))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:re(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":re(`Invalid sync modifier value "${e}".`)}(_o(e,f));if("event"===e.bindingType)return null!==t&&"none"!==t&&re("Event bindings only allow init=none."),"call"===s?Eo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===y)return Mo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&re(`Binding type "${e.bindingType}" does not support init=${t}.`),Mo(t??"state",s);const r=ee(e.node);if(null===r)return Mo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||re(`Property "${e.propName}" is not declared by wcBindable.`);const l=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||re(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||re(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Oo(e,t){return"auto"!==t?t:function(e){const t=ta(e.replaceNode.getRootNode());null===t&&re("No state tree found on this root for binding.");const n=hn(e);let o=!1;return t.createState("readonly",e=>{o=e[At](n)}),o}(e)?"state":"element"}let Ro=0,Lo=0;const jo=new WeakMap,Do=new WeakMap,Wo=new WeakMap,Bo=new WeakMap;function zo(e,t){const n=Bo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Bo.set(e,new Set([n,t]))):Bo.set(e,t)}function Fo(e){return Bo.has(e)}function qo(e,t){const n=Bo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function Vo(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))Vo(n,t)}function Uo(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class Ko{root;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}handleMutations(e){const t=[],n=[];for(const o of e)t.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));const o=[];for(const e of t)bo(e)||Vo(e,e=>{qo(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)$o(e)&&!No()||Vo(e,e=>{qo(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&ri(o)}}const Go=new WeakMap;function Ho(e){let t=Go.get(e);return void 0===t&&(t=new Ko(e),Go.set(e,t)),t}function Jo(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function Xo(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class Yo{records=new Set;rowPlan=null;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=jo.get(e);void 0===o||"disposed"===o.phase||"failed"===o.phase?(this.start(e,s,n),r.push(e)):(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(e=>this.shouldApplyState(e))}activate(e,t){if(Uo(t)&&Ho(t),null===this.rowPlan)for(const n of e){const e=jo.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!o.enableDirectionalInitialSync)return Ao(e)&&To(e),!0;const t=jo.get(e);return void 0===t||t.session!==this||(!t.options.registerAddress||"waiting-definition"===t.phase||"failed"!==t.phase&&("active"===t.phase&&this.settleInitialRecord(t),t.initialApplyDone?"state"===t.resolvedAuthority||!t.outputOnlyMember&&!t.observationPending:(t.initialApplyDone=!0,"state"===t.resolvedAuthority)))}getRecord(e){const t=jo.get(e);return t?.session===this?t:null}addTeardown(e,t){const n=jo.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(Xo(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Q(e);null===s&&re(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),zo(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,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=ko(s).wait(t,()=>{if(a())try{Z(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=jo.get(e);void 0!==t&&t.session===this&&this.disposeRecord(t)}dispose(){for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){for(const e of this.records)null!==e.address&&(on(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.records){if("active"!==t.phase)continue;const n=t.info;if(null===t.address&&null===t.patternListIndex)continue;const o="for"===n.bindingType?Zt(n):null;if(null!==t.address?(on(t.address,n),t.address=null):(rn(t.patternPathInfo,t.patternListIndex,n),t.patternPathInfo=null,t.patternListIndex=null),pn(n),en(n),this.registerAddress(t),null!==o){const e=Zt(n);e!==o&&Pt(o)&&It(e,Nt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return Uo(t)?t:null}(e);null!==t&&Ho(t)}handleMutations(e,t,n){for(const n of t)Vo(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)Vo(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&ri(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=jo.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Wo.get(t);void 0===e&&(e=Jo(t),Wo.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;zo(n,this);const o=this.knownMapFor(n);let s=Wo.get(e);void 0===s&&(s=Jo(e),Wo.set(e,s));const r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}initializeRow(e,t){this.rowPlan=e;const n={registerAddress:!1,registerPathInfo:!1,applyOnReconnect:!1},o=e.slots;for(let e=0;e<t.length;e++){const s=t[e],r=o[e],i=s.replaceNode;zo(i,this),this.addKnownRowBinding(i,s,e),this.optionsByBinding.set(s,n);const a={id:++Ro,info:s,generation:++Lo,phase:"active",teardowns:null,session:this,anchor:i,options:n,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:r.policy,resolvedAuthority:r.authority,initialSettled:!0,initialApplyDone:!1,outputOnlyMember:r.policy.outputOnly,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};if(jo.set(s,a),this.records.add(a),r.isEvent){try{Ln(s)}catch(e){throw a.phase="failed",this.runTeardowns(a),this.records.delete(a),e}a.eventAttached=!0}}}activatePlanRows(e,t,n){const o=e.slots;for(let e=0;e<t.length;e++){const s=t[e],r=jo.get(s);if(void 0!==r&&r.session===this){if(r.options.registerAddress=!0,"disposed"===r.phase||"failed"===r.phase){const t=o[e];if(r.generation=++Lo,r.phase="active",r.initialPolicy=t.policy,r.resolvedAuthority=t.authority,r.initialSettled=!0,r.initialApplyDone=!1,r.outputOnlyMember=t.policy.outputOnly,this.records.add(r),t.isEvent){try{Ln(s)}catch(e){throw r.phase="failed",this.runTeardowns(r),this.records.delete(r),e}r.eventAttached=!0}this.registerAddress(r,n);continue}null===r.address&&null===r.patternListIndex&&this.registerAddress(r,n)}else this.initialize([s],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}}addKnownRowBinding(e,t,n){const o=this.knownBindingsByNode.get(e);if(void 0===o)return void this.knownBindingsByNode.set(e,t);if(o instanceof Map)return void o.set("@plan:"+n,t);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,t),this.knownBindingsByNode.set(e,s)}start(e,t,n){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const o=this.optionsByBinding.get(e)??{...t},s={id:++Ro,info:e,generation:++Lo,phase:"discovered",teardowns:null,session:this,anchor:e.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};jo.set(e,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(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;Ln(t)?e.eventAttached=!0:t.propSegments[0]!==g?(zn(t)&&Xo(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(d)){const t=Bn(e),n=Wn(e,t),o=jn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Dn.countOf(n)&&(Dn.remove(n,e)&&jn.delete(n),!0))}return!1}(t)),vn(t)&&Xo(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(d)){const t=wn(e),n=bn(e,t),o=gn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==yn.countOf(n)&&(yn.remove(n,e)&&gn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Vn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const n=function(e,t,n){let o=ao.get(e);void 0===o&&(o=new Map,ao.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&ao.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});Xo(e,n)}!function(e){const t=X(e.node);if(null!==t){const n=Q(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&re(`CustomElementRegistry is unavailable for <${t}>.`))}if(Vn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const t=fo(e),n=ho(e),o=po(e),s=uo(e,t,null!==n,o);let r=ro.get(s);void 0===r&&(r=mo(e.propName,e.statePathName,e.inFilters,n,o),ro.set(s,r)),e.node.addEventListener(t,r),io.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{An(t)&&Xo(e,()=>function(e){if(e.propSegments[0]!==g)return!1;const t=_n.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),_n.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=X(e.info.node);if(null===n)return void t();const o=Q(e.info.node);if(null===o&&re(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=ko(o).wait(n,()=>{if(this.isAlive(e,s))try{Z(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});Xo(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=To(e.info),n=Oo(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void So++;this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending&&(e.observationPending=!1,xo()),t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=ta(e.node.getRootNode());null===o&&re("No state tree found on this root for initial binding sync.");const s=vt(e.node);o.createState("writable",t=>{t[kt](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=Xt(n);if(null!==o){const s=ta(Qt(n,t));null===s&&re("No state tree found on this root for binding.");const r=Lt(s,n.statePathInfo);!function(e,t,n){let o=sn.get(e);void 0===o&&(o=new WeakMap,sn.set(e,o));const s=o.get(t);void 0===s?o.set(t,n):s instanceof Set?s.add(n):s!==n&&o.set(t,new Set([s,n])),null!==St&&St({type:"state:binding-added",absoluteAddress:zt(e,t),binding:n})}(r,o,n),e.patternPathInfo=r,e.patternListIndex=o}else{const o=Zt(n,t);nn(o,n),e.address=o}if(!e.options.registerPathInfo)return;const s=ta(n.replaceNode.getRootNode());null===s&&re("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&jo.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,xo());const t=e.info;if(null!==e.address)try{on(e.address,t),e.address=null,pn(t),en(t)}catch{}else if(null!==e.patternListIndex)try{rn(e.patternPathInfo,e.patternListIndex,t),e.patternPathInfo=null,e.patternListIndex=null,pn(t),en(t)}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=X(e.node);if(null!==t){const n=Q(e.node),o=n?.get(t);if(void 0===o)return}if(Vn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const t=fo(e),n=uo(e,t,null!==ho(e),po(e)),o=ro.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),io.remove(n,e)&&ro.delete(n)}}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{!function(e){if(!e.propName.startsWith(m))return!1;const t=On(e),n=Mn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);e.node.removeEventListener(o,n),0!==Tn.countOf(t)&&(Tn.remove(t,e)&&Mn.delete(t))}(t)}catch{}}}}function Qo(e){let t=Do.get(e);return void 0===t&&(t=new Yo(e),Do.set(e,t)),t}function Zo(e){return jo.get(e)?.session??null}const es=new WeakMap;function ts(e,t){let n=es.get(e);n||(n=new Set,es.set(e,n)),n.add(t)}const ns=new WeakMap;function os(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ss=Object.freeze([]);const rs=new WeakMap;const is=new WeakMap;function as(e){return is.get(e)??[]}function ls(e,t){is.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});let cs=0;function ds(){return`u${(cs++).toString(36)}`}let us=0;class fs{uuid=ds();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(e,t){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._index=t,this._version=us}get index(){return this._index}set index(e){this._index=e,this._version=++us,this.indexes[this.position]=e}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=us),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(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function hs(e,t){return new fs(e,t)}const ps=new WeakMap;function ms(e){return ps.get(e)||null}function gs(e,t){null!==t?ps.set(e,t):ps.delete(e)}const ys=new WeakMap,bs=Object.freeze([]),ws=new Set;function vs(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:bs,s=Array.isArray(n)&&n.length>0?n:bs,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:bs,o=Array.isArray(t)&&t.length>0?t:bs;let s=ys.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=ms(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:ws,deleteIndexSet:new Set(i),addIndexSet:ws};let t=ms(s);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=hs(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:ws,deleteIndexSet:ws,addIndexSet:new Set(t)}}if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}(o,s))return a={oldIndexes:i,newIndexes:i,changeIndexSet:ws,deleteIndexSet:ws,addIndexSet:ws};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}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=hs(e,o);t.push(n),l.add(n)}else{const e=i[d];d!==o&&r.add(e),t.push(e)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:l}}finally{void 0!==a&&(!function(e,t,n){let o=ys.get(e);o||(o=new WeakMap,ys.set(e,o)),o.set(t,n)}(o,s,a),gs(s,a.newIndexes))}}(e,t,n);return function(e){for(let t=0;t<e.length;t++)e[t].index!==t&&(e[t].index=t)}(o.newIndexes),o}function $s(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.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(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?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 e of i)a.add(n[e]);return a}const Ss=new WeakMap;function xs(e){return Ss.get(e)??[]}function Ns(e,t){Ss.set(e,t)}const Is=new WeakMap;function Ps(e){return Is.get(e)??null}function ks(e,t){Is.set(e,t)}const _s=new WeakMap;function As(e){return _s.get(e)??[]}function Cs(e,t){_s.set(e,t)}function Es(e,t){const n=As(e);for(const e of n)$t(e,t)}function Ms(e,t,n){Es(e,t);const o=xs(e),s=Ps(e);null!==s&&s.activate(o,n.rootNode);for(const e of o){if(null===s){nn(Zt(e),e)}(null===s||s.shouldApplyState(e))&&oi(e,n)}}function Ts(e){if(!e.mounted)return;const t=xs(e),n=Ps(e);for(const e of t)if(null!==n)n.disposeBinding(e);else{on(Zt(e),e)}!function(e){const t=As(e);for(const e of t)$t(e,null)}(e)}const Os=new WeakMap,Rs=Object.freeze(new Set);function Ls(e,t){const n=Os.get(e);n?n.add(t):Os.set(e,new Set([t]))}function js(e){const t=Os.get(e);return void 0!==t?t:Rs}function Ds(e,t){const n=Os.get(e);n&&(n.delete(t),0===n.size&&Os.delete(e))}const Ws=new Set(["if","elseif","else","for"]);class Bs{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t,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(e){for(const t of this._childNodeArray)vo(t),e.appendChild(t);this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const e=this._firstNode,t=this._lastNode;if(null===e||null===t||null===e.parentNode)return this._childNodeArray;const n=[];for(let o=e;null!==o;o=o.nextSibling)if(n.push(o),o===t)return n;return this._childNodeArray}mountAfter(e){const t=e.parentNode;if(t){let n=e;for(const e of this._movableNodes()){if(n.nextSibling!==e){vo(e);const o=t;e.parentNode===t&&"function"==typeof o.moveBefore?o.moveBefore(e,n.nextSibling):t.insertBefore(e,n.nextSibling)}n=e}}this._mounted=!0}tryDestroy(){const e=Ps(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRecords();for(const e of this._childNodeArray)yo(e),null!==e.parentNode&&e.parentNode.removeChild(e);const t=xs(this);for(const e of t)if(Ws.has(e.bindingType)){const t=js(e.node);for(const e of t)e.tryDestroy()||e.unmount()}return this._mounted=!1,!0}unmount(){Ps(this)?.dispose();for(const e of this._childNodeArray)yo(e),null!==e.parentNode&&e.parentNode.removeChild(e);const e=xs(this);for(const t of e){if(Ws.has(t.bindingType)){const e=js(t.node);for(const t of e)t.unmount()}pn(t),en(t)}this._mounted=!1}}function zs(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function Fs(e){const t=document.createDocumentFragment(),n=new Bs(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function qs(e,t,n){const o=document.importNode(t.fragment,!0),s=t.nodeInfos,r=new Array(s.length);for(let e=0;e<s.length;e++){const t=ce(o,s[e].nodePath);null===t&&re(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),Je(t),V(t),r[e]=t}const i=n.slots,a=new Array(i.length),l=[];for(let e=0;e<i.length;e++){const t=i[e],n=r[t.nodeIndex],o={...t.template,node:n,replaceNode:n};a[e]=o,t.isIndexBinding&&l.push(o)}const c=function(e,t){const n=new Yo;return n.initializeRow(e,t),n}(n,a),d=new Bs(o);return ks(d,c),Ns(d,a),ls(d,l),Cs(d,r),Ls(e.node,d),d}function Vs(e){void 0!==e.uuid&&null!==e.uuid||re("BindingInfo.uuid is null.");const n=Be(e.uuid);n||re(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&zs(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=ce(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===y||s===g)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==X(r))return null;if("prop"===o&&Vn(r,e.propName))return null;let i;try{i=To({...e,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;n.push({nodeIndex:t,template:e,isEvent:"event"===o,isIndexBinding:e.statePathName in S,policy:i,authority:i.authority})}}return{directional:t,slots:n}}(n)),null!==r)return qs(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=ce(e,s.nodePath);if(null===t&&re(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Ke.has(t))continue;const r=Ge(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new Yo,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new Bs(i,s);ks(l,a.bindingSession),Ns(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in S&&c.push(e);return ls(l,c),Cs(l,a.nodes),Ls(e.node,l),l}const Us=Symbol.for("wcstack.transition-runner");function Ks(e){const t=globalThis[Us];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}const Gs=new WeakSet,Hs=Symbol.for("wcstack.state.view-transition-naming");function Js(){const e=Ks("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Xs(e,t,n){const o=function(e){const t=e.firstNode;if(null===t)return null;const n=e.lastNode;for(let e=t;null!==e;e=e.nextSibling){if(e.nodeType===Node.ELEMENT_NODE)return e;if(e===n)break}return null}(e);if(null===o||Gs.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[Hs]??={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.`)):(Gs.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${t}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${t}`))}const Ys=new WeakMap,Qs=new WeakMap,Zs=new WeakMap,er=new WeakMap;function tr(e,t,n){!function(e,t,n){let o=Qs.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,Qs.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function nr(e,t){Ys.set(e,t)}function or(e,t){let n=Zs.get(e.node);void 0===n&&(n=[],Zs.set(e.node,n)),n.length<1e3?n.push(t):Ds(e.node,t)}function sr(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function rr(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function ir(e,n,s){const r=Boolean(s);let i;const a=js(e.node);i=0===a.size?Vs(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${rr(e)}`),Ts(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${rr(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);Ms(i,vt(e.node),n);const t=Js();null!==t&&Xs(i,"branch",t)}}const ar=new WeakMap,lr=new WeakMap;const cr=new WeakMap;const dr=new WeakMap;function ur(e){return dr.get(e)??[]}const fr=new Set;const hr=Symbol.for("wcstack.trustedTypes.policy");function pr(){const e=globalThis[hr];return null===e||"object"!=typeof e?null:e}let mr;let gr=!1;function yr(e,t){if(gr)return;if(!function(){if(void 0!==mr)return mr;if(!("trustedTypes"in globalThis))return mr=!1,mr;try{document.createElement("div").innerHTML="<i></i>",mr=!1}catch{mr=!0}return mr}())return;gr=!0;const n="function"==typeof pr()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${t}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:e,property:t})}const br={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function wr(e,n,s){if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==s){null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==X(r)&&function(e,t,n){let o=ar.get(e);o||(o=new Map,ar.set(e,o)),o.has(t)||o.set(t,n)}(r,c,d);const t="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let e=!1;try{r[c]=t?function(e){if("string"!=typeof e)return e;const t=pr(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&yr(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=X(e);if(null===n)return null;const o=Q(e)?.get(n);if(void 0===o)return null;const s=ee(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Vn(r,c)){const t=Jn(r,c,e.statePathName),o=Xn(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??to()??Qn(t);if(a.visitedEdges.has(o))null!==St&&St({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=Zn(a,o);no(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Gn++,writtenValue:n};oo.push({receipt:i,node:e});try{return r()}finally{oo.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=br[c];e?e(r,s):(!function(e,t,n){let o=dr.get(e);o||(o=[],dr.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,fr.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));2===i.length&&"object"==typeof d&&null!==d&&null!==X(r)&&(u in d?function(e,t,n,o){let s=cr.get(e);s||(s=new Map,cr.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}(r,c,u,d[u]):function(e,t,n){let o=lr.get(e);o||(o=new Map,lr.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)}(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const vr=new WeakSet;function $r(e,t,n){}const Sr=new WeakMap;function xr(e,t){if(null===e)return!1;const n=Sr.get(e);if(void 0===n||0===n.size)return!1;for(const e of n)if(t===e||t.startsWith(e+s)||e.startsWith(t+s))return!0;return!1}const Nr=new WeakMap;function Ir(e,t){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{t.$postUpdate(e+s+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...r)=>t[n](e+s+o,...r)}return t[o]}return t[e+s+o]}},set:(n,o,r)=>("string"!=typeof o||(t[e+s+o]=r),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Pr=new WeakMap,kr=[];const _r=new WeakMap;let Ar=null;const Cr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Er=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function Mr(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}function Tr(e,t,n){const o=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),r=t.length>0?t+s:"";for(const e of n){if(r.length>0&&!e.startsWith(r))continue;const t=e.slice(r.length);t.length>0&&-1===t.indexOf(s)&&o.push(t)}return o}const Or={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},Rr={binding:"Bound path",watch:"$watch path"};function Lr(e,t,n,o){return`[wcs/index-arity] ${e}("${t}") requires ${"$resolve"===e?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${pe}`}function jr(e,t){return`$setAll("${e}") ${t}`}function Dr(e,t,n){return`[wcs/wildcard-rank] ${e} needs ${t} 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.${pe}`}const Wr=new WeakMap;function Br(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(xr(e.rootNode??null,n))return;const i=G(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=Wr.get(e);return void 0===n&&(n=new Set,Wr.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;const a=function(e,t,n){if(void 0!==Mr(e,t))return Er;const o=G(t).segments;let i=e,a="";for(let t=0;t<o.length;t++){const l=o[t],c=a;if(a=0===t?l:a+s+l,t>0&&t<o.length-1&&void 0!==Mr(e,a))return Cr;if(Object(i)!==i)return Cr;if(l===r){if(!Array.isArray(i)||0===i.length)return Cr;i=i[0];continue}const d=Mr(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:Tr(i,c,n)};if("function"==typeof d.get)return t===o.length-1?Er:Cr;i=d.value}return Er}(t,n,e.getterPaths);"missing"===a.existence&&(function(e,t){return!0===qr.get(e)?.has(t)}(e,n)||("binding"!==o?Ur(e,n,o,a):function(e,t,n){let o=zr.get(e);void 0===o&&(o=new Map,zr.set(e,o));if(o.set(t,n),Fr.has(e))return;Fr.add(e),setTimeout(()=>function(e){Fr.delete(e);const t=zr.get(e);if(void 0===t)return;zr.delete(e);for(const[n,o]of t)Ur(e,n,"binding",o)}(e),0)}(e,n,a)))}const zr=new WeakMap,Fr=new WeakSet,qr=new WeakMap;function Vr(e,t){let n=qr.get(e);void 0===n&&(n=new Set,qr.set(e,n)),n.add(t),zr.get(e)?.delete(t)}function Ur(e,t,n,o){console.warn(`[@wcstack/state] [${Or[n]}] ${Rr[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${he(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${pe}`),null!==St&&St({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}function Kr(e,t){const n=hn(t);if(n.pathInfo.path in S){const e=vt(t.node);return null===e&&re(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&re("ListIndex not found for loopContext:");const n=S[t];void 0===n&&re(`Invalid index name: ${t}`);const o=Gt(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&re(Dr(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[_t](n)}const Gr=new WeakSet;function Hr(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Jr=Object.freeze({[b]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&re("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[w]:function(e,t,n){const o=e.node,s=e.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[v]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;s[o]!==n&&(s[o]=n)},[y]:function(e,t,n){En(n)||re("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=rs.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||re('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=X(e);if(null===t)return null;const n=Q(e)?.get(t);return void 0===n&&re(`Custom element <${t}> is not defined for command binding.`),ee(e)}(r);null===a&&re(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||re(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${he(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),rs.delete(e));const l=new WeakRef(r);let c=null;c=o.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void rs.delete(e);const o=n[i];return"function"!=typeof o&&re(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),rs.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Xr={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!vr.has(e.replaceNode)){vr.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,n,o){const s=e.statePathInfo,i=Xt(e),a=Zt(e),l=Nt(a),c=l.length>0&&!Qs.has(e.node)?[]:l,d=vs(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!==e.node.parentNode){let t=er.get(e.node);if(void 0===t){const n=Ys.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.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}(e.node,n),er.set(e.node,t)}if(t){const t=e.node.parentNode;t.textContent="",t.appendChild(e.node)}}let f=Qs.get(e.node),h=u?1e3-function(e){return Zs.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==f){for(const t of d.deleteIndexSet){const n=f.get(t);void 0!==n&&(h<=0&&n.tryDestroy()?Ds(e.node,n):(Ts(n),n.unmount(),or(e,n),h-=1),u||f.delete(t))}u&&(Qs.delete(e.node),f=void 0)}let p=e.node;const m=G(s.path+"."+r),g=n.stateElement.loopContextStack,y=$s(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&p.isConnected&&(b=document.createDocumentFragment(),qt(b,n.rootNode));const w=t(),v=Js(),$=e.uuid??"",S=Zs.get(e.node);for(const t of d.newIndexes){let o;if(d.addIndexSet.has(t)){const r=un(m,t);g.createLoopContext(r,r=>{if(o=void 0!==S?S.pop():void 0,void 0===o&&(o=Vs(e)),null!==b)w&&b.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${t.index}`)),o.appendTo(b),w&&b.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${t.index}`));else{if(p.nextSibling!==o.firstNode){if(w){const e=document.createComment(`@@wcs-for-start:${$}:${s.path}:${t.index}`);p.parentNode.insertBefore(e,p.nextSibling),p=e}o.mountAfter(p)}if(w){const e=document.createComment(`@@wcs-for-end:${$}:${s.path}:${t.index}`),n=o.lastNode??p;n.parentNode.insertBefore(e,n.nextSibling)}}Ms(o,r,n),null!==v&&Xs(o,"row",v)}),void 0===o&&re(`Content not found for ListIndex: ${t.index} at path "${s.path}"`)}else{if(o=void 0!==f?f.get(t)??null:null,d.changeIndexSet.has(t)){const e=as(o);for(const t of e)oi(t,n)}null===o&&re(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==y&&y.has(t)&&sr(p,o.firstNode)||p.nextSibling===o.firstNode||o.mountAfter(p),e){const e=o,s=un(m,t);g.createLoopContext(s,t=>{Ms(e,t,n)})}}p=o.lastNode||p,void 0===f&&(f=new WeakMap,Qs.set(e.node,f)),f.set(t,o)}Ys.set(e.node,p),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),qt(b,null))},if:ir,else:ir,elseif:ir,radio:function(e,t,n){const o=e.node,s=os(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=os(o.value,e.inFilters),r=Array.isArray(n)?n:ss;o.checked=r.includes(s)}},Yr=new WeakMap,Qr=new WeakMap,Zr=new WeakMap;function ei(){}function ti(e){const t=e.replaceNode,n=e.propSegments[0];return function(e,t){return!0===es.get(e)?.has(t)}(t,n)?$r:function(e,t){return!0===ns.get(e)?.has(t)}(t,n)?ei:wr}function ni(e,t){const n=os(Kr(t.state,e),e.outFilters);if(!0===Qr.get(e))return void t.deferredSelectBindings.push({binding:e,value:n,stateElement:t.stateElement});let o=Yr.get(e);if(void 0===o){if(Yr.has(e))return o=ti(e),o===$r&&Yr.set(e,o),void o(e,t,n);if(o=Xr[e.bindingType],void 0===o){const t=e.propSegments[0];if(o=Jr[t],Yr.set(e,o),void 0===o){X(e.replaceNode)?(o=ti(e),o===$r&&Yr.set(e,o)):(o=wr,Yr.set(e,o))}}if(o===wr){if("SELECT"===e.node.tagName){const o=e.propSegments[0];if("value"===o||"selectedIndex"===o)return t.deferredSelectBindings.push({binding:e,value:n,stateElement:t.stateElement}),void Qr.set(e,!0)}}o(e,t,n)}else o(e,t,n)}function oi(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=Zt(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=Zo(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Zr.get(e)){const t=X(e.replaceNode);if(t&&void 0===Q(e.replaceNode)?.get(t))return void function(e,t){if(Gr.has(e))return;Gr.add(e);const n=()=>{Gr.delete(e);const t=Zo(e);(null===t||t.shouldApplyState(e))&&ri([e])},o=n=>{Gr.delete(e),Hr(t,n)},s=Zo(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Gr.delete(e),r()})||(Gr.delete(e),r()))}const r=Q(e.replaceNode);if(null===r)return Gr.delete(e),void Hr(t,new Error("CustomElementRegistry is unavailable."));ko(r).wait(t,()=>{e.replaceNode.isConnected?n():Gr.delete(e)},o)}(e,t);Zr.set(e,!0)}if(!0===t.sameRootVerified)return void ni(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Vt(o),null===o&&re("Root node for fragment not found for binding.")),o!==t.rootNode){const n=ta(o);null===n&&re("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};ni(e,r)})}else ni(e,t)}function si(e,t,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:e.statePathName,bindingType:e.bindingType,node:e.node},r=o.get(n);void 0===r?o.set(n,[{error:t,info:s}]):r.push({error:t,info:s})}else console.error(`[@wcstack/state] binding "${e.bindingType}: ${e.statePathName}" failed to apply; the rest of this batch continues.`,{node:e.node,error:t});null!==St&&St({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function ri(e,t){let n=0;const s=new Set,r=new Map,i=new Map,a=[],l=new Map;for(;n<e.length;){let c=e[n];if(!1===c.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${c.bindingType} ${c.statePathName} on ${c.node.nodeName}`,c),n++;continue}let d=c.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Vt(d),null===d&&re("Root node for fragment not found for binding."));const u=ta(d);null===u&&re("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{oi(c,f)}catch(e){si(c,e,u,l)}n++;const t=e[n];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;c=t}})}for(const{binding:e,value:n,stateElement:o}of a)try{wr(e,{propagationContextByBinding:t},n)}catch(t){si(e,t,o??null,l)}for(const[e,t]of r.entries())It(e,t);for(const[e,t]of i.entries())e.createState("writable",e=>{e[Tt](Array.from(t))});for(const[e,t]of l.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Ot](n,o)}catch(e){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:e,original:n,node:o.node})}})}function ii(e,t,n){const[o,s,r]=He(e,n),i=Qo(e);for(const e of o)$t(e,t);ri(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=Xe(o);0!==e.length&&($t(o.node,t),ri(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const ai=/\{\{\s*(.+?)\s*\}\}/g,li=new Set(["SCRIPT","STYLE"]);function ci(e){if(!o.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&li.has(e.parentElement.tagName)||di(e)}(e);const t=Array.from(e.querySelectorAll("template"));for(const e of t)if("http://www.w3.org/2000/svg"===e.namespaceURI){const t=document.createElement("template"),n=Array.from(e.childNodes);for(let e=0;e<n.length;e++){const o=n[e];t.content.appendChild(o)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),ci(t.content)}else ci(e.content)}function di(e){const t=e.data;if(ai.lastIndex=0,!ai.test(t))return;ai.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=ai.exec(t));){o.index>s&&n.appendChild(document.createTextNode(t.slice(s,o.index)));const e=o[1];n.appendChild(document.createComment(`@@: ${e}`)),s=o.index+o[0].length}s<t.length&&n.appendChild(document.createTextNode(t.slice(s))),e.parentNode.replaceChild(n,e)}let ui;function fi(){if(ui)return ui;const e=[],t=Ne("not",e)(Se);return ui={filterName:"not",args:e,filterFn:t},ui}const hi=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function pi(e,t){const n=t+s+r,o=e.indexOf("|");let i,a;if(-1!==o?(i=e.slice(0,o).trim(),a=e.slice(o)):(i=e.trim(),a=""),"."===i)i=n;else{if(!i.startsWith("."))return e;i=n+s+i.slice(1)}return a.length>0?i+a:i}function mi(e,t){const n=hi.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+pi(s,t)+r}function gi(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=pi(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function yi(e,t){return gi(e,t)}function bi(e,t){const n=o.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=mi(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=gi(r,t);e!==r&&o.setAttribute(n,e)}}}function wi(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}function vi(e){const t=[],n=Ue(e);for(const e of n){const n=ze(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:wi(o),parseBindTextResults:n})}return t}function $i(e){const t=Array.from(e.childNodes);for(const n of t)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&e.removeChild(n)}}const Si=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),xi=fi();function Ni(e,t){const n=t.outFilters;return{...t,outFilters:[...n,xi],bindingType:e}}function Ii(e,t,n,o,s,r=!0){$i(t),"string"==typeof o&&bi(t,o),Pi(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:vi(t)};return void 0!==s&&function(e,t,n){for(const o of e)for(let e=0;e<o.parseBindTextResults.length;e++){const s=o.parseBindTextResults[e];null==s.uuid&&(o.parseBindTextResults[e]=t(s,n))}}(i.nodeInfos,s,o),i}function Pi(e,t,n,s){const r=o.commentElsePrefix,i=qe(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=yi(i,n));let a=Me(i)[0];const d=Si.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=ds();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&re("'else' binding found without preceding 'if' or 'elseif' binding."),a=Ni("else",l.parseBindTextResult),p=Ii(e,f,a,m,s,!1),We(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:wi(o),parseBindTextResults:ze(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&re("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ii(e,f,a,m,s),We(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=ds(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Ni("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:wi(n),parseBindTextResults:ze(n)}),We(o,e,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:wi(g),parseBindTextResults:ze(g)})):t.replaceWith(g)}else{p=Ii(e,f,a,m,s),We(h,e,p);const n=document.createComment(`@@${d}:${h}`);t.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}async function ki(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Q(e);null===s&&re(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(Fe(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function _i(e){if(e===document)await ki(document),ci(document),Pi(document,document),ii(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await q(t.host),await ki(t),ci(t),Pi(t,t),ii(t,null)}}const Ai="2.2.0",Ci="undefined"==typeof HTMLElement?class{}:HTMLElement,Ei=/^@@wcs-(?:for|if|elseif|else):[^-]/,Mi=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,Ti=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Oi=/^@@wcs-text-start:(.+)$/;function Ri(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Li extends Ci{_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(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=Ai.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static find(e){const t=o.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const[e,o]of Object.entries(t))e.startsWith("$")||"function"==typeof o||(n[e]=o);return n}static buildContent(e,t){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=Ri(JSON.stringify(t)),e.appendChild(n);const s=Array.from(De.keys());for(const t of s){const n=Be(t);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",t);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),e.appendChild(s)}const r=Array.from(fr);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=ur(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=Ri(JSON.stringify(t)),e.appendChild(n)}}fr.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Mi.test(e.data)||Ti.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;Ei.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=Oi.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(o.tagNames.ssr),s=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;Mi.test(e.data)&&i.push(e)}for(const e of i){const t=Mi.exec(e.data),n=`@@wcs-${t[1]}-end:${t[2]}`;let o=e.nextSibling;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=e}e.remove()}Li.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(Ei.test(e.data)){const t=e.data.split(":")[1];l.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of l){const n=s.get(t);if(n){const t=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&t.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const c=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of c)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const ji=new Set(["for","if","elseif","else"]);function Di(e){const t=new Yo;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=He(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function Wi(e,t,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function Bi(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Me(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,fi()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;$i(a),"string"==typeof l&&bi(a,l),Pi(n,a,l);We(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:vi(a)})}}async function zi(e){await ki(e);const t=e.querySelectorAll(o.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${Ai}". Falling back to full render.`),Li.cleanupDom(e),!1}for(const n of t)Bi(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=Mi.exec(e.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=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:l,nodes:c})}return t}(document.body);!function(e,t){const n=new Map;for(const o of t){if(0===o.nodes.length)continue;const t=Fs(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=Di(o.nodes);ks(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");Ns(t,s),Cs(t,i);const l=[];for(const e of s)e.statePathName in S&&l.push(e);if(ls(t,l),"for"===o.type&&null!==o.index){const i=Wi(e,"for",o.uuid);if(i){const e=hs(null,o.index);tr(i,e,t),nr(i,o.nodes[o.nodes.length-1]),Ls(i,t),Es(t,un(G(o.path+"."+r),e)),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let l=n.get(o.uuid);l||(l=[],n.set(o.uuid,l)),l.push(e)}}else{const n=Wi(e,o.type,o.uuid);n&&(Ls(n,t),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[t,o]of n){const n=Wi(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=Be(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ta(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&gs(t,o)})}}(document.body,n),Li.removeBlockBoundaryComments(document.body);const s=[];for(const e of t)e.parentNode&&(s.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());Li.restoreTextBindings(document.body);const[i,a]=He(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||($t(e,null),t.setAttribute("data-wcs-completed",""))}else $t(e,null);const l=[],c=[],d=Qo(document.body).initialize(a);for(const e of d)if("event"!==e.bindingType)if(ji.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(r))continue;l.push(e)}for(const e of c)if("for"===e.bindingType){const t=Zt(e),n=ta(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&It(t,o)})}ri(l);for(const{el:e,parent:t,next:n}of s)t.insertBefore(e,n);const u=e.querySelectorAll(o.tagNames.ssr);for(const t of u){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const f=e.querySelectorAll("[data-wcs-completed]");for(const e of f)e.removeAttribute("data-wcs-completed");return!0}const Fi=Symbol.for("wcstack.binder");const qi=Symbol.for("wcstack.binder.pending"),Vi=Symbol.for("wcstack.binder.taken");function Ui(){const e=function(){const e=globalThis[Fi];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;const t=function(){const e=globalThis;let t=e[qi];return void 0===t&&(t=[],e[qi]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[Vi];return void 0===t&&(t=new WeakSet,e[Vi]=t),t}();for(const t of n)o.add(t),e.bind(t)}function Ki(e){if(Fo(e))return!0;if(!Gi(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(`[${o.bindAttributeName}]`);return null!==t&&Fo(t)}function Gi(e){return 1===e.nodeType}function Hi(e){if(Ki(e))return;ci(e),Pi(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);ii(t&&s?n:e,null)}const Ji=[];function Xi(){const e=Ji.splice(0,Ji.length);for(const t of e)Hi(t);Ui()}const Yi={protocol:"wcs-binder",version:1,bind:function(e){var t;Gi(e)&&!Ki(e)&&(t=e.getRootNode(),oa.has(t)?Hi(e):Ji.push(e))}};const Qi=new WeakMap,Zi=new WeakMap,ea=new Set;function ta(e){return Qi.get(e)??null}function na(e){return Zi.get(e)??Promise.resolve()}const oa=new WeakSet;function sa(e){oa.add(e)}function ra(e,n){const s=Qi.get(e);if(null===n){if(void 0===s)return;Qi.delete(e),ea.delete(s),null!==St&&St({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(void 0===s){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await zi(e)||await _i(e)}else await _i(e);sa(e),Xi(),t()}catch(e){n(e)}})});Zi.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await _i(e),sa(e),Xi(),t()}catch(e){n(e)}})});Zi.set(e,t)}}void 0!==s&&re('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="...">.'),Qi.set(e,n),ea.add(n),function(e,t){const n=_r.get(e);if(void 0===n||0===n.length||null===Ar)return;_r.delete(e);const o=Ar;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,n),null!==St&&St({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}let ia=0,aa=0;const la=[];function ca(e,t=0){const n=la.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?la.push(o):la.splice(n,0,o)}function da(e){queueMicrotask(()=>{throw e})}const ua=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(e,t=null){ia>aa&&(aa=ia);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&queueMicrotask(()=>{const e=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(e)})}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e){const n=new Map;for(const t of e){const e=n.get(t.absoluteAddress);null!==St&&null!=e&&null!==t.context&&e.transactionId!==t.context.transactionId&&St({type:"propagation:coalesced",absoluteAddress:t.absoluteAddress,droppedTransactionId:e.transactionId,winnerTransactionId:t.context.transactionId}),n.set(t.absoluteAddress,t.context)}const o=[],s=new Map;for(const[e,t]of n){if(null!==t&&t.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,transactionId:t.transactionId,hop:t.hop,maxHops:32}),null!==St&&St({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop});continue}const n=an(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(o.push(e),null!==t&&s.set(e,t));else!1!==n.replaceNode.isConnected&&(o.push(n),null!==t&&s.set(n,t))}try{const e=()=>{s.size>0?ri(o,s):ri(o)};if(t()||0===o.length)e();else{const t=function(e,t,n){const o=Ks(e);if(null!==o)return o.run(t,{source:e,types:n});t()}("state",e);void 0!==t&&t.catch(da)}}finally{!function(e){for(const t of la.slice())t.listener(e)}(new Set(n.keys()))}}};function fa(){return ua}const ha=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function pa(e,t,n,o){return{node:e,propName:t.propName,statePathName:t.statePathName,bindingType:t.bindingType,inFilters:t.inFilters,outFilters:t.outFilters,origin:n,raw:o}}const ma="__WCSTACK_DEVTOOLS_HOOK__";function ga(){const e=globalThis,t=e[ma];if(void 0!==t)return 2!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 2. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:2,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[ma]=n,n}const ya=e=>{null!==St&&St({type:"state:update-batch",addresses:e})};function ba(e){const t=null!==St;!function(e){St=e}(e);const n=null!==e;n&&!t?ca(ya,0):!n&&t&&function(e){const t=la.findIndex(t=>t.listener===e);-1!==t&&la.splice(t,1)}(ya)}function wa(e){return{rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency,watchPaths:e.watchPaths??null,keyedListPaths:void 0===e.listKeys||null===e.listKeys?null:new Set(e.listKeys.keys())}}function va(e){return ta(e)??re("devtools: no state tree on this root")}let $a=null;function Sa(){if(t())return;if(null!==$a)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Ai,getStateElements(){const e=[];for(const t of ea)e.push(wa(t));return e},overlays:e=>function(e){const t=mt.get(e);if(void 0===t)return[];const n=[];for(const e of t.values()){const t=e.deref();void 0!==t&&n.push(t)}return n}(va(e)).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join("."),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]})),keys(e){const t=va(e),n=[];return t.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}n.push(t)}}),n},read(e,t,n){let o;return va(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){va(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>function(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=[...e.inFilters,...e.outFilters].map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=Be(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(pa(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=le(t,Me(n));for(const o of e)r(pa(t,o,"attribute",n))}catch{}continue}const t=ha.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=Be(s);if(null===a){if(n===o.commentTextPrefix)try{r(pa(e,je(s),"comment",s))}catch{}}else r(pa(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:ba};$a=e,ga().register(e)}const xa={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Ai),Li.buildContent(o,Li.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const Na="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ia=0;async function Pa(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Ia}\n`;let s=!1;const r=e=>{e.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+o],{type:"application/javascript"}),s=URL.createObjectURL(t);try{n=await import(s)}finally{URL.revokeObjectURL(s)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+o)));n=await import(`data:application/javascript;base64,${t}`)}}catch(e){throw new Error(function(e,t,n){const o=t?.message??String(t);return n?`The inline <script> of state "${e}" 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 ${Na}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Na}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function ka(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){re(`Failed to load script file: ${e}`)}}class _a{_loopContextStack=Array(i).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&re("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=i&&re("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&&re("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const e=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==e&&re("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&&re(`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=t(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 Aa=new WeakMap;function Ca(e,t){let n=Aa.get(e);void 0===n&&(n=new Map,Aa.set(e,n));let o=n.get(t);return void 0===o&&(o=new Cn(t,e),n.set(t,o)),o}const Ea=new WeakMap;function Ma(e){const t=Ea.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return Ca(e,n)},has:(t,n)=>"string"==typeof n&&e.commandTokenNames.has(n),ownKeys:()=>Array.from(e.commandTokenNames),getOwnPropertyDescriptor(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Ca(e,n)}},set(){re("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){re("$command namespace is read-only; deleting from it is not allowed.")}});return Ea.set(e,n),n}const Ta=Symbol("wcs-stream-last-notified-uncertain"),Oa=new WeakMap;function Ra(e,t){const n=Oa.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function La(e,t){const n=Oa.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Ta,error:Object.is(o.error,null)?null:Ta})}const ja=new Set;function Da(e){ja.delete(e)}const Wa=new WeakMap;function Ba(e){return Wa.get(e)??new Map}function za(e){Da(e);const t=Wa.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,La(e,n.name)}const Fa=(e,t)=>t,qa=new Set;function Va(e,t){const n=t[O];if(void 0===n)return void Ra(e,qa);"object"==typeof n&&null!==n||re(`${O} 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&&re(`${O} entry name must be a non-empty string.`),i.includes(s)&&re(`${O} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&re(`${O} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&re(`${O} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&re(`${O} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(i)&&re(`${O} entry "${i}" conflicts with a getter declared on the state.`),e.setterPaths.has(i)&&re(`${O} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||re(`${O} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&re(`${O} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&re(`${O} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&re(`${O} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&re(`${O} 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 t||(t[i]=c.definition.initial),o.set(i,c)}!function(e,t){Wa.set(e,t)}(e,o),Ra(e,new Set(o.keys()))}const Ua=new WeakMap,Ka=new WeakMap;function Ga(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Ba(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Ba(e).has(n),ownKeys:()=>Array.from(Ba(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Ba(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){re(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){re(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Ha(e){const t=Ua.get(e);if(void 0!==t)return t;const n=Ga(e,j,e=>e.status);return Ua.set(e,n),n}function Ja(e){const t=Ka.get(e);if(void 0!==t)return t;const n=Ga(e,D,e=>e.error);return Ka.set(e,n),n}function Xa(e){Ua.delete(e),Ka.delete(e)}let Ya=null;async function Qa(e,t,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 e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;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 e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",i)}}function Za(e){const t=Ba(e);if(0!==t.size){!function(e){ja.add(e)}(e);for(const n of t.values())el(e,n)}}function el(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=Ya,r=new Set;let i;Ya=r;try{e.createState("readonly",e=>{i=n(e)})}finally{Ya=o}i instanceof Promise&&re(`${O} entry "${t.name}" args must be synchronous (it returned a Promise).`);const a=`${j}${s}${t.name}`,l=`${D}${s}${t.name}`;for(const n of r){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==a&&o.path!==l||re(`${O} entry "${t.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&&re(`${O} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=r,i}(e,t);e.createState("writable",e=>{e[t.name]=t.definition.initial}),tl(e,t,"active",null);const r=t.definition,i={fold(n){e.createState("writable",e=>{e[t.name]=r.fold(e[t.name],n)})},done(){tl(e,t,"done",null)},fail(o){tl(e,t,"error",o),n.abort()}};Qa(r.source,o,n.signal,i)}function tl(e,t,n,o){t.status=n,t.error=o;const r=function(e,t){return Oa.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),i=r.status!==n,a=!Object.is(r.error,o);(i||a)&&(!function(e,t,n,o){let s=Oa.get(e);void 0===s&&(s=new Map,Oa.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{i&&e.$postUpdate(`${j}${s}${t.name}`),a&&e.$postUpdate(`${D}${s}${t.name}`)}))}ca(function(e){const t=ja;if(0===t.size)return;const n=[];for(const o of t)for(const t of Ba(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&Ba(e).get(o.name)===o)try{el(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Ba(e).get(o.name)===o&&tl(e,o,"error",n)}},20);const nl=new WeakMap,ol=new WeakMap,sl=new Set,rl=new Map;function il(e){return nl.get(e)??rl}function al(){return sl}const ll=new Map;function cl(e){return ol.get(e)??ll}function dl(e){0===e.length&&re(`[wcs/watch-declaration-invalid] ${R} entry name must be a non-empty state path.`),e.startsWith("$")&&re(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must not start with "$" (reserved namespace).${pe}`),e.includes("@")&&re(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${pe}`),e in Object.prototype&&re(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=G(e);for(const n of t.segments)0===n.length&&re(`[wcs/watch-declaration-invalid] ${R} entry "${e}" has an empty path segment.${pe}`);return t.wildcardCount>128&&re(`[wcs/watch-declaration-invalid] ${R} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function ul(e,t){const n=t[R];if(void 0===n)return null;"object"==typeof n&&null!==n||re(`[wcs/watch-declaration-invalid] ${R} must be an object mapping state paths to handler functions.${pe}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&re(`[wcs/watch-declaration-invalid] ${R} entry "${t}" must be a function.${pe}`);const n=dl(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){nl.set(e,t)}(e,o),s.size>0?s:null}const fl=new WeakMap;function hl(e,t,n){let o=fl.get(e);void 0===o&&(o=new Map,fl.set(e,o)),o.set(t,n)}const pl=new Map;function ml(e){0===il(e).size&&0===cl(e).size||(function(e){sl.add(e)}(e),function(e){const t=[];for(const n of il(e).values())yl(e,n)&&t.push(n);for(const n of cl(e).values())for(const o of n)yl(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{hl(e,gl(e,o),n[o.path])}catch(t){wl(e,o.path,"prime",t)}})}(e))}function gl(e,t){return zt(Lt(e,t.pathInfo),null)}function yl(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const bl={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function wl(e,t,n,o){console.error(`[@wcstack/state] $watch ${bl[n]} "${t}" threw.`,o),null!==St&&St({type:"state:watch-error",phase:n,path:t,error:o})}function vl(e,t){if(e.entry.order!==t.entry.order)return e.entry.order-t.entry.order;const n=Math.min(e.indexes.length,t.indexes.length);for(let o=0;o<n;o++)if(e.indexes[o]!==t.indexes[o])return e.indexes[o]-t.indexes[o];return e.indexes.length-t.indexes.length}function $l(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=yl(t,n);try{t.createState("writable",e=>{let i;try{i=function(e,t,n){if(0===t.pathInfo.wildcardCount)return e[t.path];return e.$resolve(t.path,n)}(e,n,s)}catch(e){return void wl(0,n.path,"evaluate",e)}const a=r?function(e,t){return fl.get(e)?.get(t)}(t,o):function(e){return pl.get(e)}(o);r&&hl(t,o,i),null!==St&&St({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){wl(0,n.path,"handler",e)}}function Sl(e){return function(){const t=this.stateElement;if(!t)return;if(!0!==t.initialized)return;let n;try{t.createState("readonly",t=>{n=t[e]})}catch(t){return void console.warn(`[@wcstack/state] DCC getter "${e}" failed:`,t)}return n}}function xl(e){return function(t){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})}):n.createState("writable",n=>{n[e]=t}))}}function Nl(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[e](...t)}).then(()=>o)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[e](...t)}),o})}}function Il(e){return e.startsWith("$")}function Pl(e){const t=[];let n=e;for(;n&&n!==Object.prototype;)t.push(n),n=Object.getPrototypeOf(n);const o={};for(let e=t.length-1;e>=0;e--)Object.assign(o,Object.getOwnPropertyDescriptors(t[e]));return o}function kl(e,t){return Object.keys(e).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof e[n].value;return"method"===t?o:!o})}function _l(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||re(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||re(`${t} entries must be non-empty strings.`),e.startsWith("$")&&re(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&re(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Al(e){const t=_l(e,_)??[],n=_l(e,A)??[],o=Pl(e),s=function(e){const t=e[O];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),r=[];for(const e of t){const t=o[e];if(void 0===t){if(s.has(e)){r.push(e);continue}re(`${_} entry "${e}" is not declared on the state.${he(e,kl(o,"value"))}`)}"function"==typeof t.value&&re(`${_} entry "${e}" is a method. Declare it in ${A} instead.`)}for(const e of n){const t=o[e];void 0===t&&re(`${A} entry "${e}" is not declared on the state.${he(e,kl(o,"method"))}`),"function"!=typeof t.value&&re(`${A} entry "${e}" is not a method. Declare it in ${_} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}ca(function(e){const t=al();try{if(0===t.size)return;const n=function(){const e=aa;return aa=0,e}();if(n>32){const t=Array.from(e,e=>e.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; watch handlers for this batch were skipped.",{maxDepth:32,paths:t}),void(null!==St&&St({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=il(e).get(s),i=cl(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=Ht(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(vl),function(e){ia=e+1}(n);try{for(const e of o){if(!t.has(e.stateElement))continue;const n=il(e.stateElement).get(e.entry.path)===e.entry,o=!0===cl(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&$l(e)}}finally{ia=0}}finally{pl.clear()}},10);const Cl=new Map;class El{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice();let o=0,s=0,r=0,i="none";const a=[];for(let e=0;e<t.length;e++){const i=t[e];if("*"===i)n[e]="*",a.push(null),o++,r++;else{const t=Number(i);Number.isNaN(t)||(n[e]="*",a.push(t),s++,r++)}}const l=G(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=e,this.segments=t,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Ml(e){let t;return Cl.get(e)??(Cl.set(e,t=new El(e)),t)}function Tl(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[t];return void 0===o||null===n.listIndex?null:Gt(n.listIndex,o,n.pathInfo.wildcardCount)}const Ol=new WeakMap;function Rl(e,t){null===t?Ol.delete(e):Ol.set(e,t)}function Ll(e){const t=Ol.get(e);t&&(t.dirty=!0)}function jl(e,t){if(!e.untracking&&e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=Kt(t.pathInfo,o);if(e>0){let r=!1;const i=t.listIndex??null,a=n.listIndex??null;for(let n=0;n<e;n++){if((null!==i?Gt(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?Gt(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}const Dl=new WeakMap;class Wl{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return un(G(this.markerParentPath+s+e),this.listIndex)}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(dt(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=dt(e,t),a=ft(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a=dt(e,t),l=ft(0,t,a,r,n);return o[s](a,l,...i)}}return this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return jl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[dt(this.record,t)]}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n);const s=this.accessorNameFor(t);if(void 0!==s){this.record.setterKeys.has(s)||re(`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(t)),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(e,t)?(e[t]=n,!0):(this.receiver[dt(this.record,t)]=n,!0)}has(e,t){if("string"!=typeof t)return Reflect.has(e,t);if("$"===t[0]||"#"===t[0])return!1;if(void 0!==this.accessorNameFor(t))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return!0;if("function"==typeof this.record.stateObject[t])return!0}try{return dt(this.record,t),!0}catch{return!1}}}function Bl(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Dl.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Dl.set(e,n)),null===t)return n.noIndex??={...e.privateSnapshot};let o=n.byListIndex.get(t);return void 0===o&&(o={...e.privateSnapshot},n.byListIndex.set(t,o)),o}(e,t.listIndex):{};return new Proxy(i,new Wl(e,s,t.listIndex,r,n,o))}function zl(e){const t=e.parentStateElement,n=(t,n)=>{const o=vt(e.component);let s;return t[kt](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(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(dt(e,t))):(n,o,...r)=>{const i=dt(e,n),a=vt(e.component)?.listIndex.indexes??[],l=ft(0,n,i,"$resolve"===t?o??[]:o,a),c="$setAll"===t||"$resolve"===t&&r.length>0?"writable":"readonly";return s(c,e=>e[t](i,l,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:dt(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:dt(e,s)]=r})}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return dt(e,n),!0}catch{return!1}}})}const Fl=new WeakMap,ql=new Set;function Vl(e,t,n,o){let s=Fl.get(e);if(void 0===s){if(!o)return null;s=new Map,Fl.set(e,s)}let r=s.get(t);if(void 0===r){if(!o)return null;r=new Map,s.set(t,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function Ul(e,t){if(!e.component.isConnected)return!1;const n=vt(e.component)?.listIndex??null;if(null===t)return null===n;let o=n;for(;null!==o;){if(o===t)return!0;o=o.parentListIndex}return!1}function Kl(e,t,n,o){const r=Vl(e,t,n,!1);if(null===r)return null;const i=null===o?r.noIndex:r.byListIndex.get(o)??null;if(null!==i){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&Ul(n,t)?n:null}(i,o);if(null!==e)return{record:e,entry:i.entry}}let a=null,l=null;for(const e of r.holders){const i=e.ref.deref();void 0!==i?Ul(i,o)&&(null!==l&&re(`[wcs/mount-export-ambiguous] "${t}${s}${n}" is exported by two mounted components on the same instance: <${l.component.tagName.toLowerCase()}> and <${i.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),a=e,l=i):r.holders.delete(e)}return null===a||null===l?null:(null===o?r.noIndex=a:r.byListIndex.set(o,a),{record:l,entry:a.entry})}function Gl(e){const t=e.parentStateElement,n=vt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[kt](n,()=>{e.$postUpdate(o.exportedPath)})})}function Hl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function Jl(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}function Xl(e,t,n,o,s){const i=t.pathInfo.segments[0];if(i===E)return Jl(Ma(s),t.pathInfo.segments);if(i===j)return Jl(Ha(s),t.pathInfo.segments);if(i===D)return Jl(Ja(s),t.pathInfo.segments);if(!0===s.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const e=bt(s,t.pathInfo.path);if(null!==e)return Bl(e,t,n,o)}if(!(t.pathInfo.path in e)){if(null===t.parentAddress&&xr(function(e){return e.rootNode??null}(s),t.pathInfo.path))return;const i=t.parentAddress??re(function(e,t,n){return`[${Or.binding}] Path "${e}" does not exist on the state tree.${he(e,Tr(t,"",n))}${pe}`}(t.pathInfo.path,e,s.getterPaths)),a=Ql(e,i,n,o);if(null==a)return;const l=t.pathInfo.segments[t.pathInfo.segments.length-1];if(!0===s.hasMounts&&l!==r&&!(l in Object(a))){const e=Kl(s,i.pathInfo.path,l,t.listIndex);if(null!==e)return function(e,t,n,o,s){const r=Bl(e,un(G(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(e.record,e.entry,t.listIndex,n,o)}if(l===r){const e=t.listIndex?.index??re(Dr(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(a,e)}return Reflect.get(a,l)}if(!s.getterPaths.has(t.pathInfo.path))return Reflect.get(e,t.pathInfo.path);o.pushAddress(t);try{return Reflect.get(e,t.pathInfo.path,n)}finally{o.popAddress()}}function Yl(e,t,n,o,s){const r=zt(Lt(s,t.pathInfo),t.listIndex),i=function(e){return Ol.get(e)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Xl(e,t,n,o,s);return Rl(r,{value:a,dirty:!1}),a}function Ql(e,t,n,o){jl(o,t),function(e,t){if(null===Ya)return;const n=Lt(e,t.pathInfo);Ya.add(zt(n,t.listIndex))}(o.stateElement,t);const s=o.stateElement;return Hl(s,t)?Yl(e,t,n,o,s):Xl(e,t,n,o,s)}const Zl=new WeakMap;function ec(e,t,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=un(f,r),p=Zl.get(h),m=Ql(e,h,t,n),g=vs(r,p,m).newIndexes,y=l[c]??null;if(i.set(h,m),null===y)for(let e=0;e<g.length;e++){const t=g[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=g[y]??re(`ListIndex not found at index ${y} of ${f.path}`);s+1<o.length?a(o,s+1,e,l,c+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[e,t]of i.entries())Zl.set(e,t);return l}function tc(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=ms(Ql(e,un(a,r),t,n));null==l&&re(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??re(`ListIndex not found at index ${c} of ${a.path}`)}return r}function nc(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}function oc(e,t,n,o){"object"==typeof e&&null!==e||re(`${L} list "${t}": ${n} row at index ${o} must be a plain object (got ${null===e?"null":typeof e}).`);const s=Object.getPrototypeOf(e);s!==Object.prototype&&null!==s&&re(`${L} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function sc(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&re(`${L} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function rc(e,t,n,o){const s=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){const a=e[i];oc(a,n,o,i);const l=sc(a,t,n,o,i);r.has(l)&&re(`${L} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function ic(e,t){const n=[];for(const o of Object.keys(t))Object.is(e[o],t[o])||n.push({field:o,value:t[o]});for(const o of Object.keys(e))Object.hasOwn(t,o)||null==e[o]||n.push({field:o,value:null});return n}function ac(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const i=Ql(e,s,n,o);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=t.pathInfo.lastSegment;if(a===r){const e=t.listIndex?.index;return"number"==typeof e&&e in i}return a in i}const lc=new WeakMap;function cc(e,t){null===t?lc.delete(e):lc.set(e,t)}function dc(e,t,n){const s=G(e.wildcardParentPaths[t]),r=Lt(e.stateElement,s),i=un(s,n),a=Nt(zt(r,n)),l=e.stateProxy[_t](i),c=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${t}`),[]}}(vs(i.listIndex,a,l),e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)dc(e,t+1,n)}const uc=[];function fc(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:uc,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:uc,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const hc=[];function pc(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return hc;let r=null;const i=t+s;for(const e of o){if(e!==t&&!e.startsWith(i))continue;const o=G(e);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??hc}function mc(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const i of s){const s=G(i);if(e.listPathSet.has(o)&&s.lastSegment===r){const r=e.stateProxy[_t](t),a=Nt(zt(Lt(e.stateElement,t.pathInfo),t.listIndex)),l=fc(e,o,0,0,vs(t.listIndex,a,r));for(const t of l.fullRows){const o=un(s,t);e.result.add(o),n.push(o)}if(null!==l.movedRows){const t=pc(e,i,s);if(null===t)for(const t of l.movedRows){const o=un(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of l.movedRows)for(const s of t){const t=un(s,o);e.result.add(t),n.push(t)}}}else{const o=un(s,t.listIndex);e.result.add(o),n.push(o)}}const i=e.dynamicMap.get(o);if(i)for(const o of i){const s=G(o),r=[];if(s.wildcardCount>0){const n=Kt(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&re(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=Gt(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};dc(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&re(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=Gt(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=un(s,t);e.result.add(o),n.push(o)}}}function gc(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&re(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,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(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),n(a),i.length=0,mc(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}(u,t,a),Array.from(u.result)}function yc(e,t,n,o,s){const r=e.watchPaths;null!=r&&s&&r.has(t)&&function(e,t){pl.has(e)||pl.set(e,t)}(n,o)}function bc(e,t,n,s,r){const i=o.enablePropagationContext?to()??Qn(-1):null,a=fa();a.enqueueAbsoluteAddress(t,i),gc(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=zt(Lt(s.stateElement,t.pathInfo),t.listIndex);Ll(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function wc(e,t,n,o,s){s&&(e.getterPaths.has(t)?Ll(n):Rl(n,{value:o,dirty:!1}))}function vc(e,t,n,o,s,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const a=Ql(e,n,s,i),l=t.pathInfo.segments[t.pathInfo.segments.length-1];if(l===r){const e=t.listIndex?.index??re(Dr(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(a,e,o)}return Reflect.set(a,l,o)}if(!i.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);i.pushAddress(t),i.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}finally{bc(t,n,s,i,a)}}function $c(e,t,n,o,s,r,i){let a=t.parentAddress??re(`address.parentAddress is undefined path: ${t.pathInfo.path}`),l=function(e){return lc.get(e)??null}(a);if(null===l){const t=Ql(e,a,s,r)??[],n=ms(t)??[];l={value:[...t],listIndexes:[...n]},cc(a,l)}try{return vc(e,t,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=Ql(e,a,s,r)??[],c=Array.isArray(i)?ms(i)??[]:[],d=t.listIndex.index,u=-1!==n?l.listIndexes[n]:hs(a.listIndex,-1);c[d]=u;if(new Set(i).size===l.value.length){for(let e=0;e<c.length;e++)c[e].index=e;cc(a,null)}}}function Sc(e,t,n,o,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(n)){const l=a.get(t.pathInfo.path);if(void 0!==l){const a=Ql(e,t,o,i),c=function(e,t,n,o){const s=rc(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=rc(r,t,e,"current"),a=new Map;for(let e=0;e<r.length;e++)a.set(i[e],r[e]);const l=new Array(o.length),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=a.get(s[e]);void 0!==n&&n!==t?(l[e]=n,c.push({position:e,oldRow:n,newRow:t})):l[e]=t}return c.length>0?{list:l,matched:c}:null}(t.pathInfo.path,l,a,n);if(null!==c)return function(e,t,n,o,i,a){const l=t.pathInfo.path,c=t.listIndex;null===ms(o)&&vs(c,null,o);const d=vs(c,o,n.list),u=xc(e,t,n.list,i,a,l),f=G(l+s+r);for(const t of n.matched){const n=ic(t.oldRow,t.newRow);if(0===n.length)continue;const o=d.newIndexes[t.position];for(const r of n)void 0!==o?Sc(e,un(G(f.path+s+r.field),o),r.value,i,a):t.oldRow[r.field]=r.value}return u}(e,t,c,a,o,i)}}return xc(e,t,n,o,i,null)}function xc(e,t,n,i,a,l){const c=a.stateElement,d=t.pathInfo.path;if(!0===c.hasGraftedVolumes){const e=function(e,t){const n=Nr.get(e);if(void 0===n||0===n.size)return null;const o=t+s;for(const e of n)if(e.startsWith(o))return e;return null}(c,d);null!==e&&re(`Cannot replace "${d}" wholesale: a volume is mounted at "${e}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${e}" itself, or individual fields inside "${d}", instead.`)}const u=!!so&&(so=!1,!0);if(!(d in e)&&null!==t.parentAddress&&!c.elementPaths.has(d)){const s=Ql(e,t.parentAddress,i,a);if("object"==typeof s&&null!==s){const e=t.pathInfo.lastSegment,f=e===r?t.listIndex?.index:e;let h,p=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==f&&f in s,t=void 0!==f?s[f]:void 0;if(e&&Object.is(t,n))return!0;h=t,p=!0}const m=Hl(c,t),g=zt(Lt(c,t.pathInfo),t.listIndex);null!==St&&St({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:p}),yc(c,d,g,h,p);let y=!1;try{if(void 0===f&&re(Dr(`path "${d}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),!0===c.hasMounts&&e!==r&&!(f in s)){const o=Kl(c,t.parentAddress.pathInfo.path,e,t.listIndex);if(null!==o)return y=!0,function(e,t,n,o,s,r){const i=Bl(e,un(G(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(o.record,o.entry,t.listIndex,n,i,a)}return Reflect.set(s,f,n)}finally{bc(t,g,i,a,l),y?Ll(g):wc(c,d,g,n,m),nc(c,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Ql(e,t,i,a);if(ac(e,t,i,a)&&Object.is(o,n))return!0;f=o,h=!0}const p=c.elementPaths.has(t.pathInfo.path),m=Hl(c,t),g=zt(Lt(c,t.pathInfo),t.listIndex);null!==St&&St({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),yc(c,d,g,f,h);try{return p?$c(e,t,g,n,i,a,l):vc(e,t,g,n,i,a,l)}finally{wc(c,d,g,n,m),nc(c,t.pathInfo,{value:n})}}function Nc(e,t,n,o){return(t,s,r)=>{const i=G(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}s.length!==i.wildcardParentPathInfos.length&&re(Lr("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=un(i,tc(e,n,o,i,s));if(!(void 0!==r))return Ql(e,a,n,o);Sc(e,a,r,n,o)}}function Ic(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Tl(o,s.wildcardPaths.at(-1)??re(`lastWildcardPath is null: ${t.pathInfo.path}`))??re(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??re(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=ms(Ql(e,un(i,s),n,o))??re(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??re(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??re(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":re(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Pc(e,t,n,o){const r=Reflect.get(e,I);let i;if("function"==typeof r){const e=new Set,s={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,r=t.path;if(-1===r.indexOf("#")&&(e.add(r),t.wildcardCount>0)){const e=Ht(n.listIndex,t.wildcardCount),o=s[r];void 0===o?s[r]=[e]:o.push(e)}}i=r.call(n,Array.from(e),s)}const a=o.stateElement?(l=o.stateElement,Pr.get(l)??kr):[];var l;if(a.length>0)for(const e of a){const r=e.mountPath+s,i=new Set,a={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo.path;if(t!==e.mountPath&&!t.startsWith(r))continue;if(-1!==t.indexOf("#"))continue;const s=t===e.mountPath?"":t.slice(r.length);if(""===s)continue;i.add(s);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const e=Ht(n.listIndex,l);(a[s]??=[]).push(e)}}if(i.size>0)try{e.callback.call(Ir(e.mountPath,n),Array.from(i),a)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" $updatedCallback threw.`,t)}}return i}const kc=`${j}${s}`,_c=`${D}${s}`,Ac=new WeakMap;function Cc(e,t,n,o){const r=S[t];if(void 0!==r){0===o.addressStackLength&&re(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack,n=e?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const i=e?.listIndex;null==i&&re(`ListIndex not found: ${t.toString()}`);let a=r;const l=e.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const e=bt(o.stateElement,l.path);null!==e&&(a=r+function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(s,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const r=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1),a=e.accessorBySuffixByMarkerParent.get(r)?.get(i);return void 0!==a?a.indexShift:e.delta}(e,l.path))}const c=Gt(i,a,l.wildcardCount);return c?.index??re(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>function(e,t,n,o){const s=Nc(e,0,n,o);return(t,r)=>{const i=G(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&re(Lr("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=Tl(o,i.wildcardPaths[e]);if(t){r=Ht(t,t.length);break}}if(void 0===r){const e=o.addressStackLength>0?o.lastAddressStack:null,n=e?.listIndex??null;i.wildcardCount>0&&null!==e&&null!==n&&n.length>0&&re(function(e,t){return`$getAll("${e}") was called without indexes inside the loop context of "${t}", 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).`}(t,e.pathInfo.path)),r=[]}}const a=ec(e,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let e=0;e<a.length;e++)l.push(s(i.path,a[e]));return l}}(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>function(e,t,n,o){return(t,s,r,i)=>{const a=G(t);Array.isArray(s)||re(jr(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&re(Lr("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&re(jr(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&re(jr(t,"requires an array as the value when { spread: true } is set."));const d=ec(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&re(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=tc(e,n,o,a,d[t]);u.push(un(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;i=c?r(Ql(e,s,n,o),...d[t]):l?r[t]:r,void 0!==i&&(Sc(e,s,i,n,o),f++)}return f}}(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=Ml(t),i=Ic(e,r,n,o),a=un(r.pathInfo,i),l=zt(Lt(s,a.pathInfo),a.listIndex),c=fa();c.enqueueAbsoluteAddress(l),gc(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=zt(Lt(s,e.pathInfo),e.listIndex);Ll(t),c.enqueueAbsoluteAddress(t)}),nc(s,a.pathInfo)}}(e,0,n,o)(t);case"$resolve":return(t,s,r)=>Nc(e,0,n,o)(t,s,r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{0===o.addressStackLength&&re(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??re("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(t.path)&&t.path!==e&&n.addDynamicDependency(e,t.path)}}(0,0,0,o)(e);case"$untrackDependency":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case E:return Ma(o.stateElement);case j:return Ha(o.stateElement);case D:return Ja(o.stateElement)}if(!t.startsWith(kc)&&!t.startsWith(_c))return}const s=Ml(t),r=Ic(e,s,n,o),i=un(s.pathInfo,r);return Ql(e,i,n,o)}if("symbol"==typeof t){const s=function(e){let t=Ac.get(e);return void 0===t&&(t=new Map,Ac.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case kt:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&re("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case _t:i=t=>Ql(e,t,n,o);break;case At:i=t=>ac(e,t,n,o);break;case Ct:i=(t,s)=>Sc(e,t,s,n,o);break;case Et:i=()=>async function(e,t,n){const o=Reflect.get(e,x);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Mt:i=()=>function(e,t,n){const o=Reflect.get(e,N);"function"==typeof o&&o.call(n)}(e,0,n);break;case Tt:i=t=>Pc(e,t,n,o);break;case Ot:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,P);"function"==typeof s&&s.call(o,t,n)}(e,t,o,n);break;default:return Reflect.get(e,t,n)}return s.set(t,i),i}}class Ec{_stateElement;_addressStack=Array(i).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=ta(e);null===n&&re("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&re("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=i&&re(`Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=e}_describeAddressCycle(){const e=[];for(let t=this._addressStackIndex;t>=0&&e.length<8;t--){const n=this._addressStack[t];n&&e.push(n.pathInfo.path)}return`${Array.from(new Set(e)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&re(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return Cc(e,t,n,this)}set(e,t,n,o){return"readonly"===this._mutability&&re("This state is readonly."),function(e,t,n,o,s){if("string"==typeof t){const r=Ml(t),i=Ic(e,r,o,s);return Sc(e,un(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}}function Mc(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),o=Object.getOwnPropertyDescriptors(e);for(const e in o){const t=o[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,o),n}(e)}const Tc=new WeakMap;class Oc{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=Tc.get(e);return n?n.get(t)??null:null}(e,t)??re("State element not found for web component.")}get(e,t,n){if("string"==typeof t){let e;return this._innerStateElement.createState("readonly",n=>{e=n[t]}),e}return Reflect.get(e,t,n)}set(e,t,n,o){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,o)}}const Rc=e=>()=>e;function Lc(e,t,n,o){!function(e,t,n){let o=Tc.get(e);o||(o=new Map,Tc.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(Mc(o));const s=function(e,t){const n=new Oc(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Rc(s),enumerable:!0,configurable:!0}),ts(t,n),jc(t,n)}function jc(e,t){if(k in e){const n=e[k];"function"==typeof n?n.call(e,t).catch(e=>{re(`Error in ${k}: ${e instanceof Error?e.message:String(e)}`)}):re(`${k} is not a function.`)}}function Dc(e,t){const n=yt(t);var o,r;null!==n&&n.stateProp!==e.stateProp&&re(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&Qo(t).dispose(),function(e,t){ht.set(e,t);let n=mt.get(t.parentStateElement);void 0===n&&(n=new Map,mt.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=pt.get(t.component);void 0===o&&(o=new Map,pt.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&gt.register(t,{byMarker:n,marker:t.marker,getterPaths:t.parentStateElement.getterPaths,addedGetterPaths:t.addedGetterPaths}),t.parentStateElement.markHasMounts?.()}(t,e),t instanceof ShadowRoot&&function(e,t){const n=Qi.get(e);if(void 0!==n){if(n===t)return;re("A state tree is already registered on this root.")}Qi.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>ut(e,t,n);ci(t);const o=vt(e.component);Pi(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),ii(t,o,n)}(e,t),function(e){if(e.exports.size>0||null===e.rootEntry)return;const t=new Set([...e.getterKeys,...e.setterKeys]);for(const n of t){let t;try{t=dt(e,n)}catch{continue}const o=t.indexOf(s+e.marker);if(-1===o)continue;const r=t.slice(0,o+1+e.marker.length),i=t.slice(r.length+1),a=t.slice(0,o)+s+i,l=G(a);if(l.wildcardCount!==e.delta)continue;const c={markerTerminalPath:r,suffix:i,markerPath:t,exportedPath:a};e.exports.set(a,c),Vl(e.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:c}),e.parentStateElement.addDynamicDependency(t,a),Vr(e.parentStateElement,a)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=vt(e.component);if(e.delta>0&&null===t)return;const n=e.component.tagName.toLowerCase();for(const o of e.exports.values()){const s=`${n}|${o.exportedPath}`;if(ql.has(s))continue;const r=G(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[kt](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(ql.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${e.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(e),Gl(e),o=t,r=Promise.resolve(),Zi.set(o,r),r.then(()=>sa(o),()=>{})}const Wc=new Set;function Bc(e,t){Wc.has(e)||(Wc.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function zc(e){const t=e.rootEntry,n=vt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[kt](n,()=>{o=e[t.outerPathInfo.path]})}),o}function Fc(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Ir(e.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function qc(e,t,n){const o=n[R];if(void 0!==o){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(o)){const o=t+s+a,c=function(e,n,...o){l.call(Ir(t,this),e,n,...o)};n.push({path:o,pathInfo:G(o),handler:c,order:1e6+i++}),r.add(o),e.setPathInfo(o,"prop","watch")}n.length>0&&(!function(e,t){let n=ol.get(e);void 0===n&&(n=new Map,ol.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}(e,n),e.addVolumeWatchPaths?.(r),ml(e))}const r=n[L];if(void 0!==r){const n=new Map;for(const[e,o]of Object.entries(r))n.set(t+s+e,o);e.mergeVolumeListKeys?.(n)}const i=n[I];"function"==typeof i&&(!function(e,t){let n=Pr.get(e);void 0===n&&(n=[],Pr.set(e,n)),n.push(t)}(e,{mountPath:t,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on"])void 0!==n[e]&&console.warn(`[@wcstack/state] volume "${t}" declares ${e}, which volumes do not support. Declare it on the root state instead.`)}function Vc(e,t,n){!function(e,t,n){const o=n[R];if(void 0!==o){"object"==typeof o&&null!==o||re(`${R} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(o))"function"!=typeof t&&re(`${R} entry "${e}" must be a function.`),dl(e)}const r=n[L];if(void 0!==r){"object"==typeof r&&null!==r||re(`${L} 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)&&re(`${L} entry "${n}" must map a list path to a field name or a key function.`),e.listKeys?.has(t+s+n)&&re(`${L} entry "${t+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&re(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`)}(e,t,n);const{data:o,accessors:r}=function(e){const t={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(e)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(t[o]=s.value):n.set(o,s));return{data:t,accessors:n}}(n),i=G(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;re(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let t=0;t<i.segments.length-1;t++){const o=i.segments[t],r=""===n?o in e:void 0!==e[n+s+o];n=""===n?o:n+s+o,r||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;re(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=o}),function(e,t){let n=Nr.get(e);void 0===n&&(n=new Set,Nr.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,o]of r){const r=t+s+n,i=o.get,a=o.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(Ir(t,this))}),"function"==typeof a&&(l.set=function(e){a.call(Ir(t,this),e)}),e.defineTreeAccessor(r,l)}qc(e,t,n);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{const n=l.call(Ir(t,e));n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n}}function Uc(e,t){let n=null;try{n=Vc(e,t.mountPath,t.volumeState)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}function Kc(e,t,n,o,s){null===t?function(e,t){let n=_r.get(e);void 0===n&&(n=[],_r.set(e,n)),n.push(t)}(e,{mountPath:n,volumeState:o,onGrafted:s}):Uc(t,{mountPath:n,volumeState:o,onGrafted:s})}Ar=Uc;class Gc extends Ci{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return na(e)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_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 _a}();_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(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&re(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){this._commandTokenNames=function(e){const t=new Set,n=e[C];if(void 0===n)return t;Array.isArray(n)||re(`${C} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||re(`${C} entries must be non-empty strings.`),e===E&&re(`${C} entry "${e}" conflicts with the reserved namespace name "${E}".`),t.has(e)&&re(`${C} entry "${e}" is duplicated.`),t.add(e);return t}(e),this._eventTokenNames=function(e){const t=new Set,n=e[M];if(void 0===n)return t;Array.isArray(n)||re(`${M} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||re(`${M} entries must be non-empty strings.`),t.has(e)&&re(`${M} entry "${e}" is duplicated.`),t.add(e);return t}(e),this.__state=e,this._hasUpdatedCallback=I in e,this._hasErrorCallback=P in e,kn(this),function(e,t,n){const o=t[T];if(void 0!==o){"object"==typeof o&&null!==o||re(`${T} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||re(`${T} entry "${t}" is not declared in $eventTokens.${he(t,n)}`),"function"!=typeof s&&re(`${T} entry "${t}" must be a function.`),Pn(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const n=function(e){const t=new Set,n=new Set,o=Pl(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterPaths:t,setterPaths:n}}(e);for(const e of n.getterPaths)this._getterPaths.add(e);for(const e of n.setterPaths)this._setterPaths.add(e);var o;Xa(this),za(o=this),Da(o),Wa.delete(o),Va(this,e),this._listKeys=function(e){const t=e[L];if(void 0===t)return null;"object"==typeof t&&null!==t||re(`${L} must be an object mapping list paths to key specs.`);const n=new Map;for(const[e,o]of Object.entries(t)){0===e.length&&re(`${L} entry path must be a non-empty string.`);const t=e.split(s);t.some(e=>0===e.length)&&re(`${L} entry "${e}" must not contain empty path segments.`),t[t.length-1]===r&&re(`${L} entry "${e}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),"function"!=typeof o?("string"!=typeof o&&re(`${L} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&re(`${L} entry "${e}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&re(`${L} entry "${e}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&re(`${L} entry "${e}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(e,o)):n.set(e,o)}return n.size>0?n:null}(e),function(e){sl.delete(e),nl.delete(e)}(this),function(e){fl.delete(e)}(this),this._watchPaths=ul(this,e),this._initialized&&null!==this._rootNode&&!t()&&(ml(this),Za(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}attributeChangedCallback(e,t,n){this._initialized&&t!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===t?"absent":`"${t}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const e=this.parentNode;if(!e)return null;const t=Li.find(e);if(!t)return null;const n=t.stateData;return Object.keys(n).length>0?n:null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){re("Failed to parse JSON from script element:"+e)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const e=this.getAttribute("json");return JSON.parse(e)}{const e=this.querySelector('script[type="module"]');if(e)return await Pa(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){try{const t=await fetch(e);return t.ok||re(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e);if(e&&e.endsWith(".js"))return await ka(e);re(`Unsupported src file type: ${e}`)}}catch(e){re(`Failed to initialize state: ${e}`)}}async _initializeVolume(){const e=this._rootNode,t=this.getAttribute("mount");try{!function(e){0===e.length&&re('"mount" requires a non-empty tree path.');const t=G(e);for(const n of t.segments)0===n.length&&re(`"mount" path "${e}" has an empty segment.`),n===r&&re(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&re(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(t),this.hasAttribute("bind-component")&&re('"mount" cannot be combined with "bind-component".'),this.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),function(e,t){let n=Sr.get(e);void 0===n&&(n=new Set,Sr.set(e,n)),n.has(t)&&re(`Volume slot "${t}" is already mounted on this tree.`),n.add(t)}(e,t)}catch(e){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),e}this._volumeInitializing=!0,null===ta(e)&&function(e,t){const n=()=>{if(null!==ta(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> 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=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(e,t);const n=e=>{this._volumeGraftInfo=e,this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()};let s;try{s=await this._loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${t}" failed to load.`,e),void n(null)}null!==this._rootNode?Kc(e,ta(e),t,s,n):n(null)}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,n]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=n}await this._loadingPromise,ra(this.rootNode,this)}_failInitialization(e){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),re(e)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const r=this.parentNode,i=r instanceof ShadowRoot?r.host:r instanceof Element?r:null,a=i?X(i):null;null!==i&&null!==a||re(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),r instanceof ShadowRoot||i.hasAttribute(o.bindAttributeName)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${a}>, or mount it from the host (data-wcs="${this.getAttribute("bind-component")}: path").`);const l=["state","src","json"].filter(e=>this.hasAttribute(e));null!==this.querySelector('script[type="module"]')&&l.push('<script type="module">'),l.length>0&&re(`"bind-component" cannot be combined with ${l.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const c=this.getAttribute("bind-component");!function(e,t){let n=ns.get(e);n||(n=new Set,ns.set(e,n)),n.add(t)}(i,c);const d=Q(i);null===d&&re(`CustomElementRegistry is unavailable for <${a}>.`),await d.whenDefined(a.toLowerCase()),i.hasAttribute(o.bindAttributeName)&&await q(i),c in i||re(`Component does not have property "${c}" for state binding.`);let u=i[c];"object"==typeof u&&null!==u||re(`Component property "${c}" is not an object for state binding.`);const f=function(e,t){const n=ar.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(i,c);if(void 0!==f&&function(e,t){if(!e.hasAttribute(o.bindAttributeName))return!1;const n=ue(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(i,c)&&(i[c]=f,u=f),this._boundComponent=i,this._boundComponentStateProp=c,r instanceof ShadowRoot||(ue(i)??[]).some(e=>e.propSegments[0]===c)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${a}>, or mount it from the host (data-wcs="${c}: path").`),i.hasAttribute(o.bindAttributeName)){const o=(ue(i)??[]).filter(e=>e.propSegments[0]===c);if(o.length>0){const l=ta(i.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${a}>.`);let d=(n=i,s=c,pt.get(n)?.get(s)??null);const f=null!==d;if(null===d&&(function(e,t,n){const o=cr.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;cr.get(e).delete(t)}}(i,c,u),d=tt(i,c,o,l,u,(e=i,t=c,lr.get(e)?.get(t))),function(e){const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp,s=new Map;for(const t of e.entries)1===t.innerSegments.length&&s.set(t.innerSegments[0],t.outerPathInfo.path);let r,i=!1;for(const a of t){const t=s.get(a);if(void 0!==t){Bc(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted entry "${o}.${a}: ${t}" (the host value no longer reaches it). Remove the default to read the tree, or rename it to keep it private.`);continue}if(null===e.rootEntry)continue;if(i||(r=zc(e),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=e.rootEntry.outerPathInfo.path;Bc(`${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.`)}}(d)),this._mountRecord=d,this.parentNode!==r)return;try{Dc(d,r instanceof ShadowRoot?r:i)}catch(e){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),e}if(!f){const e=zl(d);Object.defineProperty(i,c,{get:()=>e,enumerable:!0,configurable:!0}),ts(i,c)}return jc(i,c),function(e){const t=Qe.filter(t=>void 0!==e.stateObject[t]);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;Ze.has(n)||(Ze.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${e.stateProp} declares ${t.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.`))}(d),void et(d,"$connectedCallback")}}Lc(this,this._boundComponent,this._boundComponentStateProp,u)}var e,t,n,s}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{x in e&&await e[Et]()})}async _initializeDCC(e,t){let n;try{if(this.hasAttribute("src")){const e=this.getAttribute("src");e.endsWith(".js")?n=await ka(e):re(`DCC: Unsupported src type: ${e}`)}else{const t=this.querySelector('script[type="module"]');t?n=await Pa(t,e.tagName.toLowerCase()):re(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}}catch(e){re(`DCC: Failed to load state: ${e}`)}!function(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||re(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Q(e);null!==r&&"function"==typeof r.define||re(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&re(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=Al(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(W))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const e=Q(this._shadow);return null!==e&&Z(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(m.bindableEventMap).length>0){const t=e.querySelector(p);t?t.setBindableEventMap(m.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${_} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=Pl(n);for(const[e,t]of Object.entries(g)){if(Il(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Nl(e,o)}else n.get=Sl(e),n.set=xl(e);Object.defineProperty(m.prototype,e,n)}for(const e of u)Object.defineProperty(m.prototype,e,{configurable:!0,enumerable:!0,get:Sl(e),set:xl(e)});r.define(s,m)}(e,t,n),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",e=>{N in e&&e[Mt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&ta(this._rootNode)===this._volumeGraftInfo.rootStateElement&&Fc(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const e=this._mountRecord,t=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&function(e,t){const n=Qo(t),o=vt(e.component);n.forEachActiveBindingNode(e=>$t(e,o)),ri(n.rebindAddresses()),Gl(e)}(e,t)}),et(e,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||ta(this._rootNode)===this||ra(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 e=this.parentNode;if(e instanceof ShadowRoot&&e.host.hasAttribute(W))return this.hasAttribute("bind-component")&&re(`"bind-component" cannot be used inside a [${W}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(e.host,e);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")&&!t()||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await na(this.rootNode);const e=Li.extractStateData(this),t=document.createElement(o.tagNames.ssr);t.setAttribute("version",Ai),Li.buildContent(t,e),this.parentNode?.insertBefore(t,this)}catch(e){throw this._rejectConnectedCallback?.(e),e}t()||null===this._rootNode||e!==this._connectGeneration||ml(this),t()||null===this._rootNode||e!==this._connectGeneration||this._streamsStartedGeneration===e||Za(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Fc(this._volumeGraftInfo,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._mountRecord)return et(this._mountRecord,"$disconnectedCallback"),Gl(this._mountRecord),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{ra(this.rootNode,null),e=this,Aa.delete(e),function(e){Ea.delete(e)}(this),kn(this),za(this),Xa(this),function(e){sl.delete(e)}(this),this._rootNode=null}}var e}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(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&re(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),t.set(n,o);this._listKeys=t}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}defineTreeAccessor(e,t){Object.defineProperty(this._state,e,t),"function"==typeof t.get&&this._getterPaths.add(e),"function"==typeof t.set&&this._setterPaths.add(e),this.setPathInfo(e,"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&&re("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(e){this._bindableEventMap=e}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){return this._addDependency(this._dynamicDependency,e,t)}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t,n="binding"){if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+r)),!this._pathSet.has(e)){const t=G(e);if(this._pathSet.add(e),Br(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=G(e.parentPath)}}}_createState(e,t,n){try{const o=function(e,t,n){const o=new Ec(e,n);return new Proxy(t,o)}(e,this._state,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(e){this._indexDependentGetterPaths.add(e)}setInitialState(e){this._initialized?((this._hasGraftedVolumes||this._hasMounts)&&re("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=e):this._resolveSetState?.(e)}}function Hc(e=customElements){e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Li),e.get(o.tagNames.state)||e.define(o.tagNames.state,Gc)}function Jc(e){const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}await function(t,o){const s=Jc(t);var r;s&&((r=s).tagNames&&Object.assign(n.tagNames,r.tagNames),"string"==typeof r.bindAttributeName&&(n.bindAttributeName=r.bindAttributeName),"string"==typeof r.commentTextPrefix&&(n.commentTextPrefix=r.commentTextPrefix),"string"==typeof r.commentForPrefix&&(n.commentForPrefix=r.commentForPrefix),"string"==typeof r.commentIfPrefix&&(n.commentIfPrefix=r.commentIfPrefix),"string"==typeof r.commentElseIfPrefix&&(n.commentElseIfPrefix=r.commentElseIfPrefix),"string"==typeof r.commentElsePrefix&&(n.commentElsePrefix=r.commentElsePrefix),"string"==typeof r.locale&&(n.locale=r.locale),"boolean"==typeof r.debug&&(n.debug=r.debug),"boolean"==typeof r.enableMustache&&(n.enableMustache=r.enableMustache),"boolean"==typeof r.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=r.enableDirectionalInitialSync),"boolean"==typeof r.enablePropagationContext&&(n.enablePropagationContext=r.enablePropagationContext),"boolean"==typeof r.enableContractAnalyzer&&(n.enableContractAnalyzer=r.enableContractAnalyzer),"boolean"==typeof r.sameValueGuard&&(n.sameValueGuard=r.sameValueGuard)),Hc(o),function(){const e=globalThis;void 0===e[Fi]&&(e[Fi]=Yi)}(),function(){const t=globalThis;void 0===t[e]&&(t[e]=xa)}(),Sa()}();
1
+ const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.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;const s=".",r="*",i=128,a=128,l="|",c="prevent",d="stop",u="ro",f="init",h="sync",p="else",m="...",g="on",y="eventToken",w="command",b="class",v="attr",$="style",x={};for(let e=0;e<i;e++)x[`$${e+1}`]=e;const S=Object.freeze(x),N="$connectedCallback",P="$disconnectedCallback",I="$updatedCallback",k="$errorCallback",_="$stateReadyCallback",A="$bindables",C="$commands",E="$commandTokens",M="$command",T="$eventTokens",O="$on",R="$streams",L="$watch",j="$recursion",D="**",W="$listKeys",B="$streamStatus",z="$streamError",F="data-wc-definition",q=new WeakMap,V=new WeakSet;let U=0;async function G(e){const t=function(e){let t,n=q.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++U,promise:o,resolve:t},q.set(e,n),V.has(e)&&n.resolve(),n}(e);await t.promise}function K(e){const t=q.get(e);void 0===t?V.add(e):t.resolve()}function H(e){throw new Error(`[@wcstack/state] ${e}`)}const J=new Map;let X=0;function Y(e){let t=J.get(e);return void 0!==t||(-1!==e.indexOf(D)&&H(`[wcs/recursion-unsupported] "${e}" uses "${D}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`),t=Object.freeze(new Q(e)),J.set(e,t)),t}class Q{id=++X;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(e){const t=t=>e===t?this:Y(t),n=e.split("."),o=[],s=[],i=[],a={},l=[],c=[],d=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===r&&(i.push(f),a[f]=p,l.push(t(f)),c.push(h),d.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const m=i.length>0?i[i.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=e,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?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=p}}const Z=new WeakMap;function ee(e){const t=Z.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{Z.set(e,n)}}function te(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function ne(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return te(t);if(void 0!==n)return te(n)}return te(globalThis.customElements)}function oe(e,t){e.upgrade?.(t)}function se(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.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=le(s.properties,re);if(null===r)return null;const i=void 0===s.inputs?new Map:le(s.inputs,ie);if(null===i)return null;const a=void 0===s.commands?new Map:le(s.commands,ae);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function re(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function ie(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function ae(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function le(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function ce(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:Y(n),inFilters:[],outFilters:[],bindingType:"prop"}}function de(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function ue(e,t,n={}){const s=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&H("Spread binding requires an element node.");const t=e,o=ee(t);null===o&&H(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=ne(t);null===a&&H(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||H(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}oe(a,t);const l=se(t);null===l&&H(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=ce(e,c);i.add(t),r.push(t)}for(const e of l.declaredInputs.keys()){if(d.has(e))continue;d.add(e);const t=ce(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=de(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=de(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.debug&&i.has(r[t])){const o=r[a.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[t])}return l}function fe(e,t){let n=e;if(0===t.length)return n;for(let e=0;e<t.length&&(n=n?.childNodes[t[e]]??null,null!==n);e++);return n}const he=new WeakMap;function pe(e){return he.get(e)||null}function me(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;const o=new Array(t.length+1),s=new Array(t.length+1);for(let e=0;e<=t.length;e++)o[e]=e;for(let n=1;n<=e.length;n++){s[0]=n;for(let r=1;r<=t.length;r++){const i=e[n-1]===t[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let e=0;e<=t.length;e++)o[e]=s[e]}return o[t.length]}function ge(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=me(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ye=" Validate statically: npx @wcstack/lint <file>.",we=new Set(["if","elseif","else","for"]);function be(e){H(`filter ${e} requires at least one option`)}function ve(e){H(`filter ${e} requires a number as option`)}function $e(e){H(`filter ${e} requires a number value`)}function xe(e){H(`filter ${e} requires a date value`)}function Se(e){return!(!e||isNaN(Number(e)))}const Ne={eq:e=>{const t=e?.[0]??be("eq");return e=>"number"==typeof e?(Se(t)||ve("eq"),e===Number(t)):e===t},ne:e=>{const t=e?.[0]??be("ne");return e=>"number"==typeof e?(Se(t)||ve("ne"),e!==Number(t)):e!==t},not:e=>e=>("boolean"!=typeof e&&H(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??be("lt");return Se(t)||ve("lt"),e=>("number"!=typeof e&&$e("lt"),e<Number(t))},le:e=>{const t=e?.[0]??be("le");return Se(t)||ve("le"),e=>("number"!=typeof e&&$e("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??be("gt");return Se(t)||ve("gt"),e=>("number"!=typeof e&&$e("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??be("ge");return Se(t)||ve("ge"),e=>("number"!=typeof e&&$e("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??be("inc");return Se(t)||ve("inc"),e=>("number"!=typeof e&&$e("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??be("dec");return Se(t)||ve("dec"),e=>("number"!=typeof e&&$e("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??be("mul");return Se(t)||ve("mul"),e=>("number"!=typeof e&&$e("mul"),e*Number(t))},div:e=>{const t=e?.[0]??be("div");return Se(t)||ve("div"),e=>("number"!=typeof e&&$e("div"),e/Number(t))},mod:e=>{const t=e?.[0]??be("mod");return Se(t)||ve("mod"),e=>("number"!=typeof e&&$e("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&$e("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??be("clamp");Se(t)||ve("clamp");const n=e?.[1]??be("clamp");Se(n)||ve("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&$e("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return Se(t)||ve("fix"),e=>("number"!=typeof e&&$e("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&$e("locale"),e.toLocaleString(t??o.locale))},uc:e=>e=>String(e).toUpperCase(),lc:e=>e=>String(e).toLowerCase(),cap:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??be("slice");Se(n)||ve("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Se(o)||ve("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??be("substr");Se(t)||ve("substr");const n=e?.[1]??be("substr");return Se(n)||ve("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??be("pad");Se(t)||ve("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??be("rep");return Se(t)||ve("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??be("truncate");Se(t)||ve("truncate");const n=Number(t),o=e?.[1]??"…";return e=>{const t=String(e);return t.length<=n?t:t.slice(0,n)+o}},join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||H(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=e?.[0]??"0";return Se(t)||ve("round"),e=>{"number"!=typeof e&&$e("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Se(t)||ve("floor"),e=>{"number"!=typeof e&&$e("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Se(t)||ve("ceil"),e=>{"number"!=typeof e&&$e("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Se(t)||ve("percent"),e=>("number"!=typeof e&&$e("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??be("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||xe("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||xe("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||xe("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||xe("ymd");const n=e.getFullYear().toString(),o=(e.getMonth()+1).toString().padStart(2,"0"),s=e.getDate().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},hms:e=>{const t=e?.[0]??":";return e=>{e instanceof Date||xe("hms");const n=e.getHours().toString().padStart(2,"0"),o=e.getMinutes().toString().padStart(2,"0"),s=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!1===e||null==e||0===e||""===e||Number.isNaN(e),truthy:e=>e=>!1!==e&&null!=e&&0!==e&&""!==e&&!Number.isNaN(e),defaults:e=>{const t=e?.[0]??be("defaults");return e=>!1===e||null==e||0===e||""===e||Number.isNaN(e)?t:e},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),null:e=>e=>""===e?null:e},Pe=Ne,Ie={input:Ne,output:Pe},ke=(e,t)=>n=>{const o=n[e];return o||H(`[wcs/filter-unknown] filter not found: ${e}.${ge(e,Object.keys(n))}${ye}`),o(t)};function _e(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const Ae=new Map;function Ce(e,t){const n=Ie[t];return e.map(e=>{const o=e.indexOf("("),s=e.lastIndexOf(")");if(-1!==o&&-1===s&&H(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==s&&-1===o&&H(`Invalid filter format: missing opening parenthesis in "${e}"`),-1===o){const o=e.trim(),s=`${o}():${t}`;let r=Ae.get(s);return void 0===r&&(r=ke(o,[])(n),Ae.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=e.substring(o+1,s),i=e.substring(0,o).trim(),a=function(e){const t=[];let n="",o=null,s=!1,r=-1,i=-1;const a=()=>{t.push(_e(n,r,i)),n="",s=!1,r=-1,i=-1};for(let t=0;t<e.length;t++){const l=e[t];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=_e(n,r,i);return(l||s)&&t.push(l),t}(r),l=`${i}(${a.join(",")}):${t}`;let c=Ae.get(l);return void 0===c&&(c=ke(i,a)(n),Ae.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const Ee=e=>e.trim(),Me=new Map;const Te=new Map;function Oe(e){const t=e.indexOf(l);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Te.has(s)?r=Te.get(s):(o=s.split(l).map(Ee),r=Ce(o,"output"),Te.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&H(`"${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.`);return{statePathName:n,statePathInfo:Y(n),outFilters:r}}function Re(e){const[...t]=e.split(";").map(Ee).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&H(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim();if(n===p){const e=Y("#else");return{propName:p,propSegments:[p],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===m){const t=Oe(o);return t.outFilters.length>0&&H(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&H(`Invalid spread binding "${e}": spread target path is required.`),{propName:m,propSegments:[m],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Oe(o),bindingType:n}}{const e=Oe(o),t=function(e){const t=e.indexOf(l);let n="",o=[],r="",i=[];-1!==t?(n=e.slice(0,t).trim(),r=e.slice(t+1).trim(),Me.has(r)?i=Me.get(r):(o=r.split(l).map(Ee),i=Ce(o,"input"),Me.set(r,i))):n=e.trim();const[a,c]=n.split("#").map(Ee),d=a.split(s).map(Ee);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map(Ee):[],inFilters:i}}(n);return t.propSegments[0]===y||t.propSegments[0].startsWith(g)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>we.has(e.bindingType))&&H(`[wcs/template-syntax] Invalid bindText: "${e}". '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">).${ye}`)}return n}const Le=new WeakMap,je=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),De=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function We(e){const t=Le.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=De.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return je.has(r)?(Le.set(e,s[2]),s[2]):null}function Be(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Oe(e),bindingType:"text"}}const ze=new Map;function Fe(e,t,n){if(null===n)ze.delete(e);else{ze.set(e,n);const o=ua(t);null===o&&H("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const t of e.parseBindTextResults)o.setPathInfo(t.statePathName,t.bindingType)}}function qe(e){return ze.get(e)||null}function Ve(e){if(e.nodeType===Node.ELEMENT_NODE){return Re(e.getAttribute(o.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=We(e);null===t&&H("Comment node binding text not found.");const n=qe(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Be(t),s=null):s=t,[{...o,uuid:s}]}return[]}function Ue(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function Ge(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Ue(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function Ke(e,t){for(let n=0;n<t.length;n++){const o=t[n];if(o!==e&&o.contains(e))return!0}return!1}function He(e){const t=[],n=Ge(e),s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==We(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&Ke(e,n)||t.push(e)}return t}const Je=new WeakSet;function Xe(e,t,n,o){const s=ue(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?ee(e):null;return null===n&&H("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}Je.add(e);const r=function(e,t){const n=[];for(const o of t)if("text"!==o.bindingType)n.push({...o,node:e,replaceNode:e});else{const t=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,node:e,replaceNode:t})}return n}(e,function(e,t){return void 0===t?e:e.map(e=>null!=e.uuid?e:t(e))}(s,o));return function(e,t){he.set(e,t)}(e,r),K(e),{bindings:r,deferred:null}}function Ye(e,t){const n=He(e),o=[],s=[];for(const e of n){if(Je.has(e))continue;const n=Xe(e,Ve(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Qe(e){Je.add(e)}function Ze(e){const{node:t,parseResults:n,transform:o}=e;!function(e){Je.delete(e)}(t);return Xe(t,n,{allowDeferred:!1},o).bindings}let et=0;const tt=["$watch","$streams","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion"],nt=new Set;function ot(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function st(e,t,n,o,r,i=new Set){0===n.length&&H(`Cannot build a mount record without host bindings for "${t}".`);const a=[],l=new Set;let c=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(s);l.has(n)&&H("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo};a.push(o),0===t.length&&(c=o)}a.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++et,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(r),p={};for(const e of Object.keys(r))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof r[e]&&(i.has(e)||(p[e]=r[e]));return{id:d,marker:u,component:e,stateProp:t,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:f,setterKeys:h,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function rt(e){const t=e.indexOf(s);return-1===t?e:e.slice(0,t)}function it(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function at(e,t){for(const n of e.entries)if(it(t,n.innerSegments)){const e=t.slice(n.innerSegments.length);return 0===e.length?n.outerPathInfo.path:n.outerPathInfo.path+s+e.join(s)}return null}function lt(e,t){return e.markerBasePath+s+t}function ct(e,t,n,o){let r=e.accessorBySuffixByMarkerParent.get(t);void 0===r&&(r=new Map,e.accessorBySuffixByMarkerParent.set(t,r));const i=t+s+n;r.set(n,{accessorName:o,indexShift:Y(i).wildcardCount-Y(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(i),e.addedGetterPaths.add(i))}function dt(e,t){return!e.injectedKeys.has(t)&&("function"==typeof e.stateObject[t]&&!e.getterKeys.has(t)||Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t))}function ut(e,t){return`Path "${t}" in <${e.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${e.entries.filter(e=>e.innerSegments.length>0).map(e=>e.innerSegments.join(s)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${rt(t)}: path") or declare the key on the component state.`}const ft=/^\$(\d+)$/;function ht(e,t){const n=t[0];if("$"===n||"#"===n)return t;if(e.getterKeys.has(t)||e.setterKeys.has(t))return function(e,t){const n=t.split(s);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===r){o=e;break}if(-1===o)return ct(e,e.markerBasePath,t,t),lt(e,t);if(dt(e,n[0]))return ct(e,e.markerBasePath,t,t),lt(e,t);const i=n.slice(0,o+1),a=n.slice(o+1),l=at(e,i);null===l&&H(ut(e,t)),0===a.length&&H(`Wildcard-terminal accessor "${t}" on mounted <${e.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+e.marker;return ct(e,c,a.join(s),t),c+s+a.join(s)}(e,t);const o=rt(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return lt(e,t);if(dt(e,o))return lt(e,t);const i=at(e,t.split(s));if(null!==i)return i;H(ut(e,t))}function pt(e,t,n){let o;const i=ft.exec(t.statePathName);if(null!==i){const s=function(e,t){return void 0===t?e.delta:Y(ht(e,t)).wildcardCount-Y(t).wildcardCount}(e,n);o=0===s?t.statePathName:`$${Number(i[1])+s}`}else if(o=ht(e,t.statePathName),"for"===t.bindingType){const n=Y(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+s+r,n)}return o===t.statePathName?t:{...t,statePathName:o,statePathInfo:Y(o)}}function mt(e,t,n,o,s){if(void 0===o)return;const r=Y(n).wildcardCount-Y(t).wildcardCount;return 0===r?o:(s.length<r&&H(`Cannot resolve "${t}" 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 gt=new WeakMap,yt=new WeakMap;const wt=new WeakMap;const bt=new FinalizationRegistry(function(e){const t=e.byMarker.get(e.marker);if(void 0!==t&&void 0===t.deref()&&e.byMarker.delete(e.marker),void 0!==e.getterPaths)for(const t of e.addedGetterPaths)e.getterPaths.delete(t)});function vt(e){return gt.get(e)??null}function $t(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=wt.get(e);if(void 0===o)return null;const r=t.indexOf(s,n),i=-1===r?t.slice(n):t.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 xt=new WeakMap;function St(e){let t=e;for(;t;){const e=xt.get(t);if(e)return e;let n=t.parentNode;null===n&&t instanceof ShadowRoot&&null!==vt(t)&&(n=t.host),t=n}return null}function Nt(e,t){null!==t?xt.set(e,t):xt.delete(e)}let Pt=null;const It=new WeakMap;function kt(e){return It.get(e)??[]}function _t(e,t){It.set(e,t)}function At(e){return It.has(e)}const Ct=new WeakMap;let Et=null,Mt=0;function Tt(e){return Ct.get(e)??[]}function Ot(e,t){null===Et?Ct.set(e,t):Et.set(e,t)}function Rt(e){return(Et?.has(e)??!1)||Ct.has(e)}const Lt=Symbol("$$setLoopContext"),jt=Symbol("$$getByAddress"),Dt=Symbol("$$hasByAddress"),Wt=Symbol("$$setByAddress"),Bt=Symbol("$$connectedCallback"),zt=Symbol("$$disconnectedCallback"),Ft=Symbol("$$updatedCallback"),qt=Symbol("$$errorCallback"),Vt=new WeakMap;function Ut(e,t){if(Vt.has(e)){const n=Vt.get(e);if(n.has(t))return n.get(t)}else Vt.set(e,new WeakMap);const n=Object.freeze(new Gt(e,t));return Vt.get(e).set(t,n),n}class Gt{pathInfo;stateElement;parentAbsolutePathInfo;constructor(e,t){this.pathInfo=t,this.stateElement=e,null===t.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Ut(e,t.parentPathInfo)}}const Kt=new WeakMap,Ht=new WeakMap;class Jt{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const e=this.absolutePathInfo.parentAbsolutePathInfo;if(null===e)return null;let t=null;return t=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=Xt(e,t)}}function Xt(e,t){if(null===t){let t=Ht.get(e);return void 0!==t||(t=new Jt(e,null),Ht.set(e,t)),t}{let n=Kt.get(t);void 0===n&&(n=new WeakMap,Kt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Jt(e,t),n.set(e,o)),o}}const Yt=new WeakMap;function Qt(e,t){null===t?Yt.delete(e):Yt.set(e,t)}function Zt(e){return Yt.get(e)||null}const en=new Map;function tn(e,t){let n,o;if(0===e.wildcardCount||0===t.wildcardCount)return 0;if(1===e.wildcardCount&&t.wildcardCount>0&&t.wildcardPathSet.has(e.path))return 1;e.id<t.id?(n=e,o=t):(n=t,o=e);const s=`${n.path}\t${o.path}`;let r=en.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,en.set(s,r),r}function nn(e,t,n){return t<0||t>=n?null:e.at(t-n)}function on(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const sn=new WeakMap;function rn(e){const t=St(e.node);if(null===t)return null;let n=sn.get(t);if(void 0===n)n=new WeakMap,sn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=tn(t.pathInfo,e.statePathInfo);return n>0&&(o=nn(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const an=new WeakMap;function ln(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Zt(n);null===t?H(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function cn(e,t){let n=null;if(n=an.get(e)||null,null!==n)return n;const o=ln(e,t),s=rn(e),r=ua(o);null===r&&H("No state tree found on this root for binding.");return n=Xt(Ut(r,e.statePathInfo),s),an.set(e,n),n}function dn(e){an.delete(e)}const un=new WeakMap;function fn(e,t){const n=un.get(e);void 0===n?un.set(e,t):n instanceof Set?n.add(t):n!==t&&un.set(e,new Set([n,t])),null!==Pt&&Pt({type:"state:binding-added",absoluteAddress:e,binding:t})}function hn(e,t){const n=un.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&un.delete(e),null!==Pt&&Pt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const pn=new WeakMap;function mn(e,t,n){const o=pn.get(e);if(void 0===o)return;const s=o.get(t);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(t),null!==Pt&&Pt({type:"state:binding-removed",absoluteAddress:Xt(e,t),binding:n}))}function gn(e){const t=un.get(e);return void 0!==t?t:null!==e.listIndex?pn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const yn=new WeakMap,wn=new WeakMap;class bn{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=vn(e,t)}}function vn(e,t){if(null===t){let t=wn.get(e);return void 0!==t||(t=new bn(e,null),wn.set(e,t)),t}{let n=yn.get(t);void 0===n&&(n=new WeakMap,yn.set(t,n));let o=n.get(e);return void 0!==o||(o=new bn(e,t),n.set(e,o)),o}}const $n=new WeakMap;function xn(e){let t=null;if(t=$n.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=rn(e);null===n&&H(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=vn(e.statePathInfo,n)}else t=vn(e.statePathInfo,null);return $n.set(e,t),t}function Sn(e){$n.delete(e)}function Nn(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const Pn=new Map,In=Nn();function kn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function _n(e){let t="input";for(const n of e.propModifiers)n.startsWith(g)&&(t=n.slice(2));return t}function An(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const o=_n(e),s=kn(e,o);let r=Pn.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.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 e of n)r=e.filterFn(r);const i=ua(o.getRootNode());null===i&&H("No state tree found on this root for two-way binding.");const a=St(o);i.createState("writable",e=>{e[Lt](a,()=>{let n=e[t];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(e[t]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(e[t]=n.toSpliced(o,1))}else e[t]=s?[r]:[]})})},Pn.set(s,r)),e.node.addEventListener(o,r),In.add(s,e),!0}var t,n;return!1}function Cn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function En(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Cn(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class Mn{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)t.push(n(...e));return t}}class Tn extends Mn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Pt&&Pt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const On=new WeakMap;function Rn(e,t){let n=On.get(e);void 0===n&&(n=new Map,On.set(e,n));let o=n.get(t);return void 0===o&&(o=new Tn(t,e),n.set(t,o)),o}function Ln(e){On.delete(e)}const jn=new WeakMap;function Dn(e){if(e.propSegments[0]!==y)return!1;const t=e.node,n=ee(t),o=ne(t);if(null!==n&&void 0===o?.get(n))return null===o&&H(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(jn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||H('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===ee(e)?null:se(e)}(t);null===r&&H(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&H(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${ge(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,u=e.propModifiers,f=e=>{u.includes(c)&&e.preventDefault(),u.includes(d)&&e.stopPropagation();const n=ua(t.getRootNode());null===n&&H("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||H(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${ge(l,n.eventTokenNames)}${ye}`);const o=St(t);n.createStateAsync("writable",async t=>{En(t[Lt](o,()=>{const s=null!==o?on(o.listIndex,o.pathInfo.wildcardCount):[];return Rn(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,f),jn.set(e,{eventName:a,handler:f}),!0}class Wn extends Mn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Pt&&Pt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Bn(e){return e instanceof Wn}const zn=new Map,Fn=Nn();function qn(e){const t=e.propModifiers.filter(e=>e===c||e===d).sort().join(",");return`${e.statePathName}::${t}`}const Vn=(e,t,n)=>o=>{t.includes(c)&&o.preventDefault(),t.includes(d)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ua(r);null===i&&H("No state tree found on this root for event handler.");const a=St(s),l=e.startsWith(M+".");i.createStateAsync("writable",async t=>{const c=t[Lt](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a&&!0===i.hasMounts){const e=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=gt.get(n);if(void 0!==e)return e;n=n.parentNode}return gt.get(t)??null}(s,r);if(null!==e){const t=e.indexShiftByLoopElementPath.get(a.pathInfo.path);c=void 0!==t?c-t:0}}const d=null!==a?on(a.listIndex,c):[];if(l){const s=t[jt](vn(n,null));return Bn(s)||H(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...d)}const u=t[e];return"function"!=typeof u&&H(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});En(c,`"${e}"`)})};function Un(e){if(!e.propName.startsWith(g))return!1;const t=qn(e);let n=zn.get(t);void 0===n&&(n=Vn(e.statePathName,e.propModifiers,e.statePathInfo),zn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Fn.add(t,e),!0}const Gn=new Map,Kn=Nn();function Hn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Jn(e){let t="input";for(const n of e.propModifiers)n.startsWith(g)&&(t=n.slice(2));return t}function Xn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const o=Jn(e),s=Hn(e,o);let r=Gn.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.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 e of n)s=e.filterFn(s);const r=ua(o.getRootNode());null===r&&H("No state tree found on this root for two-way binding.");const i=St(o);r.createState("writable",e=>{e[Lt](i,()=>{e[t]=s})})},Gn.set(s,r)),e.node.addEventListener(o,r),Kn.add(s,e),!0}var t,n;return!1}const Yn=new Set(["radio","checkbox"]),Qn=new Set(["value","valueAsNumber","valueAsDate"]);function Zn(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(Yn.has(e)&&"checked"===t)return!0;if(Qn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=ee(n);if(null!==s){const e=ne(n)?.get(s);void 0===e&&H(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=se(n);if(o?.knownProperties.has(t))return!0}return!1}let eo=1,to=1,no=1;const oo=new WeakMap;function so(e,t,n){let o=oo.get(e);void 0===o&&(o=new Map,oo.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=eo++,o.set(s,r)),r}function ro(e,t){return"to-element"===t?2*e:2*e+1}const io=new Set;function ao(e){return{transactionId:to++,originBindingId:e,visitedEdges:io,hop:0}}function lo(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let co=null;function uo(){return co}function fo(e,t){const n=co;co=e;try{return t()}finally{co=n}}const ho=[];let po=!1;const mo=new Map,go=Nn(),yo=new WeakMap,wo=e=>e.detail,bo=new WeakMap;function vo(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function $o(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=ee(e.node);if(null!==n){const o=ne(e.node)?.get(n);void 0===o&&H(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=se(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(g)&&(t=n.slice(2));return t}function xo(e){if(null!==ee(e.node)){const t=se(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??wo}return null}function So(e){if(null===ee(e.node))return!1;const t=se(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const No=(e,t,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),s!==wo||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=bo.get(e);void 0===r&&(r=new Set,bo.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=yo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=so(a,e,t),s=function(e,t){for(let n=ho.length-1;n>=0;n--){const o=ho[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==Pt&&Pt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:ro(n,"to-state"),node:a,member:e}));const r=ro(n,"to-state"),i=uo();if(null!==i&&i.visitedEdges.has(r))return void(null!==Pt&&Pt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=lo(i??ao(n),r)}const f=ua(a.getRootNode());null===f&&H("No state tree found on this root for two-way binding.");const h=St(a),p=()=>{r&&(po=!0);try{f.createState("writable",e=>{e[Lt](h,()=>{e[t]=c})})}finally{r&&(po=!1)}};null!==u?fo(u,p):p()};const Po=new WeakSet;function Io(e){Po.add(e)}function ko(e){return!!Po.has(e)&&(Po.delete(e),!0)}const _o=new WeakSet;function Ao(e){_o.add(e)}function Co(e){return!!_o.has(e)&&(_o.delete(e),!0)}let Eo=0;function Mo(){Eo--}function To(){return Eo>0}class Oo{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.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),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const Ro=new WeakMap;function Lo(e){let t=Ro.get(e);return void 0===t&&(t=new Oo(e),Ro.set(e,t)),t}function jo(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==f&&s!==h&&H(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&H(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Do(e){return e.propModifiers.some(e=>e.includes("="))}const Wo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Bo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function zo(e,t){return"state"===e&&"call"===t?Wo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Fo(e){if(!o.enableDirectionalInitialSync)return Do(e)&&H("init=/sync= modifiers require enableDirectionalInitialSync."),Wo;const t=null===(n=jo(e,f))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:H(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":H(`Invalid sync modifier value "${e}".`)}(jo(e,h));if("event"===e.bindingType)return null!==t&&"none"!==t&&H("Event bindings only allow init=none."),"call"===s?Bo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===w)return zo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&H(`Binding type "${e.bindingType}" does not support init=${t}.`),zo(t??"state",s);const r=se(e.node);if(null===r)return zo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||H(`Property "${e.propName}" is not declared by wcBindable.`);const l=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||H(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||H(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function qo(e,t){return"auto"!==t?t:function(e){const t=ua(e.replaceNode.getRootNode());null===t&&H("No state tree found on this root for binding.");const n=xn(e);let o=!1;return t.createState("readonly",e=>{o=e[Dt](n)}),o}(e)?"state":"element"}let Vo=0,Uo=0;const Go=new WeakMap,Ko=new WeakMap,Ho=new WeakMap,Jo=new WeakMap;function Xo(e,t){const n=Jo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Jo.set(e,new Set([n,t]))):Jo.set(e,t)}function Yo(e){return Jo.has(e)}function Qo(e,t){const n=Jo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function Zo(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))Zo(n,t)}function es(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class ts{root;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}handleMutations(e){const t=[],n=[];for(const o of e)t.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));const o=[];for(const e of t)ko(e)||Zo(e,e=>{Qo(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Co(e)&&!To()||Zo(e,e=>{Qo(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&mi(o)}}const ns=new WeakMap;function os(e){let t=ns.get(e);return void 0===t&&(t=new ts(e),ns.set(e,t)),t}function ss(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function rs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class is{records=new Set;rowPlan=null;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=Go.get(e);void 0===o||"disposed"===o.phase||"failed"===o.phase?(this.start(e,s,n),r.push(e)):(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(e=>this.shouldApplyState(e))}activate(e,t){if(es(t)&&os(t),null===this.rowPlan)for(const n of e){const e=Go.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!o.enableDirectionalInitialSync)return Do(e)&&Fo(e),!0;const t=Go.get(e);return void 0===t||t.session!==this||(!t.options.registerAddress||"waiting-definition"===t.phase||"failed"!==t.phase&&("active"===t.phase&&this.settleInitialRecord(t),t.initialApplyDone?"state"===t.resolvedAuthority||!t.outputOnlyMember&&!t.observationPending:(t.initialApplyDone=!0,"state"===t.resolvedAuthority)))}getRecord(e){const t=Go.get(e);return t?.session===this?t:null}addTeardown(e,t){const n=Go.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(rs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=ne(e);null===s&&H(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),Xo(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,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=Lo(s).wait(t,()=>{if(a())try{oe(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=Go.get(e);void 0!==t&&t.session===this&&this.disposeRecord(t)}dispose(){for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){for(const e of this.records)null!==e.address&&(hn(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.records){if("active"!==t.phase)continue;const n=t.info;if(null===t.address&&null===t.patternListIndex)continue;const o="for"===n.bindingType?cn(n):null;if(null!==t.address?(hn(t.address,n),t.address=null):(mn(t.patternPathInfo,t.patternListIndex,n),t.patternPathInfo=null,t.patternListIndex=null),Sn(n),dn(n),this.registerAddress(t),null!==o){const e=cn(n);e!==o&&At(o)&&_t(e,kt(o)),e!==o&&Rt(o)&&Ot(e,Tt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return es(t)?t:null}(e);null!==t&&os(t)}handleMutations(e,t,n){for(const n of t)Zo(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)Zo(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&mi(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=Go.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Ho.get(t);void 0===e&&(e=ss(t),Ho.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;Xo(n,this);const o=this.knownMapFor(n);let s=Ho.get(e);void 0===s&&(s=ss(e),Ho.set(e,s));const r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}initializeRow(e,t){this.rowPlan=e;const n={registerAddress:!1,registerPathInfo:!1,applyOnReconnect:!1},o=e.slots;for(let e=0;e<t.length;e++){const s=t[e],r=o[e],i=s.replaceNode;Xo(i,this),this.addKnownRowBinding(i,s,e),this.optionsByBinding.set(s,n);const a={id:++Vo,info:s,generation:++Uo,phase:"active",teardowns:null,session:this,anchor:i,options:n,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:r.policy,resolvedAuthority:r.authority,initialSettled:!0,initialApplyDone:!1,outputOnlyMember:r.policy.outputOnly,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};if(Go.set(s,a),this.records.add(a),r.isEvent){try{Un(s)}catch(e){throw a.phase="failed",this.runTeardowns(a),this.records.delete(a),e}a.eventAttached=!0}}}activatePlanRows(e,t,n){const o=e.slots;for(let e=0;e<t.length;e++){const s=t[e],r=Go.get(s);if(void 0!==r&&r.session===this){if(r.options.registerAddress=!0,"disposed"===r.phase||"failed"===r.phase){const t=o[e];if(r.generation=++Uo,r.phase="active",r.initialPolicy=t.policy,r.resolvedAuthority=t.authority,r.initialSettled=!0,r.initialApplyDone=!1,r.outputOnlyMember=t.policy.outputOnly,this.records.add(r),t.isEvent){try{Un(s)}catch(e){throw r.phase="failed",this.runTeardowns(r),this.records.delete(r),e}r.eventAttached=!0}this.registerAddress(r,n);continue}null===r.address&&null===r.patternListIndex&&this.registerAddress(r,n)}else this.initialize([s],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}}addKnownRowBinding(e,t,n){const o=this.knownBindingsByNode.get(e);if(void 0===o)return void this.knownBindingsByNode.set(e,t);if(o instanceof Map)return void o.set("@plan:"+n,t);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,t),this.knownBindingsByNode.set(e,s)}start(e,t,n){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const o=this.optionsByBinding.get(e)??{...t},s={id:++Vo,info:e,generation:++Uo,phase:"discovered",teardowns:null,session:this,anchor:e.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};Go.set(e,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(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;Un(t)?e.eventAttached=!0:t.propSegments[0]!==y?(Xn(t)&&rs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const t=Jn(e),n=Hn(e,t),o=Gn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Kn.countOf(n)&&(Kn.remove(n,e)&&Gn.delete(n),!0))}return!1}(t)),An(t)&&rs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const t=_n(e),n=kn(e,t),o=Pn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==In.countOf(n)&&(In.remove(n,e)&&Pn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Zn(t.node,t.propName)&&-1===t.propModifiers.indexOf(u)){const n=function(e,t,n){let o=yo.get(e);void 0===o&&(o=new Map,yo.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&yo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});rs(e,n)}!function(e){const t=ee(e.node);if(null!==t){const n=ne(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&H(`CustomElementRegistry is unavailable for <${t}>.`))}if(Zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(u)){const t=$o(e),n=xo(e),o=So(e),s=vo(e,t,null!==n,o);let r=mo.get(s);void 0===r&&(r=No(e.propName,e.statePathName,e.inFilters,n,o),mo.set(s,r)),e.node.addEventListener(t,r),go.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Dn(t)&&rs(e,()=>function(e){if(e.propSegments[0]!==y)return!1;const t=jn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),jn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=ee(e.info.node);if(null===n)return void t();const o=ne(e.info.node);if(null===o&&H(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=Lo(o).wait(n,()=>{if(this.isAlive(e,s))try{oe(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});rs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Fo(e.info),n=qo(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void Eo++;this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending&&(e.observationPending=!1,Mo()),t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=ua(e.node.getRootNode());null===o&&H("No state tree found on this root for initial binding sync.");const s=St(e.node);o.createState("writable",t=>{t[Lt](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=rn(n);if(null!==o){const s=ua(ln(n,t));null===s&&H("No state tree found on this root for binding.");const r=Ut(s,n.statePathInfo);!function(e,t,n){let o=pn.get(e);void 0===o&&(o=new WeakMap,pn.set(e,o));const s=o.get(t);void 0===s?o.set(t,n):s instanceof Set?s.add(n):s!==n&&o.set(t,new Set([s,n])),null!==Pt&&Pt({type:"state:binding-added",absoluteAddress:Xt(e,t),binding:n})}(r,o,n),e.patternPathInfo=r,e.patternListIndex=o}else{const o=cn(n,t);fn(o,n),e.address=o}if(!e.options.registerPathInfo)return;const s=ua(n.replaceNode.getRootNode());null===s&&H("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&Go.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,Mo());const t=e.info;if(null!==e.address)try{hn(e.address,t),e.address=null,Sn(t),dn(t)}catch{}else if(null!==e.patternListIndex)try{mn(e.patternPathInfo,e.patternListIndex,t),e.patternPathInfo=null,e.patternListIndex=null,Sn(t),dn(t)}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=ee(e.node);if(null!==t){const n=ne(e.node),o=n?.get(t);if(void 0===o)return}if(Zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(u)){const t=$o(e),n=vo(e,t,null!==xo(e),So(e)),o=mo.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),go.remove(n,e)&&mo.delete(n)}}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{!function(e){if(!e.propName.startsWith(g))return!1;const t=qn(e),n=zn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);e.node.removeEventListener(o,n),0!==Fn.countOf(t)&&(Fn.remove(t,e)&&zn.delete(t))}(t)}catch{}}}}function as(e){let t=Ko.get(e);return void 0===t&&(t=new is(e),Ko.set(e,t)),t}function ls(e){return Go.get(e)?.session??null}const cs=new WeakMap;function ds(e,t){let n=cs.get(e);n||(n=new Set,cs.set(e,n)),n.add(t)}const us=new WeakMap;function fs(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const hs=Object.freeze([]);const ps=new WeakMap;const ms=new WeakMap;function gs(e){return ms.get(e)??[]}function ys(e,t){ms.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});let ws=0;function bs(){return`u${(ws++).toString(36)}`}let vs=0;class $s{uuid=bs();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(e,t){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._index=t,this._version=vs}get index(){return this._index}set index(e){this._index=e,this._version=++vs,this.indexes[this.position]=e}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=vs),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(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function xs(e,t){return new $s(e,t)}const Ss=new WeakMap;function Ns(e){return Ss.get(e)||null}function Ps(e,t){null!==t?Ss.set(e,t):Ss.delete(e)}const Is=new WeakMap,ks=Object.freeze([]),_s=new Set;function As(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:ks,s=Array.isArray(n)&&n.length>0?n:ks,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:ks,o=Array.isArray(t)&&t.length>0?t:ks;let s=Is.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Ns(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:_s,deleteIndexSet:new Set(i),addIndexSet:_s};let t=Ns(s);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=xs(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:_s,deleteIndexSet:_s,addIndexSet:new Set(t)}}if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}(o,s))return a={oldIndexes:i,newIndexes:i,changeIndexSet:_s,deleteIndexSet:_s,addIndexSet:_s};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}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=xs(e,o);t.push(n),l.add(n)}else{const e=i[d];d!==o&&r.add(e),t.push(e)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:l}}finally{void 0!==a&&(!function(e,t,n){let o=Is.get(e);o||(o=new WeakMap,Is.set(e,o)),o.set(t,n)}(o,s,a),Ps(s,a.newIndexes))}}(e,t,n);return function(e){for(let t=0;t<e.length;t++)e[t].index!==t&&(e[t].index=t)}(o.newIndexes),o}function Cs(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.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(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?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 e of i)a.add(n[e]);return a}const Es=new WeakMap;function Ms(e){return Es.get(e)??[]}function Ts(e,t){Es.set(e,t)}const Os=new WeakMap;function Rs(e){return Os.get(e)??null}function Ls(e,t){Os.set(e,t)}const js=new WeakMap;function Ds(e){return js.get(e)??[]}function Ws(e,t){js.set(e,t)}function Bs(e,t){const n=Ds(e);for(const e of n)Nt(e,t)}function zs(e,t,n){Bs(e,t);const o=Ms(e),s=Rs(e);null!==s&&s.activate(o,n.rootNode);for(const e of o){if(null===s){fn(cn(e),e)}(null===s||s.shouldApplyState(e))&&hi(e,n)}}function Fs(e){if(!e.mounted)return;const t=Ms(e),n=Rs(e);for(const e of t)if(null!==n)n.disposeBinding(e);else{hn(cn(e),e)}!function(e){const t=Ds(e);for(const e of t)Nt(e,null)}(e)}const qs=new WeakMap,Vs=Object.freeze(new Set);function Us(e,t){const n=qs.get(e);n?n.add(t):qs.set(e,new Set([t]))}function Gs(e){const t=qs.get(e);return void 0!==t?t:Vs}function Ks(e,t){const n=qs.get(e);n&&(n.delete(t),0===n.size&&qs.delete(e))}const Hs=new Set(["if","elseif","else","for"]);class Js{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t,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(e){for(const t of this._childNodeArray)Ao(t),e.appendChild(t);this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const e=this._firstNode,t=this._lastNode;if(null===e||null===t||null===e.parentNode)return this._childNodeArray;const n=[];for(let o=e;null!==o;o=o.nextSibling)if(n.push(o),o===t)return n;return this._childNodeArray}mountAfter(e){const t=e.parentNode;if(t){let n=e;for(const e of this._movableNodes()){if(n.nextSibling!==e){Ao(e);const o=t;e.parentNode===t&&"function"==typeof o.moveBefore?o.moveBefore(e,n.nextSibling):t.insertBefore(e,n.nextSibling)}n=e}}this._mounted=!0}tryDestroy(){const e=Rs(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRecords();for(const e of this._childNodeArray)Io(e),null!==e.parentNode&&e.parentNode.removeChild(e);const t=Ms(this);for(const e of t)if(Hs.has(e.bindingType)){const t=Gs(e.node);for(const e of t)e.tryDestroy()||e.unmount()}return this._mounted=!1,!0}unmount(){Rs(this)?.dispose();for(const e of this._childNodeArray)Io(e),null!==e.parentNode&&e.parentNode.removeChild(e);const e=Ms(this);for(const t of e){if(Hs.has(t.bindingType)){const e=Gs(t.node);for(const t of e)t.unmount()}Sn(t),dn(t)}this._mounted=!1}}function Xs(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function Ys(e){const t=document.createDocumentFragment(),n=new Js(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function Qs(e,t,n){const o=document.importNode(t.fragment,!0),s=t.nodeInfos,r=new Array(s.length);for(let e=0;e<s.length;e++){const t=fe(o,s[e].nodePath);null===t&&H(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),Qe(t),K(t),r[e]=t}const i=n.slots,a=new Array(i.length),l=[];for(let e=0;e<i.length;e++){const t=i[e],n=r[t.nodeIndex],o={...t.template,node:n,replaceNode:n};a[e]=o,t.isIndexBinding&&l.push(o)}const c=function(e,t){const n=new is;return n.initializeRow(e,t),n}(n,a),d=new Js(o);return Ls(d,c),Ts(d,a),ys(d,l),Ws(d,r),Us(e.node,d),d}function Zs(e){void 0!==e.uuid&&null!==e.uuid||H("BindingInfo.uuid is null.");const n=qe(e.uuid);n||H(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&Xs(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=fe(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===w||s===y)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==ee(r))return null;if("prop"===o&&Zn(r,e.propName))return null;let i;try{i=Fo({...e,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;n.push({nodeIndex:t,template:e,isEvent:"event"===o,isIndexBinding:e.statePathName in S,policy:i,authority:i.authority})}}return{directional:t,slots:n}}(n)),null!==r)return Qs(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=fe(e,s.nodePath);if(null===t&&H(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Je.has(t))continue;const r=Xe(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new is,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new Js(i,s);Ls(l,a.bindingSession),Ts(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in S&&c.push(e);return ys(l,c),Ws(l,a.nodes),Us(e.node,l),l}const er=Symbol.for("wcstack.transition-runner");function tr(e){const t=globalThis[er];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}const nr=new WeakSet,or=Symbol.for("wcstack.state.view-transition-naming");function sr(){const e=tr("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function rr(e,t,n){const o=function(e){const t=e.firstNode;if(null===t)return null;const n=e.lastNode;for(let e=t;null!==e;e=e.nextSibling){if(e.nodeType===Node.ELEMENT_NODE)return e;if(e===n)break}return null}(e);if(null===o||nr.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[or]??={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.`)):(nr.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${t}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${t}`))}const ir=new WeakMap,ar=new WeakMap,lr=new WeakMap,cr=new WeakMap;function dr(e,t,n){!function(e,t,n){let o=ar.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ar.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function ur(e,t){ir.set(e,t)}function fr(e,t){let n=lr.get(e.node);void 0===n&&(n=[],lr.set(e.node,n)),n.length<1e3?n.push(t):Ks(e.node,t)}function hr(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function pr(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function mr(e,n,s){const r=Boolean(s);let i;const a=Gs(e.node);i=0===a.size?Zs(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${pr(e)}`),Fs(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${pr(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);zs(i,St(e.node),n);const t=sr();null!==t&&rr(i,"branch",t)}}const gr=new WeakMap,yr=new WeakMap;const wr=new WeakMap;const br=new WeakMap;function vr(e){return br.get(e)??[]}const $r=new Set;const xr=Symbol.for("wcstack.trustedTypes.policy");function Sr(){const e=globalThis[xr];return null===e||"object"!=typeof e?null:e}let Nr;let Pr=!1;function Ir(e,t){if(Pr)return;if(!function(){if(void 0!==Nr)return Nr;if(!("trustedTypes"in globalThis))return Nr=!1,Nr;try{document.createElement("div").innerHTML="<i></i>",Nr=!1}catch{Nr=!0}return Nr}())return;Pr=!0;const n="function"==typeof Sr()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${t}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:e,property:t})}const kr={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function _r(e,n,s){if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==s){null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==ee(r)&&function(e,t,n){let o=gr.get(e);o||(o=new Map,gr.set(e,o)),o.has(t)||o.set(t,n)}(r,c,d);const t="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let e=!1;try{r[c]=t?function(e){if("string"!=typeof e)return e;const t=Sr(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Ir(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=ee(e);if(null===n)return null;const o=ne(e)?.get(n);if(void 0===o)return null;const s=se(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Zn(r,c)){const t=so(r,c,e.statePathName),o=ro(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??uo()??ao(t);if(a.visitedEdges.has(o))null!==Pt&&Pt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=lo(a,o);fo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:no++,writtenValue:n};ho.push({receipt:i,node:e});try{return r()}finally{ho.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=kr[c];e?e(r,s):(!function(e,t,n){let o=br.get(e);o||(o=[],br.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,$r.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));2===i.length&&"object"==typeof d&&null!==d&&null!==ee(r)&&(u in d?function(e,t,n,o){let s=wr.get(e);s||(s=new Map,wr.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}(r,c,u,d[u]):function(e,t,n){let o=yr.get(e);o||(o=new Map,yr.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)}(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const Ar=new WeakSet;function Cr(e,t,n){}const Er=new WeakMap;function Mr(e,t){if(null===e)return!1;const n=Er.get(e);if(void 0===n||0===n.size)return!1;for(const e of n)if(t===e||t.startsWith(e+s)||e.startsWith(t+s))return!0;return!1}const Tr=new WeakMap;function Or(e,t){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{t.$postUpdate(e+s+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...r)=>t[n](e+s+o,...r)}return t[o]}return t[e+s+o]}},set:(n,o,r)=>("string"!=typeof o||(t[e+s+o]=r),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Rr=new WeakMap,Lr=[];const jr=new WeakMap;let Dr=null;const Wr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Br=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function zr(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}function Fr(e,t,n){const o=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),r=t.length>0?t+s:"";for(const e of n){if(r.length>0&&!e.startsWith(r))continue;const t=e.slice(r.length);t.length>0&&-1===t.indexOf(s)&&o.push(t)}return o}const qr={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},Vr={binding:"Bound path",watch:"$watch path"};function Ur(e,t,n,o){return`[wcs/index-arity] ${e}("${t}") requires ${"$resolve"===e?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${ye}`}function Gr(e,t){return`[wcs/recursion-anchor] "${e}" does not match the declared recursion anchor "${t}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function Kr(e,t){return`$setAll("${e}") ${t}`}function Hr(e,t,n){return`[wcs/wildcard-rank] ${e} needs ${t} 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.${ye}`}const Jr=new WeakMap;function Xr(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(Mr(e.rootNode??null,n))return;const i=Y(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=Jr.get(e);return void 0===n&&(n=new Set,Jr.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const a=function(e,t,n){if(void 0!==zr(e,t))return Br;const o=Y(t).segments;let i=e,a="";for(let t=0;t<o.length;t++){const l=o[t],c=a;if(a=0===t?l:a+s+l,t>0&&t<o.length-1&&void 0!==zr(e,a))return Wr;if(Object(i)!==i)return Wr;if(l===r){if(!Array.isArray(i)||0===i.length)return Wr;i=i[0];continue}const d=zr(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:Fr(i,c,n)};if("function"==typeof d.get)return t===o.length-1?Br:Wr;i=d.value}return Br}(t,n,e.getterPaths);"missing"===a.existence&&(function(e,t){return!0===Zr.get(e)?.has(t)}(e,n)||("binding"!==o?ti(e,n,o,a):function(e,t,n){let o=Yr.get(e);void 0===o&&(o=new Map,Yr.set(e,o));if(o.set(t,n),Qr.has(e))return;Qr.add(e),setTimeout(()=>function(e){Qr.delete(e);const t=Yr.get(e);if(void 0===t)return;Yr.delete(e);for(const[n,o]of t)ti(e,n,"binding",o)}(e),0)}(e,n,a)))}const Yr=new WeakMap,Qr=new WeakSet,Zr=new WeakMap;function ei(e,t){let n=Zr.get(e);void 0===n&&(n=new Set,Zr.set(e,n)),n.add(t),Yr.get(e)?.delete(t)}function ti(e,t,n,o){console.warn(`[@wcstack/state] [${qr[n]}] ${Vr[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ge(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ye}`),null!==Pt&&Pt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}function ni(e,t){const n=xn(t);if(n.pathInfo.path in S){const e=St(t.node);return null===e&&H(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&H("ListIndex not found for loopContext:");const n=S[t];void 0===n&&H(`Invalid index name: ${t}`);const o=nn(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&H(Hr(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[jt](n)}const oi=new WeakSet;function si(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const ri=Object.freeze({[b]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&H("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[v]:function(e,t,n){const o=e.node,s=e.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[$]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;s[o]!==n&&(s[o]=n)},[w]:function(e,t,n){Bn(n)||H("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ps.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||H('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=ee(e);if(null===t)return null;const n=ne(e)?.get(t);return void 0===n&&H(`Custom element <${t}> is not defined for command binding.`),se(e)}(r);null===a&&H(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||H(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ge(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ps.delete(e));const l=new WeakRef(r);let c=null;c=o.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void ps.delete(e);const o=n[i];return"function"!=typeof o&&H(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),ps.set(e,{token:o,unsubscribe:c,elementRef:l})}}),ii={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Ar.has(e.replaceNode)){Ar.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,n,o){const s=e.statePathInfo,i=rn(e),a=cn(e),l=kt(a),c=l.length>0&&!ar.has(e.node)?[]:l,d=As(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!==e.node.parentNode){let t=cr.get(e.node);if(void 0===t){const n=ir.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.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}(e.node,n),cr.set(e.node,t)}if(t){const t=e.node.parentNode;t.textContent="",t.appendChild(e.node)}}let f=ar.get(e.node),h=u?1e3-function(e){return lr.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==f){for(const t of d.deleteIndexSet){const n=f.get(t);void 0!==n&&(h<=0&&n.tryDestroy()?Ks(e.node,n):(Fs(n),n.unmount(),fr(e,n),h-=1),u||f.delete(t))}u&&(ar.delete(e.node),f=void 0)}let p=e.node;const m=Y(s.path+"."+r),g=n.stateElement.loopContextStack,y=Cs(d);let w=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&p.isConnected&&(w=document.createDocumentFragment(),Qt(w,n.rootNode));const b=t(),v=sr(),$=e.uuid??"",x=lr.get(e.node);for(const t of d.newIndexes){let o;if(d.addIndexSet.has(t)){const r=vn(m,t);g.createLoopContext(r,r=>{if(o=void 0!==x?x.pop():void 0,void 0===o&&(o=Zs(e)),null!==w)b&&w.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${t.index}`)),o.appendTo(w),b&&w.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${t.index}`));else{if(p.nextSibling!==o.firstNode){if(b){const e=document.createComment(`@@wcs-for-start:${$}:${s.path}:${t.index}`);p.parentNode.insertBefore(e,p.nextSibling),p=e}o.mountAfter(p)}if(b){const e=document.createComment(`@@wcs-for-end:${$}:${s.path}:${t.index}`),n=o.lastNode??p;n.parentNode.insertBefore(e,n.nextSibling)}}zs(o,r,n),null!==v&&rr(o,"row",v)}),void 0===o&&H(`Content not found for ListIndex: ${t.index} at path "${s.path}"`)}else{if(o=void 0!==f?f.get(t)??null:null,d.changeIndexSet.has(t)){const e=gs(o);for(const t of e)hi(t,n)}null===o&&H(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==y&&y.has(t)&&hr(p,o.firstNode)||p.nextSibling===o.firstNode||o.mountAfter(p),e){const e=o,s=vn(m,t);g.createLoopContext(s,t=>{zs(e,t,n)})}}p=o.lastNode||p,void 0===f&&(f=new WeakMap,ar.set(e.node,f)),f.set(t,o)}ir.set(e.node,p),null!==w&&(e.node.parentNode.insertBefore(w,e.node.nextSibling),Qt(w,null))},if:mr,else:mr,elseif:mr,radio:function(e,t,n){const o=e.node,s=fs(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=fs(o.value,e.inFilters),r=Array.isArray(n)?n:hs;o.checked=r.includes(s)}},ai=new WeakMap,li=new WeakMap,ci=new WeakMap;function di(){}function ui(e){const t=e.replaceNode,n=e.propSegments[0];return function(e,t){return!0===cs.get(e)?.has(t)}(t,n)?Cr:function(e,t){return!0===us.get(e)?.has(t)}(t,n)?di:_r}function fi(e,t){const n=fs(ni(t.state,e),e.outFilters);if(!0===li.get(e))return void t.deferredSelectBindings.push({binding:e,value:n,stateElement:t.stateElement});let o=ai.get(e);if(void 0===o){if(ai.has(e))return o=ui(e),o===Cr&&ai.set(e,o),void o(e,t,n);if(o=ii[e.bindingType],void 0===o){const t=e.propSegments[0];if(o=ri[t],ai.set(e,o),void 0===o){ee(e.replaceNode)?(o=ui(e),o===Cr&&ai.set(e,o)):(o=_r,ai.set(e,o))}}if(o===_r){if("SELECT"===e.node.tagName){const o=e.propSegments[0];if("value"===o||"selectedIndex"===o)return t.deferredSelectBindings.push({binding:e,value:n,stateElement:t.stateElement}),void li.set(e,!0)}}o(e,t,n)}else o(e,t,n)}function hi(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=cn(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=ls(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==ci.get(e)){const t=ee(e.replaceNode);if(t&&void 0===ne(e.replaceNode)?.get(t))return void function(e,t){if(oi.has(e))return;oi.add(e);const n=()=>{oi.delete(e);const t=ls(e);(null===t||t.shouldApplyState(e))&&mi([e])},o=n=>{oi.delete(e),si(t,n)},s=ls(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{oi.delete(e),r()})||(oi.delete(e),r()))}const r=ne(e.replaceNode);if(null===r)return oi.delete(e),void si(t,new Error("CustomElementRegistry is unavailable."));Lo(r).wait(t,()=>{e.replaceNode.isConnected?n():oi.delete(e)},o)}(e,t);ci.set(e,!0)}if(!0===t.sameRootVerified)return void fi(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Zt(o),null===o&&H("Root node for fragment not found for binding.")),o!==t.rootNode){const n=ua(o);null===n&&H("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};fi(e,r)})}else fi(e,t)}function pi(e,t,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:e.statePathName,bindingType:e.bindingType,node:e.node},r=o.get(n);void 0===r?o.set(n,[{error:t,info:s}]):r.push({error:t,info:s})}else console.error(`[@wcstack/state] binding "${e.bindingType}: ${e.statePathName}" failed to apply; the rest of this batch continues.`,{node:e.node,error:t});null!==Pt&&Pt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function mi(e,t){let n=0;const s=new Set,r=new Map,i=new Map,a=[],l=new Map;for(;n<e.length;){let c=e[n];if(!1===c.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${c.bindingType} ${c.statePathName} on ${c.node.nodeName}`,c),n++;continue}let d=c.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Zt(d),null===d&&H("Root node for fragment not found for binding."));const u=ua(d);null===u&&H("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{hi(c,f)}catch(e){pi(c,e,u,l)}n++;const t=e[n];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;c=t}})}for(const{binding:e,value:n,stateElement:o}of a)try{_r(e,{propagationContextByBinding:t},n)}catch(t){pi(e,t,o??null,l)}for(const[e,t]of r.entries())_t(e,t),Ot(e,t);for(const[e,t]of i.entries())e.createState("writable",e=>{e[Ft](Array.from(t))});for(const[e,t]of l.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[qt](n,o)}catch(e){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:e,original:n,node:o.node})}})}function gi(e,t,n){const[o,s,r]=Ye(e,n),i=as(e);for(const e of o)Nt(e,t);mi(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=Ze(o);0!==e.length&&(Nt(o.node,t),mi(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const yi=/\{\{\s*(.+?)\s*\}\}/g,wi=new Set(["SCRIPT","STYLE"]);function bi(e){if(!o.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&wi.has(e.parentElement.tagName)||vi(e)}(e);const t=Array.from(e.querySelectorAll("template"));for(const e of t)if("http://www.w3.org/2000/svg"===e.namespaceURI){const t=document.createElement("template"),n=Array.from(e.childNodes);for(let e=0;e<n.length;e++){const o=n[e];t.content.appendChild(o)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),bi(t.content)}else bi(e.content)}function vi(e){const t=e.data;if(yi.lastIndex=0,!yi.test(t))return;yi.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=yi.exec(t));){o.index>s&&n.appendChild(document.createTextNode(t.slice(s,o.index)));const e=o[1];n.appendChild(document.createComment(`@@: ${e}`)),s=o.index+o[0].length}s<t.length&&n.appendChild(document.createTextNode(t.slice(s))),e.parentNode.replaceChild(n,e)}let $i;function xi(){if($i)return $i;const e=[],t=ke("not",e)(Pe);return $i={filterName:"not",args:e,filterFn:t},$i}const Si=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Ni(e,t){const n=t+s+r,o=e.indexOf("|");let i,a;if(-1!==o?(i=e.slice(0,o).trim(),a=e.slice(o)):(i=e.trim(),a=""),"."===i)i=n;else{if(!i.startsWith("."))return e;i=n+s+i.slice(1)}return a.length>0?i+a:i}function Pi(e,t){const n=Si.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Ni(s,t)+r}function Ii(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Ni(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function ki(e,t){return Ii(e,t)}function _i(e,t){const n=o.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Pi(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Ii(r,t);e!==r&&o.setAttribute(n,e)}}}function Ai(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}function Ci(e){const t=[],n=He(e);for(const e of n){const n=Ve(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:Ai(o),parseBindTextResults:n})}return t}function Ei(e){const t=Array.from(e.childNodes);for(const n of t)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&e.removeChild(n)}}const Mi=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Ti=xi();function Oi(e,t){const n=t.outFilters;return{...t,outFilters:[...n,Ti],bindingType:e}}function Ri(e,t,n,o,s,r=!0){Ei(t),"string"==typeof o&&_i(t,o),Li(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ci(t)};return void 0!==s&&function(e,t,n){for(const o of e)for(let e=0;e<o.parseBindTextResults.length;e++){const s=o.parseBindTextResults[e];null==s.uuid&&(o.parseBindTextResults[e]=t(s,n))}}(i.nodeInfos,s,o),i}function Li(e,t,n,s){const r=o.commentElsePrefix,i=Ge(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=ki(i,n));let a=Re(i)[0];const d=Mi.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=bs();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&H("'else' binding found without preceding 'if' or 'elseif' binding."),a=Oi("else",l.parseBindTextResult),p=Ri(e,f,a,m,s,!1),Fe(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Ai(o),parseBindTextResults:Ve(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&H("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ri(e,f,a,m,s),Fe(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=bs(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Oi("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Ai(n),parseBindTextResults:Ve(n)}),Fe(o,e,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:Ai(g),parseBindTextResults:Ve(g)})):t.replaceWith(g)}else{p=Ri(e,f,a,m,s),Fe(h,e,p);const n=document.createComment(`@@${d}:${h}`);t.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}async function ji(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=ne(e);null===s&&H(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(Ue(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function Di(e){if(e===document)await ji(document),bi(document),Li(document,document),gi(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await G(t.host),await ji(t),bi(t),Li(t,t),gi(t,null)}}const Wi="2.3.0",Bi="undefined"==typeof HTMLElement?class{}:HTMLElement,zi=/^@@wcs-(?:for|if|elseif|else):[^-]/,Fi=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,qi=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Vi=/^@@wcs-text-start:(.+)$/;function Ui(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Gi extends Bi{_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(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=Wi.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static find(e){const t=o.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=Ui(JSON.stringify(t)),e.appendChild(n);const s=Array.from(ze.keys());for(const t of s){const n=qe(t);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",t);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),e.appendChild(s)}const r=Array.from($r);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=vr(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=Ui(JSON.stringify(t)),e.appendChild(n)}}$r.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Fi.test(e.data)||qi.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;zi.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=Vi.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(o.tagNames.ssr),s=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;Fi.test(e.data)&&i.push(e)}for(const e of i){const t=Fi.exec(e.data),n=`@@wcs-${t[1]}-end:${t[2]}`;let o=e.nextSibling;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=e}e.remove()}Gi.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(zi.test(e.data)){const t=e.data.split(":")[1];l.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of l){const n=s.get(t);if(n){const t=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&t.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const c=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of c)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const Ki=new Set(["for","if","elseif","else"]);function Hi(e){const t=new is;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=Ye(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function Ji(e,t,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function Xi(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Re(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,xi()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;Ei(a),"string"==typeof l&&_i(a,l),Li(n,a,l);Fe(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Ci(a)})}}async function Yi(e){await ji(e);const t=e.querySelectorAll(o.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${Wi}". Falling back to full render.`),Gi.cleanupDom(e),!1}for(const n of t)Xi(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=Fi.exec(e.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=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:l,nodes:c})}return t}(document.body);!function(e,t){const n=new Map;for(const o of t){if(0===o.nodes.length)continue;const t=Ys(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=Hi(o.nodes);Ls(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");Ts(t,s),Ws(t,i);const l=[];for(const e of s)e.statePathName in S&&l.push(e);if(ys(t,l),"for"===o.type&&null!==o.index){const i=Ji(e,"for",o.uuid);if(i){const e=xs(null,o.index);dr(i,e,t),ur(i,o.nodes[o.nodes.length-1]),Us(i,t),Bs(t,vn(Y(o.path+"."+r),e)),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let l=n.get(o.uuid);l||(l=[],n.set(o.uuid,l)),l.push(e)}}else{const n=Ji(e,o.type,o.uuid);n&&(Us(n,t),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[t,o]of n){const n=Ji(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=qe(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ua(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&Ps(t,o)})}}(document.body,n),Gi.removeBlockBoundaryComments(document.body);const s=[];for(const e of t)e.parentNode&&(s.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());Gi.restoreTextBindings(document.body);const[i,a]=Ye(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(Nt(e,null),t.setAttribute("data-wcs-completed",""))}else Nt(e,null);const l=[],c=[],d=as(document.body).initialize(a);for(const e of d)if("event"!==e.bindingType)if(Ki.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(r))continue;l.push(e)}for(const e of c)if("for"===e.bindingType){const t=cn(e),n=ua(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(_t(t,o),Ot(t,o))})}mi(l);for(const{el:e,parent:t,next:n}of s)t.insertBefore(e,n);const u=e.querySelectorAll(o.tagNames.ssr);for(const t of u){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const f=e.querySelectorAll("[data-wcs-completed]");for(const e of f)e.removeAttribute("data-wcs-completed");return!0}const Qi=Symbol.for("wcstack.binder");const Zi=Symbol.for("wcstack.binder.pending"),ea=Symbol.for("wcstack.binder.taken");function ta(){const e=function(){const e=globalThis[Qi];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;const t=function(){const e=globalThis;let t=e[Zi];return void 0===t&&(t=[],e[Zi]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[ea];return void 0===t&&(t=new WeakSet,e[ea]=t),t}();for(const t of n)o.add(t),e.bind(t)}function na(e){if(Yo(e))return!0;if(!oa(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(`[${o.bindAttributeName}]`);return null!==t&&Yo(t)}function oa(e){return 1===e.nodeType}function sa(e){if(na(e))return;bi(e),Li(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);gi(t&&s?n:e,null)}const ra=[];function ia(){const e=ra.splice(0,ra.length);for(const t of e)sa(t);ta()}const aa={protocol:"wcs-binder",version:1,bind:function(e){var t;oa(e)&&!na(e)&&(t=e.getRootNode(),ha.has(t)?sa(e):ra.push(e))}};const la=new WeakMap,ca=new WeakMap,da=new Set;function ua(e){return la.get(e)??null}function fa(e){return ca.get(e)??Promise.resolve()}const ha=new WeakSet;function pa(e){ha.add(e)}function ma(e,n){const s=la.get(e);if(null===n){if(void 0===s)return;la.delete(e),da.delete(s),null!==Pt&&Pt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(void 0===s){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await Yi(e)||await Di(e)}else await Di(e);pa(e),ia(),t()}catch(e){n(e)}})});ca.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await Di(e),pa(e),ia(),t()}catch(e){n(e)}})});ca.set(e,t)}}void 0!==s&&H('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="...">.'),la.set(e,n),da.add(n),function(e,t){const n=jr.get(e);if(void 0===n||0===n.length||null===Dr)return;jr.delete(e);const o=Dr;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,n),null!==Pt&&Pt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}let ga=0,ya=0;const wa=[];function ba(e,t=0){const n=wa.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?wa.push(o):wa.splice(n,0,o)}function va(e){queueMicrotask(()=>{throw e})}const $a=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(e,t=null){ga>ya&&(ya=ga);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&(Mt++,null===Et&&(Et=new Map),queueMicrotask(()=>{const e=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(e)}))}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e){const n=new Map;for(const t of e){const e=n.get(t.absoluteAddress);null!==Pt&&null!=e&&null!==t.context&&e.transactionId!==t.context.transactionId&&Pt({type:"propagation:coalesced",absoluteAddress:t.absoluteAddress,droppedTransactionId:e.transactionId,winnerTransactionId:t.context.transactionId}),n.set(t.absoluteAddress,t.context)}const o=[],s=new Map;for(const[e,t]of n){if(null!==t&&t.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,transactionId:t.transactionId,hop:t.hop,maxHops:32}),null!==Pt&&Pt({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop});continue}const n=gn(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(o.push(e),null!==t&&s.set(e,t));else!1!==n.replaceNode.isConnected&&(o.push(n),null!==t&&s.set(n,t))}try{const e=()=>{s.size>0?mi(o,s):mi(o)};if(t()||0===o.length)e();else{const t=function(e,t,n){const o=tr(e);if(null!==o)return o.run(t,{source:e,types:n});t()}("state",e);void 0!==t&&t.catch(va)}}finally{!function(){if(0!==Mt&&(Mt--,!(Mt>0||null===Et))){for(const[e,t]of Et)Ct.set(e,t);Et=null}}(),function(e){for(const t of wa.slice())t.listener(e)}(new Set(n.keys()))}}};function xa(){return $a}const Sa=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Na(e,t,n,o){return{node:e,propName:t.propName,statePathName:t.statePathName,bindingType:t.bindingType,inFilters:t.inFilters,outFilters:t.outFilters,origin:n,raw:o}}const Pa="__WCSTACK_DEVTOOLS_HOOK__";function Ia(){const e=globalThis,t=e[Pa];if(void 0!==t)return 2!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 2. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:2,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[Pa]=n,n}const ka=e=>{null!==Pt&&Pt({type:"state:update-batch",addresses:e})};function _a(e){const t=null!==Pt;!function(e){Pt=e}(e);const n=null!==e;n&&!t?ba(ka,0):!n&&t&&function(e){const t=wa.findIndex(t=>t.listener===e);-1!==t&&wa.splice(t,1)}(ka)}function Aa(e){return{rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency,watchPaths:e.watchPaths??null,keyedListPaths:void 0===e.listKeys||null===e.listKeys?null:new Set(e.listKeys.keys())}}function Ca(e){return ua(e)??H("devtools: no state tree on this root")}let Ea=null;function Ma(){if(t())return;if(null!==Ea)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Wi,getStateElements(){const e=[];for(const t of da)e.push(Aa(t));return e},overlays:e=>function(e){const t=wt.get(e);if(void 0===t)return[];const n=[];for(const e of t.values()){const t=e.deref();void 0!==t&&n.push(t)}return n}(Ca(e)).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join("."),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]})),keys(e){const t=Ca(e),n=[];return t.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}n.push(t)}}),n},read(e,t,n){let o;return Ca(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){Ca(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>function(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=[...e.inFilters,...e.outFilters].map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=qe(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(Na(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=ue(t,Re(n));for(const o of e)r(Na(t,o,"attribute",n))}catch{}continue}const t=Sa.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=qe(s);if(null===a){if(n===o.commentTextPrefix)try{r(Na(e,Be(s),"comment",s))}catch{}}else r(Na(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:_a};Ea=e,Ia().register(e)}const Ta={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Wi),Gi.buildContent(o,Gi.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const Oa="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ra=0;async function La(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Ra}\n`;let s=!1;const r=e=>{e.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+o],{type:"application/javascript"}),s=URL.createObjectURL(t);try{n=await import(s)}finally{URL.revokeObjectURL(s)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+o)));n=await import(`data:application/javascript;base64,${t}`)}}catch(e){throw new Error(function(e,t,n){const o=t?.message??String(t);return n?`The inline <script> of state "${e}" 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 ${Oa}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Oa}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function ja(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){H(`Failed to load script file: ${e}`)}}class Da{_loopContextStack=Array(a).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&H("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=a&&H("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&&H("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const e=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==e&&H("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&&H(`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=t(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 Wa=new WeakMap;function Ba(e,t){let n=Wa.get(e);void 0===n&&(n=new Map,Wa.set(e,n));let o=n.get(t);return void 0===o&&(o=new Wn(t,e),n.set(t,o)),o}const za=new WeakMap;function Fa(e){const t=za.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return Ba(e,n)},has:(t,n)=>"string"==typeof n&&e.commandTokenNames.has(n),ownKeys:()=>Array.from(e.commandTokenNames),getOwnPropertyDescriptor(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Ba(e,n)}},set(){H("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){H("$command namespace is read-only; deleting from it is not allowed.")}});return za.set(e,n),n}const qa=Symbol("wcs-stream-last-notified-uncertain"),Va=new WeakMap;function Ua(e,t){const n=Va.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Ga(e,t){const n=Va.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:qa,error:Object.is(o.error,null)?null:qa})}const Ka=new Set;function Ha(e){Ka.delete(e)}const Ja=new WeakMap;function Xa(e){return Ja.get(e)??new Map}function Ya(e){Ha(e);const t=Ja.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Ga(e,n.name)}const Qa=(e,t)=>t,Za=new Set;function el(e,t){const n=t[R];if(void 0===n)return void Ua(e,Za);"object"==typeof n&&null!==n||H(`${R} 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&&H(`${R} entry name must be a non-empty string.`),i.includes(s)&&H(`${R} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&H(`${R} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&H(`${R} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&H(`${R} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(i)&&H(`${R} entry "${i}" conflicts with a getter declared on the state.`),e.setterPaths.has(i)&&H(`${R} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||H(`${R} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&H(`${R} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&H(`${R} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&H(`${R} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&H(`${R} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??Qa,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};i in t||(t[i]=c.definition.initial),o.set(i,c)}!function(e,t){Ja.set(e,t)}(e,o),Ua(e,new Set(o.keys()))}function tl(e,t){"string"==typeof t&&0!==t.length||H(`[wcs/recursion-declaration-invalid] ${j} ${e} must be a non-empty string.`);const n=t.split(s);n.some(e=>0===e.length)&&H(`[wcs/recursion-declaration-invalid] ${j} ${e} "${t}" must not contain empty path segments.`),n.length<2&&H(`[wcs/recursion-declaration-invalid] ${j} ${e} "${t}" must name a list element: a property path ending with "${s}${r}" (for example "nodes${s}${r}").`),n[n.length-1]!==r&&H(`[wcs/recursion-declaration-invalid] ${j} ${e} "${t}" must end with "${s}${r}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&H(`[wcs/recursion-declaration-invalid] ${j} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&H(`[wcs/recursion-declaration-invalid] ${j} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===r&&H(`[wcs/recursion-declaration-invalid] ${j} ${e} "${t}" must have exactly one "${r}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===D&&H(`[wcs/recursion-declaration-invalid] ${j} ${e} "${t}" must not contain "${D}" — the declaration is what gives "${D}" its meaning.`),isNaN(Number(n[o]))||H(`[wcs/recursion-declaration-invalid] ${j} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}function nl(e){const t=[];let n=e;for(;n&&n!==Object.prototype;)t.push(n),n=Object.getPrototypeOf(n);const o={};for(let e=t.length-1;e>=0;e--)Object.assign(o,Object.getOwnPropertyDescriptors(t[e]));return o}function ol(e){return-1!==e.indexOf(D)}function sl(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+s;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(ol(o))return null;const i=o.slice(1).split(s);return i[0]===r||i.some(e=>0===e.length)?null:o}function rl(e){return 0===e.length?e:s+ll(e.slice(1))}function il(e,t,n){const o=s+e.repeat,r=t.length<=n.length?t:n,i=t.length<=n.length?n:t;if(!i.endsWith(r))return!1;const a=i.slice(0,i.length-r.length);if(0===a.length)return!0;if(a.length%o.length!==0)return!1;for(let e=0;e<a.length;e+=o.length)if(!a.startsWith(o,e))return!1;return!0}function al(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(s,o-1))if(il(e,t,n.slice(0,o)))return!0;return!1}function ll(e){const t=e.split(s);for(let e=0;e<t.length;e++)t[e]===r||Number.isNaN(Number(t[e]))||(t[e]=r);return t.join(s)}function cl(e,t){const n=e.repeat.split(s),o=s+e.repeat;let r=t;for(;r.startsWith(o);)r=r.slice(o.length);if(0===r.length||r===s+e.repeatList+s+"length")return!0;for(let e=1;e<n.length;e++)if(r===s+n.slice(0,e).join(s))return!0;return!1}function dl(e,t,n){n<0&&H(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=s+e.repeat;const a=o+t;let l=0;for(const e of a.split(s))e===r&&l++;return l>i&&H(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${a}"), which needs ${l} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),a}function ul(e,t){return dl(e,"",t)}function fl(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const o=n.slice(e.anchor.length,n.length-t.length);if(0===o.length)return 0;const r=s+e.repeat;let i=0,a=0;for(;a<o.length;){if(!o.startsWith(r,a))return null;a+=r.length,i++}return i}const hl=new WeakMap;function pl(e,t){null===t?hl.delete(e):hl.set(e,t)}function ml(e){const t=hl.get(e);t&&(t.dirty=!0)}const gl=new WeakSet;function yl(e){return"function"==typeof e.get&&gl.has(e.get)}function wl(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&yl(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}!function(e,t,n){for(const o of n){const n=Y(o),s=Ut(e,n),r=n.wildcardParentPathInfos,i=(e,t,n)=>{if(n===r.length)return void pl(Xt(s,t),null);const o=0===n?0:r[n-1].segments.length+1;let a=e;for(const e of r[n].segments.slice(o))a=a?.[e];if(!Array.isArray(a))return;const l=Ns(a);if(null===l)return;const c=Math.min(l.length,a.length);for(let e=0;e<c;e++)i(a[e],l[e],n+1)};i(t,null,0)}}(e,t,n)}}const bl="[wcs/recursion-declaration-invalid]";class vl{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(e,t){this.spec=e;const n=nl(t);for(const[t,o]of Object.entries(n)){if(!ol(t))continue;"function"==typeof o.set&&H(`${bl} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&H(`${bl} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=sl(e,t);null===n&&H(Gr(t,e.recursiveAnchor)),0===n.length&&H(`${bl} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${s}total"), not the node.`),cl(e,rl(n))&&H(`${bl} "${t}" names the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${e.recursiveAnchor}${s}total").`),this._definitions.set(t,{recursivePath:t,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(ol(t)||yl(n))continue;const e=this._matchExpansion(t);null!==e&&H(`${bl} "${t}" is already defined on the state, so the recursive getter "${e}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const e=Array.from(this._definitions.values());for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)il(this.spec,e[t].suffix,e[n].suffix)&&H(`${bl} "${e[t].recursivePath}" and "${e[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(e){for(const t of this._definitions.values())if(al(this.spec,t.suffix,e))return t.recursivePath;return null}recursiveGetterOwningPath(e){const t=this._ownerByPathInfo.get(e);if(void 0!==t)return t;const n=this.recursiveGetterOwning(e.path);return this._ownerByPathInfo.set(e,n),n}recursiveGetterOwning(e){const t=this._accessors.get(e);if(void 0!==t)return t.recursivePath;const n=ll(e),o=this._ownerByPath.get(n);if(void 0!==o)return o;let r=null;if(n.startsWith(this.spec.anchor)){r=this._matchExpansion(n);for(let e=n.lastIndexOf(s);null===r&&e>this.spec.anchor.length;e=n.lastIndexOf(s,e-1))r=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,r),r}_matchExpansion(e){for(const t of this._definitions.values())if(null!==fl(this.spec,t.suffix,e))return t.recursivePath;return null}materializeForPathInfo(e,t){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(t);if(void 0!==n)return n;const o=this.materializeFor(e,t.path);return this._accessorByPathInfo.set(t,o),o}materializeFor(e,t){const n=this._accessors.get(t);if(void 0!==n)return n;if(!t.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const e of this._definitions.values()){const n=fl(this.spec,e.suffix,t);null!==n&&(null!==o&&H(`"${t}" matches both "${o.recursivePath}" and "${e.recursivePath}".`),o=e,s=n)}return null===o?null:this._define(e,o,s,t)}_define(e,t,n,o){const s=e.findStateDescriptor(o);void 0===s||yl(s)||H(`"${o}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:t.recursivePath,depth:n}),i=t.get,a=function(){return i.call(this)};var l;return l=a,gl.add(l),e.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(e,n),this._accessors.set(o,r),r}_registerListPaths(e,t){for(const n of function(e,t){const n=[];n.push(e.anchorList);for(let o=0;o<t;o++)n.push(ul(e,o)+s+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){wl(e,t,new Set(this._accessors.keys()))}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let o=n[t];return void 0===o&&(o=dl(this.spec,e,t),n[t]=o),o}accessorFor(e){return this._accessors.get(e)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const $l=new WeakMap,xl=new WeakMap;function Sl(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Xa(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Xa(e).has(n),ownKeys:()=>Array.from(Xa(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Xa(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){H(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){H(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Nl(e){const t=$l.get(e);if(void 0!==t)return t;const n=Sl(e,B,e=>e.status);return $l.set(e,n),n}function Pl(e){const t=xl.get(e);if(void 0!==t)return t;const n=Sl(e,z,e=>e.error);return xl.set(e,n),n}function Il(e){$l.delete(e),xl.delete(e)}let kl=null;async function _l(e,t,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 e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;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 e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",i)}}function Al(e){const t=Xa(e);if(0!==t.size){!function(e){Ka.add(e)}(e);for(const n of t.values())Cl(e,n)}}function Cl(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=kl,r=new Set;let i;kl=r;try{e.createState("readonly",e=>{i=n(e)})}finally{kl=o}i instanceof Promise&&H(`${R} entry "${t.name}" args must be synchronous (it returned a Promise).`);const a=`${B}${s}${t.name}`,l=`${z}${s}${t.name}`;for(const n of r){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==a&&o.path!==l||H(`${R} entry "${t.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&&H(`${R} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=r,i}(e,t);e.createState("writable",e=>{e[t.name]=t.definition.initial}),El(e,t,"active",null);const r=t.definition,i={fold(n){e.createState("writable",e=>{e[t.name]=r.fold(e[t.name],n)})},done(){El(e,t,"done",null)},fail(o){El(e,t,"error",o),n.abort()}};_l(r.source,o,n.signal,i)}function El(e,t,n,o){t.status=n,t.error=o;const r=function(e,t){return Va.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),i=r.status!==n,a=!Object.is(r.error,o);(i||a)&&(!function(e,t,n,o){let s=Va.get(e);void 0===s&&(s=new Map,Va.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{i&&e.$postUpdate(`${B}${s}${t.name}`),a&&e.$postUpdate(`${z}${s}${t.name}`)}))}ba(function(e){const t=Ka;if(0===t.size)return;const n=[];for(const o of t)for(const t of Xa(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&Xa(e).get(o.name)===o)try{Cl(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Xa(e).get(o.name)===o&&El(e,o,"error",n)}},20);const Ml=new WeakMap,Tl=new WeakMap,Ol=new Set,Rl=new Map;function Ll(e){return Ml.get(e)??Rl}function jl(){return Ol}const Dl=new Map;function Wl(e){return Tl.get(e)??Dl}function Bl(e){0===e.length&&H(`[wcs/watch-declaration-invalid] ${L} entry name must be a non-empty state path.`),e.startsWith("$")&&H(`[wcs/watch-declaration-invalid] ${L} entry "${e}" must not start with "$" (reserved namespace).${ye}`),e.includes("@")&&H(`[wcs/watch-declaration-invalid] ${L} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ye}`),e in Object.prototype&&H(`[wcs/watch-declaration-invalid] ${L} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=Y(e);for(const n of t.segments)0===n.length&&H(`[wcs/watch-declaration-invalid] ${L} entry "${e}" has an empty path segment.${ye}`);return t.wildcardCount>i&&H(`[wcs/watch-declaration-invalid] ${L} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function zl(e,t){const n=t[L];if(void 0===n)return null;"object"==typeof n&&null!==n||H(`[wcs/watch-declaration-invalid] ${L} must be an object mapping state paths to handler functions.${ye}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&H(`[wcs/watch-declaration-invalid] ${L} entry "${t}" must be a function.${ye}`);const n=Bl(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Ml.set(e,t)}(e,o),s.size>0?s:null}const Fl=new WeakMap;function ql(e,t,n){let o=Fl.get(e);void 0===o&&(o=new Map,Fl.set(e,o)),o.set(t,n)}const Vl=new Map;function Ul(e){0===Ll(e).size&&0===Wl(e).size||(function(e){Ol.add(e)}(e),function(e){const t=[];for(const n of Ll(e).values())Kl(e,n)&&t.push(n);for(const n of Wl(e).values())for(const o of n)Kl(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{ql(e,Gl(e,o),n[o.path])}catch(t){Jl(e,o.path,"prime",t)}})}(e))}function Gl(e,t){return Xt(Ut(e,t.pathInfo),null)}function Kl(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Hl={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Jl(e,t,n,o){console.error(`[@wcstack/state] $watch ${Hl[n]} "${t}" threw.`,o),null!==Pt&&Pt({type:"state:watch-error",phase:n,path:t,error:o})}function Xl(e,t){if(e.entry.order!==t.entry.order)return e.entry.order-t.entry.order;const n=Math.min(e.indexes.length,t.indexes.length);for(let o=0;o<n;o++)if(e.indexes[o]!==t.indexes[o])return e.indexes[o]-t.indexes[o];return e.indexes.length-t.indexes.length}function Yl(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Kl(t,n);try{t.createState("writable",e=>{let i;try{i=function(e,t,n){if(0===t.pathInfo.wildcardCount)return e[t.path];return e.$resolve(t.path,n)}(e,n,s)}catch(e){return void Jl(0,n.path,"evaluate",e)}const a=r?function(e,t){return Fl.get(e)?.get(t)}(t,o):function(e){return Vl.get(e)}(o);r&&ql(t,o,i),null!==Pt&&Pt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Jl(0,n.path,"handler",e)}}function Ql(e){return function(){const t=this.stateElement;if(!t)return;if(!0!==t.initialized)return;let n;try{t.createState("readonly",t=>{n=t[e]})}catch(t){return void console.warn(`[@wcstack/state] DCC getter "${e}" failed:`,t)}return n}}function Zl(e){return function(t){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})}):n.createState("writable",n=>{n[e]=t}))}}function ec(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[e](...t)}).then(()=>o)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[e](...t)}),o})}}function tc(e){return e.startsWith("$")}function nc(e,t){return Object.keys(e).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof e[n].value;return"method"===t?o:!o})}function oc(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||H(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||H(`${t} entries must be non-empty strings.`),e.startsWith("$")&&H(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&H(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function sc(e){const t=oc(e,A)??[],n=oc(e,C)??[],o=nl(e),s=function(e){const t=e[R];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),r=[];for(const e of t){const t=o[e];if(void 0===t){if(s.has(e)){r.push(e);continue}H(`${A} entry "${e}" is not declared on the state.${ge(e,nc(o,"value"))}`)}"function"==typeof t.value&&H(`${A} entry "${e}" is a method. Declare it in ${C} instead.`)}for(const e of n){const t=o[e];void 0===t&&H(`${C} entry "${e}" is not declared on the state.${ge(e,nc(o,"method"))}`),"function"!=typeof t.value&&H(`${C} entry "${e}" is not a method. Declare it in ${A} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}ba(function(e){const t=jl();try{if(0===t.size)return;const n=function(){const e=ya;return ya=0,e}();if(n>32){const t=Array.from(e,e=>e.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; watch handlers for this batch were skipped.",{maxDepth:32,paths:t}),void(null!==Pt&&Pt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Ll(e).get(s),i=Wl(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=on(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Xl),function(e){ga=e+1}(n);try{for(const e of o){if(!t.has(e.stateElement))continue;const n=Ll(e.stateElement).get(e.entry.path)===e.entry,o=!0===Wl(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&Yl(e)}}finally{ga=0}}finally{Vl.clear()}},10);const rc=new Map;class ic{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice();let o=0,s=0,r=0,i="none";const a=[];for(let e=0;e<t.length;e++){const i=t[e];if("*"===i)n[e]="*",a.push(null),o++,r++;else{const t=Number(i);Number.isNaN(t)||(n[e]="*",a.push(t),s++,r++)}}const l=Y(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=e,this.segments=t,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function ac(e){let t;return rc.get(e)??(rc.set(e,t=new ic(e)),t)}function lc(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[t];return void 0===o||null===n.listIndex?null:nn(n.listIndex,o,n.pathInfo.wildcardCount)}function cc(e,t){if(!e.untracking&&e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=tn(t.pathInfo,o);if(e>0){let r=!1;const i=t.listIndex??null,a=n.listIndex??null;for(let n=0;n<e;n++){if((null!==i?nn(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?nn(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}const dc=new WeakMap;class uc{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return vn(Y(this.markerParentPath+s+e),this.listIndex)}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(ht(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=ht(e,t),a=mt(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a=ht(e,t),l=mt(0,t,a,r,n);return o[s](a,l,...i)}}return this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return cc(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[ht(this.record,t)]}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n);const s=this.accessorNameFor(t);if(void 0!==s){this.record.setterKeys.has(s)||H(`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(t)),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(e,t)?(e[t]=n,!0):(this.receiver[ht(this.record,t)]=n,!0)}has(e,t){if("string"!=typeof t)return Reflect.has(e,t);if("$"===t[0]||"#"===t[0])return!1;if(void 0!==this.accessorNameFor(t))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return!0;if("function"==typeof this.record.stateObject[t])return!0}try{return ht(this.record,t),!0}catch{return!1}}}function fc(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=dc.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},dc.set(e,n)),null===t)return n.noIndex??={...e.privateSnapshot};let o=n.byListIndex.get(t);return void 0===o&&(o={...e.privateSnapshot},n.byListIndex.set(t,o)),o}(e,t.listIndex):{};return new Proxy(i,new uc(e,s,t.listIndex,r,n,o))}function hc(e){const t=e.parentStateElement,n=(t,n)=>{const o=St(e.component);let s;return t[Lt](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(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(ht(e,t))):(n,o,...r)=>{const i=ht(e,n),a=St(e.component)?.listIndex.indexes??[],l=mt(0,n,i,"$resolve"===t?o??[]:o,a),c="$setAll"===t||"$resolve"===t&&r.length>0?"writable":"readonly";return s(c,e=>e[t](i,l,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:ht(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:ht(e,s)]=r})}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return ht(e,n),!0}catch{return!1}}})}const pc=new WeakMap,mc=new Set;function gc(e,t,n,o){let s=pc.get(e);if(void 0===s){if(!o)return null;s=new Map,pc.set(e,s)}let r=s.get(t);if(void 0===r){if(!o)return null;r=new Map,s.set(t,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function yc(e,t){if(!e.component.isConnected)return!1;const n=St(e.component)?.listIndex??null;if(null===t)return null===n;let o=n;for(;null!==o;){if(o===t)return!0;o=o.parentListIndex}return!1}function wc(e,t,n,o){const r=gc(e,t,n,!1);if(null===r)return null;const i=null===o?r.noIndex:r.byListIndex.get(o)??null;if(null!==i){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&yc(n,t)?n:null}(i,o);if(null!==e)return{record:e,entry:i.entry}}let a=null,l=null;for(const e of r.holders){const i=e.ref.deref();void 0!==i?yc(i,o)&&(null!==l&&H(`[wcs/mount-export-ambiguous] "${t}${s}${n}" is exported by two mounted components on the same instance: <${l.component.tagName.toLowerCase()}> and <${i.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),a=e,l=i):r.holders.delete(e)}return null===a||null===l?null:(null===o?r.noIndex=a:r.byListIndex.set(o,a),{record:l,entry:a.entry})}function bc(e){const t=e.parentStateElement,n=St(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Lt](n,()=>{e.$postUpdate(o.exportedPath)})})}function vc(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function $c(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}function xc(e,t,n,o,s){const i=t.pathInfo.segments[0];if(i===M)return $c(Fa(s),t.pathInfo.segments);if(i===B)return $c(Nl(s),t.pathInfo.segments);if(i===z)return $c(Pl(s),t.pathInfo.segments);if(!0===s.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const e=$t(s,t.pathInfo.path);if(null!==e)return fc(e,t,n,o)}if(!(t.pathInfo.path in e)){if(null===t.parentAddress&&Mr(function(e){return e.rootNode??null}(s),t.pathInfo.path))return;const i=t.parentAddress??H(function(e,t,n){return`[${qr.binding}] Path "${e}" does not exist on the state tree.${ge(e,Fr(t,"",n))}${ye}`}(t.pathInfo.path,e,s.getterPaths)),a=Nc(e,i,n,o);if(null==a)return;const l=t.pathInfo.segments[t.pathInfo.segments.length-1];if(!0===s.hasMounts&&l!==r&&!(l in Object(a))){const e=wc(s,i.pathInfo.path,l,t.listIndex);if(null!==e)return function(e,t,n,o,s){const r=fc(e,vn(Y(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(e.record,e.entry,t.listIndex,n,o)}if(l===r){const e=t.listIndex?.index??H(Hr(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(a,e)}return Reflect.get(a,l)}if(!s.getterPaths.has(t.pathInfo.path))return Reflect.get(e,t.pathInfo.path);o.pushAddress(t);try{return Reflect.get(e,t.pathInfo.path,n)}finally{o.popAddress()}}function Sc(e,t,n,o,s){const r=Xt(Ut(s,t.pathInfo),t.listIndex),i=function(e){return hl.get(e)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=xc(e,t,n,o,s);return pl(r,{value:a,dirty:!1}),a}function Nc(e,t,n,o){cc(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo),function(e,t){if(null===kl)return;const n=Ut(e,t.pathInfo);kl.add(Xt(n,t.listIndex))}(o.stateElement,t);const s=o.stateElement;return vc(s,t)?Sc(e,t,n,o,s):xc(e,t,n,o,s)}function Pc(e,t,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=vn(f,r),p=Xt(Ut(n.stateElement,f),r),m=Tt(p),g=Nc(e,h,t,n),y=As(r,m,g).newIndexes,w=l[c]??null;if(i.set(p,g),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??H(`ListIndex not found at index ${w} of ${f.path}`);s+1<o.length?a(o,s+1,e,l,c+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[e,t]of i.entries())Ot(e,Array.isArray(t)?t:[]);return l}function Ic(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Ns(Nc(e,vn(a,r),t,n));null==l&&H(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??H(`ListIndex not found at index ${c} of ${a.path}`)}return r}function kc(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}function _c(e,t,n,o){"object"==typeof e&&null!==e||H(`${W} list "${t}": ${n} row at index ${o} must be a plain object (got ${null===e?"null":typeof e}).`);const s=Object.getPrototypeOf(e);s!==Object.prototype&&null!==s&&H(`${W} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Ac(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&H(`${W} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function Cc(e,t,n,o){const s=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){const a=e[i];_c(a,n,o,i);const l=Ac(a,t,n,o,i);r.has(l)&&H(`${W} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Ec(e,t){const n=[];for(const o of Object.keys(t))Object.is(e[o],t[o])||n.push({field:o,value:t[o]});for(const o of Object.keys(e))Object.hasOwn(t,o)||null==e[o]||n.push({field:o,value:null});return n}function Mc(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const i=Nc(e,s,n,o);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=t.pathInfo.lastSegment;if(a===r){const e=t.listIndex?.index;return"number"==typeof e&&e in i}return a in i}const Tc=new WeakMap;function Oc(e,t){null===t?Tc.delete(e):Tc.set(e,t)}function Rc(e,t,n){const s=Y(e.wildcardParentPaths[t]),r=Ut(e.stateElement,s),i=vn(s,n),a=Xt(r,n),l=Tt(a),c=e.stateProxy[jt](i),d=As(i.listIndex,l,c);e.observedListValueByAbsAddress.set(a,Array.isArray(c)?c:[]);const u=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${t}`),[]}}(d,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...u);else for(const n of u)Rc(e,t+1,n)}const Lc=[];function jc(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:Lc,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Lc,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Dc=[];function Wc(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Dc;let r=null;const i=t+s;for(const e of o){if(e!==t&&!e.startsWith(i))continue;const o=Y(e);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??Dc}function Bc(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const i of s){const s=Y(i);if(e.listPathSet.has(o)&&s.lastSegment===r){const r=e.stateProxy[jt](t),a=Xt(Ut(e.stateElement,t.pathInfo),t.listIndex),l=Tt(a),c=As(t.listIndex,l,r);e.observedListValueByAbsAddress.set(a,Array.isArray(r)?r:[]);const d=jc(e,o,0,0,c);for(const t of d.fullRows){const o=vn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=Wc(e,i,s);if(null===t)for(const t of d.movedRows){const o=vn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=vn(s,o);e.result.add(t),n.push(t)}}}else{const o=vn(s,t.listIndex);e.result.add(o),n.push(o)}}const i=e.dynamicMap.get(o);if(i)for(const o of i){const s=Y(o),r=[];if(s.wildcardCount>0){const n=tn(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&H(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=nn(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Rc(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&H(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=nn(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=vn(s,t);e.result.add(o),n.push(o)}}}function zc(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&H(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),n(a),i.length=0,Bc(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}(u,t,a);for(const[e,t]of u.observedListValueByAbsAddress)Ot(e,t);return Array.from(u.result)}function Fc(e,t,n,o,s){const r=e.watchPaths;null!=r&&s&&r.has(t)&&function(e,t){Vl.has(e)||Vl.set(e,t)}(n,o)}function qc(e,t,n,s,r){const i=o.enablePropagationContext?uo()??ao(-1):null,a=xa();a.enqueueAbsoluteAddress(t,i),zc(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Xt(Ut(s.stateElement,t.pathInfo),t.listIndex);ml(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function Vc(e,t,n,o,s){s&&(e.getterPaths.has(t)?ml(n):pl(n,{value:o,dirty:!1}))}function Uc(e,t,n,o,s,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const a=Nc(e,n,s,i),l=t.pathInfo.segments[t.pathInfo.segments.length-1];if(l===r){const e=t.listIndex?.index??H(Hr(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(a,e,o)}return Reflect.set(a,l,o)}if(!i.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);i.pushAddress(t),i.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}finally{qc(t,n,s,i,a)}}function Gc(e,t,n,o,s,r,i){let a=t.parentAddress??H(`address.parentAddress is undefined path: ${t.pathInfo.path}`),l=function(e){return Tc.get(e)??null}(a);if(null===l){const t=Nc(e,a,s,r)??[],n=Ns(t)??[];l={value:[...t],listIndexes:[...n]},Oc(a,l)}try{return Uc(e,t,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=Nc(e,a,s,r)??[],c=Array.isArray(i)?Ns(i)??[]:[],d=t.listIndex.index,u=-1!==n?l.listIndexes[n]:xs(a.listIndex,-1);c[d]=u;if(new Set(i).size===l.value.length){for(let e=0;e<c.length;e++)c[e].index=e;Oc(a,null)}}}function Kc(e,t,n,o,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(n)){const l=a.get(t.pathInfo.path);if(void 0!==l){const a=Nc(e,t,o,i),c=function(e,t,n,o){const s=Cc(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Cc(r,t,e,"current"),a=new Map;for(let e=0;e<r.length;e++)a.set(i[e],r[e]);const l=new Array(o.length),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=a.get(s[e]);void 0!==n&&n!==t?(l[e]=n,c.push({position:e,oldRow:n,newRow:t})):l[e]=t}return c.length>0?{list:l,matched:c}:null}(t.pathInfo.path,l,a,n);if(null!==c)return function(e,t,n,o,i,a){const l=t.pathInfo.path,c=t.listIndex;null===Ns(o)&&As(c,null,o);const d=As(c,o,n.list),u=Hc(e,t,n.list,i,a,l),f=Y(l+s+r);for(const t of n.matched){const n=Ec(t.oldRow,t.newRow);if(0===n.length)continue;const o=d.newIndexes[t.position];for(const r of n)void 0!==o?Kc(e,vn(Y(f.path+s+r.field),o),r.value,i,a):t.oldRow[r.field]=r.value}return u}(e,t,c,a,o,i)}}return Hc(e,t,n,o,i,null)}function Hc(e,t,n,i,a,l){const c=a.stateElement,d=t.pathInfo.path;if(!0===c.hasGraftedVolumes){const e=function(e,t){const n=Tr.get(e);if(void 0===n||0===n.size)return null;const o=t+s;for(const e of n)if(e.startsWith(o))return e;return null}(c,d);null!==e&&H(`Cannot replace "${d}" wholesale: a volume is mounted at "${e}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${e}" itself, or individual fields inside "${d}", instead.`)}if(!0===c.hasRecursion){const e=c.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);null!==e&&H(`[wcs/recursion-readonly] "${d}" writes into the recursive getter "${e}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`)}const u=!!po&&(po=!1,!0);if(!(d in e)&&null!==t.parentAddress&&!c.elementPaths.has(d)){const s=Nc(e,t.parentAddress,i,a);if("object"==typeof s&&null!==s){const e=t.pathInfo.lastSegment,f=e===r?t.listIndex?.index:e;let h,p=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==f&&f in s,t=void 0!==f?s[f]:void 0;if(e&&Object.is(t,n))return!0;h=t,p=!0}const m=vc(c,t),g=Xt(Ut(c,t.pathInfo),t.listIndex);null!==Pt&&Pt({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:p}),Fc(c,d,g,h,p);let y=!1;try{if(void 0===f&&H(Hr(`path "${d}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),!0===c.hasMounts&&e!==r&&!(f in s)){const o=wc(c,t.parentAddress.pathInfo.path,e,t.listIndex);if(null!==o)return y=!0,function(e,t,n,o,s,r){const i=fc(e,vn(Y(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(o.record,o.entry,t.listIndex,n,i,a)}return Reflect.set(s,f,n)}finally{qc(t,g,i,a,l),y?ml(g):Vc(c,d,g,n,m),kc(c,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Nc(e,t,i,a);if(Mc(e,t,i,a)&&Object.is(o,n))return!0;f=o,h=!0}const p=c.elementPaths.has(t.pathInfo.path),m=vc(c,t),g=Xt(Ut(c,t.pathInfo),t.listIndex);null!==Pt&&Pt({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),Fc(c,d,g,f,h);try{return p?Gc(e,t,g,n,i,a,l):Uc(e,t,g,n,i,a,l)}finally{Vc(c,d,g,n,m),kc(c,t.pathInfo,{value:n})}}function Jc(e,t,n,o){return(t,s,r)=>{const i=Y(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}s.length!==i.wildcardParentPathInfos.length&&H(Ur("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=vn(i,Ic(e,n,o,i,s));if(!(void 0!==r))return Nc(e,a,n,o);Kc(e,a,r,n,o)}}function Xc(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=t.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const o=s+n.repeat;let r=0,i=n.anchor.length;for(;t.startsWith(o,i);)i+=o.length,r++;return i!==t.length&&46!==t.charCodeAt(i)?null:r}(t,n.pathInfo.path)}function Yc(e,t,n){const o=e.recursionRegistry,s=sl(o.spec,n);null===s&&H(Gr(n,o.spec.recursiveAnchor));const r=Xc(t,o);return null===r&&H(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function Qc(e,t,n,o,r){const i=o.spec,a=[],l=new Map,c=[],d=i.repeatList,u=i.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void a.push(vn(e,n));const s=m(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function m(o,s,r){const a=vn(o,s),c=Xt(Ut(n.stateElement,o),s),u=Nc(e,a,t,n),h=null===r?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&H(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${i.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&H(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${i.anchor}" needs a tree: give each node its own "${d}" array.`),o})(o.path,u,r),p=As(s,Tt(c),u);return l.set(c,Array.isArray(u)?u:[]),null!==h&&null!==r&&r.add(h),{rows:p.newIndexes,tracked:h}}const g=(e,t,n)=>{const{rows:i,tracked:l}=m(t,n,h);if(0===i.length)return;const u=(e=>{const t=c[e];if(void 0!==t)return t;const n=o.concretePathAt(r,e),i=0===r.length?n:o.concretePathAt("",e),a={nodePath:i,concretePathInfo:Y(n),childListPathInfo:Y(i+s+d)};return c[e]=a,a})(e),y=l;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<i.length;t++){const n=i[t];w?a.push(vn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),g(e+1,u.childListPathInfo,n)}f.delete(y)};g(0,Y(u),null);for(const[e,t]of l)Ot(e,t);return a}function Zc(e,t,n,o){const s=Jc(e,0,n,o);return(t,r)=>{if(!0===o.stateElement.hasRecursion&&ol(t)){if(void 0!==r)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=sl(r.spec,o);null===i&&H(Gr(o,r.spec.recursiveAnchor)),Array.isArray(s)||H(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&H(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=Qc(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Nc(e,a[o],t,n));return l}(e,n,o,t,r);t=Yc(o.stateElement,o,t)}const i=Y(t);if(void 0===r||Array.isArray(r)||H(`$getAll("${t}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&H(Ur("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=lc(o,i.wildcardPaths[e]);if(t){r=on(t,t.length);break}}if(void 0===r){const e=o.addressStackLength>0?o.lastAddressStack:null,n=e?.listIndex??null;i.wildcardCount>0&&null!==e&&null!==n&&n.length>0&&H(function(e,t){return`$getAll("${e}") was called without indexes inside the loop context of "${t}", 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).`}(t,e.pathInfo.path)),r=[]}}const a=Pc(e,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let e=0;e<a.length;e++)l.push(s(i.path,a[e]));return l}}function ed(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return lc(o,s.wildcardPaths.at(-1)??H(`lastWildcardPath is null: ${t.pathInfo.path}`))??H(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??H(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Ns(Nc(e,vn(i,s),n,o))??H(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??H(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??H(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":H(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function td(e,t,n,o,s,r,i){const a=n.stateElement.recursionRegistry,l=sl(a.spec,o);null===l&&H(Gr(o,a.spec.recursiveAnchor));const c=rl(l);Array.isArray(s)||H(Kr(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&H(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&H(Kr(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&H(Kr(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(e,t,n){cl(e,n)&&H(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const d=a.conflictingRecursiveGetter(c);null!==d&&H(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${d}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const u=Qc(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Kc(e,u[o],r,t,n),f++);return f}function nd(e,t,n,o){const r=Reflect.get(e,I);let i;if("function"==typeof r){const e=new Set,s={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,r=t.path;if(-1===r.indexOf("#")&&(e.add(r),t.wildcardCount>0)){const e=on(n.listIndex,t.wildcardCount),o=s[r];void 0===o?s[r]=[e]:o.push(e)}}i=r.call(n,Array.from(e),s)}const a=o.stateElement?(l=o.stateElement,Rr.get(l)??Lr):[];var l;if(a.length>0)for(const e of a){const r=e.mountPath+s,i=new Set,a={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo.path;if(t!==e.mountPath&&!t.startsWith(r))continue;if(-1!==t.indexOf("#"))continue;const s=t===e.mountPath?"":t.slice(r.length);if(""===s)continue;i.add(s);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const e=on(n.listIndex,l);(a[s]??=[]).push(e)}}if(i.size>0)try{e.callback.call(Or(e.mountPath,n),Array.from(i),a)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" $updatedCallback threw.`,t)}}return i}const od=/^\$\d+$/,sd=`${B}${s}`,rd=`${z}${s}`,id=new WeakMap;function ad(e,t,n,o){const r=S[t];if(void 0===r&&"string"==typeof t&&36===t.charCodeAt(0)&&od.test(t)&&H(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==r){0===o.addressStackLength&&H(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack,n=e?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const i=e?.listIndex;null==i&&H(`ListIndex not found: ${t.toString()}`);let a=r;const l=e.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const e=$t(o.stateElement,l.path);null!==e&&(a=r+function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(s,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const r=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1),a=e.accessorBySuffixByMarkerParent.get(r)?.get(i);return void 0!==a?a.indexShift:e.delta}(e,l.path))}const c=nn(i,a,l.wildcardCount);return c?.index??H(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Zc(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>function(e,t,n,o){return(t,s,r,i)=>{if(!0===o.stateElement.hasRecursion&&ol(t))return td(e,n,o,t,s,r,i);const a=Y(t);Array.isArray(s)||H(Kr(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&H(Ur("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&H(Kr(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&H(Kr(t,"requires an array as the value when { spread: true } is set."));const d=Pc(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&H(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=Ic(e,n,o,a,d[t]);u.push(vn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;i=c?r(Nc(e,s,n,o),...d[t]):l?r[t]:r,void 0!==i&&(Kc(e,s,i,n,o),f++)}return f}}(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=ac(t),i=ed(e,r,n,o),a=vn(r.pathInfo,i),l=Xt(Ut(s,a.pathInfo),a.listIndex),c=xa();c.enqueueAbsoluteAddress(l),zc(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Xt(Ut(s,e.pathInfo),e.listIndex);ml(t),c.enqueueAbsoluteAddress(t)}),kc(s,a.pathInfo)}}(e,0,n,o)(t);case"$resolve":return(t,s,r)=>Jc(e,0,n,o)(t,s,r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{ol(e)&&H(`[wcs/recursion-unsupported] $trackDependency("${e}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&H(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??H("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(t.path)&&t.path!==e&&n.addDynamicDependency(e,t.path)}}(0,0,0,o)(e);case"$untrackDependency":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case M:return Fa(o.stateElement);case B:return Nl(o.stateElement);case z:return Pl(o.stateElement)}if(!t.startsWith(sd)&&!t.startsWith(rd))return}const s=ac(!0===o.stateElement?.hasRecursion&&ol(t)?Yc(o.stateElement,o,t):t),r=ed(e,s,n,o),i=vn(s.pathInfo,r);return Nc(e,i,n,o)}if("symbol"==typeof t){const s=function(e){let t=id.get(e);return void 0===t&&(t=new Map,id.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Lt:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&H("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case jt:i=t=>Nc(e,t,n,o);break;case Dt:i=t=>Mc(e,t,n,o);break;case Wt:i=(t,s)=>Kc(e,t,s,n,o);break;case Bt:i=()=>async function(e,t,n){const o=Reflect.get(e,N);"function"==typeof o&&await o.call(n)}(e,0,n);break;case zt:i=()=>function(e,t,n){const o=Reflect.get(e,P);"function"==typeof o&&o.call(n)}(e,0,n);break;case Ft:i=t=>nd(e,t,n,o);break;case qt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,k);"function"==typeof s&&s.call(o,t,n)}(e,t,o,n);break;default:return Reflect.get(e,t,n)}return s.set(t,i),i}}class ld{_stateElement;_addressStack=Array(a).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=ua(e);null===n&&H("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&H("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=a&&(this._hasRepeatedAddress()&&H(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),H(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=e}_hasRepeatedAddress(){const e=new Set;for(let t=0;t<=this._addressStackIndex;t++){const n=this._addressStack[t];if(n){if(e.has(n))return!0;e.add(n)}}return!1}_tailAddressPaths(){const e=[];for(let t=this._addressStackIndex;t>=0&&e.length<8;t--){const n=this._addressStack[t];n&&e.push(n.pathInfo.path)}return e}_describeAddressCycle(){const e=this._tailAddressPaths();return`${Array.from(new Set(e)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&H(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return ad(e,t,n,this)}set(e,t,n,o){return"readonly"===this._mutability&&H("This state is readonly."),function(e,t,n,o,s){if("string"==typeof t){const r=ac(t),i=ed(e,r,o,s);return Kc(e,vn(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}}function cd(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),o=Object.getOwnPropertyDescriptors(e);for(const e in o){const t=o[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,o),n}(e)}const dd=new WeakMap;class ud{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=dd.get(e);return n?n.get(t)??null:null}(e,t)??H("State element not found for web component.")}get(e,t,n){if("string"==typeof t){let e;return this._innerStateElement.createState("readonly",n=>{e=n[t]}),e}return Reflect.get(e,t,n)}set(e,t,n,o){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,o)}}const fd=e=>()=>e;function hd(e,t,n,o){!function(e,t,n){let o=dd.get(e);o||(o=new Map,dd.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(cd(o));const s=function(e,t){const n=new ud(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:fd(s),enumerable:!0,configurable:!0}),ds(t,n),pd(t,n)}function pd(e,t){if(_ in e){const n=e[_];"function"==typeof n?n.call(e,t).catch(e=>{H(`Error in ${_}: ${e instanceof Error?e.message:String(e)}`)}):H(`${_} is not a function.`)}}function md(e,t){const n=vt(t);var o,r;null!==n&&n.stateProp!==e.stateProp&&H(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&as(t).dispose(),function(e,t){gt.set(e,t);let n=wt.get(t.parentStateElement);void 0===n&&(n=new Map,wt.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=yt.get(t.component);void 0===o&&(o=new Map,yt.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&bt.register(t,{byMarker:n,marker:t.marker,getterPaths:t.parentStateElement.getterPaths,addedGetterPaths:t.addedGetterPaths}),t.parentStateElement.markHasMounts?.()}(t,e),t instanceof ShadowRoot&&function(e,t){const n=la.get(e);if(void 0!==n){if(n===t)return;H("A state tree is already registered on this root.")}la.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>pt(e,t,n);bi(t);const o=St(e.component);Li(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),gi(t,o,n)}(e,t),function(e){if(e.exports.size>0||null===e.rootEntry)return;const t=new Set([...e.getterKeys,...e.setterKeys]);for(const n of t){let t;try{t=ht(e,n)}catch{continue}const o=t.indexOf(s+e.marker);if(-1===o)continue;const r=t.slice(0,o+1+e.marker.length),i=t.slice(r.length+1),a=t.slice(0,o)+s+i,l=Y(a);if(l.wildcardCount!==e.delta)continue;const c={markerTerminalPath:r,suffix:i,markerPath:t,exportedPath:a};e.exports.set(a,c),gc(e.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:c}),e.parentStateElement.addDynamicDependency(t,a),ei(e.parentStateElement,a)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=St(e.component);if(e.delta>0&&null===t)return;const n=e.component.tagName.toLowerCase();for(const o of e.exports.values()){const s=`${n}|${o.exportedPath}`;if(mc.has(s))continue;const r=Y(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Lt](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(mc.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${e.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(e),bc(e),o=t,r=Promise.resolve(),ca.set(o,r),r.then(()=>pa(o),()=>{})}const gd=new Set;function yd(e,t){gd.has(e)||(gd.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function wd(e){const t=e.rootEntry,n=St(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Lt](n,()=>{o=e[t.outerPathInfo.path]})}),o}function bd(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Or(e.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function vd(e,t,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=t+s+a,c=function(e,n,...o){l.call(Or(t,this),e,n,...o)};n.push({path:o,pathInfo:Y(o),handler:c,order:1e6+i++}),r.add(o),e.setPathInfo(o,"prop","watch")}n.length>0&&(!function(e,t){let n=Tl.get(e);void 0===n&&(n=new Map,Tl.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}(e,n),e.addVolumeWatchPaths?.(r),Ul(e))}const r=n[W];if(void 0!==r){const n=new Map;for(const[e,o]of Object.entries(r))n.set(t+s+e,o);e.mergeVolumeListKeys?.(n)}const i=n[I];"function"==typeof i&&(!function(e,t){let n=Rr.get(e);void 0===n&&(n=[],Rr.set(e,n)),n.push(t)}(e,{mountPath:t,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on"])void 0!==n[e]&&console.warn(`[@wcstack/state] volume "${t}" declares ${e}, which volumes do not support. Declare it on the root state instead.`)}function $d(e,t,n){!function(e,t,n){const o=n[L];if(void 0!==o){"object"==typeof o&&null!==o||H(`${L} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(o))"function"!=typeof t&&H(`${L} entry "${e}" must be a function.`),Bl(e)}const r=n[W];if(void 0!==r){"object"==typeof r&&null!==r||H(`${W} 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)&&H(`${W} entry "${n}" must map a list path to a field name or a key function.`),e.listKeys?.has(t+s+n)&&H(`${W} entry "${t+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&H(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n[j]&&H(`Volume "${t}" declares ${j}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const e of Object.keys(nl(n)))-1!==e.indexOf(D)&&H(`Volume "${t}" declares "${e}", which uses "${D}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n);const{data:o,accessors:r}=function(e){const t={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(e)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(t[o]=s.value):n.set(o,s));return{data:t,accessors:n}}(n),i=Y(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;H(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let t=0;t<i.segments.length-1;t++){const o=i.segments[t],r=""===n?o in e:void 0!==e[n+s+o];n=""===n?o:n+s+o,r||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;H(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=o}),function(e,t){let n=Tr.get(e);void 0===n&&(n=new Set,Tr.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,o]of r){const r=t+s+n,i=o.get,a=o.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(Or(t,this))}),"function"==typeof a&&(l.set=function(e){a.call(Or(t,this),e)}),e.defineTreeAccessor(r,l)}vd(e,t,n);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{const n=l.call(Or(t,e));n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n}}function xd(e,t){let n=null;try{n=$d(e,t.mountPath,t.volumeState)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}function Sd(e,t,n,o,s){null===t?function(e,t){let n=jr.get(e);void 0===n&&(n=[],jr.set(e,n)),n.push(t)}(e,{mountPath:n,volumeState:o,onGrafted:s}):xd(t,{mountPath:n,volumeState:o,onGrafted:s})}Dr=xd;class Nd extends Bi{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return fa(e)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Da}();_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(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&H(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){const n=this.__state,o=function(e){const t=e[j];if(void 0===t)return null;"object"==typeof t&&null!==t||H(`[wcs/recursion-declaration-invalid] ${j} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&H(`[wcs/recursion-declaration-invalid] ${j} must declare exactly one anchor; it is empty.`),n.length>1&&H(`[wcs/recursion-declaration-invalid] ${j} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,i]=n[0];tl("anchor",o),"string"!=typeof i&&H(`[wcs/recursion-declaration-invalid] ${j} entry "${o}" must map to the repeating sub-path as a string (for example "children${s}${r}").`),tl("repeating sub-path",i);const a=o.slice(0,o.lastIndexOf(s)),l=i.slice(0,i.lastIndexOf(s)),c=a+s+D;return Object.freeze({anchor:o,repeat:i,recursiveAnchor:c,anchorList:a,repeatList:l})}(e),i=null===o?null:new vl(o,e),a=function(e){const t=new Set,n=e[E];if(void 0===n)return t;Array.isArray(n)||H(`${E} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||H(`${E} entries must be non-empty strings.`),e===M&&H(`${E} entry "${e}" conflicts with the reserved namespace name "${M}".`),t.has(e)&&H(`${E} entry "${e}" is duplicated.`),t.add(e);return t}(e),l=function(e){const t=new Set,n=e[T];if(void 0===n)return t;Array.isArray(n)||H(`${T} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||H(`${T} entries must be non-empty strings.`),t.has(e)&&H(`${T} entry "${e}" is duplicated.`),t.add(e);return t}(e);null!==this._recursionRegistry&&this._recursionRegistry.forgetGenerated(this,n),this._recursionRegistry=i,this._commandTokenNames=a,this._eventTokenNames=l,this.__state=e,this._hasUpdatedCallback=I in e,this._hasErrorCallback=k in e,Ln(this),function(e,t,n){const o=t[O];if(void 0!==o){"object"==typeof o&&null!==o||H(`${O} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||H(`${O} entry "${t}" is not declared in $eventTokens.${ge(t,n)}`),"function"!=typeof s&&H(`${O} entry "${t}" must be a function.`),Rn(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const c=function(e){const t=new Set,n=new Set,o=nl(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterPaths:t,setterPaths:n}}(e);for(const e of c.getterPaths)this._getterPaths.add(e);for(const e of c.setterPaths)this._setterPaths.add(e);var d;Il(this),Ya(d=this),Ha(d),Ja.delete(d),el(this,e),this._listKeys=function(e){const t=e[W];if(void 0===t)return null;"object"==typeof t&&null!==t||H(`${W} must be an object mapping list paths to key specs.`);const n=new Map;for(const[e,o]of Object.entries(t)){0===e.length&&H(`${W} entry path must be a non-empty string.`);const t=e.split(s);t.some(e=>0===e.length)&&H(`${W} entry "${e}" must not contain empty path segments.`),t[t.length-1]===r&&H(`${W} entry "${e}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),-1!==e.indexOf(D)&&H(`[wcs/recursion-unsupported] ${W} entry "${e}" uses "${D}", which ${W} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${s}${r}${s}children").`),"function"!=typeof o?("string"!=typeof o&&H(`${W} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&H(`${W} entry "${e}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&H(`${W} entry "${e}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&H(`${W} entry "${e}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(e,o)):n.set(e,o)}return n.size>0?n:null}(e),null!==o&&this._listPaths.add(o.anchorList),function(e){Ol.delete(e),Ml.delete(e)}(this),function(e){Fl.delete(e)}(this),this._watchPaths=zl(this,e),this._initialized&&null!==this._rootNode&&!t()&&(Ul(this),Al(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}attributeChangedCallback(e,t,n){this._initialized&&t!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===t?"absent":`"${t}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const e=this.parentNode;if(!e)return null;const t=Gi.find(e);if(!t)return null;const n=t.stateData;return Object.keys(n).length>0?n:null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){H("Failed to parse JSON from script element:"+e)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const e=this.getAttribute("json");return JSON.parse(e)}{const e=this.querySelector('script[type="module"]');if(e)return await La(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){try{const t=await fetch(e);return t.ok||H(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e);if(e&&e.endsWith(".js"))return await ja(e);H(`Unsupported src file type: ${e}`)}}catch(e){H(`Failed to initialize state: ${e}`)}}async _initializeVolume(){const e=this._rootNode,t=this.getAttribute("mount");try{!function(e){0===e.length&&H('"mount" requires a non-empty tree path.');const t=Y(e);for(const n of t.segments)0===n.length&&H(`"mount" path "${e}" has an empty segment.`),n===r&&H(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&H(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(t),this.hasAttribute("bind-component")&&H('"mount" cannot be combined with "bind-component".'),this.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),function(e,t){let n=Er.get(e);void 0===n&&(n=new Set,Er.set(e,n)),n.has(t)&&H(`Volume slot "${t}" is already mounted on this tree.`),n.add(t)}(e,t)}catch(e){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),e}this._volumeInitializing=!0,null===ua(e)&&function(e,t){const n=()=>{if(null!==ua(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> 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=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(e,t);const n=e=>{this._volumeGraftInfo=e,this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()};let s;try{s=await this._loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${t}" failed to load.`,e),void n(null)}null!==this._rootNode?Sd(e,ua(e),t,s,n):n(null)}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,n]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=n}await this._loadingPromise,ma(this.rootNode,this)}_failInitialization(e){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),H(e)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const r=this.parentNode,i=r instanceof ShadowRoot?r.host:r instanceof Element?r:null,a=i?ee(i):null;null!==i&&null!==a||H(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),r instanceof ShadowRoot||i.hasAttribute(o.bindAttributeName)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${a}>, or mount it from the host (data-wcs="${this.getAttribute("bind-component")}: path").`);const l=["state","src","json"].filter(e=>this.hasAttribute(e));null!==this.querySelector('script[type="module"]')&&l.push('<script type="module">'),l.length>0&&H(`"bind-component" cannot be combined with ${l.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const c=this.getAttribute("bind-component");!function(e,t){let n=us.get(e);n||(n=new Set,us.set(e,n)),n.add(t)}(i,c);const d=ne(i);null===d&&H(`CustomElementRegistry is unavailable for <${a}>.`),await d.whenDefined(a.toLowerCase()),i.hasAttribute(o.bindAttributeName)&&await G(i),c in i||H(`Component does not have property "${c}" for state binding.`);let u=i[c];"object"==typeof u&&null!==u||H(`Component property "${c}" is not an object for state binding.`);const f=function(e,t){const n=gr.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(i,c);if(void 0!==f&&function(e,t){if(!e.hasAttribute(o.bindAttributeName))return!1;const n=pe(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(i,c)&&(i[c]=f,u=f),this._boundComponent=i,this._boundComponentStateProp=c,r instanceof ShadowRoot||(pe(i)??[]).some(e=>e.propSegments[0]===c)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${a}>, or mount it from the host (data-wcs="${c}: path").`),i.hasAttribute(o.bindAttributeName)){const o=(pe(i)??[]).filter(e=>e.propSegments[0]===c);if(o.length>0){const l=ua(i.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${a}>.`);let d=(n=i,s=c,yt.get(n)?.get(s)??null);const f=null!==d;if(null===d&&(function(e,t,n){const o=wr.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;wr.get(e).delete(t)}}(i,c,u),d=st(i,c,o,l,u,(e=i,t=c,yr.get(e)?.get(t))),function(e){const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp,s=new Map;for(const t of e.entries)1===t.innerSegments.length&&s.set(t.innerSegments[0],t.outerPathInfo.path);let r,i=!1;for(const a of t){const t=s.get(a);if(void 0!==t){yd(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted entry "${o}.${a}: ${t}" (the host value no longer reaches it). Remove the default to read the tree, or rename it to keep it private.`);continue}if(null===e.rootEntry)continue;if(i||(r=wd(e),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=e.rootEntry.outerPathInfo.path;yd(`${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.`)}}(d)),this._mountRecord=d,this.parentNode!==r)return;try{md(d,r instanceof ShadowRoot?r:i)}catch(e){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),e}if(!f){const e=hc(d);Object.defineProperty(i,c,{get:()=>e,enumerable:!0,configurable:!0}),ds(i,c)}return pd(i,c),function(e){const t=tt.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(D)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;nt.has(n)||(nt.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${e.stateProp} declares ${t.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(d),void ot(d,"$connectedCallback")}}hd(this,this._boundComponent,this._boundComponentStateProp,u)}var e,t,n,s}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{N in e&&await e[Bt]()})}async _initializeDCC(e,t){let n;try{if(this.hasAttribute("src")){const e=this.getAttribute("src");e.endsWith(".js")?n=await ja(e):H(`DCC: Unsupported src type: ${e}`)}else{const t=this.querySelector('script[type="module"]');t?n=await La(t,e.tagName.toLowerCase()):H(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}}catch(e){H(`DCC: Failed to load state: ${e}`)}!function(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||H(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=ne(e);null!==r&&"function"==typeof r.define||H(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&H(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=sc(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(F))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const e=ne(this._shadow);return null!==e&&oe(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(m.bindableEventMap).length>0){const t=e.querySelector(p);t?t.setBindableEventMap(m.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${A} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=nl(n);for(const[e,t]of Object.entries(g)){if(tc(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=ec(e,o)}else n.get=Ql(e),n.set=Zl(e);Object.defineProperty(m.prototype,e,n)}for(const e of u)Object.defineProperty(m.prototype,e,{configurable:!0,enumerable:!0,get:Ql(e),set:Zl(e)});r.define(s,m)}(e,t,n),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",e=>{P in e&&e[zt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&ua(this._rootNode)===this._volumeGraftInfo.rootStateElement&&bd(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const e=this._mountRecord,t=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&function(e,t){const n=as(t),o=St(e.component);n.forEachActiveBindingNode(e=>Nt(e,o)),mi(n.rebindAddresses()),bc(e)}(e,t)}),ot(e,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||ua(this._rootNode)===this||ma(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 e=this.parentNode;if(e instanceof ShadowRoot&&e.host.hasAttribute(F))return this.hasAttribute("bind-component")&&H(`"bind-component" cannot be used inside a [${F}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(e.host,e);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")&&!t()||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await fa(this.rootNode);const e=Gi.extractStateData(this),t=document.createElement(o.tagNames.ssr);t.setAttribute("version",Wi),Gi.buildContent(t,e),this.parentNode?.insertBefore(t,this)}catch(e){throw this._rejectConnectedCallback?.(e),e}t()||null===this._rootNode||e!==this._connectGeneration||Ul(this),t()||null===this._rootNode||e!==this._connectGeneration||this._streamsStartedGeneration===e||Al(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&bd(this._volumeGraftInfo,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._mountRecord)return ot(this._mountRecord,"$disconnectedCallback"),bc(this._mountRecord),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{ma(this.rootNode,null),e=this,Wa.delete(e),function(e){za.delete(e)}(this),Ln(this),Ya(this),Il(this),function(e){Ol.delete(e)}(this),this._rootNode=null}}var e}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 hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&H(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),t.set(n,o);this._listKeys=t}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(e){this._listPaths.add(e)}findStateDescriptor(e){return zr(this._state,e)}defineTreeAccessor(e,t){Object.defineProperty(this._state,e,t),"function"==typeof t.get&&this._getterPaths.add(e),"function"==typeof t.set&&this._setterPaths.add(e),this.setPathInfo(e,"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&&H("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(e){this._bindableEventMap=e}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){return this._addDependency(this._dynamicDependency,e,t)}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t,n="binding"){if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+r)),!this._pathSet.has(e)){const t=Y(e);if(this._pathSet.add(e),Xr(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=Y(e.parentPath)}}}_createState(e,t,n){try{const o=function(e,t,n){const o=new ld(e,n);return new Proxy(t,o)}(e,this._state,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(e){this._indexDependentGetterPaths.add(e)}setInitialState(e){this._initialized?((this._hasGraftedVolumes||this._hasMounts)&&H("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=e):this._resolveSetState?.(e)}}function Pd(e=customElements){e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Gi),e.get(o.tagNames.state)||e.define(o.tagNames.state,Nd)}function Id(e){const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}await function(t,o){const s=Id(t);var r;s&&((r=s).tagNames&&Object.assign(n.tagNames,r.tagNames),"string"==typeof r.bindAttributeName&&(n.bindAttributeName=r.bindAttributeName),"string"==typeof r.commentTextPrefix&&(n.commentTextPrefix=r.commentTextPrefix),"string"==typeof r.commentForPrefix&&(n.commentForPrefix=r.commentForPrefix),"string"==typeof r.commentIfPrefix&&(n.commentIfPrefix=r.commentIfPrefix),"string"==typeof r.commentElseIfPrefix&&(n.commentElseIfPrefix=r.commentElseIfPrefix),"string"==typeof r.commentElsePrefix&&(n.commentElsePrefix=r.commentElsePrefix),"string"==typeof r.locale&&(n.locale=r.locale),"boolean"==typeof r.debug&&(n.debug=r.debug),"boolean"==typeof r.enableMustache&&(n.enableMustache=r.enableMustache),"boolean"==typeof r.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=r.enableDirectionalInitialSync),"boolean"==typeof r.enablePropagationContext&&(n.enablePropagationContext=r.enablePropagationContext),"boolean"==typeof r.enableContractAnalyzer&&(n.enableContractAnalyzer=r.enableContractAnalyzer),"boolean"==typeof r.sameValueGuard&&(n.sameValueGuard=r.sameValueGuard)),Pd(o),function(){const e=globalThis;void 0===e[Qi]&&(e[Qi]=aa)}(),function(){const t=globalThis;void 0===t[e]&&(t[e]=Ta)}(),Ma()}();
2
2
  //# sourceMappingURL=auto.min.js.map