@wcstack/state 2.5.0 → 2.6.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=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),P="$connectedCallback",I="$disconnectedCallback",N="$updatedCallback",_="$errorCallback",k="$stateReadyCallback",A="$bindables",C="$commands",E="$commandTokens",M="$command",O="$eventTokens",T="$on",R="$streams",j="$watch",L="$scan",D="$recursion",W="**",B="$listKeys",z="$streamStatus",F="$streamError",q="data-wc-definition",V=new WeakMap,G=new WeakSet;let U=0;async function K(e){const t=function(e){let t,n=V.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++U,promise:o,resolve:t},V.set(e,n),G.has(e)&&n.resolve(),n}(e);await t.promise}function H(e){const t=V.get(e);void 0===t?G.add(e):t.resolve()}function J(e){throw new Error(`[@wcstack/state] ${e}`)}const X=new Map;let Q=0;function Y(e){let t=X.get(e);return void 0!==t||(-1!==e.indexOf(W)&&J(`[wcs/recursion-unsupported] "${e}" uses "${W}", 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 Z(e)),X.set(e,t)),t}class Z{id=++Q;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(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 ee=new WeakMap;function te(e){const t=ee.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{ee.set(e,n)}}function ne(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function oe(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return ne(t);if(void 0!==n)return ne(n)}return ne(globalThis.customElements)}function se(e,t){e.upgrade?.(t)}function re(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=ce(s.properties,ie);if(null===r)return null;const i=void 0===s.inputs?new Map:ce(s.inputs,ae);if(null===i)return null;const a=void 0===s.commands?new Map:ce(s.commands,le);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function ie(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 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.attribute||"string"==typeof t.attribute)}function le(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 ce(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 de(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:Y(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ue(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function fe(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&&J("Spread binding requires an element node.");const t=e,o=te(t);null===o&&J(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=oe(t);null===a&&J(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||J(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}se(a,t);const l=re(t);null===l&&J(`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=de(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=de(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=ue(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=ue(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 he(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 pe=new WeakMap;function me(e){return pe.get(e)||null}function ge(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 ye(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ge(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const we=" Validate statically: npx @wcstack/lint <file>.",be=new Set(["if","elseif","else","for"]);function ve(e){J(`filter ${e} requires at least one option`)}function $e(e){J(`filter ${e} requires a number as option`)}function xe(e){J(`filter ${e} requires a number value`)}function Se(e){J(`filter ${e} requires a date value`)}function Pe(e){return!(!e||isNaN(Number(e)))}const Ie={eq:e=>{const t=e?.[0]??ve("eq");return e=>"number"==typeof e?(Pe(t)||$e("eq"),e===Number(t)):e===t},ne:e=>{const t=e?.[0]??ve("ne");return e=>"number"==typeof e?(Pe(t)||$e("ne"),e!==Number(t)):e!==t},not:e=>e=>("boolean"!=typeof e&&J(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??ve("lt");return Pe(t)||$e("lt"),e=>("number"!=typeof e&&xe("lt"),e<Number(t))},le:e=>{const t=e?.[0]??ve("le");return Pe(t)||$e("le"),e=>("number"!=typeof e&&xe("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??ve("gt");return Pe(t)||$e("gt"),e=>("number"!=typeof e&&xe("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??ve("ge");return Pe(t)||$e("ge"),e=>("number"!=typeof e&&xe("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??ve("inc");return Pe(t)||$e("inc"),e=>("number"!=typeof e&&xe("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??ve("dec");return Pe(t)||$e("dec"),e=>("number"!=typeof e&&xe("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??ve("mul");return Pe(t)||$e("mul"),e=>("number"!=typeof e&&xe("mul"),e*Number(t))},div:e=>{const t=e?.[0]??ve("div");return Pe(t)||$e("div"),e=>("number"!=typeof e&&xe("div"),e/Number(t))},mod:e=>{const t=e?.[0]??ve("mod");return Pe(t)||$e("mod"),e=>("number"!=typeof e&&xe("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&xe("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??ve("clamp");Pe(t)||$e("clamp");const n=e?.[1]??ve("clamp");Pe(n)||$e("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&xe("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return Pe(t)||$e("fix"),e=>("number"!=typeof e&&xe("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&xe("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]??ve("slice");Pe(n)||$e("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Pe(o)||$e("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??ve("substr");Pe(t)||$e("substr");const n=e?.[1]??ve("substr");return Pe(n)||$e("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??ve("pad");Pe(t)||$e("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??ve("rep");return Pe(t)||$e("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??ve("truncate");Pe(t)||$e("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)||J(`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 Pe(t)||$e("round"),e=>{"number"!=typeof e&&xe("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Pe(t)||$e("floor"),e=>{"number"!=typeof e&&xe("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Pe(t)||$e("ceil"),e=>{"number"!=typeof e&&xe("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Pe(t)||$e("percent"),e=>("number"!=typeof e&&xe("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??ve("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Se("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Se("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Se("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Se("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||Se("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]??ve("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},Ne=Ie,_e={input:Ie,output:Ne},ke=(e,t)=>n=>{const o=n[e];return o||J(`[wcs/filter-unknown] filter not found: ${e}.${ye(e,Object.keys(n))}${we}`),o(t)};function Ae(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 Ce=new Map;function Ee(e,t){const n=_e[t];return e.map(e=>{const o=e.indexOf("("),s=e.lastIndexOf(")");if(-1!==o&&-1===s&&J(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==s&&-1===o&&J(`Invalid filter format: missing opening parenthesis in "${e}"`),-1===o){const o=e.trim(),s=`${o}():${t}`;let r=Ce.get(s);return void 0===r&&(r=ke(o,[])(n),Ce.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(Ae(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=Ae(n,r,i);return(l||s)&&t.push(l),t}(r),l=`${i}(${a.join(",")}):${t}`;let c=Ce.get(l);return void 0===c&&(c=ke(i,a)(n),Ce.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const Me=e=>e.trim(),Oe=new Map;const Te=new Map;function Re(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(Me),r=Ee(o,"output"),Te.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&J(`"${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 je(e){const[...t]=e.split(";").map(Me).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&J(`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=Re(o);return t.outFilters.length>0&&J(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&J(`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:[],...Re(o),bindingType:n}}{const e=Re(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(),Oe.has(r)?i=Oe.get(r):(o=r.split(l).map(Me),i=Ee(o,"input"),Oe.set(r,i))):n=e.trim();const[a,c]=n.split("#").map(Me),d=a.split(s).map(Me);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map(Me):[],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=>be.has(e.bindingType))&&J(`[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">).${we}`)}return n}const Le=new WeakMap,De=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),We=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Be(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=We.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return De.has(r)?(Le.set(e,s[2]),s[2]):null}function ze(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Re(e),bindingType:"text"}}const Fe=new Map;function qe(e,t,n){if(null===n)Fe.delete(e);else{Fe.set(e,n);const o=Ka(t);null===o&&J("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 Ve(e){return Fe.get(e)||null}function Ge(e){if(e.nodeType===Node.ELEMENT_NODE){return je(e.getAttribute(o.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=Be(e);null===t&&J("Comment node binding text not found.");const n=Ve(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=ze(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 Ke(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 He(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 Je(e){const t=[],n=Ke(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!==Be(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&He(e,n)||t.push(e)}return t}const Xe=new WeakSet;function Qe(e,t,n,o){const s=fe(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?te(e):null;return null===n&&J("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}Xe.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){pe.set(e,t)}(e,r),H(e),{bindings:r,deferred:null}}function Ye(e,t){const n=Je(e),o=[],s=[];for(const e of n){if(Xe.has(e))continue;const n=Qe(e,Ge(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Ze(e){Xe.add(e)}function et(e){const{node:t,parseResults:n,transform:o}=e;!function(e){Xe.delete(e)}(t);return Qe(t,n,{allowDeferred:!1},o).bindings}let tt=0;const nt=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion"],ot=new Set;function st(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 rt(e,t,n,o,r,i=new Set){0===n.length&&J(`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)&&J("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=++tt,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 it(e){const t=e.indexOf(s);return-1===t?e:e.slice(0,t)}function at(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 lt(e,t){for(const n of e.entries)if(at(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 ct(e,t){return e.markerBasePath+s+t}function dt(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 ut(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 ft(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}.${it(t)}: path") or declare the key on the component state.`}const ht=/^\$(\d+)$/;function pt(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 dt(e,e.markerBasePath,t,t),ct(e,t);if(ut(e,n[0]))return dt(e,e.markerBasePath,t,t),ct(e,t);const i=n.slice(0,o+1),a=n.slice(o+1),l=lt(e,i);null===l&&J(ft(e,t)),0===a.length&&J(`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 dt(e,c,a.join(s),t),c+s+a.join(s)}(e,t);const o=it(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return ct(e,t);if(ut(e,o))return ct(e,t);const i=lt(e,t.split(s));if(null!==i)return i;J(ft(e,t))}function mt(e,t,n){let o;const i=ht.exec(t.statePathName);if(null!==i){const s=function(e,t){return void 0===t?e.delta:Y(pt(e,t)).wildcardCount-Y(t).wildcardCount}(e,n);o=0===s?t.statePathName:`$${Number(i[1])+s}`}else if(o=pt(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 gt(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&&J(`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 yt=new WeakMap,wt=new WeakMap;const bt=new WeakMap;const vt=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)}),$t=new WeakMap;function xt(e){return $t.get(e)??null}function St(e){return yt.get(e)??null}function Pt(e){const t=bt.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}function It(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=bt.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 Nt=new WeakMap;function _t(e){let t=e;for(;t;){const e=Nt.get(t);if(e)return e;let n=t.parentNode;null===n&&t instanceof ShadowRoot&&null!==St(t)&&(n=t.host),t=n}return null}function kt(e,t){null!==t?Nt.set(e,t):Nt.delete(e)}let At=null;const Ct=new WeakMap;function Et(e){return Ct.get(e)??[]}function Mt(e,t){Ct.set(e,t)}function Ot(e){return Ct.has(e)}const Tt=new WeakMap;let Rt=null,jt=0;function Lt(e){return Tt.get(e)??[]}function Dt(e,t){null===Rt?Tt.set(e,t):Rt.set(e,t)}function Wt(){jt++,null===Rt&&(Rt=new Map)}function Bt(){if(0!==jt&&(jt--,!(jt>0||null===Rt))){for(const[e,t]of Rt)Tt.set(e,t);Rt=null}}function zt(e){return(Rt?.has(e)??!1)||Tt.has(e)}const Ft=Symbol("$$setLoopContext"),qt=Symbol("$$getByAddress"),Vt=Symbol("$$hasByAddress"),Gt=Symbol("$$setByAddress"),Ut=Symbol("$$connectedCallback"),Kt=Symbol("$$disconnectedCallback"),Ht=Symbol("$$updatedCallback"),Jt=Symbol("$$errorCallback"),Xt=new WeakMap;function Qt(e,t){if(Xt.has(e)){const n=Xt.get(e);if(n.has(t))return n.get(t)}else Xt.set(e,new WeakMap);const n=Object.freeze(new Yt(e,t));return Xt.get(e).set(t,n),n}class Yt{pathInfo;stateElement;parentAbsolutePathInfo;constructor(e,t){this.pathInfo=t,this.stateElement=e,null===t.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Qt(e,t.parentPathInfo)}}const Zt=new WeakMap,en=new WeakMap;class tn{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=nn(e,t)}}function nn(e,t){if(null===t){let t=en.get(e);return void 0!==t||(t=new tn(e,null),en.set(e,t)),t}{let n=Zt.get(t);void 0===n&&(n=new WeakMap,Zt.set(t,n));let o=n.get(e);return void 0!==o||(o=new tn(e,t),n.set(e,o)),o}}const on=new WeakMap;function sn(e,t){null===t?on.delete(e):on.set(e,t)}function rn(e){return on.get(e)||null}const an=new Map;function ln(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=an.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,an.set(s,r),r}function cn(e,t,n){return t<0||t>=n?null:e.at(t-n)}function dn(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const un=new WeakMap;function fn(e){const t=_t(e.node);if(null===t)return null;let n=un.get(t);if(void 0===n)n=new WeakMap,un.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=ln(t.pathInfo,e.statePathInfo);return n>0&&(o=cn(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const hn=new WeakMap;function pn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=rn(n);null===t?J(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function mn(e,t){let n=null;if(n=hn.get(e)||null,null!==n)return n;const o=pn(e,t),s=fn(e),r=Ka(o);null===r&&J("No state tree found on this root for binding.");return n=nn(Qt(r,e.statePathInfo),s),hn.set(e,n),n}function gn(e){hn.delete(e)}const yn=new WeakMap;function wn(e,t){const n=yn.get(e);void 0===n?yn.set(e,t):n instanceof Set?n.add(t):n!==t&&yn.set(e,new Set([n,t])),null!==At&&At({type:"state:binding-added",absoluteAddress:e,binding:t})}function bn(e,t){const n=yn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&yn.delete(e),null!==At&&At({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const vn=new WeakMap;function $n(e,t,n){const o=vn.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!==At&&At({type:"state:binding-removed",absoluteAddress:nn(e,t),binding:n}))}function xn(e){const t=yn.get(e);return void 0!==t?t:null!==e.listIndex?vn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const Sn=new WeakMap,Pn=new WeakMap;class In{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=Nn(e,t)}}function Nn(e,t){if(null===t){let t=Pn.get(e);return void 0!==t||(t=new In(e,null),Pn.set(e,t)),t}{let n=Sn.get(t);void 0===n&&(n=new WeakMap,Sn.set(t,n));let o=n.get(e);return void 0!==o||(o=new In(e,t),n.set(e,o)),o}}const _n=new WeakMap;function kn(e){let t=null;if(t=_n.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=fn(e);null===n&&J(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=Nn(e.statePathInfo,n)}else t=Nn(e.statePathInfo,null);return _n.set(e,t),t}function An(e){_n.delete(e)}function Cn(){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 En=new Map,Mn=Cn();function On(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Tn(e){let t="input";for(const n of e.propModifiers)n.startsWith(g)&&(t=n.slice(2));return t}function Rn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const o=Tn(e),s=On(e,o);let r=En.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=Ka(o.getRootNode());null===i&&J("No state tree found on this root for two-way binding.");const a=_t(o);i.createState("writable",e=>{e[Ft](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]:[]})})},En.set(s,r)),e.node.addEventListener(o,r),Mn.add(s,e),!0}var t,n;return!1}function jn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Ln(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)jn(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class Dn{_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 Wn extends Dn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==At&&At({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Bn=new WeakMap;function zn(e,t){let n=Bn.get(e);void 0===n&&(n=new Map,Bn.set(e,n));let o=n.get(t);return void 0===o&&(o=new Wn(t,e),n.set(t,o)),o}const Fn=new WeakMap;function qn(e){if(e.propSegments[0]!==y)return!1;const t=e.node,n=te(t),o=oe(t);if(null!==n&&void 0===o?.get(n))return null===o&&J(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Fn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||J('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===te(e)?null:re(e)}(t);null===r&&J(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&J(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${ye(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=Ka(t.getRootNode());null===n&&J("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||J(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${ye(l,n.eventTokenNames)}${we}`);const o=_t(t);n.createStateAsync("writable",async t=>{Ln(t[Ft](o,()=>{const s=null!==o?dn(o.listIndex,o.pathInfo.wildcardCount):[];return zn(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,f),Fn.set(e,{eventName:a,handler:f}),!0}class Vn extends Dn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==At&&At({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Gn(e){return e instanceof Vn}const Un=new Map,Kn=Cn();function Hn(e){const t=e.propModifiers.filter(e=>e===c||e===d).sort().join(",");return`${e.statePathName}::${t}`}const Jn=(e,t,n)=>o=>{t.includes(c)&&o.preventDefault(),t.includes(d)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Ka(r);null===i&&J("No state tree found on this root for event handler.");const a=_t(s),l=e.startsWith(M+".");i.createStateAsync("writable",async t=>{const c=t[Ft](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=yt.get(n);if(void 0!==e)return e;n=n.parentNode}return yt.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?dn(a.listIndex,c):[];if(l){const s=t[qt](Nn(n,null));return Gn(s)||J(`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&&J(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Ln(c,`"${e}"`)})};function Xn(e){if(!e.propName.startsWith(g))return!1;const t=Hn(e);let n=Un.get(t);void 0===n&&(n=Jn(e.statePathName,e.propModifiers,e.statePathInfo),Un.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Kn.add(t,e),!0}const Qn=new Map,Yn=Cn();function Zn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function eo(e){let t="input";for(const n of e.propModifiers)n.startsWith(g)&&(t=n.slice(2));return t}function to(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const o=eo(e),s=Zn(e,o);let r=Qn.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=Ka(o.getRootNode());null===r&&J("No state tree found on this root for two-way binding.");const i=_t(o);r.createState("writable",e=>{e[Ft](i,()=>{e[t]=s})})},Qn.set(s,r)),e.node.addEventListener(o,r),Yn.add(s,e),!0}var t,n;return!1}const no=new Set(["radio","checkbox"]),oo=new Set(["value","valueAsNumber","valueAsDate"]);function so(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(no.has(e)&&"checked"===t)return!0;if(oo.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=te(n);if(null!==s){const e=oe(n)?.get(s);void 0===e&&J(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=re(n);if(o?.knownProperties.has(t))return!0}return!1}let ro=1,io=1,ao=1;const lo=new WeakMap;function co(e,t,n){let o=lo.get(e);void 0===o&&(o=new Map,lo.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=ro++,o.set(s,r)),r}function uo(e,t){return"to-element"===t?2*e:2*e+1}const fo=new Set;function ho(e){return{transactionId:io++,originBindingId:e,visitedEdges:fo,hop:0}}function po(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 mo=null;function go(){return mo}function yo(e,t){const n=mo;mo=e;try{return t()}finally{mo=n}}const wo=[];let bo=!1;const vo=new Map,$o=Cn(),xo=new WeakMap,So=e=>e.detail,Po=new WeakMap;function Io(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 No(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=te(e.node);if(null!==n){const o=oe(e.node)?.get(n);void 0===o&&J(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=re(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 _o(e){if(null!==te(e.node)){const t=re(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??So}return null}function ko(e){if(null===te(e.node))return!1;const t=re(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const Ao=(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!==So||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=Po.get(e);void 0===r&&(r=new Set,Po.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=xo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=co(a,e,t),s=function(e,t){for(let n=wo.length-1;n>=0;n--){const o=wo[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!==At&&At({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:uo(n,"to-state"),node:a,member:e}));const r=uo(n,"to-state"),i=go();if(null!==i&&i.visitedEdges.has(r))return void(null!==At&&At({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=po(i??ho(n),r)}const f=Ka(a.getRootNode());null===f&&J("No state tree found on this root for two-way binding.");const h=_t(a),p=()=>{r&&(bo=!0);try{f.createState("writable",e=>{e[Ft](h,()=>{e[t]=c})})}finally{r&&(bo=!1)}};null!==u?yo(u,p):p()};const Co=new WeakSet;function Eo(e){Co.add(e)}function Mo(e){return!!Co.has(e)&&(Co.delete(e),!0)}const Oo=new WeakSet;function To(e){Oo.add(e)}function Ro(e){return!!Oo.has(e)&&(Oo.delete(e),!0)}let jo=0;function Lo(){jo--}function Do(){return jo>0}class Wo{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 Bo=new WeakMap;function zo(e){let t=Bo.get(e);return void 0===t&&(t=new Wo(e),Bo.set(e,t)),t}function Fo(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&&J(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&J(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function qo(e){return e.propModifiers.some(e=>e.includes("="))}const Vo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Go=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Uo(e,t){return"state"===e&&"call"===t?Vo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Ko(e){if(!o.enableDirectionalInitialSync)return qo(e)&&J("init=/sync= modifiers require enableDirectionalInitialSync."),Vo;const t=null===(n=Fo(e,f))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:J(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":J(`Invalid sync modifier value "${e}".`)}(Fo(e,h));if("event"===e.bindingType)return null!==t&&"none"!==t&&J("Event bindings only allow init=none."),"call"===s?Go:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===w)return Uo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&J(`Binding type "${e.bindingType}" does not support init=${t}.`),Uo(t??"state",s);const r=re(e.node);if(null===r)return Uo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||J(`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)||J(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||J(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Ho(e,t){return"auto"!==t?t:function(e){const t=Ka(e.replaceNode.getRootNode());null===t&&J("No state tree found on this root for binding.");const n=kn(e);let o=!1;return t.createState("readonly",e=>{o=e[Vt](n)}),o}(e)?"state":"element"}let Jo=0,Xo=0;const Qo=new WeakMap,Yo=new WeakMap,Zo=new WeakMap,es=new WeakMap;function ts(e,t){const n=es.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):es.set(e,new Set([n,t]))):es.set(e,t)}function ns(e){return es.has(e)}function os(e,t){const n=es.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function ss(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))ss(n,t)}function rs(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class is{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)Mo(e)||ss(e,e=>{os(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Ro(e)&&!Do()||ss(e,e=>{os(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&ga(o)}}const as=new WeakMap;function ls(e){let t=as.get(e);return void 0===t&&(t=new is(e),as.set(e,t)),t}function cs(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 ds(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class us{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=Qo.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(rs(t)&&ls(t),null===this.rowPlan)for(const n of e){const e=Qo.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 qo(e)&&Ko(e),!0;const t=Qo.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=Qo.get(e);return t?.session===this?t:null}addTeardown(e,t){const n=Qo.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(ds(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=oe(e);null===s&&J(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),ts(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=zo(s).wait(t,()=>{if(a())try{se(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=Qo.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&&(bn(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?mn(n):null;if(null!==t.address?(bn(t.address,n),t.address=null):($n(t.patternPathInfo,t.patternListIndex,n),t.patternPathInfo=null,t.patternListIndex=null),An(n),gn(n),this.registerAddress(t),null!==o){const e=mn(n);e!==o&&Ot(o)&&Mt(e,Et(o)),e!==o&&zt(o)&&Dt(e,Lt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return rs(t)?t:null}(e);null!==t&&ls(t)}handleMutations(e,t,n){for(const n of t)ss(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)ss(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&ga(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=Qo.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=Zo.get(t);void 0===e&&(e=cs(t),Zo.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;ts(n,this);const o=this.knownMapFor(n);let s=Zo.get(e);void 0===s&&(s=cs(e),Zo.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;ts(i,this),this.addKnownRowBinding(i,s,e),this.optionsByBinding.set(s,n);const a={id:++Jo,info:s,generation:++Xo,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(Qo.set(s,a),this.records.add(a),r.isEvent){try{Xn(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=Qo.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=++Xo,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{Xn(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:++Jo,info:e,generation:++Xo,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};Qo.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;Xn(t)?e.eventAttached=!0:t.propSegments[0]!==y?(to(t)&&ds(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const t=eo(e),n=Zn(e,t),o=Qn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Yn.countOf(n)&&(Yn.remove(n,e)&&Qn.delete(n),!0))}return!1}(t)),Rn(t)&&ds(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const t=Tn(e),n=On(e,t),o=En.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Mn.countOf(n)&&(Mn.remove(n,e)&&En.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&so(t.node,t.propName)&&-1===t.propModifiers.indexOf(u)){const n=function(e,t,n){let o=xo.get(e);void 0===o&&(o=new Map,xo.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&&xo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});ds(e,n)}!function(e){const t=te(e.node);if(null!==t){const n=oe(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&J(`CustomElementRegistry is unavailable for <${t}>.`))}if(so(e.node,e.propName)&&-1===e.propModifiers.indexOf(u)){const t=No(e),n=_o(e),o=ko(e),s=Io(e,t,null!==n,o);let r=vo.get(s);void 0===r&&(r=Ao(e.propName,e.statePathName,e.inFilters,n,o),vo.set(s,r)),e.node.addEventListener(t,r),$o.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{qn(t)&&ds(e,()=>function(e){if(e.propSegments[0]!==y)return!1;const t=Fn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Fn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=te(e.info.node);if(null===n)return void t();const o=oe(e.info.node);if(null===o&&J(`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=zo(o).wait(n,()=>{if(this.isAlive(e,s))try{se(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))});ds(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Ko(e.info),n=Ho(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 jo++;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,Lo()),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=Ka(e.node.getRootNode());null===o&&J("No state tree found on this root for initial binding sync.");const s=_t(e.node);o.createState("writable",t=>{t[Ft](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=fn(n);if(null!==o){const s=Ka(pn(n,t));null===s&&J("No state tree found on this root for binding.");const r=Qt(s,n.statePathInfo);!function(e,t,n){let o=vn.get(e);void 0===o&&(o=new WeakMap,vn.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!==At&&At({type:"state:binding-added",absoluteAddress:nn(e,t),binding:n})}(r,o,n),e.patternPathInfo=r,e.patternListIndex=o}else{const o=mn(n,t);wn(o,n),e.address=o}if(!e.options.registerPathInfo)return;const s=Ka(n.replaceNode.getRootNode());null===s&&J("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&&Qo.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,Lo());const t=e.info;if(null!==e.address)try{bn(e.address,t),e.address=null,An(t),gn(t)}catch{}else if(null!==e.patternListIndex)try{$n(e.patternPathInfo,e.patternListIndex,t),e.patternPathInfo=null,e.patternListIndex=null,An(t),gn(t)}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=te(e.node);if(null!==t){const n=oe(e.node),o=n?.get(t);if(void 0===o)return}if(so(e.node,e.propName)&&-1===e.propModifiers.indexOf(u)){const t=No(e),n=Io(e,t,null!==_o(e),ko(e)),o=vo.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),$o.remove(n,e)&&vo.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=Hn(e),n=Un.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);e.node.removeEventListener(o,n),0!==Kn.countOf(t)&&(Kn.remove(t,e)&&Un.delete(t))}(t)}catch{}}}}function fs(e){let t=Yo.get(e);return void 0===t&&(t=new us(e),Yo.set(e,t)),t}function hs(e){return Qo.get(e)?.session??null}const ps=new WeakMap;function ms(e,t){let n=ps.get(e);n||(n=new Set,ps.set(e,n)),n.add(t)}const gs=new WeakMap;function ys(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ws=Object.freeze([]);const bs=new WeakMap;const vs=new WeakMap;function $s(e){return vs.get(e)??[]}function xs(e,t){vs.set(e,t)}const Ss=new WeakMap;function Ps(e){return Ss.get(e)??[]}function Is(e,t){Ss.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 Ns=0;function _s(){return`u${(Ns++).toString(36)}`}let ks=0,As=0;const Cs=Symbol("wcs.listIndex.noValue");class Es{uuid=_s();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Cs,this._index=t,this._version=ks,this._chainGeneration=As}get index(){return this._index}set index(e){this._index=e,this._version=++ks,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(e){this._value=e}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=ks),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===As||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=As),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++ks,As++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Ms(e,t,n=e){return new Es(e,t,n)}function Os(e,t){e.reparent(t)}function Ts(e){return e.homeParentListIndex}function Rs(e,t){e.value=t}function js(e,t){const n=e.value;return n!==Cs&&n===t.value}const Ls=new WeakMap,Ds=new WeakSet;function Ws(e){return Ds.has(e)}function Bs(e,t){const n=Ts(e),o=e.parentListIndex;return null===n||n===o||Ds.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Ds.has(e)&&!Ds.has(n)&&n.position===e.position&&js(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Ds.has(e)&&!Ds.has(t)}(o,t)?t:null:n}function zs(e){const t=Ls.get(e);return void 0===t?null:t}function Fs(e,t){const n=Ls.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Bs(o,t);if(null!==e)for(const t of n)Os(t,e)}return n}function qs(e,t){null!==t?Ls.set(e,t):Ls.delete(e)}const Vs=new WeakMap,Gs=Object.freeze([]),Us=new Set;function Ks(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Gs,s=Array.isArray(n)&&n.length>0?n:Gs,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Gs,o=Array.isArray(t)&&t.length>0?t:Gs;let s=Vs.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Fs(o,e)||[],a=i.length>0?Ts(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Us,deleteIndexSet:new Set(i),addIndexSet:Us};let t=Fs(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Ms(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:Us,deleteIndexSet:Us,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 l={oldIndexes:i,newIndexes:i,changeIndexSet:Us,deleteIndexSet:Us,addIndexSet:Us};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,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=Ms(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=Vs.get(e);o||(o=new WeakMap,Vs.set(e,o)),o.set(t,n)}(o,s,l),qs(s,l.newIndexes))}}(e,t,n);return function(e,t){for(let n=0;n<e.length;n++)e[n].index!==n&&(e[n].index=n),Rs(e[n],t[n])}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Gs),function(e){for(const t of e)Ds.add(t)}(o.deleteIndexSet),function(e){for(const t of e)Ds.delete(t)}(o.newIndexes),o}function Hs(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 Js=new WeakSet;const Xs=new WeakMap;function Qs(e){return Xs.get(e)??null}function Ys(e,t){Xs.set(e,t)}const Zs=new WeakMap;function er(e){return Zs.get(e)??[]}function tr(e,t){Zs.set(e,t)}function nr(e,t){const n=er(e);for(const e of n)kt(e,t)}function or(e,t,n){nr(e,t);const o=$s(e),s=Qs(e);null!==s&&s.activate(o,n.rootNode);for(const e of o){if(null===s){wn(mn(e),e)}(null===s||s.shouldApplyState(e))&&pa(e,n)}}function sr(e){if(!e.mounted)return;const t=$s(e),n=Qs(e);for(const e of t)if(null!==n)n.disposeBinding(e);else{bn(mn(e),e)}!function(e){const t=er(e);for(const e of t)kt(e,null)}(e)}const rr=new WeakMap,ir=Object.freeze(new Set);function ar(e,t){const n=rr.get(e);n?n.add(t):rr.set(e,new Set([t]))}function lr(e){const t=rr.get(e);return void 0!==t?t:ir}function cr(e,t){const n=rr.get(e);n&&(n.delete(t),0===n.size&&rr.delete(e))}const dr=new Set(["if","elseif","else","for"]);class ur{_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)To(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){To(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=Qs(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRecords();for(const e of this._childNodeArray)Eo(e),null!==e.parentNode&&e.parentNode.removeChild(e);const t=$s(this);for(const e of t)if(dr.has(e.bindingType)){const t=lr(e.node);for(const e of t)e.tryDestroy()||e.unmount()}return this._mounted=!1,!0}unmountInPlace(){Qs(this)?.dispose(),this._teardownBindings()}_teardownBindings(){const e=$s(this);for(const t of e){if(dr.has(t.bindingType)){const e=lr(t.node);for(const t of e)t.unmount()}An(t),gn(t)}}unmount(){Qs(this)?.dispose();for(const e of this._childNodeArray)Eo(e),null!==e.parentNode&&e.parentNode.removeChild(e);const e=$s(this);for(const t of e){if(dr.has(t.bindingType)){const e=lr(t.node);for(const t of e)t.unmount()}An(t),gn(t)}this._mounted=!1}}function fr(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 hr(e){const t=document.createDocumentFragment(),n=new ur(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 pr(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=he(o,s[e].nodePath);null===t&&J(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),Ze(t),H(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 us;return n.initializeRow(e,t),n}(n,a),d=new ur(o);return Ys(d,c),xs(d,a),Is(d,l),tr(d,r),ar(e.node,d),d}function mr(e){void 0!==e.uuid&&null!==e.uuid||J("BindingInfo.uuid is null.");const n=Ve(e.uuid);n||J(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&fr(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=he(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!==te(r))return null;if("prop"===o&&so(r,e.propName))return null;let i;try{i=Ko({...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 pr(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=he(e,s.nodePath);if(null===t&&J(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Xe.has(t))continue;const r=Qe(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new us,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 ur(i,s);Ys(l,a.bindingSession),xs(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in S&&c.push(e);return Is(l,c),tr(l,a.nodes),ar(e.node,l),l}const gr=/\{\{\s*(.+?)\s*\}\}/g,yr=new Set(["SCRIPT","STYLE"]);function wr(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&&yr.has(e.parentElement.tagName)||br(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),wr(t.content)}else wr(e.content)}function br(e){const t=e.data;if(gr.lastIndex=0,!gr.test(t))return;gr.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=gr.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 vr;function $r(){if(vr)return vr;const e=[],t=ke("not",e)(Ne);return vr={filterName:"not",args:e,filterFn:t},vr}const xr=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Sr(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 Pr(e,t){const n=xr.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Sr(s,t)+r}function Ir(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=Sr(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Nr(e,t){return Ir(e,t)}function _r(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=Pr(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Ir(r,t);e!==r&&o.setAttribute(n,e)}}}function kr(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 Ar(e){const t=[],n=Je(e);for(const e of n){const n=Ge(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:kr(o),parseBindTextResults:n})}return t}function Cr(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 Er=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Mr=$r();function Or(e,t){const n=t.outFilters;return{...t,outFilters:[...n,Mr],bindingType:e}}function Tr(e,t,n,o,s,r=!0){Cr(t),"string"==typeof o&&_r(t,o),Rr(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ar(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 Rr(e,t,n,s){const r=o.commentElsePrefix,i=Ke(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=Nr(i,n));let a=je(i)[0];const d=Er.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=_s();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&J("'else' binding found without preceding 'if' or 'elseif' binding."),a=Or("else",l.parseBindTextResult),p=Tr(e,f,a,m,s,!1),qe(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:kr(o),parseBindTextResults:Ge(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&J("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Tr(e,f,a,m,s),qe(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=_s(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Or("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:kr(n),parseBindTextResults:Ge(n)}),qe(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:kr(g),parseBindTextResults:Ge(g)})):t.replaceWith(g)}else{p=Tr(e,f,a,m,s),qe(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)}}const jr=new WeakMap;function Lr(e,t,n){let o=jr.get(e);void 0===o&&(o=new Map,jr.set(e,o));const s=o.get(t);null!=s&&J(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function Dr(e,t){if(null===e)return!1;const n=jr.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+s)||e.startsWith(t+s))return!0;return!1}const Wr=new WeakMap;function Br(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 zr=new WeakMap,Fr=[];const qr=new WeakMap,Vr=new WeakSet;function Gr(e){console.error(`[@wcstack/state] volume "${e.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),e.onGrafted(null)}let Ur=null;const Kr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Hr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function Jr(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 Xr(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",scan:"wcs/scan-path-missing"},Yr={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Zr(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}.${we}`}function ei(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 ti(e,t){return`$setAll("${e}") ${t}`}function ni(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.${we}`}const oi=new WeakMap;function si(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(Dr(!1===e.isConnected?null:e.rootNode??null,n))return;const i=Y(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=oi.get(e);return void 0===n&&(n=new Set,oi.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!==Jr(e,t))return Hr;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!==Jr(e,a))return Kr;if(Object(i)!==i)return Kr;if(l===r){if(!Array.isArray(i)||0===i.length)return Kr;i=i[0];continue}const d=Jr(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:Xr(i,c,n)};if("function"==typeof d.get)return t===o.length-1?Hr:Kr;i=d.value}return Hr}(t,n,e.getterPaths);"missing"===a.existence&&(function(e,t){return!0===ai.get(e)?.has(t)}(e,n)||("binding"!==o?ci(e,n,o,a):function(e,t,n){let o=ri.get(e);void 0===o&&(o=new Map,ri.set(e,o));if(o.set(t,n),ii.has(e))return;ii.add(e),setTimeout(()=>function(e){ii.delete(e);const t=ri.get(e);if(void 0===t)return;ri.delete(e);for(const[n,o]of t)ci(e,n,"binding",o)}(e),0)}(e,n,a)))}const ri=new WeakMap,ii=new WeakSet,ai=new WeakMap;function li(e,t){let n=ai.get(e);void 0===n&&(n=new Set,ai.set(e,n)),n.add(t),ri.get(e)?.delete(t)}function ci(e,t,n,o){console.warn(`[@wcstack/state] [${Qr[n]}] ${Yr[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ye(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${we}`),null!==At&&At({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const di=new WeakMap,ui=new Set;function fi(e,t,n,o){let s=di.get(e);if(void 0===s){if(!o)return null;s=new Map,di.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 hi(e,t){if(!e.component.isConnected)return!1;const n=_t(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 pi(e,t,n,o){const r=fi(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&&hi(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?hi(i,o)&&(null!==l&&J(`[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 mi(e){const t=e.parentStateElement,n=_t(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Ft](n,()=>{e.$postUpdate(o.exportedPath)})})}function gi(e,t){const n=St(t);var o,r;null!==n&&n.stateProp!==e.stateProp&&J(`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&&fs(t).dispose(),function(e,t){yt.set(e,t),$t.set(t,e);let n=bt.get(t.parentStateElement);void 0===n&&(n=new Map,bt.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=wt.get(t.component);void 0===o&&(o=new Map,wt.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&vt.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=Va.get(e);if(void 0!==n){if(n===t)return;J("A state tree is already registered on this root.")}Va.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>mt(e,t,n);wr(t);const o=_t(e.component);Rr(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),ya(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=pt(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),fi(e.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:c}),e.parentStateElement.addDynamicDependency(t,a),li(e.parentStateElement,a)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=_t(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(ui.has(s))continue;const r=Y(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Ft](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(ui.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),mi(e),o=t,r=Promise.resolve(),Ga.set(o,r),r.then(()=>Xa(o),()=>{})}function yi(e,t){const n=fs(t),o=_t(e.component);n.forEachActiveBindingNode(e=>kt(e,o));ga(n.rebindAddresses()),mi(e)}function wi(e,t){if(function(e){const t=bt.get(e);return void 0!==t&&t.size>0}(t))for(const n of Pt(t)){if(!bi(n.component,e))continue;const t=xt(n);null!==t&&yi(n,t)}}function bi(e,t){for(let n=t.firstNode;null!==n;n=n.nextSibling){if(n===e||n.contains(e))return!0;if(n===t.lastNode)break}return!1}const vi=Symbol.for("wcstack.transition-runner");function $i(e){const t=globalThis[vi];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}function xi(e,t,n){const o=$i(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Si=new WeakSet,Pi=Symbol.for("wcstack.state.view-transition-naming");function Ii(){const e=$i("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Ni(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||Si.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[Pi]??={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.`)):(Si.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 _i=new WeakMap,ki=new WeakMap,Ai=new WeakMap,Ci=new WeakMap;function Ei(e,t,n){!function(e,t,n){let o=ki.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ki.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function Mi(e,t){_i.set(e,t)}function Oi(e,t){let n=Ai.get(e.node);void 0===n&&(n=[],Ai.set(e.node,n)),n.length<1e3?n.push(t):cr(e.node,t)}function Ti(e){return e.nodeType===Node.ELEMENT_NODE||(e.nodeType===Node.TEXT_NODE?""!==(e.textContent?.trim()??""):e.nodeType===Node.COMMENT_NODE&&e.data.startsWith("@@wcs-"))}function Ri(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 ji(e,t,n){if(o=t,!Js.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const Li=new Set(["if","elseif","else","for"]);function Di(e,t){for(const n of $s(e))if(t.appliedBindingSet.delete(n),Li.has(n.bindingType))for(const e of lr(n.node))Di(e,t)}function Wi(e){for(const t of $s(e)){if(!Li.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of lr(t.node))Wi(n),e&&n.mounted&&(sr(n),n.unmount(),cr(t.node,n))}}function Bi(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function zi(e,n,s){const r=Boolean(s);let i;const a=lr(e.node);i=0===a.size?mr(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Bi(e)}`),sr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Bi(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);or(i,_t(e.node),n);const t=Ii();null!==t&&Ni(i,"branch",t)}}const Fi=new WeakMap,qi=new WeakMap;const Vi=new WeakMap;const Gi=new WeakMap;function Ui(e){return Gi.get(e)??[]}const Ki=new Set;const Hi=Symbol.for("wcstack.trustedTypes.policy");function Ji(){const e=globalThis[Hi];return null===e||"object"!=typeof e?null:e}let Xi;let Qi=!1;function Yi(e,t){if(Qi)return;if(!function(){if(void 0!==Xi)return Xi;if(!("trustedTypes"in globalThis))return Xi=!1,Xi;try{document.createElement("div").innerHTML="<i></i>",Xi=!1}catch{Xi=!0}return Xi}())return;Qi=!0;const n="function"==typeof Ji()?.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 Zi={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 ea(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!==te(r)&&function(e,t,n){let o=Fi.get(e);o||(o=new Map,Fi.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=Ji(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Yi(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=te(e);if(null===n)return null;const o=oe(e)?.get(n);if(void 0===o)return null;const s=re(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&&so(r,c)){const t=co(r,c,e.statePathName),o=uo(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??go()??ho(t);if(a.visitedEdges.has(o))null!==At&&At({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=po(a,o);yo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:ao++,writtenValue:n};wo.push({receipt:i,node:e});try{return r()}finally{wo.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=Zi[c];e?e(r,s):(!function(e,t,n){let o=Gi.get(e);o||(o=[],Gi.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,Ki.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!==te(r)&&(u in d?function(e,t,n,o){let s=Vi.get(e);s||(s=new Map,Vi.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=qi.get(e);o||(o=new Map,qi.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 ta=new WeakSet;function na(e,t,n){}function oa(e,t){const n=kn(t);if(n.pathInfo.path in S){const e=_t(t.node);return null===e&&J(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&J("ListIndex not found for loopContext:");const n=S[t];void 0===n&&J(`Invalid index name: ${t}`);const o=cn(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&J(ni(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[qt](n)}const sa=new WeakSet;function ra(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const ia=Object.freeze({[b]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&J("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){Gn(n)||J("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=bs.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||J('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=te(e);if(null===t)return null;const n=oe(e)?.get(t);return void 0===n&&J(`Custom element <${t}> is not defined for command binding.`),re(e)}(r);null===a&&J(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||J(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ye(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),bs.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 bs.delete(e);const o=n[i];return"function"!=typeof o&&J(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),bs.set(e,{token:o,unsubscribe:c,elementRef:l})}}),aa={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!ta.has(e.replaceNode)){ta.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=fn(e),a=mn(e),l=Et(a),c=l.length>0&&!ki.has(e.node)?[]:l,d=Ks(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);let u=ki.get(e.node);const f=void 0!==u?ji(u,c,d):null,h=Array.isArray(c)&&c.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=Ci.get(e.node);if(void 0===t){const n=_i.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Ti(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Ti(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),Ci.set(e.node,t)}if(t){const t=e.node.parentNode;t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return Ai.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){for(const t of d.deleteIndexSet){const n=u.get(t);void 0!==n&&(null!==f&&f.reused.has(n)?(sr(n),Wi(n),n.unmountInPlace()):p<=0&&n.tryDestroy()?cr(e.node,n):(sr(n),n.unmount(),Oi(e,n),p-=1),h||u.delete(t))}h&&(ki.delete(e.node),u=void 0)}let m=e.node;const g=Y(s.path+"."+r),y=n.stateElement.loopContextStack,w=Hs(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&m.isConnected&&null===f&&(b=document.createDocumentFragment(),sn(b,n.rootNode));const v=t(),$=Ii(),x=e.uuid??"",S=Ai.get(e.node);for(const t of d.newIndexes){let o;if(d.addIndexSet.has(t)){const r=Nn(g,t);y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=mr(e):Di(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);m.parentNode.insertBefore(e,m.nextSibling),m=e}o.mountAfter(m)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??m;n.parentNode.insertBefore(e,n.nextSibling)}}or(o,r,n),null!==$&&Ni(o,"row",$)}),void 0===o&&J(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)&&wi(o,n.stateElement)}else{if(o=void 0!==u?u.get(t)??null:null,d.changeIndexSet.has(t)){const e=Ps(o);for(const t of e)pa(t,n)}null===o&&J(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&Ri(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),e){const e=o,s=Nn(g,t);y.createLoopContext(s,t=>{or(e,t,n)})}}m=o.lastNode||m,void 0===u&&(u=new WeakMap,ki.set(e.node,u)),u.set(t,o)}_i.set(e.node,m),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),sn(b,null))},if:zi,else:zi,elseif:zi,radio:function(e,t,n){const o=e.node,s=ys(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=ys(o.value,e.inFilters),r=Array.isArray(n)?n:ws;o.checked=r.includes(s)}},la=new WeakMap,ca=new WeakMap,da=new WeakMap;function ua(){}function fa(e){const t=e.replaceNode,n=e.propSegments[0];return function(e,t){return!0===ps.get(e)?.has(t)}(t,n)?na:function(e,t){return!0===gs.get(e)?.has(t)}(t,n)?ua:ea}function ha(e,t){const n=ys(oa(t.state,e),e.outFilters);if(!0===ca.get(e))return void t.deferredSelectBindings.push({binding:e,value:n,stateElement:t.stateElement});let o=la.get(e);if(void 0===o){if(la.has(e))return o=fa(e),o===na&&la.set(e,o),void o(e,t,n);if(o=aa[e.bindingType],void 0===o){const t=e.propSegments[0];if(o=ia[t],la.set(e,o),void 0===o){te(e.replaceNode)?(o=fa(e),o===na&&la.set(e,o)):(o=ea,la.set(e,o))}}if(o===ea){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 ca.set(e,!0)}}o(e,t,n)}else o(e,t,n)}function pa(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=mn(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=hs(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==da.get(e)){const t=te(e.replaceNode);if(t&&void 0===oe(e.replaceNode)?.get(t))return void function(e,t){if(sa.has(e))return;sa.add(e);const n=()=>{sa.delete(e);const t=hs(e);(null===t||t.shouldApplyState(e))&&ga([e])},o=n=>{sa.delete(e),ra(t,n)},s=hs(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{sa.delete(e),r()})||(sa.delete(e),r()))}const r=oe(e.replaceNode);if(null===r)return sa.delete(e),void ra(t,new Error("CustomElementRegistry is unavailable."));zo(r).wait(t,()=>{e.replaceNode.isConnected?n():sa.delete(e)},o)}(e,t);da.set(e,!0)}if(!0===t.sameRootVerified)return void ha(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=rn(o),null===o&&J("Root node for fragment not found for binding.")),o!==t.rootNode){const n=Ka(o);null===n&&J("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};ha(e,r)})}else ha(e,t)}function ma(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!==At&&At({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function ga(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=rn(d),null===d&&J("Root node for fragment not found for binding."));const u=Ka(d);null===u&&J("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{pa(n,f)}catch(e){ma(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{ea(e,{propagationContextByBinding:t},n)}catch(t){ma(e,t,o??null,c)}for(const[e,t]of i.entries())Mt(e,t),Dt(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Ht](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Jt](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 ya(e,t,n){const[o,s,r]=Ye(e,n),i=fs(e);for(const e of o)kt(e,t);ga(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=et(o);0!==e.length&&(kt(o.node,t),ga(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}async function wa(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=oe(e);null===s&&J(`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 ba(e){if(e===document)await wa(document),wr(document),Rr(document,document),ya(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await K(t.host),await wa(t),wr(t),Rr(t,t),ya(t,null)}}const va="2.5.0",$a="undefined"==typeof HTMLElement?class{}:HTMLElement,xa=/^@@wcs-(?:for|if|elseif|else):[^-]/,Sa=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,Pa=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Ia=/^@@wcs-text-start:(.+)$/;function Na(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class _a extends $a{_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=va.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=Na(JSON.stringify(t)),e.appendChild(n);const s=Array.from(Fe.keys());for(const t of s){const n=Ve(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(Ki);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=Ui(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=Na(JSON.stringify(t)),e.appendChild(n)}}Ki.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Sa.test(e.data)||Pa.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;xa.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=Ia.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;Sa.test(e.data)&&i.push(e)}for(const e of i){const t=Sa.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()}_a.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(xa.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 ka=new Set(["for","if","elseif","else"]);function Aa(e){const t=new us;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 Ca(e,t,n){for(const o of t)"event"===o.bindingType||ka.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in S||Y(o.statePathName).wildcardCount>n||e.push(o)}function Ea(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 Ma(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=je(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,$r()],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;Cr(a),"string"==typeof l&&_r(a,l),Rr(n,a,l);qe(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Ar(a)})}}async function Oa(e){await wa(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="${va}". Falling back to full render.`),_a.cleanupDom(e),!1}for(const n of t)Ma(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=Sa.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),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=hr(s.nodes),{bindingInfos:i,subscriberNodes:a,bindingSession:l}=Aa(s.nodes);Ys(t,l);for(const e of a)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");xs(t,i),tr(t,a);const c=[];for(const e of i)e.statePathName in S&&c.push(e);if(Is(t,c),"for"===s.type&&null!==s.index){const a=Ea(e,"for",s.uuid);if(a){const e=Ms(null,s.index);Ei(a,e,t),Mi(a,s.nodes[s.nodes.length-1]),ar(a,t);const c=Y(s.path+"."+r);nr(t,Nn(c,e)),l.initialize(i,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ca(o,i,c.wildcardCount);let d=n.get(s.uuid);d||(d=[],n.set(s.uuid,d)),d.push(e)}}else{const n=Ea(e,s.type,s.uuid);n&&(ar(n,t),l.initialize(i,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ca(o,i,0))}}for(const[t,o]of n){const n=Ea(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=Ve(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Ka(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&qs(t,o)})}return o}(document.body,n);_a.removeBlockBoundaryComments(document.body);const i=[];for(const e of t)e.parentNode&&(i.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());_a.restoreTextBindings(document.body);const[a,l]=Ye(document.body);for(const e of a)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(kt(e,null),t.setAttribute("data-wcs-completed",""))}else kt(e,null);const c=[],d=[],u=fs(document.body).initialize(l);for(const e of u)if("event"!==e.bindingType)if(ka.has(e.bindingType))d.push(e);else{if(e.statePathName.includes(r))continue;c.push(e)}for(const e of d)if("for"===e.bindingType){const t=mn(e),n=Ka(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(Mt(t,o),Dt(t,o))})}ga([...c,...s]);for(const{el:e,parent:t,next:n}of i)t.insertBefore(e,n);const f=e.querySelectorAll(o.tagNames.ssr);for(const t of f){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 h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0}const Ta=Symbol.for("wcstack.binder");const Ra=Symbol.for("wcstack.binder.pending"),ja=Symbol.for("wcstack.binder.taken");function La(){const e=function(){const e=globalThis[Ta];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[Ra];return void 0===t&&(t=[],e[Ra]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[ja];return void 0===t&&(t=new WeakSet,e[ja]=t),t}();for(const t of n)o.add(t),e.bind(t)}function Da(e){if(ns(e))return!0;if(!Wa(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(`[${o.bindAttributeName}]`);return null!==t&&ns(t)}function Wa(e){return 1===e.nodeType}function Ba(e){if(Da(e))return;wr(e),Rr(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);ya(t&&s?n:e,null)}const za=[];function Fa(){const e=za.splice(0,za.length);for(const t of e)Ba(t);La()}const qa={protocol:"wcs-binder",version:1,bind:function(e){var t;Wa(e)&&!Da(e)&&(t=e.getRootNode(),Ja.has(t)?Ba(e):za.push(e))}};const Va=new WeakMap,Ga=new WeakMap,Ua=new Set;function Ka(e){return Va.get(e)??null}function Ha(e){return Ga.get(e)??Promise.resolve()}const Ja=new WeakSet;function Xa(e){Ja.add(e)}function Qa(e,n){const s=Va.get(e);if(null===n){if(void 0===s)return;Va.delete(e),Ua.delete(s),null!==At&&At({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;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 Oa(e)||await ba(e)}else await ba(e);Xa(e),Fa(),t()}catch(e){n(e)}})});Ga.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await ba(e),Xa(e),Fa(),t()}catch(e){n(e)}})});Ga.set(e,t)}}void 0!==s&&J('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Va.set(e,n),Ua.add(n),function(e,t){Vr.delete(e);const n=qr.get(e);if(void 0===n||0===n.length||null===Ur)return;qr.delete(e);const o=Ur;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,n),null!==At&&At({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}let Ya=0,Za=0;function el(e){Ya=e+1}function tl(){Ya=0}const nl=new WeakMap,ol=new Set,sl=new Set;function rl(e){return e.byFromPath.size>0||e.byResetPath.size>0}function il(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function al(e){return nl.get(e)}function ll(e){cl(e),nl.delete(e)}function cl(e){ol.delete(e),sl.delete(e)}const dl=new WeakSet;let ul=0;function fl(e){return al(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function hl(e){if(0===sl.size)return;if(t=e.absolutePathInfo.stateElement,!sl.has(t))return;var t;const n=fl(e);if(void 0!==n)for(const e of n)pl(e)}function pl(e){dl.has(e)||(dl.add(e),ul++)}function ml(e){return!!dl.delete(e)&&(ul--,!0)}const gl=[];function yl(e,t=0){const n=gl.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?gl.push(o):gl.splice(n,0,o)}function wl(e){queueMicrotask(()=>{throw e})}const bl=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){Ya>Za&&(Za=Ya),hl(e);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Wt(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){const o=new Map;for(const t of e){const e=o.get(t.absoluteAddress);null!==At&&null!=e&&null!==t.context&&e.transactionId!==t.context.transactionId&&At({type:"propagation:coalesced",absoluteAddress:t.absoluteAddress,droppedTransactionId:e.transactionId,winnerTransactionId:t.context.transactionId}),o.set(t.absoluteAddress,t.context)}const s=new Set(o.keys());for(const e of n)o.has(e)||o.set(e,null);const r=[],i=new Map;for(const[e,t]of o){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!==At&&At({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop});continue}const n=xn(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(r.push(e),null!==t&&i.set(e,t));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==t&&i.set(n,t))}try{const e=()=>{i.size>0?ga(r,i):ga(r)};if(t()||0===r.length)e();else{const t=xi("state",e);void 0!==t&&t.catch(wl)}}finally{Bt(),function(e){for(const t of gl.slice())t.listener(e)}(s)}}};function vl(){return bl}const $l=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function xl(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 Sl="__WCSTACK_DEVTOOLS_HOOK__";function Pl(){const e=globalThis,t=e[Sl];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[Sl]=n,n}const Il=e=>{null!==At&&At({type:"state:update-batch",addresses:e})};function Nl(e){const t=null!==At;!function(e){At=e}(e);const n=null!==e;n&&!t?yl(Il,0):!n&&t&&function(e){const t=gl.findIndex(t=>t.listener===e);-1!==t&&gl.splice(t,1)}(Il)}function _l(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 kl(e){return Ka(e)??J("devtools: no state tree on this root")}let Al=null;function Cl(){if(t())return;if(null!==Al)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:va,getStateElements(){const e=[];for(const t of Ua)e.push(_l(t));return e},overlays:e=>Pt(kl(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=kl(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 kl(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){kl(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=Ve(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(xl(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=fe(t,je(n));for(const o of e)r(xl(t,o,"attribute",n))}catch{}continue}const t=$l.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=Ve(s);if(null===a){if(n===o.commentTextPrefix)try{r(xl(e,ze(s),"comment",s))}catch{}}else r(xl(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:Nl};Al=e,Pl().register(e)}const El={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",va),_a.buildContent(o,_a.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const Ml="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ol=0;async function Tl(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Ol}\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 ${Ml}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Ml}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Rl(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){J(`Failed to load script file: ${e}`)}}class jl{_loopContextStack=Array(a).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&J("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=a&&J("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&&J("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&&J("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&&J(`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 Ll=new WeakMap;function Dl(e,t){let n=Ll.get(e);void 0===n&&(n=new Map,Ll.set(e,n));let o=n.get(t);return void 0===o&&(o=new Vn(t,e),n.set(t,o)),o}const Wl=new WeakMap;function Bl(e){const t=Wl.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 Dl(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:Dl(e,n)}},set(){J("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){J("$command namespace is read-only; deleting from it is not allowed.")}});return Wl.set(e,n),n}const zl=Symbol("wcs-stream-last-notified-uncertain"),Fl=new WeakMap;function ql(e,t){const n=Fl.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Vl(e,t){const n=Fl.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:zl,error:Object.is(o.error,null)?null:zl})}const Gl=new Set;function Ul(e){Gl.delete(e)}const Kl=new WeakMap;function Hl(e){return Kl.get(e)??new Map}function Jl(e){Ul(e);const t=Kl.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Vl(e,n.name)}const Xl=(e,t)=>t,Ql=new Set;function Yl(e,t){const n=t[R];if(void 0===n)return void ql(e,Ql);"object"==typeof n&&null!==n||J(`${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&&J(`${R} entry name must be a non-empty string.`),i.includes(s)&&J(`${R} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&J(`${R} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&J(`${R} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&J(`${R} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(i)&&J(`${R} entry "${i}" conflicts with a getter declared on the state.`),e.setterPaths.has(i)&&J(`${R} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||J(`${R} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&J(`${R} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&J(`${R} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&J(`${R} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&J(`${R} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??Xl,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){Kl.set(e,t)}(e,o),ql(e,new Set(o.keys()))}function Zl(e,t){"string"==typeof t&&0!==t.length||J(`[wcs/recursion-declaration-invalid] ${D} ${e} must be a non-empty string.`);const n=t.split(s);n.some(e=>0===e.length)&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must not contain empty path segments.`),n.length<2&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must name a list element: a property path ending with "${s}${r}" (for example "nodes${s}${r}").`),n[n.length-1]!==r&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must end with "${s}${r}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===r&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must have exactly one "${r}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===W&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must not contain "${W}" — the declaration is what gives "${W}" its meaning.`),isNaN(Number(n[o]))||J(`[wcs/recursion-declaration-invalid] ${D} ${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 ec(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 tc(e){return-1!==e.indexOf(W)}function nc(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(tc(o))return null;const i=o.slice(1).split(s);return i[0]===r||i.some(e=>0===e.length)?null:o}function oc(e){return 0===e.length?e:s+ic(e.slice(1))}function sc(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 rc(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(s,o-1))if(sc(e,t,n.slice(0,o)))return!0;return!1}function ic(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 ac(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 lc(e,t,n){n<0&&J(`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&&J(`[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 cc(e,t){return lc(e,"",t)}function dc(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 uc=new WeakMap;function fc(e,t){null===t?uc.delete(e):uc.set(e,t)}function hc(e){const t=uc.get(e);t&&(t.dirty=!0)}const pc=new WeakSet;function mc(e){return"function"==typeof e.get&&pc.has(e.get)}function gc(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&mc(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=Qt(e,n),r=n.wildcardParentPathInfos,i=(e,t,n)=>{if(n===r.length)return void fc(nn(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=zs(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 yc="[wcs/recursion-declaration-invalid]";class wc{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=ec(t);for(const[t,o]of Object.entries(n)){if(!tc(t))continue;"function"==typeof o.set&&J(`${yc} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&J(`${yc} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=nc(e,t);null===n&&J(ei(t,e.recursiveAnchor)),0===n.length&&J(`${yc} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${s}total"), not the node.`),ac(e,oc(n))&&J(`${yc} "${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(tc(t)||mc(n))continue;const e=this._matchExpansion(t);null!==e&&J(`${yc} "${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++)sc(this.spec,e[t].suffix,e[n].suffix)&&J(`${yc} "${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(rc(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=ic(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!==dc(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=dc(this.spec,e.suffix,t);null!==n&&(null!==o&&J(`"${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||mc(s)||J(`"${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,pc.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(cc(e,o)+s+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return gc(e,t,n),n}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=lc(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 bc=new WeakMap,vc=new WeakMap;function $c(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Hl(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Hl(e).has(n),ownKeys:()=>Array.from(Hl(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Hl(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){J(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){J(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function xc(e){const t=bc.get(e);if(void 0!==t)return t;const n=$c(e,z,e=>e.status);return bc.set(e,n),n}function Sc(e){const t=vc.get(e);if(void 0!==t)return t;const n=$c(e,F,e=>e.error);return vc.set(e,n),n}function Pc(e){bc.delete(e),vc.delete(e)}const Ic=Object.freeze([]),Nc=Object.freeze([]);function _c(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??Ic,i=e.dynamicDependency.get(n)??Ic,a=t.byFromPath.get(n)??Nc;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}let kc=null;async function Ac(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 Cc(e){const t=Hl(e);if(0!==t.size){!function(e){Gl.add(e)}(e);for(const n of t.values())Ec(e,n)}}function Ec(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=kc,r=new Set;let i;kc=r;try{e.createState("readonly",e=>{i=n(e)})}finally{kc=o}i instanceof Promise&&J(`${R} entry "${t.name}" args must be synchronous (it returned a Promise).`);const a=`${z}${s}${t.name}`,l=`${F}${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||J(`${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&&J(`${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);!function(e,t){const n=al(e);if(void 0!==n&&0!==t.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==t.name)continue;const s=_c(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&J(`[wcs/scan-feedback-loop] ${R} entry "${t.name}" args read "${n}", which is derived from the ${L} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(e,t),e.createState("writable",e=>{e[t.name]=t.definition.initial}),Mc(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(){Mc(e,t,"done",null)},fail(o){Mc(e,t,"error",o),n.abort()}};Ac(r.source,o,n.signal,i)}function Mc(e,t,n,o){t.status=n,t.error=o;const r=function(e,t){return Fl.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=Fl.get(e);void 0===s&&(s=new Map,Fl.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{i&&e.$postUpdate(`${z}${s}${t.name}`),a&&e.$postUpdate(`${F}${s}${t.name}`)}))}yl(function(e){const t=Gl;if(0===t.size)return;const n=[];for(const o of t)for(const t of Hl(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)&&Hl(e).get(o.name)===o)try{Ec(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Hl(e).get(o.name)===o&&Mc(e,o,"error",n)}},20);const Oc=new WeakMap,Tc=new WeakMap,Rc=new Set,jc=new Map;function Lc(e){return Oc.get(e)??jc}function Dc(e){Rc.add(e),function(e){const t=nl.get(e);void 0!==t&&(rl(t)&&ol.add(e),function(e){return e.eventResetByPath.size>0}(t)&&sl.add(e))}(e)}function Wc(){return Rc}const Bc=new Map;function zc(e){return Tc.get(e)??Bc}function Fc(e){0===e.length&&J(`[wcs/watch-declaration-invalid] ${j} entry name must be a non-empty state path.`),e.startsWith("$")&&J(`[wcs/watch-declaration-invalid] ${j} entry "${e}" must not start with "$" (reserved namespace).${we}`),e.includes("@")&&J(`[wcs/watch-declaration-invalid] ${j} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${we}`),e in Object.prototype&&J(`[wcs/watch-declaration-invalid] ${j} 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&&J(`[wcs/watch-declaration-invalid] ${j} entry "${e}" has an empty path segment.${we}`);return t.wildcardCount>i&&J(`[wcs/watch-declaration-invalid] ${j} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function qc(e,t){const n=t[j];if(void 0===n)return null;"object"==typeof n&&null!==n||J(`[wcs/watch-declaration-invalid] ${j} must be an object mapping state paths to handler functions.${we}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&J(`[wcs/watch-declaration-invalid] ${j} entry "${t}" must be a function.${we}`);const n=Fc(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Oc.set(e,t)}(e,o),s.size>0?s:null}const Vc=new WeakMap;function Gc(e,t,n){let o=Vc.get(e);void 0===o&&(o=new Map,Vc.set(e,o)),o.set(t,n)}const Uc=new Map;function Kc(e,t){Uc.has(e)||Uc.set(e,t)}function Hc(e){return Uc.get(e)}function Jc(e){return Uc.has(e)}function Xc(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ws(t))return!0;return!1}function Qc(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[qt](Nn(t.wildcardParentPathInfos[i],r)),l=zs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=cn(o,i,t.wildcardCount);if(l!==c&&!js(l,c)){if(Ws(c))return"gone";s="replaced"}r=l}return s}function Yc(e,t,n){const o=new Map;for(const s of n){const n=Qc(e,t,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),e=>e.row)}const Zc=/^(?:0|[1-9]\d*)$/;function ed(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function td(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return null;const t=Object.getPrototypeOf(e);if(Array.isArray(e)){return t===Array.prototype&&Reflect.ownKeys(e).every(t=>"length"===t||"string"==typeof t&&Zc.test(t)&&ed(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&ed(e,t))?"object":null}function nd(e,t){const n=td(e);if(null===n)return e;const o=e,s=t.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(e.length):null===Object.getPrototypeOf(e)?Object.create(null):{},t.set(o,r);for(const e of Object.keys(o))r[e]=nd(o[e],t);return r}function od(e){return nd(e,new Map)}function sd(e,t,n){if(Object.is(e,t))return!0;const o=td(t);if(null===o||"object"!=typeof e||null===e)return!1;const s=e,r=t;if("array"===o){if(!Array.isArray(e)||e.length!==t.length)return!1}else if(Array.isArray(e)||Object.keys(s).length!==Object.keys(r).length)return!1;if(td(e)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let t=0;t<e.length;t++)if(!sd(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&sd(s[e],r[e],n))}function rd(e,t){return sd(e,t,new Map)}const id=new WeakMap;function ad(e,t){if("function"!=typeof t)return;const n=id.get(t);void 0===n?id.set(t,new Set([e])):n.add(e)}const ld={"read-source":e=>`${L} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${L} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${L} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${L} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${L} could not write the output "${e}".`},cd={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function dd(e,t,n){null!==At&&At({type:"state:watch-error",phase:t,path:`${L}.${e}`,error:n})}function ud(e,t,n){console.error(`[@wcstack/state] ${ld[n](e)}`,t),dd(e,cd[n],t)}function fd(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function hd(e,t){t.then(void 0,()=>{}),ud(e,new TypeError(`${L} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const pd=new WeakSet;const md=Object.freeze([]);function gd(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function yd(e,t){let n=0;for(;n<e.indexes.length-1&&e.indexes[n]===t.indexes[n];)n++;return e.indexes[n]-t.indexes[n]}function wd(e,t){return t.has(e.stateElement)&&!0===al(e.stateElement)?.entries.has(e.entry)}function bd(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>vd(n,e))||ml(t)}function vd(e,t){return vl().hasQueuedPath(e,t)}function $d(e,t){!function(e,t,n){if(0!==ul)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=fl(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||ml(t)}}(e,t,vd)}function xd(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function Sd(e,t,n){if(!wd(e,n))return bd(e),null;const{stateElement:o,entry:s}=e;if(e.reset)return{group:e,next:s.initial};const r=s.source;if(function(e,t){for(const n of t.pathInfo.cumulativePaths)if(e.getterPaths.has(n))return!0;return!1}(o,r))return function(e,t,n){if(pd.has(e))return;pd.add(e);const o=`[wcs/scan-source-computed] ${L} entry "${t}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),dd(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=Hl(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name],o=0===r.pathInfo.wildcardCount?e.rows:Yc(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(yd)){let n;try{n=xd(t,r,e)}catch(e){ud(s.name,e,"read-source");continue}const o=a(l,n,Hc(e.absAddress),...e.indexes);if(fd(o))return void hd(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){ud(s.name,e,i.failure)}return i.plan}function Pd(e,t){const{group:n}=e;if(!wd(n,t))return void bd(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||ml(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!rd(o,s.initial):!Object.is(o,e.next)){const o=n.reset?od(s.initial):e.next;t[s.name]=o,ad(s.name,o)}})}catch(e){ud(s.name,e,"write")}}function Id(e,t,n){if($d(e,t),0===ol.size)return md;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=al(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=dn(n.listIndex,r.wildcardCount)}for(const s of i)gd(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)gd(o,e,t).reset=!0}if(0===o.size)return md;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];el(n);try{for(const n of s){const o=Sd(n,e,t);null!==o&&r.push(o)}}finally{tl()}return r}function Nd(e){(0!==Lc(e).size||0!==zc(e).size||function(e){const t=nl.get(e);return void 0!==t&&rl(t)}(e))&&(Dc(e),function(e){const t=[];for(const n of Lc(e).values())kd(e,n)&&t.push(n);for(const n of zc(e).values())for(const o of n)kd(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{Gc(e,_d(e,o),n[o.path])}catch(t){Cd(e,o.path,"prime",t)}})}(e))}function _d(e,t){return nn(Qt(e,t.pathInfo),null)}function kd(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Ad={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Cd(e,t,n,o){console.error(`[@wcstack/state] $watch ${Ad[n]} "${t}" threw.`,o),null!==At&&At({type:"state:watch-error",phase:n,path:t,error:o})}function Ed(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Md(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 Od(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=kd(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 Cd(0,n.path,"evaluate",e)}const a=r?function(e,t){return Vc.get(e)?.get(t)}(t,o):Hc(o);r&&Gc(t,o,i),null!==At&&At({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Cd(0,n.path,"handler",e)}}yl(function(e){const t=Wc();try{if(0===t.size)return void $d(e,t);const n=function(){const e=Za;return Za=0,e}();if(n>32){$d(e,null);const t=Array.from(e,e=>e.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:t}),void(null!==At&&At({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){el(n);try{for(const n of e)Pd(n,t)}finally{tl()}}}(Id(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Lc(e).get(s),i=zc(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=dn(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Md);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(Xc(o.absAddress.listIndex)||s?.entry===o.entry&&Ed(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(Yc(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){Cd(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);el(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Lc(e.stateElement).get(e.entry.path)===e.entry,o=!0===zc(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&Od(e)}}finally{tl()}}(e,t,n)}finally{Uc.clear()}},10);const Td="[wcs/scan-declaration-invalid]",Rd=Object.freeze([]);function jd(e){return`${L} entry "${e}"`}function Ld(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Dd(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${r}${r}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${we}`}function Wd(e,t,n){0===n.length&&J(`${Td} ${e} "${t}" must be a non-empty state path.${we}`),n.startsWith("$")&&J(`${Td} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${we}`),n.includes("@")&&J(`${Td} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${we}`),n in Object.prototype&&J(`${Td} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${we}`);const o=Y(n);for(const s of o.segments)0===s.length&&J(`${Td} ${e} ${t} "${n}" has an empty path segment.${we}`);return o.wildcardCount>i&&J(`${Td} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Bd(e,t,n,o){const i=jd(e);0===e.length&&J(`${Td} ${L} entry name must be a non-empty string.${we}`),(e.includes(s)||e.includes(r))&&J(`${Td} ${i} must be a flat property name ("${s}" and "${r}" are not allowed). The output is a property the runtime owns.${we}`),e.startsWith("$")&&J(`${Td} ${i} must not start with "$" (reserved namespace).${we}`),e in Object.prototype&&J(`${Td} ${i} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${we}`),t.has(e)&&J(`${Td} ${i} conflicts with a getter declared on the state.${we}`),n.has(e)&&J(`${Td} ${i} conflicts with a setter declared on the state.${we}`),o.has(e)&&J(`${Td} ${i} conflicts with the ${R} entry of the same name — each output has exactly one owner.${we}`)}function zd(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===id.get(t)?.has(e)}(e,o)&&J(`${Td} ${jd(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${we}`)}function Fd(e,t,n,o,r,i){const a=jd(e),l=void 0!==t.from,c=void 0!==t.on;if(l===c&&J(`${Td} ${a} must declare exactly one of "from" (a state path) or "on" (an event-token name).${we}`),c){const e=t.on;return"string"==typeof e&&0!==e.length||J(`${Td} ${a} "on" must be a non-empty event-token name.${we}`),n.has(e)||J(`${Td} ${a} on "${e}" is not declared in ${O}.${ye(e,n)}${we}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&J(`${Td} ${a} "from" must be a state path string.${we}`);const u=Wd(a,"from",d),f=Ld(u,o)??i?.recursiveGetterOwning(d)??null;null!==f&&J(Dd(a,"from",d,f));const h=Ld(u,r);return null!==h&&J(function(e,t,n){return`${Td} ${e} from "${t}" ${n===t?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${we}`}(a,d,h)),(d===e||d.startsWith(e+s))&&J(`${Td} ${a} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${we}`),{kind:"path",path:d,pathInfo:u}}function qd(e,t,n,o){if(void 0===t)return Rd;const i=jd(e);Array.isArray(t)||J(`${Td} ${i} "resetOn" must be an array of state paths.${we}`);const a=[];for(const e of t){"string"!=typeof e&&J(`${Td} ${i} "resetOn" must contain only state path strings.${we}`);const t=Wd(i,"resetOn",e);t.wildcardCount>0&&J(`${Td} ${i} resetOn "${e}" must not contain "${r}" — a reset returns the whole output to "initial".${we}`);const l=Ld(t,o);null!==l&&J(Dd(i,"resetOn",e,l)),"path"===n.kind&&e===n.path&&J(`${Td} ${i} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${we}`),"path"===n.kind&&e.startsWith(n.path+s)&&J(`${Td} ${i} resetOn "${e}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${we}`),a.push(e)}return a}function Vd(e,t,n=null){const o=e[L];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&J(`${Td} ${L} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${we}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(ec(e)))"function"==typeof n.get?s.add(t):"function"==typeof n.set&&i.add(t),"function"==typeof n.set&&r.add(t),"function"==typeof n.value&&a.set(t,n.value);const l=function(e){const t=e[R];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),c=[];let d=0;for(const[e,u]of Object.entries(o)){Bd(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&J(`${Td} ${jd(e)} must be an object ({ from | on, initial, fold, resetOn? }).${we}`);const o=u;zd(e,a,o);const f=Fd(e,o,t,s,i,n);"initial"in o||J(`${Td} ${jd(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${we}`),"function"!=typeof o.fold&&J(`${Td} ${jd(e)} fold must be a function.${we}`);const h=qd(e,o.resetOn,f,s);c.push({name:e,source:f,fold:o.fold,initial:o.initial,resetOn:h,order:d++})}return function(e){const t=new Set(e.map(e=>e.name)),n=new Map;for(const o of e){for(const e of o.resetOn){const n=Y(e).segments[0];t.has(n)&&J(`${Td} ${jd(o.name)} resetOn "${e}" reads the ${L} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${we}`)}if("path"===o.source.kind){const e=o.source.pathInfo.segments[0];t.has(e)&&n.set(o.name,e)}}for(const e of n.keys()){const o=[e];let s=n.get(e);for(;void 0!==s&&o.length<=t.size;)s===e&&J(`${Td} ${L} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${we}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Gd(e){const t=e.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[e.name];i="threw";const a=function(e){return dl.has(e)}(e),l=a&&!rd(n,e.initial)?od(e.initial):n,c=t(l,o,...s);if(fd(c))return void hd(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,ad(e.name,c)),a&&ml(e)}catch(t){ud(e.name,t,i)}}}function Ud(e,t,n){const o=function(e,t){ll(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&il(n,e.source.path,e);for(const t of e.resetOn)il(o,t,e),"event"===e.source.kind&&il(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return nl.set(e,r),r}(e,t);for(const o of t){const t=n.get(o.name);"event"===o.source.kind&&void 0!==t&&(o.resetOn.some(n=>t.includes(n)&&vl().hasQueuedPath(e,n))&&pl(o))}const s=new Set;for(const t of o.byFromPath.keys())s.add(t),e.setPathInfo(t,"prop","scan");for(const t of o.byResetPath.keys())e.setPathInfo(t,"prop","scan");return s.size>0?s:null}function Kd(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 Hd(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 Jd(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 Xd(e){return e.startsWith("$")}function Qd(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 Yd(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||J(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||J(`${t} entries must be non-empty strings.`),e.startsWith("$")&&J(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&J(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Zd(e){const t=Yd(e,A)??[],n=Yd(e,C)??[],o=ec(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}J(`${A} entry "${e}" is not declared on the state.${ye(e,Qd(o,"value"))}`)}"function"==typeof t.value&&J(`${A} entry "${e}" is a method. Declare it in ${C} instead.`)}for(const e of n){const t=o[e];void 0===t&&J(`${C} entry "${e}" is not declared on the state.${ye(e,Qd(o,"method"))}`),"function"!=typeof t.value&&J(`${C} entry "${e}" is not a method. Declare it in ${A} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}const eu=new Map;class tu{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 nu(e){let t;return eu.get(e)??(eu.set(e,t=new tu(e)),t)}function ou(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:cn(n.listIndex,o,n.pathInfo.wildcardCount)}function su(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=ln(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?cn(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?cn(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}const ru=new WeakMap;class iu{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 Nn(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(pt(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=pt(e,t),a=gt(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a=pt(e,t),l=gt(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 su(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[pt(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)||J(`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[pt(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 pt(this.record,t),!0}catch{return!1}}}function au(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=ru.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},ru.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 iu(e,s,t.listIndex,r,n,o))}function lu(e){const t=e.parentStateElement,n=(t,n)=>{const o=_t(e.component);let s;return t[Ft](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(pt(e,t))):(n,o,...r)=>{const i=pt(e,n),a=_t(e.component)?.listIndex.indexes??[],l=gt(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:pt(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:pt(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 pt(e,n),!0}catch{return!1}}})}function cu(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function du(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 uu(e,t,n,o,s){const i=t.pathInfo.segments[0];if(i===M)return du(Bl(s),t.pathInfo.segments);if(i===z)return du(xc(s),t.pathInfo.segments);if(i===F)return du(Sc(s),t.pathInfo.segments);if(!0===s.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const e=It(s,t.pathInfo.path);if(null!==e)return au(e,t,n,o)}if(!(t.pathInfo.path in e)){if(null===t.parentAddress&&Dr(function(e){return e.rootNode??null}(s),t.pathInfo.path))return;const i=t.parentAddress??J(function(e,t,n){return`[${Qr.binding}] Path "${e}" does not exist on the state tree.${ye(e,Xr(t,"",n))}${we}`}(t.pathInfo.path,e,s.getterPaths)),a=hu(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=pi(s,i.pathInfo.path,l,t.listIndex);if(null!==e)return function(e,t,n,o,s){const r=au(e,Nn(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??J(ni(`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 fu(e,t,n,o,s){const r=nn(Qt(s,t.pathInfo),t.listIndex),i=function(e){return uc.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=uu(e,t,n,o,s);return fc(r,{value:l,dirty:!1,generation:a}),l}function hu(e,t,n,o){su(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo),function(e,t){if(null===kc)return;const n=Qt(e,t.pathInfo);kc.add(nn(n,t.listIndex))}(o.stateElement,t);const s=o.stateElement;return cu(s,t)?fu(e,t,n,o,s):uu(e,t,n,o,s)}function pu(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=Nn(f,r),p=nn(Qt(n.stateElement,f),r),m=Lt(p),g=hu(e,h,t,n),y=Ks(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]??J(`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())Dt(e,Array.isArray(t)?t:[]);return l}function mu(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Fs(hu(e,Nn(a,r),t,n),r);null==l&&J(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??J(`ListIndex not found at index ${c} of ${a.path}`)}return r}function gu(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 yu(e,t,n,o){"object"==typeof e&&null!==e||J(`${B} 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&&J(`${B} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function wu(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&J(`${B} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function bu(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];yu(a,n,o,i);const l=wu(a,t,n,o,i);r.has(l)&&J(`${B} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function vu(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 $u(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const i=hu(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 xu=new WeakMap;function Su(e,t){null===t?xu.delete(e):xu.set(e,t)}function Pu(e,t,n){const s=Y(e.wildcardParentPaths[t]),r=Qt(e.stateElement,s),i=Nn(s,n),a=nn(r,n),l=Lt(a),c=e.stateProxy[qt](i),d=Ks(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)Pu(e,t+1,n)}const Iu=[];function Nu(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:Iu,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Iu,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const _u=[];function ku(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return _u;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??_u}function Au(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[qt](t),a=nn(Qt(e.stateElement,t.pathInfo),t.listIndex),l=Lt(a),c=Ks(t.listIndex,l,r);e.observedListValueByAbsAddress.set(a,Array.isArray(r)?r:[]);const d=Nu(e,o,0,0,c);for(const t of d.fullRows){const o=Nn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=ku(e,i,s);if(null===t)for(const t of d.movedRows){const o=Nn(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=Nn(s,o);e.result.add(t),n.push(t)}}}else{const o=Nn(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=ln(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&J(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=cn(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};Pu(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&J(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=cn(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=Nn(s,t);e.result.add(o),n.push(o)}}}function Cu(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&&J(`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,Au(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)Dt(e,t);return Array.from(u.result)}function Eu(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||Kc(n,o)}function Mu(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?go()??ho(-1):null,c=vl();c.enqueueAbsoluteAddress(t,l),i&&hc(t),Cu(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=nn(Qt(s.stateElement,t.pathInfo),t.listIndex);hc(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Ou(e,t,n,o,s){s&&(e.getterPaths.has(t)?hc(n):fc(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function Tu(e,t,n,o,s,i,a,l){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const a=hu(e,n,s,i),l=t.pathInfo.segments[t.pathInfo.segments.length-1];if(l===r){const e=t.listIndex?.index??J(ni(`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{Mu(t,n,s,i,a,l)}}function Ru(e,t,n,o,i,a,l,c){const d=t.parentAddress??J(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=hu(e,d,i,a)??[];let f=(h=u,xu.get(h)??null);var h;if(null===f){const e=zs(u)??[];f={value:[...u],listIndexes:[...e]},Su(u,f)}try{return Tu(e,t,n,o,i,a,l,c)}finally{const n=f.value.indexOf(o),l=hu(e,d,i,a)??[],c=Array.isArray(l)?zs(l)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:Ms(d.listIndex,-1);c[h]=p;if(new Set(l).size===f.value.length){for(let e=0;e<c.length;e++)c[e].index=e;Su(u,null),function(e,t,n,o,i,a){const l=a.stateElement,c=vl(),d=nn(Qt(l,e.pathInfo),e.listIndex);Et(d)===n&&(qs(t.value,t.listIndexes),Mt(d,t.value),function(e){Js.add(e)}(t.value));c.enqueueRenderOnlyAddress(d);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=Y(e.pathInfo.path+s+r),h=Qt(l,f);for(let e=0;e<o.length;e++){const n=o[e],s=u.get(n);if(s===e)continue;const r=Nn(f,n),d=nn(h,n);if(void 0===s){const n=nn(h,t.listIndexes[e]??null);Jc(n)&&Kc(d,Hc(n)),Mu(r,d,i,a,null,cu(l,r),"full");continue}Cu(l,r,l.staticDependency,l.dynamicDependency,l.listPaths,i,"new",e=>{const t=nn(Qt(l,e.pathInfo),e.listIndex);hc(t),c.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(d,f,l,c,i,a)}}}function ju(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=hu(e,t,o,i),c=function(e,t,n,o){const s=bu(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=bu(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===zs(o)&&Ks(c,null,o);const d=Ks(c,o,n.list),u=Lu(e,t,n.list,i,a,l),f=Y(l+s+r);for(const t of n.matched){const n=vu(t.oldRow,t.newRow);if(0===n.length)continue;const o=d.newIndexes[t.position];for(const r of n)void 0!==o?ju(e,Nn(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 Lu(e,t,n,o,i,null)}function Lu(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=Wr.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&&J(`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&&J(`[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=!!bo&&(bo=!1,!0);if(!(d in e)&&null!==t.parentAddress&&!c.elementPaths.has(d)){const s=hu(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=cu(c,t),g=nn(Qt(c,t.pathInfo),t.listIndex);null!==At&&At({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:p}),Eu(c,d,g,h,p);let y=!1;try{if(void 0===f&&J(ni(`path "${d}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),!0===c.hasMounts&&e!==r&&!(f in s)){const o=pi(c,t.parentAddress.pathInfo.path,e,t.listIndex);if(null!==o)return y=!0,function(e,t,n,o,s,r){const i=au(e,Nn(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{Mu(t,g,i,a,l,m),y?hc(g):Ou(c,d,g,n,m),gu(c,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=hu(e,t,i,a);if($u(e,t,i,a)&&Object.is(o,n))return!0;f=o,h=!0}const p=c.elementPaths.has(t.pathInfo.path),m=cu(c,t),g=nn(Qt(c,t.pathInfo),t.listIndex);null!==At&&At({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),Eu(c,d,g,f,h);try{return p?Ru(e,t,g,n,i,a,l,m):Tu(e,t,g,n,i,a,l,m)}finally{p||Ou(c,d,g,n,m),gu(c,t.pathInfo,{value:n})}}function Du(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&&J(Zr("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=Nn(i,mu(e,n,o,i,s));if(!(void 0!==r))return hu(e,a,n,o);ju(e,a,r,n,o)}}function Wu(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 Bu(e,t,n){const o=e.recursionRegistry,s=nc(o.spec,n);null===s&&J(ei(n,o.spec.recursiveAnchor));const r=Wu(t,o);return null===r&&J(`[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 zu(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(Nn(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=Nn(o,s),c=nn(Qt(n.stateElement,o),s),u=hu(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)&&J(`[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)&&J(`[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=Ks(s,Lt(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(Nn(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)Dt(e,t);return a}function Fu(e,t,n,o){const s=Du(e,0,n,o);return(t,r)=>{if(!0===o.stateElement.hasRecursion&&tc(t)){if(void 0!==r)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=nc(r.spec,o);null===i&&J(ei(o,r.spec.recursiveAnchor)),Array.isArray(s)||J(`[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&&J(`[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=zu(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(hu(e,a[o],t,n));return l}(e,n,o,t,r);t=Bu(o.stateElement,o,t)}const i=Y(t);if(void 0===r||Array.isArray(r)||J(`$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&&J(Zr("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=ou(o,i.wildcardPaths[e]);if(t){r=dn(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&&J(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=pu(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 qu(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return ou(o,s.wildcardPaths.at(-1)??J(`lastWildcardPath is null: ${t.pathInfo.path}`))??J(`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]??J(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Fs(hu(e,Nn(i,s),n,o),s)??J(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??J(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??J(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":J(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Vu(e,t,n,o,s,r,i){const a=n.stateElement.recursionRegistry,l=nc(a.spec,o);null===l&&J(ei(o,a.spec.recursiveAnchor));const c=oc(l);Array.isArray(s)||J(ti(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&J(`[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&&J(ti(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&J(ti(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){ac(e,n)&&J(`[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&&J(`[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=zu(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(ju(e,u[o],r,t,n),f++);return f}function Gu(e,t,n,o){const r=Reflect.get(e,N);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=dn(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,zr.get(l)??Fr):[];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=dn(n.listIndex,l);(a[s]??=[]).push(e)}}if(i.size>0)try{e.callback.call(Br(e.mountPath,n),Array.from(i),a)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" $updatedCallback threw.`,t)}}return i}const Uu=/^\$\d+$/,Ku=`${z}${s}`,Hu=`${F}${s}`,Ju=new WeakMap;function Xu(e,t,n,o){const r=S[t];if(void 0===r&&"string"==typeof t&&36===t.charCodeAt(0)&&Uu.test(t)&&J(`[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&&J(`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&&J(`ListIndex not found: ${t.toString()}`);let a=r;const l=e.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const e=It(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=cn(i,a,l.wildcardCount);return c?.index??J(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Fu(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&&tc(t))return Vu(e,n,o,t,s,r,i);const a=Y(t);Array.isArray(s)||J(ti(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&J(Zr("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&J(ti(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&J(ti(t,"requires an array as the value when { spread: true } is set."));const d=pu(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&J(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=mu(e,n,o,a,d[t]);u.push(Nn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;i=c?r(hu(e,s,n,o),...d[t]):l?r[t]:r,void 0!==i&&(ju(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=nu(t),i=qu(e,r,n,o),a=Nn(r.pathInfo,i),l=nn(Qt(s,a.pathInfo),a.listIndex),c=vl();c.enqueueAbsoluteAddress(l),Cu(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=nn(Qt(s,e.pathInfo),e.listIndex);hc(t),c.enqueueAbsoluteAddress(t)}),gu(s,a.pathInfo)}}(e,0,n,o)(t);case"$resolve":return(t,s,r)=>Du(e,0,n,o)(t,s,r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{tc(e)&&J(`[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&&J(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??J("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 Bl(o.stateElement);case z:return xc(o.stateElement);case F:return Sc(o.stateElement)}if(!t.startsWith(Ku)&&!t.startsWith(Hu))return}const s=nu(!0===o.stateElement?.hasRecursion&&tc(t)?Bu(o.stateElement,o,t):t),r=qu(e,s,n,o),i=Nn(s.pathInfo,r);return hu(e,i,n,o)}if("symbol"==typeof t){const s=function(e){let t=Ju.get(e);return void 0===t&&(t=new Map,Ju.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Ft:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&J("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 qt:i=t=>hu(e,t,n,o);break;case Vt:i=t=>$u(e,t,n,o);break;case Gt:i=(t,s)=>ju(e,t,s,n,o);break;case Ut:i=()=>async function(e,t,n){const o=Reflect.get(e,P);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Kt:i=()=>function(e,t,n){const o=Reflect.get(e,I);"function"==typeof o&&o.call(n)}(e,0,n);break;case Ht:i=t=>Gu(e,t,n,o);break;case Jt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,_);"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 Qu{_stateElement;_addressStack=Array(a).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=Ka(e);null===n&&J("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&&J("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()&&J(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),J(`[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&&J(`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 Xu(e,t,n,this)}set(e,t,n,o){return"readonly"===this._mutability&&J("This state is readonly."),function(e,t,n,o,s){if("string"==typeof t){const r=nu(t),i=qu(e,r,o,s);return ju(e,Nn(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 Yu(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 Zu=new WeakMap;class ef{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=Zu.get(e);return n?n.get(t)??null:null}(e,t)??J("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 tf=e=>()=>e;function nf(e,t,n,o){!function(e,t,n){let o=Zu.get(e);o||(o=new Map,Zu.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(Yu(o));const s=function(e,t){const n=new ef(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:tf(s),enumerable:!0,configurable:!0}),ms(t,n),of(t,n)}function of(e,t){if(k in e){const n=e[k];"function"==typeof n?n.call(e,t).catch(e=>{J(`Error in ${k}: ${e instanceof Error?e.message:String(e)}`)}):J(`${k} is not a function.`)}}const sf=new Set;function rf(e,t){sf.has(e)||(sf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function af(e){const t=e.rootEntry,n=_t(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Ft](n,()=>{o=e[t.outerPathInfo.path]})}),o}function lf(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Br(e.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function cf(e,t,n){const o=n[j];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(Br(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=Tc.get(e);void 0===n&&(n=new Map,Tc.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),Nd(e))}const r=n[B];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[N];"function"==typeof i&&(!function(e,t){let n=zr.get(e);void 0===n&&(n=[],zr.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 df(e,t,n){!function(e,t,n){const o=n[j];if(void 0!==o){"object"==typeof o&&null!==o||J(`${j} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(o))"function"!=typeof t&&J(`${j} entry "${e}" must be a function.`),Fc(e)}const r=n[B];if(void 0!==r){"object"==typeof r&&null!==r||J(`${B} 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)&&J(`${B} entry "${n}" must map a list path to a field name or a key function.`),e.listKeys?.has(t+s+n)&&J(`${B} entry "${t+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&J(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&J(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[D]&&J(`Volume "${t}" declares ${D}, 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(ec(n)))-1!==e.indexOf(W)&&J(`Volume "${t}" declares "${e}", which uses "${W}". 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;J(`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;J(`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=Wr.get(e);void 0===n&&(n=new Set,Wr.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(Br(t,this))}),"function"==typeof a&&(l.set=function(e){a.call(Br(t,this),e)}),e.defineTreeAccessor(r,l)}cf(e,t,n);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(Br(t,e))}catch(e){return void console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)}n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n}}function uf(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=df(e,t.mountPath,t.volumeState)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}function ff(e,t,n,o,s,r){const i={mountPath:n,volumeState:o,onGrafted:s,acquireSlot:r};null===t?function(e,t){if(Vr.has(e))return void Gr(t);let n=qr.get(e);void 0===n&&(n=[],qr.set(e,n)),n.push(t)}(e,i):uf(t,i)}Ur=uf;const hf=new Set(["for","if","elseif","else"]);function pf(e,n,o){const s=new Map;for(const e of o){const t=Y(e);if(null===t.lastWildcardPath)continue;const n=s.get(t.lastWildcardPath);void 0===n?s.set(t.lastWildcardPath,[t]):n.push(t)}const r=[],i=new Set,a=t=>{const n=nn(Qt(e,t.pathInfo),t.listIndex);if(i.has(n))return;i.add(n);const o=xn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(Nn(n,t.listIndex))}};Wt();try{if(e.createState("readonly",t=>{for(const o of n){const n=Nn(Y(o),null);a(n);try{Cu(e,n,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",a)}catch{}}}),0===r.length)return;const o=function(e){const t=[],n=[];for(const o of e)hf.has(o.bindingType)?t.push(o):n.push(o);return t.sort((e,t)=>0!==(e.replaceNode.compareDocumentPosition(t.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),t.concat(n)}(r),s=()=>{ga(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=xi("state",s);void 0!==i&&i.catch(wl)}finally{Bt()}}class mf extends $a{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Ha(e)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!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 jl}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_volumeGraftInfo=null;_volumeInitializing=!1;_volumeMountPath=null;_volumeSlotRootNode=null;_volumeDetachedFrom=null;_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&&J(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){const n=this.__state,o=function(e){const t=e[D];if(void 0===t)return null;"object"==typeof t&&null!==t||J(`[wcs/recursion-declaration-invalid] ${D} 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&&J(`[wcs/recursion-declaration-invalid] ${D} must declare exactly one anchor; it is empty.`),n.length>1&&J(`[wcs/recursion-declaration-invalid] ${D} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,i]=n[0];Zl("anchor",o),"string"!=typeof i&&J(`[wcs/recursion-declaration-invalid] ${D} entry "${o}" must map to the repeating sub-path as a string (for example "children${s}${r}").`),Zl("repeating sub-path",i);const a=o.slice(0,o.lastIndexOf(s)),l=i.slice(0,i.lastIndexOf(s)),c=a+s+W;return Object.freeze({anchor:o,repeat:i,recursiveAnchor:c,anchorList:a,repeatList:l})}(e),i=null===o?null:new wc(o,e),a=function(e){const t=new Set,n=e[E];if(void 0===n)return t;Array.isArray(n)||J(`${E} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||J(`${E} entries must be non-empty strings.`),e===M&&J(`${E} entry "${e}" conflicts with the reserved namespace name "${M}".`),t.has(e)&&J(`${E} entry "${e}" is duplicated.`),t.add(e);return t}(e),l=function(e){const t=new Set,n=e[O];if(void 0===n)return t;Array.isArray(n)||J(`${O} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||J(`${O} entries must be non-empty strings.`),t.has(e)&&J(`${O} entry "${e}" is duplicated.`),t.add(e);return t}(e),c=function(e){const t=e[B];if(void 0===t)return null;"object"==typeof t&&null!==t||J(`${B} 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&&J(`${B} entry path must be a non-empty string.`);const t=e.split(s);t.some(e=>0===e.length)&&J(`${B} entry "${e}" must not contain empty path segments.`),t[t.length-1]===r&&J(`${B} entry "${e}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),-1!==e.indexOf(W)&&J(`[wcs/recursion-unsupported] ${B} entry "${e}" uses "${W}", which ${B} 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&&J(`${B} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&J(`${B} entry "${e}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&J(`${B} entry "${e}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&J(`${B} 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),d=Vd(e,l,i);if(null!==this._recursionRegistry)for(const e of this._recursionRegistry.forgetGenerated(this,n))this._generatedPaths.add(e);var u;this._recursionRegistry=i,this._commandTokenNames=a,this._eventTokenNames=l,this._stateGeneration++,this.__state=e,void 0!==n&&(u=this,oi.delete(u),ri.delete(u)),this._hasUpdatedCallback=N in e,this._hasErrorCallback=_ in e,function(e){Bn.delete(e)}(this),null!==d&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=od(n.initial);e[n.name]=t,ad(n.name,t)}}(e,d),function(e,t){for(const n of t)"event"===n.source.kind&&zn(e,n.source.tokenName).subscribe(Gd(n))}(this,d)),function(e,t,n){const o=t[T];if(void 0!==o){"object"==typeof o&&null!==o||J(`${T} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||J(`${T} entry "${t}" is not declared in $eventTokens.${ye(t,n)}`),"function"!=typeof s&&J(`${T} entry "${t}" must be a function.`),zn(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const f=function(e){const t=new Set,n=new Set,o=ec(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 f.getterPaths)this._getterPaths.add(e);for(const e of f.setterPaths)this._setterPaths.add(e);Pc(this),function(e){Jl(e),Ul(e),Kl.delete(e)}(this),Yl(this,e),this._listKeys=c,null!==o&&this._listPaths.add(o.anchorList),this._rebuildPathInfo();const h=function(e){const t=new Map,n=al(e);if(void 0!==n)for(const e of n.entries)ml(e)&&t.set(e.name,e.resetOn);return ll(e),t}(this);this._scanPaths=null===d?null:Ud(this,d,h),function(e){Rc.delete(e),cl(e),Oc.delete(e)}(this),function(e){Vc.delete(e)}(this),this._watchPaths=qc(this,e),this._initialized&&null!==this._rootNode&&!t()&&(Nd(this),Cc(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=_a.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){J("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 Tl(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||J(`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 Rl(e);J(`Unsupported src file type: ${e}`)}}catch(e){J(`Failed to initialize state: ${e}`)}}async _initializeVolume(){const e=this._rootNode,t=this.getAttribute("mount");try{!function(e){0===e.length&&J('"mount" requires a non-empty tree path.');const t=Y(e);for(const n of t.segments)0===n.length&&J(`"mount" path "${e}" has an empty segment.`),n===r&&J(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&J(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(t),this.hasAttribute("bind-component")&&J('"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).`),Lr(e,t,this),this._volumeMountPath=t,this._volumeSlotRootNode=e}catch(e){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),e}this._volumeInitializing=!0,null===Ka(e)&&function(e,t){const n=()=>{if(null!==Ka(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,null===e&&this._releaseVolumeSlot(),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)}if(null===this._rootNode)return void n(null);const i=this._rootNode;this._acquireVolumeSlot(i)?ff(i,Ka(i),t,s,n,()=>this._acquireVolumeSlot(i)):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}return await this._loadingPromise,null!==this._rootNode&&(Qa(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),J(e)}_failInitializeLoudly(e){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),null!==this._rootNode&&null===Ka(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),Ga.set(e,n)}(this._rootNode,e),function(e){Vr.add(e);const t=qr.get(e);if(void 0!==t){qr.delete(e);for(const e of t)Gr(e)}}(this._rootNode)),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?te(i):null;null!==i&&null!==a||J(`"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&&J(`"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=gs.get(e);n||(n=new Set,gs.set(e,n)),n.add(t)}(i,c);const d=oe(i);null===d&&J(`CustomElementRegistry is unavailable for <${a}>.`),await d.whenDefined(a.toLowerCase()),i.hasAttribute(o.bindAttributeName)&&await K(i),c in i||J(`Component does not have property "${c}" for state binding.`);let u=i[c];"object"==typeof u&&null!==u||J(`Component property "${c}" is not an object for state binding.`);const f=function(e,t){const n=Fi.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=me(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||(me(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=(me(i)??[]).filter(e=>e.propSegments[0]===c);if(o.length>0){const l=Ka(i.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${a}>.`);let d=(n=i,s=c,wt.get(n)?.get(s)??null);const f=null!==d;if(null===d&&(function(e,t,n){const o=Vi.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;Vi.get(e).delete(t)}}(i,c,u),d=rt(i,c,o,l,u,(e=i,t=c,qi.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){rf(`${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=af(e),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=e.rootEntry.outerPathInfo.path;rf(`${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{gi(d,r instanceof ShadowRoot?r:i)}catch(e){throw this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),e}if(!f){const e=lu(d);Object.defineProperty(i,c,{get:()=>e,enumerable:!0,configurable:!0}),ms(i,c)}return of(i,c),function(e){const t=nt.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(W)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;ot.has(n)||(ot.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 st(d,"$connectedCallback")}}nf(this,this._boundComponent,this._boundComponentStateProp,u)}var e,t,n,s}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{P in e&&await e[Ut]()})}async _initializeDCC(e,t){let n;try{if(this.hasAttribute("src")){const e=this.getAttribute("src");e.endsWith(".js")?n=await Rl(e):J(`DCC: Unsupported src type: ${e}`)}else{const t=this.querySelector('script[type="module"]');t?n=await Tl(t,e.tagName.toLowerCase()):J(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}}catch(e){J(`DCC: Failed to load state: ${e}`)}!function(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||J(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=oe(e);null!==r&&"function"==typeof r.define||J(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&J(`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}=Zd(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(q))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const e=oe(this._shadow);return null!==e&&se(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=ec(n);for(const[e,t]of Object.entries(g)){if(Xd(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Jd(e,o)}else n.get=Kd(e),n.set=Hd(e);Object.defineProperty(m.prototype,e,n)}for(const e of u)Object.defineProperty(m.prototype,e,{configurable:!0,enumerable:!0,get:Kd(e),set:Hd(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=>{I in e&&e[Kt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Ka(this._rootNode)===this._volumeGraftInfo.rootStateElement&&lf(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const e=this._mountRecord,t=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&yi(e,t)}),st(e,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||Ka(this._rootNode)===this||Qa(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(q)){try{this.hasAttribute("bind-component")&&J(`"bind-component" cannot be used inside a [${q}] host. DCC state comes from the template, not from a component property.`),await this._initializeDCC(e.host,e)}catch(e){this._failInitializeLoudly(e)}return}if(this.hasAttribute("mount")){if(this._volumeInitializing){if(this._volumeDetachedFrom===this._rootNode)try{Lr(this._rootNode,this._volumeMountPath,this),this._volumeSlotRootNode=this._rootNode}catch{}return void(this._volumeDetachedFrom=null)}return void await this._initializeVolume()}try{await this._initializeBindWebComponent()}catch(e){this._failInitializeLoudly(e)}if(null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();let t=!1;try{t=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!t)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const e=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(e)}if(this.hasAttribute("enable-ssr")&&!t()||e!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await Ha(this.rootNode);const e=_a.extractStateData(this),t=document.createElement(o.tagNames.ssr);t.setAttribute("version",va),_a.buildContent(t,e),this.parentNode?.insertBefore(t,this)}catch(e){throw this._rejectConnectedCallback?.(e),e}t()||null===this._rootNode||e!==this._connectGeneration||Nd(this),t()||null===this._rootNode||e!==this._connectGeneration||this._streamsStartedGeneration===e||Cc(this),this._resolveConnectedCallback?.()}_releaseVolumeSlot(){null!==this._volumeSlotRootNode&&(!function(e,t,n){const o=jr.get(e);o?.get(t)===n&&o.set(t,null)}(this._volumeSlotRootNode,this._volumeMountPath,this),this._volumeSlotRootNode=null)}_acquireVolumeSlot(e){if(this._volumeSlotRootNode===e)return!0;const t=this._volumeMountPath;try{Lr(e,t,this)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> will not graft: another volume already holds the "${t}" slot on this root. Keep one volume per mount path.`),!1}return this._volumeSlotRootNode=e,!0}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&lf(this._volumeGraftInfo,"$disconnectedCallback"),this._initialized||(this._volumeDetachedFrom=this._volumeSlotRootNode,this._releaseVolumeSlot()),void(this._rootNode=null);if(null!==this._mountRecord)return st(this._mountRecord,"$disconnectedCallback"),mi(this._mountRecord),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&(t=this._rootNode,Vr.delete(t)),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Qa(this.rootNode,null),e=this,Wl.delete(e),Jl(this),Pc(this),function(e){Rc.delete(e),cl(e)}(this),this._rootNode=null}}var e,t}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 scanPaths(){return this._scanPaths}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)&&J(`$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 Jr(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 stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&J("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("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}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),si(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)}}}_rebuildPathInfo(){for(const[e,t]of Array.from(this._pathRegistrations))t.bound&&!this._generatedPaths.has(e)&&this.setPathInfo(e,t.bindingType)}_createState(e,t,n){try{const o=function(e,t,n){const o=new Qu(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){if(!this._initialized)return this._initializeFailed&&J(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);this._volumeInitializing&&J(`Cannot replace the state of <${o.tagNames.state} mount="${this.getAttribute("mount")}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${this.getAttribute("mount")}" on the root state instead.`),(this._hasGraftedVolumes||this._hasMounts)&&J("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.");const t=this.__state;this._state=e;const n=function(e){const t=new Set;for(const n of e)if(void 0!==n)for(const[e,o]of Object.entries(ec(n)))e.startsWith("$")||e.includes(r)||"function"==typeof o.value||t.add(e);return t}([t,e]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(e){pf(this,e,this._pathRegistrations.keys())}}function gf(e=customElements){e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,_a),e.get(o.tagNames.state)||e.define(o.tagNames.state,mf)}function yf(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=yf(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)),gf(o),function(){const e=globalThis;void 0===e[Ta]&&(e[Ta]=qa)}(),function(){const t=globalThis;void 0===t[e]&&(t[e]=El)}(),Cl()}();
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),P="$connectedCallback",N="$disconnectedCallback",I="$updatedCallback",_="$errorCallback",k="$stateReadyCallback",A="$bindables",C="$commands",E="$commandTokens",M="$command",O="$eventTokens",T="$on",R="$streams",j="$watch",L="$scan",D="$recursion",W="**",B="$listKeys",z="$streamStatus",F="$streamError",q="data-wc-definition",V=new WeakMap,G=new WeakSet;let U=0;async function K(e){const t=function(e){let t,n=V.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++U,promise:o,resolve:t},V.set(e,n),G.has(e)&&n.resolve(),n}(e);await t.promise}function H(e){const t=V.get(e);void 0===t?G.add(e):t.resolve()}function J(e){throw new Error(`[@wcstack/state] ${e}`)}const X=new Map;let Q=0;function Y(e){let t=X.get(e);return void 0!==t||(-1!==e.indexOf(W)&&J(`[wcs/recursion-unsupported] "${e}" uses "${W}", 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 Z(e)),X.set(e,t)),t}class Z{id=++Q;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(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 ee=new WeakMap;function te(e){const t=ee.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{ee.set(e,n)}}function ne(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function oe(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return ne(t);if(void 0!==n)return ne(n)}return ne(globalThis.customElements)}function se(e,t){e.upgrade?.(t)}function re(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=ce(s.properties,ie);if(null===r)return null;const i=void 0===s.inputs?new Map:ce(s.inputs,ae);if(null===i)return null;const a=void 0===s.commands?new Map:ce(s.commands,le);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function ie(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 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.attribute||"string"==typeof t.attribute)}function le(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 ce(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 de(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:Y(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ue(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function fe(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&&J("Spread binding requires an element node.");const t=e,o=te(t);null===o&&J(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=oe(t);null===a&&J(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||J(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}se(a,t);const l=re(t);null===l&&J(`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=de(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=de(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=ue(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=ue(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 he(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 pe=new WeakMap;function me(e){return pe.get(e)||null}function ge(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 ye(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ge(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const we=" Validate statically: npx @wcstack/lint <file>.",be=new Set(["if","elseif","else","for"]);function ve(e){J(`filter ${e} requires at least one option`)}function $e(e){J(`filter ${e} requires a number as option`)}function xe(e){J(`filter ${e} requires a number value`)}function Se(e){J(`filter ${e} requires a date value`)}const Pe=new Set(["not","abs","uc","lc","cap","trim","rev","int","float","date","time","datetime","falsy","truthy","boolean","number","string","null"]),Ne=new Set(["clamp","slice","substr","pad","truncate"]);function Ie(e){return Pe.has(e)?0:Ne.has(e)?2:1}const _e=new Set(["for","if","elseif","else","..."]),ke=/(?:^|\|)\s*(eq|ne|defaults)\s*\(\s*(true|false|null)\s*\)/g;function Ae(e,t,n){(function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];null!==t?o===t&&(t=null):"'"!==o&&'"'!==o||(t=o)}return null!==t})(e)&&n.push(`"${e}": 3.0 rejects the unterminated quote.`);for(const[,t,o]of e.matchAll(ke))n.push(`"${t}(${o})": 3.0 reads an unquoted ${o} as a ${"null"===o?"null":"boolean"}, not the text. Write ${t}('${o}') to keep the text.`);null!==t&&n.push(...Ce([t]))}function Ce(e){const t=[];for(const n of e)for(const e of[...n.inFilters,...n.outFilters]){const n=Ie(e.filterName);e.args.length>n&&t.push(`"${e.filterName}" takes at most ${n} argument(s); 3.0 rejects more.`)}return t}function Ee(e,t=null){const n=[],o=e.indexOf(":");if(-1===o)return n;const s=e.slice(0,o).trim(),r=s.split("#"),i=r[0].split("|")[0].trim();return r.length>2&&n.push(`"${s}": 3.0 rejects a second "#". Write "${r[0].trim()}#${r.slice(1).map(e=>e.trim()).join(",")}".`),"else"===i&&e.slice(o+1).trim().length>0&&n.push(`"${e}": 3.0 rejects a value after "else:".`),_e.has(i)&&i!==s&&n.push(`"${s}": 3.0 rejects modifiers and filters on "${i}". Write "${i}:".`),"radio"!==i&&"checkbox"!==i||i===s||n.push(`"${s}": 3.0 keeps this a ${i} binding that honours the modifiers (2.x binds a property named "${i}").`),Ae(e.slice(o+1).trim(),t,n),n}const Me=new Set,Oe=new Set;function Te(e){Me.has(e)||(Me.add(e),console.warn(`[@wcstack/state] [wcs/v3-migration] ${e} See "Preparing for 3.0" in the @wcstack/state README.`))}const Re='A write through a readonly state ($resolve with a value, $setAll): 3.0 throws. Write from createState("writable", …).';function je(e){e.forEach(Te)}function Le(e,t){const n="{{"+e;Oe.has(n)||(Oe.add(n),je(function(e,t=null){const n=[];return Ae(e,t,n),n}(e,t)))}function De(e){return!(!e||isNaN(Number(e)))}function We(e,t){0n===t&&Te(`"${e}" got 0n: 3.0 treats it as falsy.`)}const Be={eq:e=>{const t=e?.[0]??ve("eq");return e=>"number"==typeof e?(De(t)||$e("eq"),e===Number(t)):e===t},ne:e=>{const t=e?.[0]??ve("ne");return e=>"number"==typeof e?(De(t)||$e("ne"),e!==Number(t)):e!==t},not:e=>e=>("boolean"!=typeof e&&J(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??ve("lt");return De(t)||$e("lt"),e=>("number"!=typeof e&&xe("lt"),e<Number(t))},le:e=>{const t=e?.[0]??ve("le");return De(t)||$e("le"),e=>("number"!=typeof e&&xe("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??ve("gt");return De(t)||$e("gt"),e=>("number"!=typeof e&&xe("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??ve("ge");return De(t)||$e("ge"),e=>("number"!=typeof e&&xe("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??ve("inc");return De(t)||$e("inc"),e=>("number"!=typeof e&&xe("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??ve("dec");return De(t)||$e("dec"),e=>("number"!=typeof e&&xe("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??ve("mul");return De(t)||$e("mul"),e=>("number"!=typeof e&&xe("mul"),e*Number(t))},div:e=>{const t=e?.[0]??ve("div");return De(t)||$e("div"),e=>("number"!=typeof e&&xe("div"),e/Number(t))},mod:e=>{const t=e?.[0]??ve("mod");return De(t)||$e("mod"),e=>("number"!=typeof e&&xe("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&xe("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??ve("clamp");De(t)||$e("clamp");const n=e?.[1]??ve("clamp");De(n)||$e("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&xe("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return De(t)||$e("fix"),e=>("number"!=typeof e&&xe("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&xe("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]??ve("slice");De(n)||$e("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(De(o)||$e("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??ve("substr");De(t)||$e("substr");const n=e?.[1]??ve("substr");return De(n)||$e("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??ve("pad");De(t)||$e("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??ve("rep");return De(t)||$e("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??ve("truncate");De(t)||$e("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)||J(`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 De(t)||$e("round"),e=>{"number"!=typeof e&&xe("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return De(t)||$e("floor"),e=>{"number"!=typeof e&&xe("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return De(t)||$e("ceil"),e=>{"number"!=typeof e&&xe("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return De(t)||$e("percent"),e=>("number"!=typeof e&&xe("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??ve("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Se("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Se("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Se("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Se("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||Se("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=>(We("falsy",e),!1===e||null==e||0===e||""===e||Number.isNaN(e)),truthy:e=>e=>(We("truthy",e),!1!==e&&null!=e&&0!==e&&""!==e&&!Number.isNaN(e)),defaults:e=>{const t=e?.[0]??ve("defaults");return e=>(We("defaults",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},ze=Be,Fe={input:Be,output:ze},qe=(e,t)=>n=>{const o=n[e];return o||J(`[wcs/filter-unknown] filter not found: ${e}.${ye(e,Object.keys(n))}${we}`),o(t)};function Ve(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 Ge=new Map;function Ue(e,t){const n=Fe[t];return e.map(e=>{const o=e.indexOf("("),s=e.lastIndexOf(")");if(-1!==o&&-1===s&&J(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==s&&-1===o&&J(`Invalid filter format: missing opening parenthesis in "${e}"`),-1===o){const o=e.trim(),s=`${o}():${t}`;let r=Ge.get(s);return void 0===r&&(r=qe(o,[])(n),Ge.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(Ve(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=Ve(n,r,i);return(l||s)&&t.push(l),t}(r),l=`${i}(${a.join(",")}):${t}`;let c=Ge.get(l);return void 0===c&&(c=qe(i,a)(n),Ge.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const Ke=e=>e.trim(),He=new Map;const Je=new Map;function Xe(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(),Je.has(s)?r=Je.get(s):(o=s.split(l).map(Ke),r=Ue(o,"output"),Je.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&J(`"${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 Qe(e){const[...t]=e.split(";").map(Ke).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&J(`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=Xe(o);return t.outFilters.length>0&&J(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&J(`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:[],...Xe(o),bindingType:n}}{const e=Xe(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(),He.has(r)?i=He.get(r):(o=r.split(l).map(Ke),i=Ue(o,"input"),He.set(r,i))):n=e.trim();const[a,c]=n.split("#").map(Ke),d=a.split(s).map(Ke);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map(Ke):[],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=>be.has(e.bindingType))&&J(`[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">).${we}`)}return n}const Ye=new WeakMap,Ze=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),et=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function tt(e){const t=Ye.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=et.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Ze.has(r)?(Ye.set(e,s[2]),s[2]):null}function nt(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Xe(e),bindingType:"text"}}const ot=new Map;function st(e,t,n){if(null===n)ot.delete(e);else{ot.set(e,n);const o=rc(t);null===o&&J("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 rt(e){return ot.get(e)||null}function it(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e.getAttribute(o.bindAttributeName)||"",n=Qe(t);return function(e,t){if(!Oe.has(e)){Oe.add(e);for(const t of e.split(";"))je(Ee(t.trim()));je(Ce(t))}}(t,n),n}if(e.nodeType===Node.COMMENT_NODE){const t=tt(e);null===t&&J("Comment node binding text not found.");const n=rt(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=nt(t),Le(t,o),s=null):s=t,[{...o,uuid:s}]}return[]}function at(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function lt(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!at(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function ct(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 dt(e){const t=[],n=lt(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!==tt(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&ct(e,n)||t.push(e)}return t}const ut=new WeakSet;function ft(e,t,n,o){const s=fe(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?te(e):null;return null===n&&J("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}ut.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){pe.set(e,t)}(e,r),H(e),{bindings:r,deferred:null}}function ht(e,t){const n=dt(e),o=[],s=[];for(const e of n){if(ut.has(e))continue;const n=ft(e,it(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function pt(e){ut.add(e)}function mt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){ut.delete(e)}(t);return ft(t,n,{allowDeferred:!1},o).bindings}let gt=0;const yt=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],wt=new Set;function bt(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 vt(e,t,n,o,r,i=new Set){0===n.length&&J(`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)&&J("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(u)};a.push(o),0===t.length&&(c=o)}a.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++gt,f=`#m${d}`,{getterKeys:h,setterKeys:p}=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),m={};for(const e of Object.keys(r))e.startsWith("$")||h.has(e)||p.has(e)||"function"!=typeof r[e]&&(i.has(e)||(m[e]=r[e]));return{id:d,marker:f,component:e,stateProp:t,parentStateElement:o,entries:a,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?f:c.outerPathInfo.path+s+f,stateObject:r,getterKeys:h,setterKeys:p,injectedKeys:i,privateSnapshot:m,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function $t(e){const t=e.indexOf(s);return-1===t?e:e.slice(0,t)}function xt(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(xt(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 Pt(e,t){return e.markerBasePath+s+t}function Nt(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 It(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 _t(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}.${$t(t)}: path") or declare the key on the component state.`}const kt=/^\$(\d+)$/;function At(e,t){const n=Ct(e,t),o=t[0];if("$"!==o&&"#"!==o&&!n.includes(e.marker)){const n=t.split(s),o=e.entries.find(e=>e.innerSegments.every((e,t)=>n[t]===e));if(void 0!==o&&!0===o.readonly){const n=0===o.innerSegments.length?"":s+o.innerSegments.join(s);Te(`<${e.component.tagName.toLowerCase()}> writes "${t}" through "${e.stateProp}${n}#${u}: ${o.outerPathInfo.path}": 3.0 throws. Write it on the host, or drop #${u}.`)}}return n}function Ct(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 Nt(e,e.markerBasePath,t,t),Pt(e,t);if(It(e,n[0]))return Nt(e,e.markerBasePath,t,t),Pt(e,t);const i=n.slice(0,o+1),a=n.slice(o+1),l=St(e,i);null===l&&J(_t(e,t)),0===a.length&&J(`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 Nt(e,c,a.join(s),t),c+s+a.join(s)}(e,t);const o=$t(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return Pt(e,t);if(It(e,o))return Pt(e,t);const i=St(e,t.split(s));if(null!==i)return i;J(_t(e,t))}function Et(e,t,n){let o;const i=kt.exec(t.statePathName);if(null!==i){const s=function(e,t){return void 0===t?e.delta:Y(Ct(e,t)).wildcardCount-Y(t).wildcardCount}(e,n);o=0===s?t.statePathName:`$${Number(i[1])+s}`}else if(o=Ct(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&&J(`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 Ot=new WeakMap,Tt=new WeakMap;const Rt=new WeakMap;const jt=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)}),Lt=new WeakMap;function Dt(e){return Lt.get(e)??null}function Wt(e){return Ot.get(e)??null}function Bt(e){const t=Rt.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}function zt(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Rt.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 Ft=new WeakMap;function qt(e){let t=e;for(;t;){const e=Ft.get(t);if(e)return e;let n=t.parentNode;null===n&&t instanceof ShadowRoot&&null!==Wt(t)&&(n=t.host),t=n}return null}function Vt(e,t){null!==t?Ft.set(e,t):Ft.delete(e)}let Gt=null;const Ut=new WeakMap;function Kt(e){return Ut.get(e)??[]}function Ht(e,t){Ut.set(e,t)}function Jt(e){return Ut.has(e)}const Xt=new WeakMap;let Qt=null,Yt=0;function Zt(e){return Xt.get(e)??[]}function en(e,t){null===Qt?Xt.set(e,t):Qt.set(e,t)}function tn(){Yt++,null===Qt&&(Qt=new Map)}function nn(){if(0!==Yt&&(Yt--,!(Yt>0||null===Qt))){for(const[e,t]of Qt)Xt.set(e,t);Qt=null}}function on(e){return(Qt?.has(e)??!1)||Xt.has(e)}const sn=Symbol("$$setLoopContext"),rn=Symbol("$$getByAddress"),an=Symbol("$$hasByAddress"),ln=Symbol("$$setByAddress"),cn=Symbol("$$connectedCallback"),dn=Symbol("$$disconnectedCallback"),un=Symbol("$$updatedCallback"),fn=Symbol("$$errorCallback"),hn=new WeakMap,pn=new WeakMap;class mn{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function gn(e,t){if(null===t){let t=pn.get(e);return void 0!==t||(t=new mn(e,null),pn.set(e,t)),t}{let n=hn.get(t);void 0===n&&(n=new WeakMap,hn.set(t,n));let o=n.get(e);return void 0!==o||(o=new mn(e,t),n.set(e,o)),o}}const yn=new WeakMap;function wn(e,t){let n=yn.get(e);void 0===n&&(n=new Map,yn.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new bn(e,t)),n.set(t,o)),o}class bn{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function vn(e,t){return gn(wn(e,t.pathInfo),t.listIndex)}function $n(e,t,n){return gn(wn(e,t),n)}const xn=new WeakMap;function Sn(e,t){null===t?xn.delete(e):xn.set(e,t)}function Pn(e){return xn.get(e)||null}const Nn=new Map;function In(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=Nn.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Nn.set(s,r),r}function _n(e,t,n){return t<0||t>=n?null:e.at(t-n)}function kn(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const An=new WeakMap;function Cn(e){const t=qt(e.node);if(null===t)return null;let n=An.get(t);if(void 0===n)n=new WeakMap,An.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=In(t.pathInfo,e.statePathInfo);return n>0&&(o=_n(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const En=new WeakMap;function Mn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Pn(n);null===t?J(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function On(e,t){let n=null;if(n=En.get(e)||null,null!==n)return n;const o=Mn(e,t),s=Cn(e),r=rc(o);return null===r&&J("No state tree found on this root for binding."),n=$n(r,e.statePathInfo,s),En.set(e,n),n}function Tn(e){En.delete(e)}const Rn=new WeakMap;function jn(e,t){const n=Rn.get(e);void 0===n?Rn.set(e,t):n instanceof Set?n.add(t):n!==t&&Rn.set(e,new Set([n,t])),null!==Gt&&Gt({type:"state:binding-added",absoluteAddress:e,binding:t})}function Ln(e,t){const n=Rn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&Rn.delete(e),null!==Gt&&Gt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const Dn=new WeakMap;function Wn(e,t,n){const o=Dn.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!==Gt&&Gt({type:"state:binding-removed",absoluteAddress:gn(e,t),binding:n}))}function Bn(e){const t=Rn.get(e);return void 0!==t?t:null!==e.listIndex?Dn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const zn=new WeakMap,Fn=new WeakMap;class qn{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=Fn.get(e);return void 0!==t||(t=new qn(e,null),Fn.set(e,t)),t}{let n=zn.get(t);void 0===n&&(n=new WeakMap,zn.set(t,n));let o=n.get(e);return void 0!==o||(o=new qn(e,t),n.set(e,o)),o}}const Gn=new WeakMap;function Un(e){let t=null;if(t=Gn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=Cn(e);null===n&&J(`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 Gn.set(e,t),t}function Kn(e){Gn.delete(e)}function Hn(){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 Jn=new Map,Xn=Hn();function Qn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Yn(e){let t="input";for(const n of e.propModifiers)n.startsWith(g)&&(t=n.slice(2));return t}function Zn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const o=Yn(e),s=Qn(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("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=rc(o.getRootNode());null===i&&J("No state tree found on this root for two-way binding.");const a=qt(o);i.createState("writable",e=>{e[sn](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]:[]})})},Jn.set(s,r)),e.node.addEventListener(o,r),Xn.add(s,e),!0}var t,n;return!1}function eo(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function to(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)eo(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class no{_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 oo extends no{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Gt&&Gt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const so=new WeakMap;function ro(e,t){let n=so.get(e);void 0===n&&(n=new Map,so.set(e,n));let o=n.get(t);return void 0===o&&(o=new oo(t,e),n.set(t,o)),o}const io=new WeakMap;function ao(e){if(e.propSegments[0]!==y)return!1;const t=e.node,n=te(t),o=oe(t);if(null!==n&&void 0===o?.get(n))return null===o&&J(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(io.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||J('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===te(e)?null:re(e)}(t);null===r&&J(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&J(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${ye(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=rc(t.getRootNode());null===n&&J("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||J(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${ye(l,n.eventTokenNames)}${we}`);const o=qt(t);n.createStateAsync("writable",async t=>{to(t[sn](o,()=>{const s=null!==o?kn(o.listIndex,o.pathInfo.wildcardCount):[];return ro(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,f),io.set(e,{eventName:a,handler:f}),!0}class lo extends no{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Gt&&Gt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function co(e){return e instanceof lo}const uo=new Map,fo=Hn();function ho(e){const t=e.propModifiers.filter(e=>e===c||e===d).sort().join(",");return`${e.statePathName}::${t}`}const po=(e,t,n)=>o=>{t.includes(c)&&o.preventDefault(),t.includes(d)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=rc(r);null===i&&J("No state tree found on this root for event handler.");const a=qt(s),l=e.startsWith(M+".");i.createStateAsync("writable",async t=>{const c=t[sn](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=Ot.get(n);if(void 0!==e)return e;n=n.parentNode}return Ot.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?kn(a.listIndex,c):[];if(l){const s=t[rn](Vn(n,null));return co(s)||J(`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&&J(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});to(c,`"${e}"`)})};function mo(e){if(!e.propName.startsWith(g))return!1;const t=ho(e);let n=uo.get(t);void 0===n&&(n=po(e.statePathName,e.propModifiers,e.statePathInfo),uo.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),fo.add(t,e),!0}const go=new Map,yo=Hn();function wo(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function bo(e){let t="input";for(const n of e.propModifiers)n.startsWith(g)&&(t=n.slice(2));return t}function vo(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const o=bo(e),s=wo(e,o);let r=go.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=rc(o.getRootNode());null===r&&J("No state tree found on this root for two-way binding.");const i=qt(o);r.createState("writable",e=>{e[sn](i,()=>{e[t]=s})})},go.set(s,r)),e.node.addEventListener(o,r),yo.add(s,e),!0}var t,n;return!1}const $o=new Set(["radio","checkbox"]),xo=new Set(["value","valueAsNumber","valueAsDate"]);function So(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($o.has(e)&&"checked"===t)return!0;if(xo.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=te(n);if(null!==s){const e=oe(n)?.get(s);void 0===e&&J(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=re(n);if(o?.knownProperties.has(t))return!0}return!1}let Po=1,No=1,Io=1;const _o=new WeakMap;function ko(e,t,n){let o=_o.get(e);void 0===o&&(o=new Map,_o.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=Po++,o.set(s,r)),r}function Ao(e,t){return"to-element"===t?2*e:2*e+1}const Co=new Set;function Eo(e){return{transactionId:No++,originBindingId:e,visitedEdges:Co,hop:0}}function Mo(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 Oo=null;function To(){return Oo}function Ro(e,t){const n=Oo;Oo=e;try{return t()}finally{Oo=n}}const jo=[];let Lo=!1;const Do=new Map,Wo=Hn(),Bo=new WeakMap,zo=e=>e.detail,Fo=new WeakMap;function qo(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 Vo(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=te(e.node);if(null!==n){const o=oe(e.node)?.get(n);void 0===o&&J(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=re(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 Go(e){if(null!==te(e.node)){const t=re(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??zo}return null}function Uo(e){if(null===te(e.node))return!1;const t=re(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const Ko=(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!==zo||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=Fo.get(e);void 0===r&&(r=new Set,Fo.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=Bo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=ko(a,e,t),s=function(e,t){for(let n=jo.length-1;n>=0;n--){const o=jo[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!==Gt&&Gt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Ao(n,"to-state"),node:a,member:e}));const r=Ao(n,"to-state"),i=To();if(null!==i&&i.visitedEdges.has(r))return void(null!==Gt&&Gt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=Mo(i??Eo(n),r)}const f=rc(a.getRootNode());null===f&&J("No state tree found on this root for two-way binding.");const h=qt(a),p=()=>{r&&(Lo=!0);try{f.createState("writable",e=>{e[sn](h,()=>{e[t]=c})})}finally{r&&(Lo=!1)}};null!==u?Ro(u,p):p()};const Ho=new WeakSet;function Jo(e){Ho.add(e)}function Xo(e){return!!Ho.has(e)&&(Ho.delete(e),!0)}const Qo=new WeakMap;function Yo(e,t){const n=Qo.get(e);return!(void 0===n||n<t)&&(n===t?Qo.delete(e):Qo.set(e,n-t),!0)}const Zo=new WeakSet;function es(e){Zo.add(e)}function ts(e){return!!Zo.has(e)&&(Zo.delete(e),!0)}let ns=0;function os(){ns--}function ss(){return ns>0}class rs{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 is=new WeakMap;function as(e){let t=is.get(e);return void 0===t&&(t=new rs(e),is.set(e,t)),t}function ls(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&&J(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&J(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function cs(e){return e.propModifiers.some(e=>e.includes("="))}const ds=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),us=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function fs(e,t){return"state"===e&&"call"===t?ds:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function hs(e){if(!o.enableDirectionalInitialSync)return cs(e)&&J("init=/sync= modifiers require enableDirectionalInitialSync."),ds;const t=null===(n=ls(e,f))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:J(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":J(`Invalid sync modifier value "${e}".`)}(ls(e,h));if("event"===e.bindingType)return null!==t&&"none"!==t&&J("Event bindings only allow init=none."),"call"===s?us:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===w)return fs("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&J(`Binding type "${e.bindingType}" does not support init=${t}.`),fs(t??"state",s);const r=re(e.node);if(null===r)return fs(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||J(`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)||J(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||J(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function ps(e,t){return"auto"!==t?t:function(e){const t=rc(e.replaceNode.getRootNode());null===t&&J("No state tree found on this root for binding.");const n=Un(e);let o=!1;return t.createState("readonly",e=>{o=e[an](n)}),o}(e)?"state":"element"}let ms=0,gs=0;const ys=new WeakMap,ws=new WeakMap,bs=new WeakMap,vs=new WeakMap;function $s(e,t){const n=vs.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):vs.set(e,new Set([n,t]))):vs.set(e,t)}function xs(e){return vs.has(e)}function Ss(e,t){const n=vs.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function Ps(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))Ps(n,t)}function Ns(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class Is{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(let o=0;o<e.length;o++){const s=e[o],r=s.removedNodes;if(0===r.length||!Yo(s.target,r.length))for(let e=0;e<r.length;e++)t.push(r[e]);const i=s.addedNodes;for(let e=0;e<i.length;e++)n.push(i[e])}const o=[];for(const e of t)Xo(e)||Ps(e,e=>{Ss(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)ts(e)&&!ss()||Ps(e,e=>{Ss(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&kl(o)}}const _s=new WeakMap;function ks(e){let t=_s.get(e);return void 0===t&&(t=new Is(e),_s.set(e,t)),t}function As(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 Cs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class Es{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=ys.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(Ns(t)&&ks(t),null===this.rowPlan)for(const n of e){const e=ys.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 cs(e)&&hs(e),!0;const t=ys.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=ys.get(e);return t?.session===this?t:null}addTeardown(e,t){const n=ys.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(Cs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=oe(e);null===s&&J(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),$s(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=as(s).wait(t,()=>{if(a())try{se(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=ys.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;if(0===this.records.size)return!0;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&&(Ln(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?On(n):null;if(null!==t.address?(Ln(t.address,n),t.address=null):(Wn(t.patternPathInfo,t.patternListIndex,n),t.patternPathInfo=null,t.patternListIndex=null),Kn(n),Tn(n),this.registerAddress(t),null!==o){const e=On(n);e!==o&&Jt(o)&&Ht(e,Kt(o)),e!==o&&on(o)&&en(e,Zt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return Ns(t)?t:null}(e);null!==t&&ks(t)}handleMutations(e,t,n){for(const n of t)Ps(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)Ps(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&kl(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=ys.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=bs.get(t);void 0===e&&(e=As(t),bs.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;$s(n,this);const o=this.knownMapFor(n);let s=bs.get(e);void 0===s&&(s=As(e),bs.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;$s(i,this),this.addKnownRowBinding(i,s,e),this.optionsByBinding.set(s,n);const a={id:++ms,info:s,generation:++gs,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(ys.set(s,a),this.records.add(a),r.isEvent){try{mo(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=ys.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=++gs,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{mo(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:++ms,info:e,generation:++gs,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};ys.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;mo(t)?e.eventAttached=!0:t.propSegments[0]!==y?(vo(t)&&Cs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const t=bo(e),n=wo(e,t),o=go.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==yo.countOf(n)&&(yo.remove(n,e)&&go.delete(n),!0))}return!1}(t)),Zn(t)&&Cs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(u)){const t=Yn(e),n=Qn(e,t),o=Jn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Xn.countOf(n)&&(Xn.remove(n,e)&&Jn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&So(t.node,t.propName)&&-1===t.propModifiers.indexOf(u)){const n=function(e,t,n){let o=Bo.get(e);void 0===o&&(o=new Map,Bo.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&&Bo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});Cs(e,n)}!function(e){const t=te(e.node);if(null!==t){const n=oe(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&J(`CustomElementRegistry is unavailable for <${t}>.`))}if(So(e.node,e.propName)&&-1===e.propModifiers.indexOf(u)){const t=Vo(e),n=Go(e),o=Uo(e),s=qo(e,t,null!==n,o);let r=Do.get(s);void 0===r&&(r=Ko(e.propName,e.statePathName,e.inFilters,n,o),Do.set(s,r)),e.node.addEventListener(t,r),Wo.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{ao(t)&&Cs(e,()=>function(e){if(e.propSegments[0]!==y)return!1;const t=io.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),io.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=te(e.info.node);if(null===n)return void t();const o=oe(e.info.node);if(null===o&&J(`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=as(o).wait(n,()=>{if(this.isAlive(e,s))try{se(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))});Cs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=hs(e.info),n=ps(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 ns++;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,os()),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=rc(e.node.getRootNode());null===o&&J("No state tree found on this root for initial binding sync.");const s=qt(e.node);o.createState("writable",t=>{t[sn](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=Cn(n);if(null!==o){const s=rc(Mn(n,t));null===s&&J("No state tree found on this root for binding.");const r=wn(s,n.statePathInfo);!function(e,t,n){let o=Dn.get(e);void 0===o&&(o=new WeakMap,Dn.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!==Gt&&Gt({type:"state:binding-added",absoluteAddress:gn(e,t),binding:n})}(r,o,n),e.patternPathInfo=r,e.patternListIndex=o}else{const o=On(n,t);jn(o,n),e.address=o}if(!e.options.registerPathInfo)return;const s=rc(n.replaceNode.getRootNode());null===s&&J("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&&ys.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,os());const t=e.info;if(null!==e.address)try{Ln(e.address,t),e.address=null,Kn(t),Tn(t)}catch{}else if(null!==e.patternListIndex)try{Wn(e.patternPathInfo,e.patternListIndex,t),e.patternPathInfo=null,e.patternListIndex=null,Kn(t),Tn(t)}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=te(e.node);if(null!==t){const n=oe(e.node),o=n?.get(t);if(void 0===o)return}if(So(e.node,e.propName)&&-1===e.propModifiers.indexOf(u)){const t=Vo(e),n=qo(e,t,null!==Go(e),Uo(e)),o=Do.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),Wo.remove(n,e)&&Do.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=ho(e),n=uo.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);e.node.removeEventListener(o,n),0!==fo.countOf(t)&&(fo.remove(t,e)&&uo.delete(t))}(t)}catch{}}}}function Ms(e){let t=ws.get(e);return void 0===t&&(t=new Es(e),ws.set(e,t)),t}function Os(e){return ys.get(e)?.session??null}const Ts=new WeakMap;function Rs(e,t){let n=Ts.get(e);n||(n=new Set,Ts.set(e,n)),n.add(t)}const js=new WeakMap;function Ls(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const Ds=Object.freeze([]);const Ws=new WeakMap;const Bs=new WeakMap;function zs(e){return Bs.get(e)??[]}function Fs(e,t){Bs.set(e,t)}const qs=new WeakMap;function Vs(e){return qs.get(e)??[]}function Gs(e,t){qs.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 Us=0;function Ks(){return`u${(Us++).toString(36)}`}let Hs=0,Js=0;const Xs=Symbol("wcs.listIndex.noValue");class Qs{uuid=Ks();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Xs,this._index=t,this._version=Hs,this._chainGeneration=Js}get index(){return this._index}set index(e){this._index=e,this._version=++Hs,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(e){this._value=e}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=Hs),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Js||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Js),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Hs,Js++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Ys(e,t,n=e){return new Qs(e,t,n)}function Zs(e,t){e.reparent(t)}function er(e){return e.homeParentListIndex}function tr(e,t){e.value=t}function nr(e,t){const n=e.value;return n!==Xs&&n===t.value}const or=new WeakMap,sr=new WeakSet;function rr(e){return sr.has(e)}function ir(e,t){const n=er(e),o=e.parentListIndex;return null===n||n===o||sr.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!sr.has(e)&&!sr.has(n)&&n.position===e.position&&nr(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&sr.has(e)&&!sr.has(t)}(o,t)?t:null:n}function ar(e){const t=or.get(e);return void 0===t?null:t}function lr(e,t){const n=or.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=ir(o,t);if(null!==e)for(const t of n)Zs(t,e)}return n}function cr(e,t){null!==t?or.set(e,t):or.delete(e)}const dr=new WeakMap;function ur(e,t){null===t?dr.delete(e):dr.set(e,t)}function fr(e){const t=dr.get(e);t&&(t.dirty=!0)}const hr=Symbol.for("wcstack.transition-runner");function pr(e){const t=globalThis[hr];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}function mr(e,t,n){const o=pr(e);if(null!==o)return o.run(t,{source:e,types:n});t()}let gr=0,yr=0;function wr(e){gr=e+1}function br(){gr=0}const vr=new WeakMap,$r=new Set,xr=new Set;function Sr(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Pr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function Nr(e){return vr.get(e)}function Ir(e){_r(e),vr.delete(e)}function _r(e){$r.delete(e),xr.delete(e)}const kr=new WeakSet;let Ar=0;function Cr(e){return Nr(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Er(e){if(0===xr.size)return;if(t=e.absolutePathInfo.stateElement,!xr.has(t))return;var t;const n=Cr(e);if(void 0!==n)for(const e of n)Mr(e)}function Mr(e){kr.has(e)||(kr.add(e),Ar++)}function Or(e){return!!kr.delete(e)&&(Ar--,!0)}const Tr=[];function Rr(e,t=0){const n=Tr.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Tr.push(o):Tr.splice(n,0,o)}function jr(e){queueMicrotask(()=>{throw e})}class Lr{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){gr>yr&&(yr=gr),Er(e);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){tn(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){const o=new Map;for(const t of e){const e=o.get(t.absoluteAddress);null!==Gt&&null!=e&&null!==t.context&&e.transactionId!==t.context.transactionId&&Gt({type:"propagation:coalesced",absoluteAddress:t.absoluteAddress,droppedTransactionId:e.transactionId,winnerTransactionId:t.context.transactionId}),o.set(t.absoluteAddress,t.context)}const s=new Set(o.keys());for(const e of n)o.has(e)||o.set(e,null);const r=[],i=new Map;for(const[e,t]of o){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!==Gt&&Gt({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop});continue}const n=Bn(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(r.push(e),null!==t&&i.set(e,t));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==t&&i.set(n,t))}try{const e=()=>{i.size>0?kl(r,i):kl(r)};if(t()||0===r.length)e();else{const t=mr("state",e);void 0!==t&&t.catch(jr)}}finally{nn(),function(e){for(const t of Tr.slice())t.listener(e)}(s)}}}const Dr=new Lr;function Wr(){return Dr}const Br=new WeakMap,zr=new WeakMap,Fr=new WeakMap,qr=new WeakMap;let Vr=!1;const Gr=new WeakMap,Ur=new WeakMap,Kr=[];function Hr(e){let t=Br.get(e);return void 0===t&&Br.set(e,t={byPath:new Map,lastValue:new Map}),t}function Jr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function Xr(e,t,n,o){const s=function(e,t){let n=e.byPath.get(t);return void 0===n&&e.byPath.set(t,n=new Map),n}(e,t);let r=zr.get(o);if(void 0===r&&zr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(s.get(e).delete(o),r.set(t,n),Jr(s,n,o)),!1}return r.set(t,n),Jr(s,n,o),!0}function Qr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function Yr(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&Qr(Fr,o.listIndex,r),null!==r.levelListIndex&&Qr(qr,r.levelListIndex,r))}function Zr(e,t,n,o,s){Vr=!0;const r=Hr(e);Yr(r,t,s,o,Xr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function ei(e,t,n){if("number"!=typeof t)return;const o=e.indexes[t];if(void 0!==o)for(const t of e.getters)n.push(vn(e.stateElement,Vn(t,o)))}function ti(e,t){if(void 0!==e)for(const n of e)t.push(n)}function ni(e){const t=qr.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function oi(e){if(!Vr)return;const t=Fr.get(e);if(void 0!==t){Fr.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=zr.get(o),r=s.get(n);s.delete(n),Br.get(t).byPath.get(n).get(r).delete(o),null!==e.levelListIndex&&ni(e)}}}function si(e,t,n){if(!Vr)return;const o=qr.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=Br.get(e),i=o.byPath.get(s);i.get(t).delete(r),Jr(i,n,r),zr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(fr(r),Wr().enqueueAbsoluteAddress(r,null))}}const ri=new WeakMap,ii=Object.freeze([]),ai=new Set;function li(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:ii,s=Array.isArray(n)&&n.length>0?n:ii,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:ii,o=Array.isArray(t)&&t.length>0?t:ii;let s=ri.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=lr(o,e)||[],a=i.length>0?er(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:ai,deleteIndexSet:new Set(i),addIndexSet:ai};let t=lr(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Ys(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:ai,deleteIndexSet:ai,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 l={oldIndexes:i,newIndexes:i,changeIndexSet:ai,deleteIndexSet:ai,addIndexSet:ai};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,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=Ys(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=ri.get(e);o||(o=new WeakMap,ri.set(e,o)),o.set(t,n)}(o,s,l),cr(s,l.newIndexes))}}(e,t,n);!function(e,t){for(let n=0;n<e.length;n++){if(e[n].index!==n){const t=e[n].index;e[n].index=n,si(e[n],t,n)}tr(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:ii),function(e){for(const t of e)sr.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)oi(e);return function(e){for(const t of e)sr.delete(t)}(o.newIndexes),function(e,t){if(!Vr||e===t)return;const n=Ur.get(e);if(void 0===n)return;Ur.delete(e);const o=Ur.get(t);Ur.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=Hr(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=e[n],r=t[n];if(s!==r)for(const e of[s,r])if(void 0!==e&&!rr(e))for(const t of o.getters){const n=vn(o.stateElement,Vn(t,e));fr(n),Wr().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function ci(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 di=new WeakSet;const ui=new WeakMap;function fi(e){return ui.get(e)??null}function hi(e,t){ui.set(e,t)}const pi=new WeakMap;function mi(e){return pi.get(e)??[]}function gi(e,t){pi.set(e,t)}function yi(e,t){const n=mi(e);for(const e of n)Vt(e,t)}function wi(e,t,n){yi(e,t);const o=zs(e),s=fi(e);null!==s&&s.activate(o,n.rootNode);for(const e of o){if(null===s){jn(On(e),e)}(null===s||s.shouldApplyState(e))&&Il(e,n)}}function bi(e){if(!e.mounted)return;const t=zs(e),n=fi(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{Ln(On(o),o)}}!function(e){const t=mi(e);for(let e=0;e<t.length;e++)Vt(t[e],null)}(e)}function vi(){return Object.freeze(new Set)}const $i=new WeakMap,xi=vi();function Si(e,t){const n=$i.get(e);n?n.add(t):$i.set(e,new Set([t]))}function Pi(e){const t=$i.get(e);return void 0!==t?t:xi}function Ni(e,t){const n=$i.get(e);n&&(n.delete(t),0===n.size&&$i.delete(e))}const Ii=new Set(["if","elseif","else","for"]);class _i{_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){const t=this._childNodeArray;for(let n=0;n<t.length;n++){const o=t[n];es(o),e.appendChild(o)}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){es(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=fi(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRecords();const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Jo(n),n.parentNode.removeChild(n))}const n=zs(this);for(let e=0;e<n.length;e++){const t=n[e];Ii.has(t.bindingType)&&Pi(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){fi(this)?.dispose(),this._teardownBindings()}_teardownBindings(){const e=zs(this);for(let t=0;t<e.length;t++){const n=e[t];Ii.has(n.bindingType)&&Pi(n.node).forEach(e=>{e.unmount()}),Kn(n),Tn(n)}}unmount(){fi(this)?.dispose();for(const e of this._childNodeArray)null!==e.parentNode&&(Jo(e),e.parentNode.removeChild(e));const e=zs(this);for(let t=0;t<e.length;t++){const n=e[t];Ii.has(n.bindingType)&&Pi(n.node).forEach(e=>{e.unmount()}),Kn(n),Tn(n)}this._mounted=!1}}function ki(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 Ai(e){const t=document.createDocumentFragment(),n=new _i(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 Ci(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=he(o,s[e].nodePath);null===t&&J(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),pt(t),H(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 Es;return n.initializeRow(e,t),n}(n,a),d=new _i(o);return hi(d,c),Fs(d,a),Gs(d,l),gi(d,r),Si(e.node,d),d}function Ei(e){void 0!==e.uuid&&null!==e.uuid||J("BindingInfo.uuid is null.");const n=rt(e.uuid);n||J(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&ki(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=he(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!==te(r))return null;if("prop"===o&&So(r,e.propName))return null;let i;try{i=hs({...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 Ci(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=he(e,s.nodePath);if(null===t&&J(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),ut.has(t))continue;const r=ft(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new Es,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 _i(i,s);hi(l,a.bindingSession),Fs(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in S&&c.push(e);return Gs(l,c),gi(l,a.nodes),Si(e.node,l),l}const Mi=/\{\{\s*(.+?)\s*\}\}/g,Oi=new Set(["SCRIPT","STYLE"]);function Ti(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&&Oi.has(e.parentElement.tagName)||Ri(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),Ti(t.content)}else Ti(e.content)}function Ri(e){const t=e.data;if(Mi.lastIndex=0,!Mi.test(t))return;Mi.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Mi.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 ji;function Li(){if(ji)return ji;const e=[],t=qe("not",e)(ze);return ji={filterName:"not",args:e,filterFn:t},ji}const Di=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Wi(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 Bi(e,t){const n=Di.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Wi(s,t)+r}function zi(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=Wi(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Fi(e,t){return zi(e,t)}function qi(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=Bi(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=zi(r,t);e!==r&&o.setAttribute(n,e)}}}function Vi(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 Gi(e){const t=[],n=dt(e);for(const e of n){const n=it(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:Vi(o),parseBindTextResults:n})}return t}function Ui(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 Ki=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Hi=Li();function Ji(e,t){const n=t.outFilters;return{...t,outFilters:[...n,Hi],bindingType:e}}function Xi(e,t,n,o,s,r=!0){Ui(t),"string"==typeof o&&qi(t,o),Qi(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Gi(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 Qi(e,t,n,s){const r=o.commentElsePrefix,i=lt(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=Fi(i,n));let a=Qe(i)[0];const d=Ki.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Ks();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&J("'else' binding found without preceding 'if' or 'elseif' binding."),a=Ji("else",l.parseBindTextResult),p=Xi(e,f,a,m,s,!1),st(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:Vi(o),parseBindTextResults:it(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&J("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Xi(e,f,a,m,s),st(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=Ks(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Ji("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Vi(n),parseBindTextResults:it(n)}),st(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:Vi(g),parseBindTextResults:it(g)})):t.replaceWith(g)}else{p=Xi(e,f,a,m,s),st(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)}}const Yi=new WeakMap;function Zi(e,t,n){let o=Yi.get(e);void 0===o&&(o=new Map,Yi.set(e,o));const s=o.get(t);null!=s&&J(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function ea(e,t){if(null===e)return!1;const n=Yi.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+s)||e.startsWith(t+s))return!0;return!1}const ta=new WeakMap;function na(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 oa=new WeakMap,sa=[];const ra=new WeakMap,ia=new WeakSet;function aa(e){console.error(`[@wcstack/state] volume "${e.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),e.onGrafted(null)}let la=null;const ca=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),da=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function ua(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 fa(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 ha={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},pa={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function ma(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}.${we}`}function ga(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 ya(e,t){return`$setAll("${e}") ${t}`}function wa(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.${we}`}const ba=new WeakMap;function va(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(ea(!1===e.isConnected?null:e.rootNode??null,n))return;const i=Y(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=ba.get(e);return void 0===n&&(n=new Set,ba.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!==ua(e,t))return da;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!==ua(e,a))return ca;if(Object(i)!==i)return ca;if(l===r){if(!Array.isArray(i)||0===i.length)return ca;i=i[0];continue}const d=ua(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:fa(i,c,n)};if("function"==typeof d.get)return t===o.length-1?da:ca;i=d.value}return da}(t,n,e.getterPaths);"missing"===a.existence&&(function(e,t){return!0===Sa.get(e)?.has(t)}(e,n)||("binding"!==o?Na(e,n,o,a):function(e,t,n){let o=$a.get(e);void 0===o&&(o=new Map,$a.set(e,o));if(o.set(t,n),xa.has(e))return;xa.add(e),setTimeout(()=>function(e){xa.delete(e);const t=$a.get(e);if(void 0===t)return;$a.delete(e);for(const[n,o]of t)Na(e,n,"binding",o)}(e),0)}(e,n,a)))}const $a=new WeakMap,xa=new WeakSet,Sa=new WeakMap;function Pa(e,t){let n=Sa.get(e);void 0===n&&(n=new Set,Sa.set(e,n)),n.add(t),$a.get(e)?.delete(t)}function Na(e,t,n,o){console.warn(`[@wcstack/state] [${ha[n]}] ${pa[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ye(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${we}`),null!==Gt&&Gt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Ia=new WeakMap,_a=new Set;function ka(e,t,n,o){let s=Ia.get(e);if(void 0===s){if(!o)return null;s=new Map,Ia.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 Aa(e,t){if(!e.component.isConnected)return!1;const n=qt(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 Ca(e,t,n,o){const r=ka(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&&Aa(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?Aa(i,o)&&(null!==l&&J(`[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 Ea(e){const t=e.parentStateElement,n=qt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[sn](n,()=>{e.$postUpdate(o.exportedPath)})})}function Ma(e,t){const n=Wt(t);var o,r;null!==n&&n.stateProp!==e.stateProp&&J(`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&&Ms(t).dispose(),function(e,t){Ot.set(e,t),Lt.set(t,e);let n=Rt.get(t.parentStateElement);void 0===n&&(n=new Map,Rt.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Tt.get(t.component);void 0===o&&(o=new Map,Tt.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&jt.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=nc.get(e);if(void 0!==n){if(n===t)return;J("A state tree is already registered on this root.")}nc.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Et(e,t,n);Ti(t);const o=qt(e.component);Qi(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),Al(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=Ct(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),ka(e.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:c}),e.parentStateElement.addDynamicDependency(t,a),Pa(e.parentStateElement,a)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=qt(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(_a.has(s))continue;const r=Y(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[sn](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(_a.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),Ea(e),o=t,r=Promise.resolve(),oc.set(o,r),r.then(()=>lc(o),()=>{})}function Oa(e,t){const n=Ms(t),o=qt(e.component);n.forEachActiveBindingNode(e=>Vt(e,o));kl(n.rebindAddresses()),Ea(e)}function Ta(e,t){if(function(e){const t=Rt.get(e);return void 0!==t&&t.size>0}(t))for(const n of Bt(t)){if(!Ra(n.component,e))continue;const t=Dt(n);null!==t&&Oa(n,t)}}function Ra(e,t){for(let n=t.firstNode;null!==n;n=n.nextSibling){if(n===e||n.contains(e))return!0;if(n===t.lastNode)break}return!1}const ja=new WeakSet,La=Symbol.for("wcstack.state.view-transition-naming");function Da(){const e=pr("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Wa(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||ja.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[La]??={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.`)):(ja.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 Ba=new WeakMap,za=new WeakMap,Fa=new WeakMap,qa=new WeakMap;function Va(e,t,n){!function(e,t,n){let o=za.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,za.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function Ga(e,t){Ba.set(e,t)}function Ua(e){return e.nodeType===Node.ELEMENT_NODE||(e.nodeType===Node.TEXT_NODE?""!==(e.textContent?.trim()??""):e.nodeType===Node.COMMENT_NODE&&e.data.startsWith("@@wcs-"))}function Ka(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 Ha(e,t,n){if(o=t,!di.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const Ja=new Set(["if","elseif","else","for"]);function Xa(e,t){for(const n of zs(e))if(t.appliedBindingSet.delete(n),Ja.has(n.bindingType))for(const e of Pi(n.node))Xa(e,t)}function Qa(e){for(const t of zs(e)){if(!Ja.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Pi(t.node))Qa(n),e&&n.mounted&&(bi(n),n.unmount(),Ni(t.node,n))}}function Ya(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Za(e,n,s){const r=Boolean(s);let i;const a=Pi(e.node);i=0===a.size?Ei(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Ya(e)}`),bi(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Ya(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);wi(i,qt(e.node),n);const t=Da();null!==t&&Wa(i,"branch",t)}}const el=new WeakMap,tl=new WeakMap;const nl=new WeakMap;const ol=new WeakMap;function sl(e){return ol.get(e)??[]}const rl=new Set;const il=Symbol.for("wcstack.trustedTypes.policy");function al(){const e=globalThis[il];return null===e||"object"!=typeof e?null:e}let ll;let cl=!1;function dl(e,t){if(cl)return;if(!function(){if(void 0!==ll)return ll;if(!("trustedTypes"in globalThis))return ll=!1,ll;try{document.createElement("div").innerHTML="<i></i>",ll=!1}catch{ll=!0}return ll}())return;cl=!0;const n="function"==typeof al()?.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 ul={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 fl(e,n,s){if(void 0===s){const t=1===e.propSegments.length?e.propSegments[0]:"";return"textContent"!==t&&"innerText"!==t&&"innerHTML"!==t||Te(`"${t}: ${e.statePathName}" got undefined: 3.0 empties it. Return "" for no value.`),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!==te(r)&&function(e,t,n){let o=el.get(e);o||(o=new Map,el.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=al(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&dl(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=te(e);if(null===n)return null;const o=oe(e)?.get(n);if(void 0===o)return null;const s=re(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&&So(r,c)){const t=ko(r,c,e.statePathName),o=Ao(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??To()??Eo(t);if(a.visitedEdges.has(o))null!==Gt&&Gt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=Mo(a,o);Ro(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Io++,writtenValue:n};jo.push({receipt:i,node:e});try{return r()}finally{jo.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=ul[c];e?e(r,s):(!function(e,t,n){let o=ol.get(e);o||(o=[],ol.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,rl.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!==te(r)&&(u in d?function(e,t,n,o){let s=nl.get(e);s||(s=new Map,nl.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=tl.get(e);o||(o=new Map,tl.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 hl=new WeakSet;function pl(e,t,n){}function ml(e,t){const n=Un(t);if(n.pathInfo.path in S){const e=qt(t.node);return null===e&&J(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&J("ListIndex not found for loopContext:");const n=S[t];void 0===n&&J(`Invalid index name: ${t}`);const o=_n(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&J(wa(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[rn](n)}const gl=new WeakSet;function yl(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const wl=Object.freeze({[b]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&J("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];null==n&&Te(`"attr.${s}: ${e.statePathName}" got ${n}: 3.0 removes the attribute.`),o.getAttribute(s)!==n&&o.setAttribute(s,n)},[$]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;void 0===n&&Te(`"style.${o}: ${e.statePathName}" got undefined: 3.0 clears it.`),s[o]!==n&&(s[o]=n)},[w]:function(e,t,n){co(n)||J("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Ws.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||J('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=te(e);if(null===t)return null;const n=oe(e)?.get(t);return void 0===n&&J(`Custom element <${t}> is not defined for command binding.`),re(e)}(r);null===a&&J(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||J(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ye(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Ws.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 Ws.delete(e);const o=n[i];return"function"!=typeof o&&J(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),Ws.set(e,{token:o,unsubscribe:c,elementRef:l})}}),bl={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!hl.has(e.replaceNode)){hl.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=Cn(e),a=On(e),l=Kt(a),c=l.length>0&&!za.has(e.node)?[]:l,d=li(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);let u=za.get(e.node);const f=void 0!==u?Ha(u,c,d):null,h=Array.isArray(c)&&c.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=qa.get(e.node);if(void 0===t){const n=Ba.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Ua(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Ua(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),qa.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){Qo.set(e,(Qo.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return Fa.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;d.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(bi(o),Qa(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Ni(e.node,o):(bi(o),o.unmount(),function(e,t){let n=Fa.get(e.node);void 0===n&&(n=[],Fa.set(e.node,n)),n.length<1e3?n.push(t):Ni(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(za.delete(e.node),u=void 0)}let m=e.node;const g=Y(s.path+"."+r),y=n.stateElement.loopContextStack,w=ci(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&m.isConnected&&null===f&&(b=document.createDocumentFragment(),Sn(b,n.rootNode));const v=t(),$=Da(),x=e.uuid??"",S=Fa.get(e.node);for(const t of d.newIndexes){let o;if(d.addIndexSet.has(t)){const r=Vn(g,t);y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=Ei(e):Xa(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);m.parentNode.insertBefore(e,m.nextSibling),m=e}o.mountAfter(m)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??m;n.parentNode.insertBefore(e,n.nextSibling)}}wi(o,r,n),null!==$&&Wa(o,"row",$)}),void 0===o&&J(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)&&Ta(o,n.stateElement)}else{if(o=void 0!==u?u.get(t)??null:null,d.changeIndexSet.has(t)){const e=Vs(o);for(const t of e)Il(t,n)}null===o&&J(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&Ka(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),e){const e=o,s=Vn(g,t);y.createLoopContext(s,t=>{wi(e,t,n)})}}m=o.lastNode||m,void 0===u&&(u=new WeakMap,za.set(e.node,u)),u.set(t,o)}Ba.set(e.node,m),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Sn(b,null))},if:Za,else:Za,elseif:Za,radio:function(e,t,n){const o=e.node,s=Ls(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=Ls(o.value,e.inFilters),r=Array.isArray(n)?n:Ds;o.checked=r.includes(s)}},vl=new WeakMap,$l=new WeakMap,xl=new WeakMap;function Sl(){}function Pl(e){const t=e.replaceNode,n=e.propSegments[0];return function(e,t){return!0===Ts.get(e)?.has(t)}(t,n)?pl:function(e,t){return!0===js.get(e)?.has(t)}(t,n)?Sl:fl}function Nl(e,t){const n=Ls(ml(t.state,e),e.outFilters);if(!0===$l.get(e))return void t.deferredSelectBindings.push({binding:e,value:n,stateElement:t.stateElement});let o=vl.get(e);if(void 0===o){if(vl.has(e))return o=Pl(e),o===pl&&vl.set(e,o),void o(e,t,n);if(o=bl[e.bindingType],void 0===o){const t=e.propSegments[0];if(o=wl[t],vl.set(e,o),void 0===o){te(e.replaceNode)?(o=Pl(e),o===pl&&vl.set(e,o)):(o=fl,vl.set(e,o))}}if(o===fl){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 $l.set(e,!0)}}o(e,t,n)}else o(e,t,n)}function Il(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=On(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=Os(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==xl.get(e)){const t=te(e.replaceNode);if(t&&void 0===oe(e.replaceNode)?.get(t))return void function(e,t){if(gl.has(e))return;gl.add(e);const n=()=>{gl.delete(e);const t=Os(e);(null===t||t.shouldApplyState(e))&&kl([e])},o=n=>{gl.delete(e),yl(t,n)},s=Os(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{gl.delete(e),r()})||(gl.delete(e),r()))}const r=oe(e.replaceNode);if(null===r)return gl.delete(e),void yl(t,new Error("CustomElementRegistry is unavailable."));as(r).wait(t,()=>{e.replaceNode.isConnected?n():gl.delete(e)},o)}(e,t);xl.set(e,!0)}if(!0===t.sameRootVerified)return void Nl(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Pn(o),null===o&&J("Root node for fragment not found for binding.")),o!==t.rootNode){const n=rc(o);null===n&&J("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};Nl(e,r)})}else Nl(e,t)}function _l(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!==Gt&&Gt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function kl(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Pn(d),null===d&&J("Root node for fragment not found for binding."));const u=rc(d);null===u&&J("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{Il(n,f)}catch(e){_l(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{fl(e,{propagationContextByBinding:t},n)}catch(t){_l(e,t,o??null,c)}for(const[e,t]of i.entries())Ht(e,t),en(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[un](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[fn](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 Al(e,t,n){const[o,s,r]=ht(e,n),i=Ms(e);for(const e of o)Vt(e,t);kl(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=mt(o);0!==e.length&&(Vt(o.node,t),kl(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}async function Cl(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=oe(e);null===s&&J(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(at(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function El(e){if(e===document)await Cl(document),Ti(document),Qi(document,document),Al(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await K(t.host),await Cl(t),Ti(t),Qi(t,t),Al(t,null)}}const Ml="2.6.0",Ol="undefined"==typeof HTMLElement?class{}:HTMLElement,Tl=/^@@wcs-(?:for|if|elseif|else):[^-]/,Rl=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,jl=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Ll=/^@@wcs-text-start:(.+)$/;function Dl(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Wl extends Ol{_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=Ml.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=Dl(JSON.stringify(t)),e.appendChild(n);const s=Array.from(ot.keys());for(const t of s){const n=rt(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(rl);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=sl(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=Dl(JSON.stringify(t)),e.appendChild(n)}}rl.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Rl.test(e.data)||jl.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;Tl.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=Ll.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;Rl.test(e.data)&&i.push(e)}for(const e of i){const t=Rl.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()}Wl.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(Tl.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 Bl=new Set(["for","if","elseif","else"]);function zl(e){const t=new Es;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]=ht(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 Fl(e,t,n){for(const o of t)"event"===o.bindingType||Bl.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in S||Y(o.statePathName).wildcardCount>n||e.push(o)}function ql(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 Vl(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Qe(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,Li()],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;Ui(a),"string"==typeof l&&qi(a,l),Qi(n,a,l);st(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Gi(a)})}}async function Gl(e){await Cl(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="${Ml}". Falling back to full render.`),Wl.cleanupDom(e),!1}for(const n of t)Vl(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=Rl.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),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=Ai(s.nodes),{bindingInfos:i,subscriberNodes:a,bindingSession:l}=zl(s.nodes);hi(t,l);for(const e of a)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");Fs(t,i),gi(t,a);const c=[];for(const e of i)e.statePathName in S&&c.push(e);if(Gs(t,c),"for"===s.type&&null!==s.index){const a=ql(e,"for",s.uuid);if(a){const e=Ys(null,s.index);Va(a,e,t),Ga(a,s.nodes[s.nodes.length-1]),Si(a,t);const c=Y(s.path+"."+r);yi(t,Vn(c,e)),l.initialize(i,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Fl(o,i,c.wildcardCount);let d=n.get(s.uuid);d||(d=[],n.set(s.uuid,d)),d.push(e)}}else{const n=ql(e,s.type,s.uuid);n&&(Si(n,t),l.initialize(i,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Fl(o,i,0))}}for(const[t,o]of n){const n=ql(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=rt(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=rc(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&cr(t,o)})}return o}(document.body,n);Wl.removeBlockBoundaryComments(document.body);const i=[];for(const e of t)e.parentNode&&(i.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());Wl.restoreTextBindings(document.body);const[a,l]=ht(document.body);for(const e of a)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(Vt(e,null),t.setAttribute("data-wcs-completed",""))}else Vt(e,null);const c=[],d=[],u=Ms(document.body).initialize(l);for(const e of u)if("event"!==e.bindingType)if(Bl.has(e.bindingType))d.push(e);else{if(e.statePathName.includes(r))continue;c.push(e)}for(const e of d)if("for"===e.bindingType){const t=On(e),n=rc(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(Ht(t,o),en(t,o))})}kl([...c,...s]);for(const{el:e,parent:t,next:n}of i)t.insertBefore(e,n);const f=e.querySelectorAll(o.tagNames.ssr);for(const t of f){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 h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0}const Ul=Symbol.for("wcstack.binder");const Kl=Symbol.for("wcstack.binder.pending"),Hl=Symbol.for("wcstack.binder.taken");function Jl(){const e=function(){const e=globalThis[Ul];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[Kl];return void 0===t&&(t=[],e[Kl]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[Hl];return void 0===t&&(t=new WeakSet,e[Hl]=t),t}();for(const t of n)o.add(t),e.bind(t)}function Xl(e){if(xs(e))return!0;if(!Ql(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(`[${o.bindAttributeName}]`);return null!==t&&xs(t)}function Ql(e){return 1===e.nodeType}function Yl(e){if(Xl(e))return;Ti(e),Qi(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Al(t&&s?n:e,null)}const Zl=[];function ec(){const e=Zl.splice(0,Zl.length);for(const t of e)Yl(t);Jl()}const tc={protocol:"wcs-binder",version:1,bind:function(e){var t;Ql(e)&&!Xl(e)&&(t=e.getRootNode(),ac.has(t)?Yl(e):Zl.push(e))}};const nc=new WeakMap,oc=new WeakMap,sc=new Set;function rc(e){return nc.get(e)??null}function ic(e){return oc.get(e)??Promise.resolve()}const ac=new WeakSet;function lc(e){ac.add(e)}function cc(e,n){const s=nc.get(e);if(null===n){if(void 0===s)return;nc.delete(e),sc.delete(s),null!==Gt&&Gt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;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 Gl(e)||await El(e)}else await El(e);lc(e),ec(),t()}catch(e){n(e)}})});oc.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await El(e),lc(e),ec(),t()}catch(e){n(e)}})});oc.set(e,t)}}void 0!==s&&J('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),nc.set(e,n),sc.add(n),function(e,t){ia.delete(e);const n=ra.get(e);if(void 0===n||0===n.length||null===la)return;ra.delete(e);const o=la;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,n),null!==Gt&&Gt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const dc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function uc(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 fc="__WCSTACK_DEVTOOLS_HOOK__";function hc(){const e=globalThis,t=e[fc];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[fc]=n,n}const pc=e=>{null!==Gt&&Gt({type:"state:update-batch",addresses:e})};function mc(e){const t=null!==Gt;!function(e){Gt=e}(e);const n=null!==e;n&&!t?Rr(pc,0):!n&&t&&function(e){const t=Tr.findIndex(t=>t.listener===e);-1!==t&&Tr.splice(t,1)}(pc)}function gc(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 yc(e){return rc(e)??J("devtools: no state tree on this root")}let wc=null;function bc(){if(t())return;if(null!==wc)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Ml,getStateElements(){const e=[];for(const t of sc)e.push(gc(t));return e},overlays:e=>Bt(yc(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=yc(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 yc(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){yc(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=rt(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(uc(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=fe(t,Qe(n));for(const o of e)r(uc(t,o,"attribute",n))}catch{}continue}const t=dc.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=rt(s);if(null===a){if(n===o.commentTextPrefix)try{r(uc(e,nt(s),"comment",s))}catch{}}else r(uc(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:mc};wc=e,hc().register(e)}const vc={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",Ml),Wl.buildContent(o,Wl.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const $c="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let xc=0;async function Sc(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++xc}\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 ${$c}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${$c}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Pc(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){J(`Failed to load script file: ${e}`)}}class Nc{_loopContextStack=Array(a).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&J("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=a&&J("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&&J("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&&J("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&&J(`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 Ic=new WeakMap;function _c(e,t){let n=Ic.get(e);void 0===n&&(n=new Map,Ic.set(e,n));let o=n.get(t);return void 0===o&&(o=new lo(t,e),n.set(t,o)),o}const kc=new WeakMap;function Ac(e){const t=kc.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 _c(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:_c(e,n)}},set(){J("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){J("$command namespace is read-only; deleting from it is not allowed.")}});return kc.set(e,n),n}const Cc=Symbol("wcs-stream-last-notified-uncertain"),Ec=new WeakMap;function Mc(e,t){const n=Ec.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Oc(e,t){const n=Ec.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Cc,error:Object.is(o.error,null)?null:Cc})}const Tc=new Set;function Rc(e){Tc.delete(e)}const jc=new WeakMap;function Lc(e){return jc.get(e)??new Map}function Dc(e){Rc(e);const t=jc.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Oc(e,n.name)}const Wc=(e,t)=>t,Bc=new Set;function zc(e,t){const n=t[R];if(void 0===n)return void Mc(e,Bc);"object"==typeof n&&null!==n||J(`${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&&J(`${R} entry name must be a non-empty string.`),i.includes(s)&&J(`${R} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&J(`${R} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&J(`${R} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&J(`${R} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(i)&&J(`${R} entry "${i}" conflicts with a getter declared on the state.`),e.setterPaths.has(i)&&J(`${R} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||J(`${R} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&J(`${R} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&J(`${R} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&J(`${R} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&J(`${R} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??Wc,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){jc.set(e,t)}(e,o),Mc(e,new Set(o.keys()))}function Fc(e,t){"string"==typeof t&&0!==t.length||J(`[wcs/recursion-declaration-invalid] ${D} ${e} must be a non-empty string.`);const n=t.split(s);n.some(e=>0===e.length)&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must not contain empty path segments.`),n.length<2&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must name a list element: a property path ending with "${s}${r}" (for example "nodes${s}${r}").`),n[n.length-1]!==r&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must end with "${s}${r}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===r&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must have exactly one "${r}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===W&&J(`[wcs/recursion-declaration-invalid] ${D} ${e} "${t}" must not contain "${W}" — the declaration is what gives "${W}" its meaning.`),isNaN(Number(n[o]))||J(`[wcs/recursion-declaration-invalid] ${D} ${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 qc(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 Vc(e){return-1!==e.indexOf(W)}function Gc(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(Vc(o))return null;const i=o.slice(1).split(s);return i[0]===r||i.some(e=>0===e.length)?null:o}function Uc(e){return 0===e.length?e:s+Jc(e.slice(1))}function Kc(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 Hc(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(s,o-1))if(Kc(e,t,n.slice(0,o)))return!0;return!1}function Jc(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 Xc(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 Qc(e,t,n){n<0&&J(`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&&J(`[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 Yc(e,t){return Qc(e,"",t)}function Zc(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 ed=new WeakSet;function td(e){return"function"==typeof e.get&&ed.has(e.get)}function nd(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&td(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=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void ur($n(e,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=t;for(const e of s[i].segments.slice(a))l=l?.[e];if(!Array.isArray(l))return;const c=ar(l);if(null===c)return;const d=Math.min(c.length,l.length);for(let e=0;e<d;e++)r(l[e],c[e],i+1)};r(t,null,0)}}(e,t,n)}}const od="[wcs/recursion-declaration-invalid]";class sd{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=qc(t);for(const[t,o]of Object.entries(n)){if(!Vc(t))continue;"function"==typeof o.set&&J(`${od} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&J(`${od} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Gc(e,t);null===n&&J(ga(t,e.recursiveAnchor)),0===n.length&&J(`${od} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${s}total"), not the node.`),Xc(e,Uc(n))&&J(`${od} "${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(Vc(t)||td(n))continue;const e=this._matchExpansion(t);null!==e&&J(`${od} "${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++)Kc(this.spec,e[t].suffix,e[n].suffix)&&J(`${od} "${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(Hc(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=Jc(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!==Zc(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=Zc(this.spec,e.suffix,t);null!==n&&(null!==o&&J(`"${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||td(s)||J(`"${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,ed.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(Yc(e,o)+s+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return nd(e,t,n),n}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=Qc(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 rd=new WeakMap,id=new WeakMap;function ad(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Lc(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Lc(e).has(n),ownKeys:()=>Array.from(Lc(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Lc(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){J(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){J(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function ld(e){const t=rd.get(e);if(void 0!==t)return t;const n=ad(e,z,e=>e.status);return rd.set(e,n),n}function cd(e){const t=id.get(e);if(void 0!==t)return t;const n=ad(e,F,e=>e.error);return id.set(e,n),n}function dd(e){rd.delete(e),id.delete(e)}const ud=Object.freeze([]),fd=Object.freeze([]);function hd(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??ud,i=e.dynamicDependency.get(n)??ud,a=t.byFromPath.get(n)??fd;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}let pd=null;async function md(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 gd(e){$d();const t=Lc(e);if(0!==t.size){!function(e){Tc.add(e)}(e);for(const n of t.values())yd(e,n)}}function yd(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=pd,r=new Set;let i;pd=r;try{e.createState("readonly",e=>{i=n(e)})}finally{pd=o}i instanceof Promise&&J(`${R} entry "${t.name}" args must be synchronous (it returned a Promise).`);const a=`${z}${s}${t.name}`,l=`${F}${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||J(`${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&&J(`${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);!function(e,t){const n=Nr(e);if(void 0!==n&&0!==t.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==t.name)continue;const s=hd(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&J(`[wcs/scan-feedback-loop] ${R} entry "${t.name}" args read "${n}", which is derived from the ${L} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(e,t),e.createState("writable",e=>{e[t.name]=t.definition.initial}),wd(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(){wd(e,t,"done",null)},fail(o){wd(e,t,"error",o),n.abort()}};md(r.source,o,n.signal,i)}function wd(e,t,n,o){t.status=n,t.error=o;const r=function(e,t){return Ec.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=Ec.get(e);void 0===s&&(s=new Map,Ec.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{i&&e.$postUpdate(`${z}${s}${t.name}`),a&&e.$postUpdate(`${F}${s}${t.name}`)}))}function bd(e){const t=Tc;if(0===t.size)return;const n=[];for(const o of t)for(const t of Lc(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)&&Lc(e).get(o.name)===o)try{yd(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Lc(e).get(o.name)===o&&wd(e,o,"error",n)}}let vd=!1;function $d(){vd||(vd=!0,Rr(bd,20))}const xd=new WeakMap,Sd=new WeakMap,Pd=new Set,Nd=new Map;function Id(e){return xd.get(e)??Nd}function _d(e){Pd.add(e),function(e){const t=vr.get(e);void 0!==t&&(Sr(t)&&$r.add(e),function(e){return e.eventResetByPath.size>0}(t)&&xr.add(e))}(e)}function kd(){return Pd}const Ad=new Map;function Cd(e){return Sd.get(e)??Ad}function Ed(e){0===e.length&&J(`[wcs/watch-declaration-invalid] ${j} entry name must be a non-empty state path.`),e.startsWith("$")&&J(`[wcs/watch-declaration-invalid] ${j} entry "${e}" must not start with "$" (reserved namespace).${we}`),e.includes("@")&&J(`[wcs/watch-declaration-invalid] ${j} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${we}`),e in Object.prototype&&J(`[wcs/watch-declaration-invalid] ${j} 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&&J(`[wcs/watch-declaration-invalid] ${j} entry "${e}" has an empty path segment.${we}`);return t.wildcardCount>i&&J(`[wcs/watch-declaration-invalid] ${j} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Md(e,t){const n=t[j];if(void 0===n)return null;"object"==typeof n&&null!==n||J(`[wcs/watch-declaration-invalid] ${j} must be an object mapping state paths to handler functions.${we}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&J(`[wcs/watch-declaration-invalid] ${j} entry "${t}" must be a function.${we}`);const n=Ed(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){xd.set(e,t)}(e,o),s.size>0?s:null}const Od=new WeakMap;function Td(e,t,n){let o=Od.get(e);void 0===o&&(o=new Map,Od.set(e,o)),o.set(t,n)}const Rd=new Map;function jd(e,t){Rd.has(e)||Rd.set(e,t)}function Ld(e){return Rd.get(e)}function Dd(e){return Rd.has(e)}function Wd(e){for(let t=e;null!==t;t=t.parentListIndex)if(rr(t))return!0;return!1}function Bd(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[rn](Vn(t.wildcardParentPathInfos[i],r)),l=ar(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=_n(o,i,t.wildcardCount);if(l!==c&&!nr(l,c)){if(rr(c))return"gone";s="replaced"}r=l}return s}function zd(e,t,n){const o=new Map;for(const s of n){const n=Bd(e,t,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),e=>e.row)}const Fd=/^(?:0|[1-9]\d*)$/;function qd(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Vd(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return null;const t=Object.getPrototypeOf(e);if(Array.isArray(e)){return t===Array.prototype&&Reflect.ownKeys(e).every(t=>"length"===t||"string"==typeof t&&Fd.test(t)&&qd(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&qd(e,t))?"object":null}function Gd(e,t){const n=Vd(e);if(null===n)return e;const o=e,s=t.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(e.length):null===Object.getPrototypeOf(e)?Object.create(null):{},t.set(o,r);for(const e of Object.keys(o))r[e]=Gd(o[e],t);return r}function Ud(e){return Gd(e,new Map)}function Kd(e,t,n){if(Object.is(e,t))return!0;const o=Vd(t);if(null===o||"object"!=typeof e||null===e)return!1;const s=e,r=t;if("array"===o){if(!Array.isArray(e)||e.length!==t.length)return!1}else if(Array.isArray(e)||Object.keys(s).length!==Object.keys(r).length)return!1;if(Vd(e)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let t=0;t<e.length;t++)if(!Kd(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&Kd(s[e],r[e],n))}function Hd(e,t){return Kd(e,t,new Map)}const Jd=new WeakMap;function Xd(e,t){if("function"!=typeof t)return;const n=Jd.get(t);void 0===n?Jd.set(t,new Set([e])):n.add(e)}const Qd={"read-source":e=>`${L} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${L} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${L} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${L} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${L} could not write the output "${e}".`},Yd={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Zd(e,t,n){null!==Gt&&Gt({type:"state:watch-error",phase:t,path:`${L}.${e}`,error:n})}function eu(e,t,n){console.error(`[@wcstack/state] ${Qd[n](e)}`,t),Zd(e,Yd[n],t)}function tu(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function nu(e,t){t.then(void 0,()=>{}),eu(e,new TypeError(`${L} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const ou=new WeakSet;const su=Object.freeze([]);function ru(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function iu(e,t){let n=0;for(;n<e.indexes.length-1&&e.indexes[n]===t.indexes[n];)n++;return e.indexes[n]-t.indexes[n]}function au(e,t){return t.has(e.stateElement)&&!0===Nr(e.stateElement)?.entries.has(e.entry)}function lu(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>cu(n,e))||Or(t)}function cu(e,t){return Wr().hasQueuedPath(e,t)}function du(e,t){!function(e,t,n){if(0!==Ar)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=Cr(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||Or(t)}}(e,t,cu)}function uu(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function fu(e,t,n){if(!au(e,n))return lu(e),null;const{stateElement:o,entry:s}=e;if(e.reset)return{group:e,next:s.initial};const r=s.source;if(function(e,t){for(const n of t.pathInfo.cumulativePaths)if(e.getterPaths.has(n))return!0;return!1}(o,r))return function(e,t,n){if(ou.has(e))return;ou.add(e);const o=`[wcs/scan-source-computed] ${L} entry "${t}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),Zd(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=Lc(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name],o=0===r.pathInfo.wildcardCount?e.rows:zd(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(iu)){let n;try{n=uu(t,r,e)}catch(e){eu(s.name,e,"read-source");continue}const o=a(l,n,Ld(e.absAddress),...e.indexes);if(tu(o))return void nu(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){eu(s.name,e,i.failure)}return i.plan}function hu(e,t){const{group:n}=e;if(!au(n,t))return void lu(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Or(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!Hd(o,s.initial):!Object.is(o,e.next)){const o=n.reset?Ud(s.initial):e.next;t[s.name]=o,Xd(s.name,o)}})}catch(e){eu(s.name,e,"write")}}function pu(e,t,n){if(du(e,t),0===$r.size)return su;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=Nr(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=kn(n.listIndex,r.wildcardCount)}for(const s of i)ru(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)ru(o,e,t).reset=!0}if(0===o.size)return su;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];wr(n);try{for(const n of s){const o=fu(n,e,t);null!==o&&r.push(o)}}finally{br()}return r}function mu(e){Pu(),(0!==Id(e).size||0!==Cd(e).size||function(e){const t=vr.get(e);return void 0!==t&&Sr(t)}(e))&&(_d(e),function(e){const t=[];for(const n of Id(e).values())gu(e,n)&&t.push(n);for(const n of Cd(e).values())for(const o of n)gu(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{Td(e,$n(e,o.pathInfo,null),n[o.path])}catch(t){wu(e,o.path,"prime",t)}})}(e))}function gu(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const yu={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function wu(e,t,n,o){console.error(`[@wcstack/state] $watch ${yu[n]} "${t}" threw.`,o),null!==Gt&&Gt({type:"state:watch-error",phase:n,path:t,error:o})}function bu(e){const t=kd();try{if(0===t.size)return void du(e,t);const n=function(){const e=yr;return yr=0,e}();if(n>32){du(e,null);const t=Array.from(e,e=>e.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:t}),void(null!==Gt&&Gt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){wr(n);try{for(const n of e)hu(n,t)}finally{br()}}}(pu(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Id(e).get(s),i=Cd(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=kn(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort($u);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(Wd(o.absAddress.listIndex)||s?.entry===o.entry&&vu(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(zd(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){wu(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);wr(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Id(e.stateElement).get(e.entry.path)===e.entry,o=!0===Cd(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&xu(e)}}finally{br()}}(e,t,n)}finally{Rd.clear()}}function vu(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function $u(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 xu(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=gu(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 wu(0,n.path,"evaluate",e)}const a=r?function(e,t){return Od.get(e)?.get(t)}(t,o):Ld(o);r&&Td(t,o,i),null!==Gt&&Gt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){wu(0,n.path,"handler",e)}}let Su=!1;function Pu(){Su||(Su=!0,Rr(bu,10))}const Nu="[wcs/scan-declaration-invalid]",Iu=Object.freeze([]);function _u(e){return`${L} entry "${e}"`}function ku(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Au(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${r}${r}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${we}`}function Cu(e,t,n){0===n.length&&J(`${Nu} ${e} "${t}" must be a non-empty state path.${we}`),n.startsWith("$")&&J(`${Nu} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${we}`),n.includes("@")&&J(`${Nu} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${we}`),n in Object.prototype&&J(`${Nu} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${we}`);const o=Y(n);for(const s of o.segments)0===s.length&&J(`${Nu} ${e} ${t} "${n}" has an empty path segment.${we}`);return o.wildcardCount>i&&J(`${Nu} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Eu(e,t,n,o){const i=_u(e);0===e.length&&J(`${Nu} ${L} entry name must be a non-empty string.${we}`),(e.includes(s)||e.includes(r))&&J(`${Nu} ${i} must be a flat property name ("${s}" and "${r}" are not allowed). The output is a property the runtime owns.${we}`),e.startsWith("$")&&J(`${Nu} ${i} must not start with "$" (reserved namespace).${we}`),e in Object.prototype&&J(`${Nu} ${i} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${we}`),t.has(e)&&J(`${Nu} ${i} conflicts with a getter declared on the state.${we}`),n.has(e)&&J(`${Nu} ${i} conflicts with a setter declared on the state.${we}`),o.has(e)&&J(`${Nu} ${i} conflicts with the ${R} entry of the same name — each output has exactly one owner.${we}`)}function Mu(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Jd.get(t)?.has(e)}(e,o)&&J(`${Nu} ${_u(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${we}`)}function Ou(e,t,n,o,r,i){const a=_u(e),l=void 0!==t.from,c=void 0!==t.on;if(l===c&&J(`${Nu} ${a} must declare exactly one of "from" (a state path) or "on" (an event-token name).${we}`),c){const e=t.on;return"string"==typeof e&&0!==e.length||J(`${Nu} ${a} "on" must be a non-empty event-token name.${we}`),n.has(e)||J(`${Nu} ${a} on "${e}" is not declared in ${O}.${ye(e,n)}${we}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&J(`${Nu} ${a} "from" must be a state path string.${we}`);const u=Cu(a,"from",d),f=ku(u,o)??i?.recursiveGetterOwning(d)??null;null!==f&&J(Au(a,"from",d,f));const h=ku(u,r);return null!==h&&J(function(e,t,n){return`${Nu} ${e} from "${t}" ${n===t?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${we}`}(a,d,h)),(d===e||d.startsWith(e+s))&&J(`${Nu} ${a} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${we}`),{kind:"path",path:d,pathInfo:u}}function Tu(e,t,n,o){if(void 0===t)return Iu;const i=_u(e);Array.isArray(t)||J(`${Nu} ${i} "resetOn" must be an array of state paths.${we}`);const a=[];for(const e of t){"string"!=typeof e&&J(`${Nu} ${i} "resetOn" must contain only state path strings.${we}`);const t=Cu(i,"resetOn",e);t.wildcardCount>0&&J(`${Nu} ${i} resetOn "${e}" must not contain "${r}" — a reset returns the whole output to "initial".${we}`);const l=ku(t,o);null!==l&&J(Au(i,"resetOn",e,l)),"path"===n.kind&&e===n.path&&J(`${Nu} ${i} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${we}`),"path"===n.kind&&e.startsWith(n.path+s)&&J(`${Nu} ${i} resetOn "${e}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${we}`),a.push(e)}return a}function Ru(e,t,n=null){const o=e[L];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&J(`${Nu} ${L} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${we}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(qc(e)))"function"==typeof n.get?s.add(t):"function"==typeof n.set&&i.add(t),"function"==typeof n.set&&r.add(t),"function"==typeof n.value&&a.set(t,n.value);const l=function(e){const t=e[R];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),c=[];let d=0;for(const[e,u]of Object.entries(o)){Eu(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&J(`${Nu} ${_u(e)} must be an object ({ from | on, initial, fold, resetOn? }).${we}`);const o=u;Mu(e,a,o);const f=Ou(e,o,t,s,i,n);"initial"in o||J(`${Nu} ${_u(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${we}`),"function"!=typeof o.fold&&J(`${Nu} ${_u(e)} fold must be a function.${we}`);const h=Tu(e,o.resetOn,f,s);c.push({name:e,source:f,fold:o.fold,initial:o.initial,resetOn:h,order:d++})}return function(e){const t=new Set(e.map(e=>e.name)),n=new Map;for(const o of e){for(const e of o.resetOn){const n=Y(e).segments[0];t.has(n)&&J(`${Nu} ${_u(o.name)} resetOn "${e}" reads the ${L} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${we}`)}if("path"===o.source.kind){const e=o.source.pathInfo.segments[0];t.has(e)&&n.set(o.name,e)}}for(const e of n.keys()){const o=[e];let s=n.get(e);for(;void 0!==s&&o.length<=t.size;)s===e&&J(`${Nu} ${L} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${we}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function ju(e){const t=e.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[e.name];i="threw";const a=function(e){return kr.has(e)}(e),l=a&&!Hd(n,e.initial)?Ud(e.initial):n,c=t(l,o,...s);if(tu(c))return void nu(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Xd(e.name,c)),a&&Or(e)}catch(t){eu(e.name,t,i)}}}function Lu(e,t,n){const o=function(e,t){Ir(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Pr(n,e.source.path,e);for(const t of e.resetOn)Pr(o,t,e),"event"===e.source.kind&&Pr(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return vr.set(e,r),r}(e,t);for(const o of t){const t=n.get(o.name);"event"===o.source.kind&&void 0!==t&&(o.resetOn.some(n=>t.includes(n)&&Wr().hasQueuedPath(e,n))&&Mr(o))}const s=new Set;for(const t of o.byFromPath.keys())s.add(t),e.setPathInfo(t,"prop","scan");for(const t of o.byResetPath.keys())e.setPathInfo(t,"prop","scan");return s.size>0?s:null}function Du(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 Wu(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 Bu(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 zu(e){return e.startsWith("$")}function Fu(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 qu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||J(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||J(`${t} entries must be non-empty strings.`),e.startsWith("$")&&J(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&J(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Vu(e){const t=qu(e,A)??[],n=qu(e,C)??[],o=qc(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}J(`${A} entry "${e}" is not declared on the state.${ye(e,Fu(o,"value"))}`)}"function"==typeof t.value&&J(`${A} entry "${e}" is a method. Declare it in ${C} instead.`)}for(const e of n){const t=o[e];void 0===t&&J(`${C} entry "${e}" is not declared on the state.${ye(e,Fu(o,"method"))}`),"function"!=typeof t.value&&J(`${C} entry "${e}" is not a method. Declare it in ${A} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}const Gu=new Map;class Uu{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 Ku(e){let t;return Gu.get(e)??(Gu.set(e,t=new Uu(e)),t)}function Hu(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:_n(n.listIndex,o,n.pathInfo.wildcardCount)}function Ju(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=In(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?_n(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?_n(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}const Xu=new WeakMap;class Qu{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(Ct(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=r.length>0?At(e,t):Ct(e,t),a=Mt(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?At(e,t):Ct(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 Ju(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[Ct(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)||J(`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[At(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 Ct(this.record,t),!0}catch{return!1}}}function Yu(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Xu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Xu.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 Qu(e,s,t.listIndex,r,n,o))}function Zu(e){const t=e.parentStateElement,n=(t,n)=>{const o=qt(e.component);let s;return t[sn](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(Ct(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?At(e,n):Ct(e,n),l=qt(e.component)?.listIndex.indexes??[],c=Mt(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:Ct(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:At(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 Ct(e,n),!0}catch{return!1}}})}function ef(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function tf(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 nf(e,t,n,o,s){const i=t.pathInfo.segments[0];if(i===M)return tf(Ac(s),t.pathInfo.segments);if(i===z)return tf(ld(s),t.pathInfo.segments);if(i===F)return tf(cd(s),t.pathInfo.segments);if(!0===s.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const e=zt(s,t.pathInfo.path);if(null!==e)return Yu(e,t,n,o)}if(!(t.pathInfo.path in e)){if(null===t.parentAddress&&ea(function(e){return e.rootNode??null}(s),t.pathInfo.path))return;const i=t.parentAddress??J(function(e,t,n){return`[${ha.binding}] Path "${e}" does not exist on the state tree.${ye(e,fa(t,"",n))}${we}`}(t.pathInfo.path,e,s.getterPaths)),a=sf(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=Ca(s,i.pathInfo.path,l,t.listIndex);if(null!==e)return function(e,t,n,o,s){const r=Yu(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??J(wa(`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 of(e,t,n,o,s){const r=vn(s,t),i=function(e){return dr.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=nf(e,t,n,o,s);return ur(r,{value:l,dirty:!1,generation:a}),l}function sf(e,t,n,o){Ju(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo),function(e,t){null!==pd&&pd.add(vn(e,t))}(o.stateElement,t);const s=o.stateElement;return ef(s,t)?of(e,t,n,o,s):nf(e,t,n,o,s)}function rf(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=vn(n.stateElement,h),m=Zt(p),g=sf(e,h,t,n),y=li(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]??J(`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())en(e,Array.isArray(t)?t:[]);return l}function af(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=lr(sf(e,Vn(a,r),t,n),r);null==l&&J(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??J(`ListIndex not found at index ${c} of ${a.path}`)}return r}function lf(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 cf(e,t,n,o){"object"==typeof e&&null!==e||J(`${B} 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&&J(`${B} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function df(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&J(`${B} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function uf(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];cf(a,n,o,i);const l=df(a,t,n,o,i);r.has(l)&&J(`${B} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function ff(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 hf(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const i=sf(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 pf=new WeakMap;function mf(e,t){null===t?pf.delete(e):pf.set(e,t)}function gf(e,t,n){const s=Vn(Y(e.wildcardParentPaths[t]),n),r=vn(e.stateElement,s),i=Zt(r),a=e.stateProxy[rn](s),l=li(s.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const 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}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)gf(e,t+1,n)}const yf=[];function wf(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:yf,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:yf,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const bf=[];function vf(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return bf;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??bf}function $f(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[rn](t),a=vn(e.stateElement,t),l=Zt(a),c=li(t.listIndex,l,r);e.observedListValueByAbsAddress.set(a,Array.isArray(r)?r:[]);const d=wf(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=vf(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=In(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&J(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=_n(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};gf(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&J(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=_n(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 xf(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&&J(`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,$f(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)en(e,t);return Array.from(u.result)}function Sf(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||jd(n,o)}function Pf(e,t,n,s,r){if(!function(e,t){return!0===Br.get(e)?.byPath.has(t)||!0===Gr.get(e)?.has(t)}(e,t))return;const i=Wr(),a=o.enablePropagationContext?To()??null:null;for(const o of function(e,t,n,o,s){const r=Br.get(e),i=r?.byPath.get(t),a=Gr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return Kr;r.lastValue.set(t,s);const l=[],c=!n||!Object.is(o,s);if(void 0!==i&&(n&&ti(i.get(o),l),c&&ti(i.get(s),l)),void 0!==a)for(const e of a)n&&ei(e,o,l),c&&ei(e,s,l);return l}(e,t,n,s,r))fr(o),i.enqueueAbsoluteAddress(o,a)}function Nf(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?To()??Eo(-1):null,c=Wr();c.enqueueAbsoluteAddress(t,l),i&&fr(t),xf(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=vn(s.stateElement,t);fr(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function If(e,t,n,o,s){s&&(e.getterPaths.has(t)?fr(n):ur(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function _f(e,t,n,o,s,i,a,l){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const a=sf(e,n,s,i),l=t.pathInfo.segments[t.pathInfo.segments.length-1];if(l===r){const e=t.listIndex?.index??J(wa(`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{Nf(t,n,s,i,a,l)}}function kf(e,t,n,o,i,a,l,c){const d=t.parentAddress??J(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=sf(e,d,i,a)??[];let f=(h=u,pf.get(h)??null);var h;if(null===f){const e=ar(u)??[];f={value:[...u],listIndexes:[...e]},mf(u,f)}try{return _f(e,t,n,o,i,a,l,c)}finally{const n=f.value.indexOf(o),l=sf(e,d,i,a)??[],c=Array.isArray(l)?ar(l)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:Ys(d.listIndex,-1);c[h]=p;if(new Set(l).size===f.value.length){for(let e=0;e<c.length;e++)c[e].index=e;mf(u,null),function(e,t,n,o,i,a){const l=a.stateElement,c=Wr(),d=vn(l,e);Kt(d)===n&&(cr(t.value,t.listIndexes),Ht(d,t.value),function(e){di.add(e)}(t.value));c.enqueueRenderOnlyAddress(d);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=Y(e.pathInfo.path+s+r);for(let e=0;e<o.length;e++){const n=o[e],s=u.get(n);if(s===e)continue;const r=Vn(f,n),d=vn(l,r);if(void 0===s){const n=$n(l,f,t.listIndexes[e]??null);Dd(n)&&jd(d,Ld(n)),Nf(r,d,i,a,null,ef(l,r),"full");continue}xf(l,r,l.staticDependency,l.dynamicDependency,l.listPaths,i,"new",e=>{const t=vn(l,e);fr(t),c.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(d,f,l,c,i,a)}}}function Af(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=sf(e,t,o,i),c=function(e,t,n,o){const s=uf(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=uf(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===ar(o)&&li(c,null,o);const d=li(c,o,n.list),u=Cf(e,t,n.list,i,a,l),f=Y(l+s+r);for(const t of n.matched){const n=ff(t.oldRow,t.newRow);if(0===n.length)continue;const o=d.newIndexes[t.position];for(const r of n)void 0!==o?Af(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 Cf(e,t,n,o,i,null)}function Cf(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=ta.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&&J(`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&&J(`[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=!!Lo&&(Lo=!1,!0);if(!(d in e)&&null!==t.parentAddress&&!c.elementPaths.has(d)){const s=sf(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}Pf(c,d,p,h,n);const m=ef(c,t),g=vn(c,t);null!==Gt&&Gt({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:p}),Sf(c,d,g,h,p);let y=!1;try{if(void 0===f&&J(wa(`path "${d}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),!0===c.hasMounts&&e!==r&&!(f in s)){const o=Ca(c,t.parentAddress.pathInfo.path,e,t.listIndex);if(null!==o)return y=!0,function(e,t,n,o,s,r){const i=Yu(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{Nf(t,g,i,a,l,m),y?fr(g):If(c,d,g,n,m),lf(c,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=sf(e,t,i,a);if(hf(e,t,i,a)&&Object.is(o,n))return!0;f=o,h=!0}Pf(c,d,h,f,n);const p=c.elementPaths.has(t.pathInfo.path),m=ef(c,t),g=vn(c,t);null!==Gt&&Gt({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),Sf(c,d,g,f,h);try{return p?kf(e,t,g,n,i,a,l,m):_f(e,t,g,n,i,a,l,m)}finally{p||If(c,d,g,n,m),lf(c,t.pathInfo,{value:n})}}function Ef(e,t,n,o){return(t,s,...r)=>{const i=r[0],a=Y(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==a.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(a.path,e.path)}s.length!==a.wildcardParentPathInfos.length&&J(ma("$resolve",t,a.wildcardParentPathInfos.length,s.length));const l=Vn(a,af(e,n,o,a,s));if(!(void 0!==i))return r.length>0&&Te(`$resolve("${t}", indexes, undefined): 3.0 writes undefined. Pass two arguments to read.`),sf(e,l,n,o);"readonly"===o.mutability&&Te(Re),Af(e,l,i,n,o)}}function Mf(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 Of(e,t,n){const o=e.recursionRegistry,s=Gc(o.spec,n);null===s&&J(ga(n,o.spec.recursiveAnchor));const r=Mf(t,o);return null===r&&J(`[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 Tf(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=vn(n.stateElement,a),u=sf(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)&&J(`[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)&&J(`[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=li(s,Zt(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)en(e,t);return a}function Rf(e,t,n,o){const s=Ef(e,0,n,o);return(t,r)=>{if(!0===o.stateElement.hasRecursion&&Vc(t)){if(void 0!==r)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Gc(r.spec,o);null===i&&J(ga(o,r.spec.recursiveAnchor)),Array.isArray(s)||J(`[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&&J(`[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=Tf(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(sf(e,a[o],t,n));return l}(e,n,o,t,r);t=Of(o.stateElement,o,t)}const i=Y(t);if(void 0===r||Array.isArray(r)||J(`$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&&J(ma("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=Hu(o,i.wildcardPaths[e]);if(t){r=kn(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&&J(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=rf(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 jf(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Hu(o,s.wildcardPaths.at(-1)??J(`lastWildcardPath is null: ${t.pathInfo.path}`))??J(`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]??J(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=lr(sf(e,Vn(i,s),n,o),s)??J(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??J(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??J(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":J(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Lf(e,t,n,o,s,r,i){const a=n.stateElement.recursionRegistry,l=Gc(a.spec,o);null===l&&J(ga(o,a.spec.recursiveAnchor));const c=Uc(l);Array.isArray(s)||J(ya(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&J(`[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&&J(ya(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&J(ya(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){Xc(e,n)&&J(`[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&&J(`[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=Tf(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Af(e,u[o],r,t,n),f++);return f}function Df(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=kn(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,oa.get(l)??sa):[];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=kn(n.listIndex,l);(a[s]??=[]).push(e)}}if(i.size>0)try{e.callback.call(na(e.mountPath,n),Array.from(i),a)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" $updatedCallback threw.`,t)}}return i}const Wf=/^\$\d+$/,Bf=`${z}${s}`,zf=`${F}${s}`,Ff=new WeakMap;function qf(e,t,n,o){const r=S[t];if(void 0===r&&"string"==typeof t&&36===t.charCodeAt(0)&&Wf.test(t)&&J(`[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&&J(`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&&J(`ListIndex not found: ${t.toString()}`);let a=r;const l=e.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const e=zt(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=_n(i,a,l.wildcardCount);return c?.index??J(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Rf(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>function(e,t,n,o){return(t,s,r,i)=>{if("readonly"===o.mutability&&Te(Re),!0===o.stateElement.hasRecursion&&Vc(t))return Lf(e,n,o,t,s,r,i);const a=Y(t);Array.isArray(s)||J(ya(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&J(ma("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&J(ya(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&J(ya(t,"requires an array as the value when { spread: true } is set."));const d=rf(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&J(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=af(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(sf(e,s,n,o),...d[t]):l?r[t]:r,void 0!==i&&(Af(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=Ku(t),i=jf(e,r,n,o),a=Vn(r.pathInfo,i),l=vn(s,a),c=Wr();c.enqueueAbsoluteAddress(l),xf(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=vn(s,e);fr(t),c.enqueueAbsoluteAddress(t)}),lf(s,a.pathInfo)}}(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Ef(e,0,n,o)(t,s,...r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{Vc(e)&&J(`[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&&J(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??J("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"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;let r;o.beginUntrack();try{r=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Zr(o.stateElement,e,t,vn(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;let r,i;o.beginUntrack();try{r=n[e],i=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Zr(o.stateElement,e,i,vn(o.stateElement,s),r),Object.is(r,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||J(`$eqIndex("${e}") needs a list row scope.`);const r=_n(s.listIndex,t-1,s.pathInfo.wildcardCount);null===r&&J(`$eqIndex("${e}", ${t}): no list index at that level.`);const i=t===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[e],i&&(l=n[s.pathInfo.wildcardParentPaths[t-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const t=i?ar(l):null;null!==t?function(e,t,n,o,s){Vr=!0,Hr(e).lastValue.set(t,s);let r=Gr.get(e);void 0===r&&Gr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=Ur.get(o);void 0===l?Ur.set(o,l=[]):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a&&(a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a)),a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){Vr=!0;const r=Hr(e);Yr(r,t,s,o,Xr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,vn(o.stateElement,s),a)}return Object.is(a,r.index)};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 Ac(o.stateElement);case z:return ld(o.stateElement);case F:return cd(o.stateElement)}if(!t.startsWith(Bf)&&!t.startsWith(zf))return}const s=Ku(!0===o.stateElement?.hasRecursion&&Vc(t)?Of(o.stateElement,o,t):t),r=jf(e,s,n,o),i=Vn(s.pathInfo,r);return sf(e,i,n,o)}if("symbol"==typeof t){const s=function(e){let t=Ff.get(e);return void 0===t&&(t=new Map,Ff.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case sn:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&J("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 rn:i=t=>sf(e,t,n,o);break;case an:i=t=>hf(e,t,n,o);break;case ln:i=(t,s)=>Af(e,t,s,n,o);break;case cn:i=()=>async function(e,t,n){const o=Reflect.get(e,P);"function"==typeof o&&await o.call(n)}(e,0,n);break;case dn:i=()=>function(e,t,n){const o=Reflect.get(e,N);"function"==typeof o&&o.call(n)}(e,0,n);break;case un:i=t=>Df(e,t,n,o);break;case fn:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,_);"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 Vf{_stateElement;_addressStack=Array(a).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=rc(e);null===n&&J("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get mutability(){return this._mutability}get stateElement(){return this._stateElement}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&J("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()&&J(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),J(`[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&&J(`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 qf(e,t,n,this)}set(e,t,n,o){return"readonly"===this._mutability&&J("This state is readonly."),function(e,t,n,o,s){if("string"==typeof t){const r=Ku(t),i=jf(e,r,o,s);return Af(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 Gf(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 Uf=new WeakMap;class Kf{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=Uf.get(e);return n?n.get(t)??null:null}(e,t)??J("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 Hf=e=>()=>e;function Jf(e,t,n,o){!function(e,t,n){let o=Uf.get(e);o||(o=new Map,Uf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(Gf(o));const s=function(e,t){const n=new Kf(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Hf(s),enumerable:!0,configurable:!0}),Rs(t,n),Xf(t,n)}function Xf(e,t){if(k in e){const n=e[k];"function"==typeof n?n.call(e,t).catch(e=>{J(`Error in ${k}: ${e instanceof Error?e.message:String(e)}`)}):J(`${k} is not a function.`)}}const Qf=new Set;function Yf(e,t){Qf.has(e)||(Qf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function Zf(e){const t=e.rootEntry,n=qt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[sn](n,()=>{o=e[t.outerPathInfo.path]})}),o}function eh(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(na(e.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function th(e,t,n){const o=n[j];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(na(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=Sd.get(e);void 0===n&&(n=new Map,Sd.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),mu(e))}const r=n[B];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=oa.get(e);void 0===n&&(n=[],oa.set(e,n)),n.push(t)}(e,{mountPath:t,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on","$errorCallback"])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 nh(e,t,n){!function(e,t,n){const o=n[j];if(void 0!==o){"object"==typeof o&&null!==o||J(`${j} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(o))"function"!=typeof t&&J(`${j} entry "${e}" must be a function.`),Ed(e)}const r=n[B];if(void 0!==r){"object"==typeof r&&null!==r||J(`${B} 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)&&J(`${B} entry "${n}" must map a list path to a field name or a key function.`),e.listKeys?.has(t+s+n)&&J(`${B} entry "${t+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&J(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&J(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[D]&&J(`Volume "${t}" declares ${D}, 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(qc(n)))-1!==e.indexOf(W)&&J(`Volume "${t}" declares "${e}", which uses "${W}". 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;J(`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;J(`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=ta.get(e);void 0===n&&(n=new Set,ta.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(na(t,this))}),"function"==typeof a&&(l.set=function(e){a.call(na(t,this),e)}),e.defineTreeAccessor(r,l)}th(e,t,n);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(na(t,e))}catch(e){return void console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)}n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n}}function oh(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=nh(e,t.mountPath,t.volumeState)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}function sh(e,t,n,o,s,r){const i={mountPath:n,volumeState:o,onGrafted:s,acquireSlot:r};null===t?(ih(),function(e,t){if(ia.has(e))return void aa(t);let n=ra.get(e);void 0===n&&(n=[],ra.set(e,n)),n.push(t)}(e,i)):oh(t,i)}let rh=!1;function ih(){rh||(rh=!0,la=oh)}const ah=new Set(["for","if","elseif","else"]);function lh(e,n,o){const s=new Map;for(const e of o){const t=Y(e);if(null===t.lastWildcardPath)continue;const n=s.get(t.lastWildcardPath);void 0===n?s.set(t.lastWildcardPath,[t]):n.push(t)}const r=[],i=new Set,a=t=>{const n=vn(e,t);if(i.has(n))return;i.add(n);const o=Bn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(Vn(n,t.listIndex))}};tn();try{if(e.createState("readonly",t=>{for(const o of n){const n=Vn(Y(o),null);a(n);try{xf(e,n,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",a)}catch{}}}),0===r.length)return;const o=function(e){const t=[],n=[];for(const o of e)ah.has(o.bindingType)?t.push(o):n.push(o);return t.sort((e,t)=>0!==(e.replaceNode.compareDocumentPosition(t.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),t.concat(n)}(r),s=()=>{kl(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=mr("state",s);void 0!==i&&i.catch(jr)}finally{nn()}}class ch extends Ol{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return ic(e)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!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 Nc}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_volumeGraftInfo=null;_volumeInitializing=!1;_volumeMountPath=null;_volumeSlotRootNode=null;_volumeDetachedFrom=null;_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&&J(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){const n=this.__state,o=function(e){const t=e[D];if(void 0===t)return null;"object"==typeof t&&null!==t||J(`[wcs/recursion-declaration-invalid] ${D} 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&&J(`[wcs/recursion-declaration-invalid] ${D} must declare exactly one anchor; it is empty.`),n.length>1&&J(`[wcs/recursion-declaration-invalid] ${D} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,i]=n[0];Fc("anchor",o),"string"!=typeof i&&J(`[wcs/recursion-declaration-invalid] ${D} entry "${o}" must map to the repeating sub-path as a string (for example "children${s}${r}").`),Fc("repeating sub-path",i);const a=o.slice(0,o.lastIndexOf(s)),l=i.slice(0,i.lastIndexOf(s)),c=a+s+W;return Object.freeze({anchor:o,repeat:i,recursiveAnchor:c,anchorList:a,repeatList:l})}(e),i=null===o?null:new sd(o,e),a=function(e){const t=new Set,n=e[E];if(void 0===n)return t;Array.isArray(n)||J(`${E} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||J(`${E} entries must be non-empty strings.`),e===M&&J(`${E} entry "${e}" conflicts with the reserved namespace name "${M}".`),t.has(e)&&J(`${E} entry "${e}" is duplicated.`),t.add(e);return t}(e),l=function(e){const t=new Set,n=e[O];if(void 0===n)return t;Array.isArray(n)||J(`${O} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||J(`${O} entries must be non-empty strings.`),t.has(e)&&J(`${O} entry "${e}" is duplicated.`),t.add(e);return t}(e),c=function(e){const t=e[B];if(void 0===t)return null;"object"==typeof t&&null!==t||J(`${B} 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&&J(`${B} entry path must be a non-empty string.`);const t=e.split(s);t.some(e=>0===e.length)&&J(`${B} entry "${e}" must not contain empty path segments.`),t[t.length-1]===r&&J(`${B} entry "${e}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),-1!==e.indexOf(W)&&J(`[wcs/recursion-unsupported] ${B} entry "${e}" uses "${W}", which ${B} 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&&J(`${B} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&J(`${B} entry "${e}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&J(`${B} entry "${e}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&J(`${B} 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),d=Ru(e,l,i);if(null!==this._recursionRegistry)for(const e of this._recursionRegistry.forgetGenerated(this,n))this._generatedPaths.add(e);var u;this._recursionRegistry=i,this._commandTokenNames=a,this._eventTokenNames=l,this._stateGeneration++,this.__state=e,void 0!==n&&(u=this,ba.delete(u),$a.delete(u)),this._hasUpdatedCallback=I in e,this._hasErrorCallback=_ in e,function(e){so.delete(e)}(this),null!==d&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=Ud(n.initial);e[n.name]=t,Xd(n.name,t)}}(e,d),function(e,t){for(const n of t)"event"===n.source.kind&&ro(e,n.source.tokenName).subscribe(ju(n))}(this,d)),function(e,t,n){const o=t[T];if(void 0!==o){"object"==typeof o&&null!==o||J(`${T} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||J(`${T} entry "${t}" is not declared in $eventTokens.${ye(t,n)}`),"function"!=typeof s&&J(`${T} entry "${t}" must be a function.`),ro(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const f=function(e){const t=new Set,n=new Set,o=qc(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 f.getterPaths)this._getterPaths.add(e);for(const e of f.setterPaths)this._setterPaths.add(e);dd(this),function(e){Dc(e),Rc(e),jc.delete(e)}(this),zc(this,e),this._listKeys=c,null!==o&&this._listPaths.add(o.anchorList),this._rebuildPathInfo();const h=function(e){const t=new Map,n=Nr(e);if(void 0!==n)for(const e of n.entries)Or(e)&&t.set(e.name,e.resetOn);return Ir(e),t}(this);this._scanPaths=null===d?null:Lu(this,d,h),function(e){Pd.delete(e),_r(e),xd.delete(e)}(this),function(e){Od.delete(e)}(this),this._watchPaths=Md(this,e),this._initialized&&null!==this._rootNode&&!t()&&(mu(this),gd(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=Wl.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){J("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 Sc(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||J(`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 Pc(e);J(`Unsupported src file type: ${e}`)}}catch(e){J(`Failed to initialize state: ${e}`)}}async _initializeVolume(){const e=this._rootNode,t=this.getAttribute("mount");try{!function(e){0===e.length&&J('"mount" requires a non-empty tree path.');const t=Y(e);for(const n of t.segments)0===n.length&&J(`"mount" path "${e}" has an empty segment.`),n===r&&J(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&J(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(t),this.hasAttribute("bind-component")&&J('"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).`),Zi(e,t,this),this._volumeMountPath=t,this._volumeSlotRootNode=e}catch(e){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),e}this._volumeInitializing=!0,null===rc(e)&&function(e,t){const n=()=>{if(null!==rc(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,null===e&&this._releaseVolumeSlot(),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)}if(null===this._rootNode)return void n(null);const i=this._rootNode;this._acquireVolumeSlot(i)?sh(i,rc(i),t,s,n,()=>this._acquireVolumeSlot(i)):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}return await this._loadingPromise,null!==this._rootNode&&(cc(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),J(e)}_failInitializeLoudly(e){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),null!==this._rootNode&&null===rc(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),oc.set(e,n)}(this._rootNode,e),function(e){ia.add(e);const t=ra.get(e);if(void 0!==t){ra.delete(e);for(const e of t)aa(e)}}(this._rootNode)),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?te(i):null;null!==i&&null!==a||J(`"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&&J(`"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=js.get(e);n||(n=new Set,js.set(e,n)),n.add(t)}(i,c);const d=oe(i);null===d&&J(`CustomElementRegistry is unavailable for <${a}>.`),await d.whenDefined(a.toLowerCase()),i.hasAttribute(o.bindAttributeName)&&await K(i),c in i||J(`Component does not have property "${c}" for state binding.`);let u=i[c];"object"==typeof u&&null!==u||J(`Component property "${c}" is not an object for state binding.`);const f=function(e,t){const n=el.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=me(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||(me(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=(me(i)??[]).filter(e=>e.propSegments[0]===c);if(o.length>0){const l=rc(i.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${a}>.`);let d=(n=i,s=c,Tt.get(n)?.get(s)??null);const f=null!==d;if(null===d&&(function(e,t,n){const o=nl.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;nl.get(e).delete(t)}}(i,c,u),d=vt(i,c,o,l,u,(e=i,t=c,tl.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){Yf(`${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. [wcs/v3-migration] In 3.0 the mount wins over the default.`);continue}if(null===e.rootEntry)continue;if(i||(r=Zf(e),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=e.rootEntry.outerPathInfo.path;Yf(`${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{Ma(d,r instanceof ShadowRoot?r:i)}catch(e){throw this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),e}if(!f){const e=Zu(d);Object.defineProperty(i,c,{get:()=>e,enumerable:!0,configurable:!0}),Rs(i,c)}return Xf(i,c),function(e){const t=yt.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(W)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;wt.has(n)||(wt.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 bt(d,"$connectedCallback")}}Jf(this,this._boundComponent,this._boundComponentStateProp,u)}var e,t,n,s}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{P in e&&await e[cn]()})}async _initializeDCC(e,t){let n;try{if(this.hasAttribute("src")){const e=this.getAttribute("src");e.endsWith(".js")?n=await Pc(e):J(`DCC: Unsupported src type: ${e}`)}else{const t=this.querySelector('script[type="module"]');t?n=await Sc(t,e.tagName.toLowerCase()):J(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}}catch(e){J(`DCC: Failed to load state: ${e}`)}!function(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||J(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=oe(e);null!==r&&"function"==typeof r.define||J(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&J(`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}=Vu(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(q))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const e=oe(this._shadow);return null!==e&&se(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=qc(n);for(const[e,t]of Object.entries(g)){if(zu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Bu(e,o)}else n.get=Du(e),n.set=Wu(e);Object.defineProperty(m.prototype,e,n)}for(const e of u)Object.defineProperty(m.prototype,e,{configurable:!0,enumerable:!0,get:Du(e),set:Wu(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[dn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&rc(this._rootNode)===this._volumeGraftInfo.rootStateElement&&eh(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const e=this._mountRecord,t=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&Oa(e,t)}),bt(e,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||rc(this._rootNode)===this||cc(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(q)){try{this.hasAttribute("bind-component")&&J(`"bind-component" cannot be used inside a [${q}] host. DCC state comes from the template, not from a component property.`),await this._initializeDCC(e.host,e)}catch(e){this._failInitializeLoudly(e)}return}if(this.hasAttribute("mount")){if(this._volumeInitializing){if(this._volumeDetachedFrom===this._rootNode)try{Zi(this._rootNode,this._volumeMountPath,this),this._volumeSlotRootNode=this._rootNode}catch{}return void(this._volumeDetachedFrom=null)}return void await this._initializeVolume()}try{await this._initializeBindWebComponent()}catch(e){this._failInitializeLoudly(e)}if(null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();let t=!1;try{t=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!t)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const e=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(e)}if(this.hasAttribute("enable-ssr")&&!t()||e!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await ic(this.rootNode);const e=Wl.extractStateData(this),t=document.createElement(o.tagNames.ssr);t.setAttribute("version",Ml),Wl.buildContent(t,e),this.parentNode?.insertBefore(t,this)}catch(e){throw this._rejectConnectedCallback?.(e),e}t()||null===this._rootNode||e!==this._connectGeneration||mu(this),t()||null===this._rootNode||e!==this._connectGeneration||this._streamsStartedGeneration===e||gd(this),this._resolveConnectedCallback?.()}_releaseVolumeSlot(){null!==this._volumeSlotRootNode&&(!function(e,t,n){const o=Yi.get(e);o?.get(t)===n&&o.set(t,null)}(this._volumeSlotRootNode,this._volumeMountPath,this),this._volumeSlotRootNode=null)}_acquireVolumeSlot(e){if(this._volumeSlotRootNode===e)return!0;const t=this._volumeMountPath;try{Zi(e,t,this)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> will not graft: another volume already holds the "${t}" slot on this root. Keep one volume per mount path.`),!1}return this._volumeSlotRootNode=e,!0}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&eh(this._volumeGraftInfo,"$disconnectedCallback"),this._initialized||(this._volumeDetachedFrom=this._volumeSlotRootNode,this._releaseVolumeSlot()),void(this._rootNode=null);if(null!==this._mountRecord)return bt(this._mountRecord,"$disconnectedCallback"),Ea(this._mountRecord),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&(t=this._rootNode,ia.delete(t)),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{cc(this.rootNode,null),e=this,kc.delete(e),Dc(this),dd(this),function(e){Pd.delete(e),_r(e)}(this),this._rootNode=null}}var e,t}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 scanPaths(){return this._scanPaths}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)&&J(`$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 ua(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 stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&J("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("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}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),va(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)}}}_rebuildPathInfo(){for(const[e,t]of Array.from(this._pathRegistrations))t.bound&&!this._generatedPaths.has(e)&&this.setPathInfo(e,t.bindingType)}_createState(e,t,n){try{const o=function(e,t,n){const o=new Vf(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){if(!this._initialized)return this._initializeFailed&&J(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);this._volumeInitializing&&J(`Cannot replace the state of <${o.tagNames.state} mount="${this.getAttribute("mount")}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${this.getAttribute("mount")}" on the root state instead.`),(this._hasGraftedVolumes||this._hasMounts)&&J("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.");const t=this.__state;this._state=e;const n=function(e){const t=new Set;for(const n of e)if(void 0!==n)for(const[e,o]of Object.entries(qc(n)))e.startsWith("$")||e.includes(r)||"function"==typeof o.value||t.add(e);return t}([t,e]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(e){lh(this,e,this._pathRegistrations.keys())}}function dh(e=customElements){e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Wl),e.get(o.tagNames.state)||e.define(o.tagNames.state,ch)}function uh(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=uh(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)),Pu(),$d(),ih(),dh(o),function(){const e=globalThis;void 0===e[Ul]&&(e[Ul]=tc)}(),function(){const t=globalThis;void 0===t[e]&&(t[e]=vc)}(),bc()}();
2
2
  //# sourceMappingURL=auto.min.js.map