@wcstack/state 3.4.0 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.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={seen:!1},o={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},s=o;function r(){return s}const i=Symbol.for("wcstack.binder");const a=Symbol.for("wcstack.binder.pending"),l=Symbol.for("wcstack.binder.taken");function c(){const e=function(){const e=globalThis[i];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[a];return void 0===t&&(t=[],e[a]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[l];return void 0===t&&(t=new WeakSet,e[l]=t),t}();for(const t of n)o.add(t),e.bind(t)}const d=".",u="*",f=128,h=128,p=100,g="#",m="|",y="prevent",w="stop",b="ro",v=Object.freeze([y,w,b]),$="init",x="sync",S=Object.freeze([$,x]),I="else",P="...",k="on",A="eventToken",N="state",_="command",T="class",E="attr",C="style",M="$",O={};for(let e=0;e<f;e++)O[`${M}${e+1}`]=e;const R=Object.freeze(O),j="$connectedCallback",L="$disconnectedCallback",W="$renderedCallback",D="$errorCallback",B="$stateReadyCallback",z="$bindables",F="$commands",q="$commandTokens",V="$command",H="$eventTokens",U="$on",K="$stream",G="$watch",J="$scan",X="$recursion",Y="**",Q="$listKeys",Z="$streamStatus",ee="$streamError",te="data-wc-definition",ne=/\{\{\s*(.+?)\s*\}\}/g,oe=new Set(["SCRIPT","STYLE"]);function se(e){if(!s.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&&oe.has(e.parentElement.tagName)||re(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),se(t.content)}else se(e.content)}function re(e){const t=e.data;if(ne.lastIndex=0,!ne.test(t))return;ne.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=ne.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)}function ie(e){throw new Error(`[@wcstack/state] ${e}`)}const ae=new Map;let le=0;function ce(e){let t=ae.get(e);if(void 0!==t)return t;-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] "${e}" uses "${Y}", 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.`);const n=function(e){let t=1;for(let n=0;n<e.length;n++)e[n]===d&&t++;return t}(e);return n>512&&ie(`[wcs/binding-syntax] "${e}" has ${n} path segments — the limit is 512. Every prefix of a path is interned, so the cost grows with the square of the depth.`),t=Object.freeze(new de(e)),ae.set(e,t),t}class de{id=++le;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:ce(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],d=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===u&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),c.push(t(h)),d.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=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=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=d,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function ue(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 fe(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ue(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const he=" Validate statically: npx @wcstack/lint <file>.",pe=new Set(["if","elseif","else","for"]);function ge(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}function me(e){if(0===e.length)return"";let t="";for(let n=0;n<e.length;n++){const o=e[n];n>0&&(t+="|"),t+=`${o.filterName}(${ge(o.args,o.literals??o.args)})`}return t}const ye=new Map([["not",()=>e=>!e]]),we=new Map([["not",[0,0]]]),be={input:new Map,output:new Map},ve={input:new Map,output:new Map},$e={input:new Map,output:new Map},xe=new Map;function Se(e,t,n,o){const s=be[e],r=ve[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}const i=o??{},a=$e[e];for(const[e,n]of[...a])Object.prototype.hasOwnProperty.call(t,n)&&i[e]!==n&&a.delete(e);for(const e of Object.keys(i))a.set(e,i[e]);xe.clear()}function Ie(e,t,n,o=t){const s=$e[n].get(e)??e,r=`${s}${ge(t,o)}:${n}`,i=xe.get(r);if(void 0!==i)return i;const a=be[n].get(s)??ye.get(s);if(void 0===a){const t=0===be[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";ie(`[wcs/filter-unknown] filter not found: ${e}.${fe(e,function(e){return[...new Set([...ye.keys(),...be[e].keys()])]}(n))}${t}${he}`)}const l=ve[n].get(s)??we.get(s);void 0!==l&&(t.length<l[0]||t.length>l[1])&&ie(t.length<l[0]?`[wcs/filter-arity] filter "${e}" requires at least ${l[0]} argument(s) (${t.length} given).${he}`:`[wcs/filter-arity] filter "${e}" accepts at most ${l[1]} argument(s) (${t.length} given).${he}`);const c=a(t,o);return xe.set(r,c),c}function Pe(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 ke=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function Ae(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:ke.test(e)?Number(e):e)}function Ne(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=Pe(o,i,a);t.push(e),n.push(Ae(e,r)),o="",r=!1,i=-1,a=-1};for(let t=0;t<e.length;t++){const n=e[t];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&ie(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${he}`);const c=Pe(o,i,a);return(c||r)&&(t.push(c),n.push(Ae(c,r))),{args:t,literals:n}}const _e=e=>e.trim(),Te=e=>"'"===e||'"'===e;function Ee(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if(Te(s))n=s;else if(s===t)return o}return-1}function Ce(e,t){const n=[];let o=null,s=0;for(let r=0;r<e.length;r++){const i=e[r];null!==o?i===o&&(o=null):Te(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}function Me(e,t,n){const o=n??e.join("|");return e.map(e=>{const n=Ee(e,"(");let s=function(e,t){let n=null,o=-1;for(let s=0;s<e.length;s++){const r=e[s];null!==n?r===n&&(n=null):Te(r)?n=r:r===t&&(o=s)}return o}(e,")");if(-1===s&&(s=e.lastIndexOf(")")),-1!==n&&-1===s&&ie(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${e}".${he}`),-1!==s&&-1===n&&ie(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${e}".${he}`),-1!==s&&s<n&&ie(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${e}".${he}`),-1!==s&&e.slice(s+1).trim().length>0){const t=e.slice(s+1).trim();ie(`[wcs/binding-syntax] "${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,s+1)}|${t}").${he}`)}const r=(-1===n?e:e.substring(0,n)).trim();if(0===r.length&&ie(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${he}`),r.includes(g)){const[e,n]=r.split(g);ie("input"===t?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${g}${n}" comes before the input filters, not inside one — write "<property>${g}${n}|${e}".${he}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${g}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${e}" here.${he}`)}if(-1===n)return{filterName:r,args:[],literals:[]};return{filterName:r,...Ne(e.substring(n+1,s))}})}const Oe=new Map;function Re(e){const t=Ee(e,m);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Oe.has(s)?r=Oe.get(s):(o=Ce(s,m).map(_e),r=Me(o,"input",e),Oe.set(s,r))):n=e.trim();const i=n.split(g).map(_e);i.length>2&&ie(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${g}" — write "${i[0]}${g}${i.slice(1).join(",")}".${he}`);const[a,l]=i,c=a.split(d).map(_e);c.length>1&&""===c[0]||0!==a.length&&!c.some(e=>0===e.length)||ie(`[wcs/binding-syntax] "${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${he}`);return{propName:a,propSegments:c,propModifiers:l?l.split(",").map(_e):[],inFilters:r}}const je=new Map;function Le(e){const t=Ee(e,m);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=Ce(s,m).map(_e),r=Me(o,"output",e),je.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&ie(`"${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.`);const i=n,a=i.startsWith(d),l=a?i.slice(1):i;(l.length>0&&l.split(d).some(e=>0===e.length)||!a&&0===l.length)&&ie(`[wcs/binding-syntax] "${e}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).${he}`);return{statePathName:i,statePathInfo:ce(i),outFilters:r}}const We=new Set([I,"if","elseif","for",P]),De=new Set([T,E,C,_,A,N]);function Be(e){const[...t]=function(e){return Ce(e,";")}(e).map(_e).filter(e=>e.length>0),n=t.map(e=>{const t=Ee(e,":");-1===t&&ie(`[wcs/binding-syntax] Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.${he}`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(g)[0].split(m)[0].trim();if(s!==n&&We.has(s)&&ie(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${he}`),n===I){o.length>0&&ie(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${he}`);const t=ce("#else");return{propName:I,propSegments:[I],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===P){0===o.length&&ie(`[wcs/binding-syntax] Invalid spread binding "${e}": spread target path is required.${he}`);const t=Le(o);return t.outFilters.length>0&&ie(`[wcs/binding-syntax] Invalid spread binding "${e}": filters are not allowed on spread targets.${he}`),{propName:P,propSegments:[P],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Le(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Le(o);return{...Re(n),...e,bindingType:s}}{const e=Le(o),t=Re(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||De.has(o[0]))&&ie(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...De].join(", ")}).${he}`),{...t,propName:o.join(d),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===A||t.propSegments[0].startsWith(k)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>pe.has(e.bindingType))&&ie(`[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">).${he}`)}return n}const ze=new WeakMap,Fe=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),qe=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Ve(e){const t=ze.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),o=qe.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return Fe.has(r)?(ze.set(e,o[2]),o[2]):null}function He(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Le(e),bindingType:"text"}}const Ue=new WeakMap,Ke=new WeakSet;let Ge=0;async function Je(e){const t=function(e){let t,n=Ue.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++Ge,promise:o,resolve:t},Ue.set(e,n),Ke.has(e)&&n.resolve(),n}(e);await t.promise}function Xe(e){const t=Ue.get(e);void 0===t?Ke.add(e):t.resolve()}const Ye=new WeakMap;function Qe(e){const t=Ye.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{Ye.set(e,n)}}function Ze(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function et(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Ze(t);if(void 0!==n)return Ze(n)}return Ze(globalThis.customElements)}function tt(e,t){e.upgrade?.(t)}function nt(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=it(s.properties,ot);if(null===r)return null;const i=void 0===s.inputs?new Map:it(s.inputs,st);if(null===i)return null;const a=void 0===s.commands?new Map:it(s.commands,rt);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function ot(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 st(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 rt(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 it(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 at(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ce(n),inFilters:[],outFilters:[],bindingType:"prop"}}function lt(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function ct(e,t,n={}){const o=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&&ie("Spread binding requires an element node.");const t=e,s=Qe(t);null===s&&ie(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=et(t);null===a&&ie(`CustomElementRegistry is unavailable for <${s}>.`);if(void 0===a.get(s)){o||ie(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}tt(a,t);const l=nt(t);null===l&&ie(`Spread binding "${n.statePathName}" requires <${s}> 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=at(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=at(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=lt(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=lt(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(s.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 dt(e,t){let n=e;for(let e=0;e<t.length;e++){let o=t[e];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function ut(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:Ie(s.filterName,s.args,t,r)})}return n}function ft(e){return{...e,inFilters:ut(e.inFilters,"input"),outFilters:ut(e.outFilters,"output")}}const ht=new WeakMap;function pt(e){return ht.get(e)||null}function gt(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(s.bindAttributeName)}function mt(e){const t=[],n=e.querySelectorAll(`${s.tagNames.state}[bind-component]`);for(const o of n){if(!gt(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function yt(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 wt(e){const t=[],n=mt(e),o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==Ve(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();){const e=o.currentNode;n.length>0&&yt(e,n)||t.push(e)}return t}const bt=new WeakSet;function vt(e,t,n,o){const s=ct(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Qe(e):null;return null===n&&ie("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}bt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=ut(o.inFilters,"input"),s=ut(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:e});else{const r=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:r})}}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){ht.set(e,t)}(e,r),Xe(e),{bindings:r,deferred:null}}function $t(e,t){return xt(wt(e),t)}function xt(e,t){const n=[],o=[];for(const s of e){if(bt.has(s))continue;const e=vt(s,oc(s),{allowDeferred:!0},t);null===e.deferred?n.push(...e.bindings):o.push(e.deferred)}return[e,n,o]}function St(e){bt.add(e)}function It(e){const{node:t,parseResults:n,transform:o}=e;!function(e){bt.delete(e)}(t);return vt(t,n,{allowDeferred:!1},o).bindings}const Pt=new WeakMap;let kt=null;function At(e){let t=e;for(;t;){const e=Pt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==kt&&t instanceof ShadowRoot&&(n=kt(t)),t=n}return null}function Nt(e,t){null!==t?Pt.set(e,t):Pt.delete(e)}let _t=null;let Tt=0;function Et(){return`u${(Tt++).toString(36)}`}let Ct=0,Mt=0;const Ot=Symbol("wcs.listIndex.noValue");class Rt{uuid=Et();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;cacheStamp=0;ref;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ot,this._index=t,this._version=Ct,this._chainGeneration=Mt}get index(){return this._index}set index(e){this._index=e,this._version=++Ct,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}set homeParentListIndex(e){this._homeParentListIndex=e}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=Ct),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Mt||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Mt),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Ct,Mt++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function jt(e,t,n=e){return new Rt(e,t,n)}function Lt(e,t){e.reparent(t)}function Wt(e){return e.homeParentListIndex}function Dt(e,t){e.homeParentListIndex=t}function Bt(e){return e?.cacheStamp}function zt(e,t){const n=e,o=n.value,s=o!==Ot&&!Object.is(o,t);return o!==t&&(Ft.get(o)?.delete(n.ref),function(e,t){if("object"!=typeof e||null===e||null===t.parentListIndex)return;let n=Ft.get(e);void 0===n?(n=new Set,Ft.set(e,n)):n.size>=(qt.get(n)??8)&&(Vt(n,t,!0),qt.set(n,2*n.size+8));n.add(t.ref??=new WeakRef(t))}(t,n)),n.value=t,s}const Ft=new WeakMap,qt=new WeakMap;function Vt(e,t,n=!1){const o=[];return e?.forEach(s=>{const r=s.deref();void 0===r||n&&Ut(r)?e.delete(s):r!==t&&o.push(r)}),o}const Ht=new WeakSet;function Ut(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ht.has(t))return!0;return!1}function Kt(e){return e.value}function Gt(e,t){const n=e.value;return n!==Ot&&n===t.value}let Jt=0;const Xt=new WeakSet;function Yt(e){Xt.add(e)}function Qt(e){return Xt.has(e)}const Zt=new WeakMap;function en(e){return Ht.has(e)}const tn=new WeakMap;const nn=new WeakMap,on=new WeakMap;function sn(e,t){return!0===tn.get(t)?.has(e)}function rn(e,t){return sn(e,t)||Ut(t)}const an=new WeakMap;function ln(e){an.delete(e)}function cn(e,t,n){const o=Object(Kt(t)),s=Kt(n);for(const t in s)if(s[t]===e&&o[t]!==e)return!1;return!0}function dn(e,t){return!rn(e,t)&&an.get(t)!==Jt}const un=new WeakMap,fn=new WeakMap;const hn=new WeakSet;function pn(e,t){const n=(o=e,Vt(Ft.get(o.value),o));var o;if(0===n.length)return n;const s=new Set(Zt.get(t()));return n.filter(t=>t.position===e.position&&!s.has(t)&&!Ut(t))}function gn(e,t,n){const o=Wt(t),s=t.parentListIndex;return null!==o&&o!==s&&!rn(e,o)&&cn(e,o,s)?o:function(e,t,n,o){return null!==t&&null!==o&&o!==n&&!!Ht.has(t)&&!(!dn(e,o)||o.position!==t.position)&&!sn(e,t)&&Gt(o,t)}(e,o,s,n)||function(e,t,n){return t!==n&&null!==t&&null!==n&&t.position===n.position&&rn(e,t)&&dn(e,n)}(e,s,n)?n:null}function mn(e){const t=Zt.get(e);return void 0===t?null:t}function yn(e,t){const n=Zt.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o&&!Qt(e)){const s=null!==t&&o.parentListIndex!==t&&an.get(t)!==Jt,r=gn(e,o,t);if(null!==r&&hn.has(e)){hn.delete(e);const t=[...e];Yt(t),Zt.set(t,n),Sn(e,t);const o=n.map((t,n)=>{const o=jt(r,n);return zt(o,e[n]),o});return Zt.set(e,o),o}if(null!==r)for(const e of n)Lt(e,r);else if(s){!function(e,t){let n=un.get(e);void 0===n?(n=new Set,un.set(e,n)):n.size>=(fn.get(e)??8)&&(n.forEach(t=>{rn(e,t)&&n.delete(t)}),fn.set(e,2*n.size+8));for(const e of t)n.add(e)}(e,[o.parentListIndex,t]);const s=o.parentListIndex;if(null!==s&&s.position===t.position&&!cn(e,s,t)&&cn(e,t,s))for(const e of n)Lt(e,t)}}return n}const wn=new WeakSet;function bn(e){wn.delete(e)}function vn(e,t,n=!1){null!==t?(n?wn.add(t):bn(t),Zt.set(e,t)):Zt.delete(e)}const $n=new WeakMap;function xn(e){let t=$n.get(e);return void 0===t&&(t={value:e},$n.set(e,t)),t}function Sn(e,t){const n=$n.get(e);void 0!==n&&(n.value=t,$n.delete(e))}const In=new WeakMap,Pn=new WeakMap,kn=new Set,An=new WeakMap,Nn=new WeakMap;function _n(e){const t=e.absolutePathInfo.stateElement;let n=Pn.get(t);return void 0===n&&(n=new WeakMap,Pn.set(t,n)),n}function Tn(e){return In.get(e)??[]}function En(e,t){const n=In.get(e);In.set(e,t),Nn.delete(e);const o=_n(e);n!==t&&void 0!==n&&o.get(n).delete(e);const s=o.get(t);void 0===s?o.set(t,new Set([e])):s.has(e)||(s.size>=(An.get(s)??8)&&(s.forEach(e=>{Cn(e.listIndex)&&s.delete(e)}),An.set(s,Math.max(8,2*s.size))),s.add(e))}function Cn(e){for(let t=e;null!==t;t=t.parentListIndex)if(en(t))return!0;return!1}function Mn(e,t){const n=_n(e).get(t);return void 0===n?kn:(n.forEach(e=>{Cn(e.listIndex)&&n.delete(e)}),n)}function On(e,t){return!Nn.has(e)&&(Nn.set(e,t),!0)}function Rn(e){return In.has(e)}const jn=new WeakMap;let Ln=null,Wn=0;function Dn(e){return jn.get(e)??[]}function Bn(e,t){null===Ln?jn.set(e,t):Ln.set(e,t)}function zn(){Wn++,null===Ln&&(Ln=new Map)}function Fn(){if(0!==Wn&&(Wn--,!(Wn>0||null===Ln))){for(const[e,t]of Ln)jn.set(e,t);Ln=null}}function qn(e){return(Ln?.has(e)??!1)||jn.has(e)}const Vn=Symbol("$$setLoopContext"),Hn=Symbol("$$getByAddress"),Un=Symbol("$$hasByAddress"),Kn=Symbol("$$connectedCallback"),Gn=Symbol("$$disconnectedCallback"),Jn=Symbol("$$updatedCallback"),Xn=Symbol("$$errorCallback"),Yn=new WeakMap,Qn=new WeakMap;class Zn{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function eo(e,t){if(null===t){let t=Qn.get(e);return void 0!==t||(t=new Zn(e,null),Qn.set(e,t)),t}{let n=Yn.get(t);void 0===n&&(n=new WeakMap,Yn.set(t,n));let o=n.get(e);return void 0!==o||(o=new Zn(e,t),n.set(e,o)),o}}const to=new WeakMap;function no(e,t){let n=to.get(e);void 0===n&&(n=new Map,to.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new oo(e,t)),n.set(t,o)),o}class oo{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function so(e,t){return eo(no(e,t.pathInfo),t.listIndex)}function ro(e,t,n){return eo(no(e,t),n)}const io=new WeakMap;function ao(e,t){null===t?io.delete(e):io.set(e,t)}function lo(e){return io.get(e)||null}const co=new Map;function uo(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=co.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,co.set(s,r),r}function fo(e,t,n){return t<0||t>=n?null:e.at(t-n)}function ho(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const po=new WeakMap;function go(e){const t=At(e.node);if(null===t)return null;let n=po.get(t);if(void 0===n)n=new WeakMap,po.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=uo(t.pathInfo,e.statePathInfo);return n>0&&(o=fo(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const mo=new WeakMap;function yo(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=lo(n);null===t?ie(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function wo(e,t){let n=null;if(n=mo.get(e)||null,null!==n)return n;const o=yo(e,t),s=go(e),r=Jl(o);return null===r&&ie("No state tree found on this root for binding."),n=ro(r,e.statePathInfo,s),mo.set(e,n),n}function bo(e){mo.delete(e)}const vo=new WeakMap;function $o(e,t){const n=vo.get(e);void 0===n?vo.set(e,t):n instanceof Set?n.add(t):n!==t&&vo.set(e,new Set([n,t])),null!==_t&&_t({type:"state:binding-added",absoluteAddress:e,binding:t})}function xo(e,t){const n=vo.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&vo.delete(e),null!==_t&&_t({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const So=new WeakMap;function Io(e){const t=vo.get(e);return void 0!==t?t:null!==e.listIndex?So.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const Po=new WeakMap,ko=new WeakMap;class Ao{pathInfo;listIndex;_parentAddress;_rowAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t,this._rowAddress=null!==t&&e.lastSegment===u}get parentAddress(){const e=this._parentAddress;if(void 0!==e&&(!this._rowAddress||e.listIndex===this.listIndex.parentListIndex))return e;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let n=null;n=this.pathInfo.segments[this.pathInfo.segments.length-1]===u?this.listIndex?.parentListIndex??null:this.listIndex;const o=_o(t,n);return void 0!==e&&!No(o,this.listIndex)&&No(e,this.listIndex)?e:this._parentAddress=o}}function No(e,t){const n=e.pathInfo;let o=Kt(e.listIndex);for(const e of n.segments.slice(n.wildcardPositions[n.wildcardCount-1]+1))o=Object(o)[e];return mn(o)?.[t.index]===t}function _o(e,t){if(null===t){let t=ko.get(e);return void 0!==t||(t=new Ao(e,null),ko.set(e,t)),t}{let n=Po.get(t);void 0===n&&(n=new WeakMap,Po.set(t,n));let o=n.get(e);return void 0!==o||(o=new Ao(e,t),n.set(e,o)),o}}const To=new WeakMap;function Eo(e){let t=null;if(t=To.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=go(e);null===n&&ie(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=_o(e.statePathInfo,n)}else t=_o(e.statePathInfo,null);return To.set(e,t),t}function Co(e){To.delete(e)}function Mo(){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 Oo=new Map,Ro=Mo();function jo(e,t){const n=me(e.inFilters);return`${e.statePathName}::${t}::${n}`}function Lo(e){let t="input";for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}function Wo(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const o=Lo(e),s=jo(e,o);let r=Oo.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=Jl(o.getRootNode());null===i&&ie("No state tree found on this root for two-way binding.");const a=At(o);i.createState("writable",e=>{e[Vn](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]:[]})})},Oo.set(s,r)),e.node.addEventListener(o,r),Ro.add(s,e),!0}var t,n;return!1}function Do(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Bo(e,t){console.error(`[wcstack/state] ${t} rejected.`,e)}function zo(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Do(e)&&Promise.resolve(e).catch(e=>Bo(e,t))}class Fo{_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)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,e)}return t}}class qo extends Fo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==_t&&_t({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Vo=new WeakMap;function Ho(e,t){let n=Vo.get(e);void 0===n&&(n=new Map,Vo.set(e,n));let o=n.get(t);return void 0===o&&(o=new qo(t,e),n.set(t,o)),o}const Uo=new WeakMap;function Ko(e){if(e.propSegments[0]!==A)return!1;const t=e.node,n=Qe(t),o=et(t);if(null!==n&&void 0===o?.get(n))return null===o&&ie(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Uo.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||ie('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Qe(e)?null:nt(e)}(t);null===r&&ie(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&ie(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${fe(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(y)&&e.preventDefault(),c.includes(w)&&e.stopPropagation();const n=Jl(t.getRootNode());null===n&&ie("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||ie(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${fe(l,n.eventTokenNames)}${he}`);const o=At(t);n.createStateAsync("writable",async t=>{zo(t[Vn](o,()=>{const s=null!==o?ho(o.listIndex,o.pathInfo.wildcardCount):[];return Ho(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Uo.set(e,{eventName:a,handler:d}),!0}class Go extends Fo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==_t&&_t({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Jo(e){return e instanceof Go}const Xo=new Map,Yo=Mo();function Qo(e){const t=e.propModifiers.filter(e=>e===y||e===w).sort().join(",");return`${e.statePathName}::${t}`}const Zo=(e,t,n)=>o=>{t.includes(y)&&o.preventDefault(),t.includes(w)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Jl(r);null===i&&ie("No state tree found on this root for event handler.");const a=At(s),l=e.startsWith(V+".");i.createStateAsync("writable",async t=>{const c=t[Vn](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const e=i.addressHooks;if(e){const t=e.handlerScope;for(let e=0;e<t.length;e++)c=t[e](i,s,r,a,c)}}const d=null!==a?ho(a.listIndex,c):[];if(l){const s=t[Hn](_o(n,null));return Jo(s)||ie(`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&&ie(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});zo(c,`"${e}"`)}).catch(t=>Bo(t,`"${e}"`))};function es(e){return"event"===e.bindingType&&e.propName.startsWith(k)}function ts(e){if(!es(e))return!1;const t=Qo(e);let n=Xo.get(t);void 0===n&&(n=Zo(e.statePathName,e.propModifiers,e.statePathInfo),Xo.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Yo.add(t,e),!0}function ns(e){if(!es(e))return!1;const t=Qo(e),n=Xo.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Yo.countOf(t)&&(Yo.remove(t,e)&&Xo.delete(t),!0)}const os=new Map,ss=Mo();function rs(e,t){const n=me(e.inFilters);return`${e.statePathName}::${t}::${n}`}function is(e){let t="input";for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}function as(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const o=is(e),s=rs(e,o);let r=os.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=Jl(o.getRootNode());null===r&&ie("No state tree found on this root for two-way binding.");const i=At(o);r.createState("writable",e=>{e[Vn](i,()=>{e[t]=s})})},os.set(s,r)),e.node.addEventListener(o,r),ss.add(s,e),!0}var t,n;return!1}const ls=new Set(["radio","checkbox"]),cs=new Set(["value","valueAsNumber","valueAsDate"]);function ds(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(ls.has(e)&&"checked"===t)return!0;if(cs.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Qe(n);if(null!==s){const e=et(n)?.get(s);void 0===e&&ie(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=nt(n);if(o?.knownProperties.has(t))return!0}return!1}let us=1,fs=1,hs=1;const ps=new WeakMap;function gs(e,t,n){let o=ps.get(e);void 0===o&&(o=new Map,ps.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=us++,o.set(s,r)),r}function ms(e,t){return"to-element"===t?2*e:2*e+1}const ys=new Set;function ws(e){return{transactionId:fs++,originBindingId:e,visitedEdges:ys,hop:0}}function bs(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 vs=null;function $s(){return vs}function xs(e,t){const n=vs;vs=e;try{return t()}finally{vs=n}}const Ss=[];let Is=0;function Ps(e,t,n,o,s=!1){Is=s?2:1;try{e.createState("writable",e=>{e[Vn](t,()=>{e[n]=o})})}finally{Is=0}}const ks=new Map,As=Mo(),Ns=new WeakMap,_s=e=>e.detail,Ts=new WeakMap;const Es=new WeakMap;let Cs=0;const Ms=new WeakMap;function Os(e,t,n,o){const s=me(e.inFilters);return`${e.propName}::${e.statePathName}::${t}::${s}::${function(e){if(null===e)return"n";let t=Es.get(e);return void 0===t&&Es.set(e,t=++Cs),`g${t}`}(n)}::${o?"o":"s"}`}const Rs=(e,t,n,o,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==o)l=o(i),o!==_s||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=Ts.get(e);void 0===r&&(r=new Set,Ts.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=Ns.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(s.enablePropagationContext){const n=gs(a,e,t),o=function(e,t){for(let n=Ss.length-1;n>=0;n--){const o=Ss[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==o&&Object.is(o.writtenValue,l))return s.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:o.transactionId,coveredBySameValueGuard:s.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==_t&&_t({type:"propagation:suppressed",reason:"confirmation",transactionId:o.transactionId,edgeId:ms(n,"to-state"),node:a,member:e}));const r=ms(n,"to-state"),i=$s();if(null!==i&&i.visitedEdges.has(r))return void(null!==_t&&_t({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=bs(i??ws(n),r)}const f=Jl(a.getRootNode());null===f&&ie("No state tree found on this root for two-way binding.");const h=At(a),p=()=>Ps(f,h,t,c,r);null!==u?xs(u,p):p()};function js(e){const t=Qe(e.node);if(null!==t){const n=et(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&ie(`CustomElementRegistry is unavailable for <${t}>.`))}if(ds(e.node,e.propName)&&-1===e.propModifiers.indexOf(b)){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Qe(e.node);if(null!==n){const o=et(e.node)?.get(n);void 0===o&&ie(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=nt(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}(e),n=function(e){if(null!==Qe(e.node)){const t=nt(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??_s}return null}(e),o=function(e){if(null===Qe(e.node))return!1;const t=nt(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}(e),s=Os(e,t,n,o);Ms.set(e,{key:s,eventName:t});let r=ks.get(s);void 0===r&&(r=Rs(e.propName,e.statePathName,e.inFilters,n,o),ks.set(s,r)),e.node.addEventListener(t,r),As.add(s,e)}}const Ls=new WeakSet;function Ws(e){Ls.add(e)}function Ds(e){return!!Ls.has(e)&&(Ls.delete(e),!0)}const Bs=new WeakMap;function zs(e,t){const n=Bs.get(e);return!(void 0===n||n<t)&&(n===t?Bs.delete(e):Bs.set(e,n-t),!0)}const Fs=new WeakSet;function qs(e){Fs.add(e)}function Vs(e){return!!Fs.has(e)&&(Fs.delete(e),!0)}let Hs=0;function Us(){Hs--}function Ks(){return Hs>0}class Gs{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 Js=new WeakMap;function Xs(e){let t=Js.get(e);return void 0===t&&(t=new Gs(e),Js.set(e,t)),t}const Ys=new Set([T,E,C,_]);function Qs(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!==$&&s!==x&&ie(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&ie(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Zs(e){return e.propModifiers.some(e=>e.includes("="))}const er=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),tr=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function nr(e,t){return"state"===e&&"call"===t?er:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function or(e){if(!s.enableDirectionalInitialSync)return Zs(e)&&ie("init=/sync= modifiers require enableDirectionalInitialSync."),er;const t=null===(n=Qs(e,$))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:ie(`Invalid init modifier value "${n}".`);var n;const o=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":ie(`Invalid sync modifier value "${e}".`)}(Qs(e,x));if("event"===e.bindingType)return null!==t&&"none"!==t&&ie("Event bindings only allow init=none."),"call"===o?tr:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(Ys.has(e.propSegments[0]))return nr("state",o);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&ie(`Binding type "${e.bindingType}" does not support init=${t}.`),nr(t??"state",o);const r=nt(e.node);if(null===r)return nr(t??"state",o);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||ie(`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)||ie(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==o||i||ie(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:o,observable:i,outputOnly:i&&!a}}function sr(e){let t=e.getRootNode();return t instanceof DocumentFragment&&!(t instanceof ShadowRoot)&&(t=lo(t)),null===t?null:Jl(t)}function rr(e,t){return"auto"!==t?t:function(e){const t=sr(e.replaceNode);null===t&&ie("No state tree found on this root for binding.");const n=Eo(e);let o=!1;return t.createState("readonly",e=>{o=e[Un](n)}),o}(e)?"state":"element"}let ir=0,ar=null,lr=0;const cr=["active","disposed","failed"],dr=new WeakMap,ur=new WeakMap,fr=new WeakMap,hr=new WeakMap,pr=new WeakMap,gr=new WeakMap;function mr(e,t){const n=gr.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):gr.set(e,new Set([n,t]))):gr.set(e,t)}function yr(e){return gr.has(e)}function wr(e,t){const n=gr.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function br(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))br(n,t)}function vr(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class $r{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||!zs(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)Ds(e)||br(e,e=>{wr(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Vs(e)&&!Ks()||br(e,e=>{wr(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&Rl(o)}}const xr=new WeakMap;function Sr(e){let t=xr.get(e);return void 0===t&&(t=new $r(e),xr.set(e,t)),t}function Ir(e){const t=me(e.inFilters),n=me(e.outFilters);return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function Pr(e,t,n){const o=Jl(yo(e,n));null===o&&ie("No state tree found on this root for binding.");const s=no(o,e.statePathInfo);return function(e,t,n){let o=So.get(e);void 0===o&&(o=new WeakMap,So.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!==_t&&_t({type:"state:binding-added",absoluteAddress:eo(e,t),binding:n})}(s,t,e),s}function kr(e,t){const n=wo(e,t);return $o(n,e),n}function Ar(e,t,n,o){null!==t?xo(t,e):function(e,t,n){const o=So.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!==_t&&_t({type:"state:binding-removed",absoluteAddress:eo(e,t),binding:n}))}(n,o,e),Co(e),bo(e)}function Nr(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class _r{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;disposedAt=0;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=this.rowOf(e),i=null===o?-1:o.bindings.indexOf(e);if(null!==o&&0===o.phases[i]){const t=o;this.observe(e.replaceNode),s.registerAddress&&null===t.addresses[i]&&null===t.patternPathInfos[i]&&(t.registered=!0,this.registerRowSlot(t,i));continue}const a=fr.get(e);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(e,s,n),r.push(e)):(this.observe(a.anchor),s.registerAddress&&null===a.address&&null===a.patternListIndex&&(a.options.registerAddress=!0,this.registerAddress(a)),"active"===a.phase&&this.settleInitialRecord(a),this.settleConnectedSnapshot(a))}return r.filter(e=>this.shouldApplyState(e))}activate(e,t){if(vr(t)&&Sr(t),null===this.rowPlan)for(const n of e){const e=fr.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(!s.enableDirectionalInitialSync)return Zs(e)&&or(e),!0;const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0){if(!t.registered)return!0;if(2===t.phases[n])return!1;const e=t.plan.slots[n];return 1&t.flags[n]?"state"===e.authority||!e.policy.outputOnly:(t.flags[n]|=1,"state"===e.authority)}}const n=fr.get(e);return void 0===n||n.session!==this||(!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority)))}getRecord(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0){let o=ur.get(t);void 0===o&&ur.set(t,o=[]);return{id:o[n]??(o[n]=++ir),info:e,generation:t.generation,phase:cr[t.phases[n]],teardowns:null}}const o=fr.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=fr.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(Nr(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=this.deferredByNode.get(e)??new Set,r=()=>s.delete(a)&&this.deferred.delete(a),i=()=>{const s=et(e);null===s&&ie(`CustomElementRegistry is unavailable for <${t}>.`),a.cancel=Xs(s).wait(t,()=>{if(r())try{tt(s,e),n()}catch(e){o(e)}},e=>{r()&&o(e)})},a={node:e,born:++lr,cancel:null,arm:()=>{if(null===a.cancel&&this.deferred.has(a))try{i()}catch(e){r(),o(e)}}},l=e.getRootNode();if(null!==ar||11===l.nodeType&&!vr(l)){if(null===ar){const e=ar=[];queueMicrotask(()=>{ar=null;for(let t=0;t<e.length;t++)e[t].arm()})}ar.push(a)}else i();return vr(l)&&Sr(l),mr(e,this),this.deferredByNode.set(e,s.add(a)),this.deferred.add(a),()=>{r(),a.cancel?.()}}disposeBinding(e){const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0)return void this.disposeRowSlot(t,n)}const n=fr.get(e);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(e){for(let t=0;t<e.length;t++)this.disposeBinding(e[t]);if(!(this.rows.size>0))for(const e of Array.from(this.deferred))e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}destroyRow(e){const t=e.length>0?this.rowOf(e[0]):null;null!==t?(this.destroyRowRecord(t),this.rows.delete(t)):this.destroyRecords()}destroyRowRecord(e){for(let t=0;t<e.bindings.length;t++){const n=e.addresses[t];null!==n&&(xo(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){this.disposedAt=lr;for(const e of Array.from(this.rows))for(let t=0;t<e.bindings.length;t++)this.disposeRowSlot(e,t);for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))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(){this.disposedAt=lr;for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(xo(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.rows)for(let n=0;n<t.bindings.length;n++)0===t.phases[n]&&e(t.bindings[n].node);for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.rows)for(let n=0;n<t.bindings.length;n++){if(0!==t.phases[n])continue;if(null===t.addresses[n]&&null===t.patternPathInfos[n])continue;const o=t.bindings[n];this.unregisterRowSlot(t,n),this.registerRowSlot(t,n),this.shouldApplyState(o)&&e.push(o)}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?wo(n):null;if(Ar(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=wo(n);e!==o&&Rn(o)&&En(e,Tn(o)),e!==o&&qn(o)&&Bn(e,Dn(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return vr(t)?t:null}(e);null!==t&&Sr(t)}handleMutations(e,t,n){for(const n of t)br(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)br(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&Rl(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);this.deferredByNode.get(e)?.forEach(e=>{e.cancel?.(),e.cancel=null,this.deferred.delete(e)})}handleAddedNode(e,t){this.deferredByNode.get(e)?.forEach(e=>{e.born<=this.disposedAt||(this.deferred.add(e),e.arm())});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=fr.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||n.pendingDefinitions>0&&n.generation>this.disposedAt)&&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=pr.get(t);void 0===e&&(e=Ir(t),pr.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;mr(n,this);const o=this.knownMapFor(n);let s=pr.get(e);void 0===s&&(s=Ir(e),pr.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=e.slots,o=t.length,s={id:++ir,session:this,generation:++lr,plan:e,bindings:t,registered:!1,phases:new Array(o).fill(0),flags:new Array(o).fill(0),addresses:new Array(o).fill(null),patternPathInfos:new Array(o).fill(null),patternListIndexes:new Array(o).fill(null)};this.rows.add(s);for(let e=0;e<o;e++){const o=t[e],r=o.replaceNode;if(mr(r,this),this.addKnownRowBinding(r,o,e),dr.set(o,s),n[e].isEvent){let t=!1;try{t=ts(o)}catch(t){throw s.phases[e]=2,t}t&&(s.flags[e]|=2)}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++lr,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){let n=!1;try{n=ts(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}n&&(o.flags[e]|=2)}this.registerRowSlot(o,e,n)}}rowOf(e){const t=dr.get(e);return void 0!==t&&t.session===this?t:null}registerRowSlot(e,t,n){if(null!==e.addresses[t]||null!==e.patternPathInfos[t])return;const o=e.bindings[t],s=go(o);null!==s?(e.patternPathInfos[t]=Pr(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=kr(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(Ar(e.bindings[t],n,o,e.patternListIndexes[t]),e.addresses[t]=null,e.patternPathInfos[t]=null,e.patternListIndexes[t]=null)}disposeRowSlot(e,t){if(1!==e.phases[t]){e.phases[t]=1,this.runRowSlotTeardowns(e,t);for(let t=0;t<e.phases.length;t++)if(0===e.phases[t])return;this.rows.delete(e)}}runRowSlotTeardowns(e,t){try{this.unregisterRowSlot(e,t)}catch{}if(2&e.flags[t]){e.flags[t]&=-3;try{ns(e.bindings[t])}catch{}}}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:++ir,info:e,generation:++lr,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};fr.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;ts(t)?e.eventAttached=!0:t.propSegments[0]!==A?(as(t)&&Nr(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const t=is(e),n=rs(e,t),o=os.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==ss.countOf(n)&&(ss.remove(n,e)&&os.delete(n),!0))}return!1}(t)),Wo(t)&&Nr(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const t=Lo(e),n=jo(e,t),o=Oo.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Ro.countOf(n)&&(Ro.remove(n,e)&&Oo.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(s.enableDirectionalInitialSync&&ds(t.node,t.propName)&&-1===t.propModifiers.indexOf(b)){const n=function(e,t,n){let o=Ns.get(e);void 0===o&&(o=new Map,Ns.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&&Ns.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});Nr(e,n)}js(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Ko(t)&&Nr(e,()=>function(e){if(e.propSegments[0]!==A)return!1;const t=Uo.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Uo.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Qe(e.info.node);if(null===n)return void t();const o=et(e.info.node);if(null===o&&ie(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation;Nr(e,this.deferUntilDefined(e.info.node,n,()=>{this.isAlive(e,s)&&(t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e)))},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))}))}settleInitialRecord(e){if(s.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=or(e.info),n=rr(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 Hs++;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,Us()),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=sr(e.node);null===o&&ie("No state tree found on this root for initial binding sync."),Ps(o,At(e.node),e.statePathName,n)}(e.info,r))}settleConnectedSnapshot(e){if(s.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=go(n);if(null!==o?(e.patternPathInfo=Pr(n,o,t),e.patternListIndex=o):e.address=kr(n,t),!e.options.registerPathInfo)return;const s=Jl(n.replaceNode.getRootNode());null===s&&ie("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&&fr.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,Us());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{Ar(t,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=Ms.get(e);if(void 0===t)return;Ms.delete(e);const n=ks.get(t.key);void 0!==n&&(e.node.removeEventListener(t.eventName,n),As.remove(t.key,e)&&ks.delete(t.key))}(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{ns(t)}catch{}}}}function Tr(e){let t=hr.get(e);return void 0===t&&(t=new _r(e),hr.set(e,t)),t}function Er(e){return fr.get(e)?.session??dr.get(e)?.session??null}let Cr=null;function Mr(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const Or=Object.freeze([]);const Rr=new WeakMap;const jr=new WeakMap;function Lr(e){return jr.get(e)??[]}function Wr(e,t){jr.set(e,t)}const Dr=new WeakMap;function Br(e){return Dr.get(e)??[]}function zr(e,t){Dr.set(e,t)}function Fr(e,t){const n=Br(e);for(const e of n)Nt(e,t)}const qr=new WeakMap;function Vr(e){return qr.get(e)??[]}function Hr(e,t){qr.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});const Ur=new WeakMap,Kr=new WeakSet;function Gr(e,t){if(null===t)Ur.delete(e);else{Ur.set(e,t);const{stateElement:n,pathInfo:o}=e.absolutePathInfo;if(o.wildcardCount>0){for(let e=o.parentPathInfo;null!==e&&e.wildcardCount===o.wildcardCount&&!Kr.has(e);e=e.parentPathInfo)Kr.add(e);n.setPathInfo(o.lastWildcardPath,"prop","internal")}}}function Jr(e){const t=Ur.get(e);t&&(t.dirty=!0),null!==e.listIndex&&Kr.has(e.absolutePathInfo.pathInfo)&&e.listIndex.cacheStamp++}const Xr=Symbol.for("wcstack.transition-runner");function Yr(e){const t=globalThis[Xr];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 Qr(e,t,n){const o=Yr(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Zr=[],ei=[];let ti=-1,ni=0,oi=!1;function si(e){ei.includes(e)||ei.push(e)}function ri(e,t=0){const n=Zr.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Zr.push(o):Zr.splice(n,0,o)}function ii(e){queueMicrotask(()=>{throw e})}class ai{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<ei.length;t++)ei[t](e);ti>ni&&(ni=ti),ti<0&&(oi=!0);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(){zn(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],Jt++,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=[]){let o=oi?0:ni;ni=0,oi=!1;const s=new Map,r=new Set;for(let t=0;t<e.length;t++){const n=e[t],o=s.get(n.absoluteAddress);null!==_t&&null!=o&&null!==n.context&&o.transactionId!==n.context.transactionId&&_t({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:o.transactionId,winnerTransactionId:n.context.transactionId}),s.set(n.absoluteAddress,n.context),r.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];s.has(t)||s.set(t,null)}const i=[],a=new Map;s.forEach((e,t)=>{if(null!==e&&e.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),void(null!==_t&&_t({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=Io(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(i.push(t),null!==e&&a.set(t,e));else!1!==n.replaceNode.isConnected&&(i.push(n),null!==e&&a.set(n,e))});try{const e=()=>{ti=o+1;try{a.size>0?Rl(i,a):Rl(i)}finally{ti=-1}};if(o>p&&i.length>0){if(101===o++){const e=[...new Set(Array.from(r,e=>e.absolutePathInfo.pathInfo.path))];console.error("[@wcstack/state] render chain depth limit exceeded; bindings for this batch were not applied.",{maxDepth:p,paths:e}),null!==_t&&_t({type:"state:render-chain-limit",maxDepth:p,paths:e})}}else if(t()||0===i.length)e();else{const t=Qr("state",e);void 0!==t&&t.catch(ii)}}finally{Fn(),ti=o,function(e){for(const t of Zr.slice())t.listener(e)}(r),ti=-1}}}const li=new ai;function ci(){return li}const di=new WeakMap,ui=new WeakMap,fi=new WeakMap,hi=new WeakMap;let pi=!1;const gi=new WeakMap;function mi(e){const t=e.absolutePathInfo.stateElement;let n=gi.get(t);void 0===n&&gi.set(t,n=new Set),n.add(e)}function yi(e){const t=gi.get(e);return void 0===t?null:(gi.delete(e),t)}const wi=new WeakMap,bi=new WeakMap,vi=new WeakMap,$i=new WeakMap,xi=new WeakMap,Si=[];function Ii(e,t){const n=Pi(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ce(t).cumulativePaths;if(o.length<2)return;let s=xi.get(e);void 0===s&&xi.set(e,s=new Map);for(let e=0;e<o.length-1;e++){let n=s.get(o[e]);void 0===n&&s.set(o[e],n=new Set),n.add(t)}}function Pi(e){let t=di.get(e);return void 0===t&&di.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function ki(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function Ai(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function Ni(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=ui.get(o);if(void 0===r&&ui.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(Ai(s,e,o),r.set(t,n),ki(s,n,o)),!1}return r.set(t,n),ki(s,n,o),!0}function _i(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):(o.push(n),!1)}function Ti(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&_i(fi,o.listIndex,r)&&function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){let n=vi.get(t);void 0===n&&vi.set(t,n=new Set),n.add(e)}}(o.listIndex),null!==r.levelListIndex&&_i(hi,r.levelListIndex,r))}function Ei(e,t,n,o,s){pi=!0;const r=Pi(e);Ii(e,t);Ti(r,t,s,o,Ni(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function Ci(e,t){Pi(e).tracked.add(t)}function Mi(e,t){return!0===di.get(e)?.byPath.has(t)||!0===wi.get(e)?.has(t)}function Oi(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(so(e.stateElement,_o(t,o)))}function Ri(e,t){if(!pi||e===t)return;const n=bi.get(e);if(void 0===n)return;bi.delete(e);const o=bi.get(t);bi.set(t,void 0===o?n:o.concat(n)),bn(t);for(const o of n){o.indexes=t;const n=Pi(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&&!en(e))for(const t of o.getters){const n=so(o.stateElement,_o(t,e));Jr(n),ci().enqueueAbsoluteAddress(n,null),mi(n)}}}function ji(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Li(e,t,n,o,s){const r=di.get(e),i=r?.byPath.get(t),a=wi.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return Si;const l=r.lastValue.has(t),c=r.lastValue.get(t);r.lastValue.set(t,s);const d=[],u=!n||!Object.is(o,s),f=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&ji(i.get(o),d),f&&ji(i.get(c),d),u&&ji(i.get(s),d)),void 0!==a)for(const e of a)n&&Oi(e,o,d),f&&Oi(e,c,d),u&&Oi(e,s,d);return d}function Wi(e,t){return!0===xi.get(e)?.has(t)}function Di(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Bi(e,t,n,o,s=!0){const r=ce(t).segments.length,i=[];for(const a of xi.get(e).get(t)){const t=ce(a).segments.slice(r);if(t.includes(u)){zi(e,a,i);continue}const l=s?Di(n,t):void 0;for(const n of Li(e,a,s,l,Di(o,t)))i.push(n)}return i}function zi(e,t,n){const o=di.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())ji(e,n);const s=wi.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)Oi(e,t,n)}function Fi(e){const t=hi.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function qi(e){const t=fi.get(e);if(void 0!==t){fi.delete(e),function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){const n=vi.get(t);void 0!==n&&(n.delete(e),0===n.size&&vi.delete(t))}}(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=ui.get(o),r=s.get(n);s.delete(n),Ai(di.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Fi(e)}}}function Vi(e){const t=$i.get(e);if(void 0!==t){$i.delete(e);for(const e of t){const t=wi.get(e.stateElement),n=t.get(e.path);n.delete(e),0===n.size&&t.delete(e.path);const o=bi.get(e.indexes);o.splice(o.indexOf(e),1),0===o.length&&bi.delete(e.indexes)}}}function Hi(e){if(!pi)return;qi(e),Vi(e);const t=vi.get(e);if(void 0!==t){vi.delete(e);for(const e of t)qi(e),Vi(e),vi.delete(e)}}function Ui(e,t,n){if(!pi)return;const o=hi.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=di.get(e),i=o.byPath.get(s);Ai(i,t,r),ki(i,n,r),ui.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Jr(r),ci().enqueueAbsoluteAddress(r,null),mi(r))}}const Ki=new WeakMap,Gi=Object.freeze([]),Ji=new Set,Xi=new WeakMap,Yi=new WeakMap;function Qi(e,t){Yi.set(e,new WeakRef(Object(t)))}function Zi(e){return Yi.get(e)?.deref()}function ea(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}function ta(e){!function(e){for(const t of e)Ht.add(t)}(e);for(const t of e)Hi(t)}function na(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Gi,s=Array.isArray(n)&&n.length>0?n:Gi,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Gi,o=Array.isArray(t)&&t.length>0?t:Gi;let s=Ki.get(n);return s&&s.get(o)||null}(o,s);if(r&&r.newIndexes===yn(s,e))return r;const i=yn(o,e)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Ji,deleteIndexSet:new Set(i),addIndexSet:Ji};let t=yn(s,e);if(null===t&&null!==e&&function(e,t){const n=un.get(e);for(const o of n??[])if(rn(e,o))n.delete(o);else if(o!==t)return!0;return!1}(o,e)&&Qi(s,o),0===o.length||null===t&&Zi(s)===o){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=jt(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:Ji,deleteIndexSet:new Set(i),addIndexSet:new Set(t)}}if(ea(o,s)&&(t??i)===i)return o!==s&&oa(o,i,e),a={oldIndexes:i,newIndexes:i,changeIndexSet:Ji,deleteIndexSet:Ji,addIndexSet:Ji};if(null!==t)return sa(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,l=new Set;let c=!1;for(let o=0;o<s.length;o++){const a=s[o],d=n.get(a),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=jt(e,o);t.push(n),l.add(n)}else{const e=i[u];c=!0,u!==o&&r.add(e),t.push(e)}}c&&oa(o,t,e);return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:l}}finally{void 0!==a&&(!function(e,t,n){let o=Ki.get(e);o||(o=new WeakMap,Ki.set(e,o)),o.set(t,n)}(o,s,a),bn(i),vn(s,a.newIndexes))}}(e,t,n);return function(e,t){const n=e.newIndexes;let o;for(let e=0;e<n.length;e++){if(n[e].index!==e){const t=n[e].index;n[e].index=e,Ui(n[e],t,e)}zt(n[e],t[e])&&(o??=[]).push(n[e])}const s=Xi.get(t);s?.[0]===Jt&&(o=o?s[1].concat(o):s[1]),o&&Xi.set(t,[Jt,o]),e.valueChangeIndexes=o}(o,Array.isArray(n)&&n.length>0?n:Gi),function(e){for(const t of e)Ht.delete(t)}(o.newIndexes),Zi(n)!==t&&(ta(o.deleteIndexSet),Ri(o.oldIndexes,o.newIndexes)),o}function oa(e,t,n){var o;if(o=e,hn.add(o),null!==n)for(const e of t)Dt(e,n)}function sa(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}}function ra(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 ia=new WeakMap;function aa(e){return ia.get(e)??null}function la(e,t){ia.set(e,t)}const ca=new WeakMap;const da=new WeakMap;function ua(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function fa(e,t,n,o,s){const r=function(e,t,n){let o=da.get(e);void 0===o&&da.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let e=0;e<t.length;e++){const d=t[e];if(!n.shouldApplyState(d))continue;const u=r[e];if(null===u||ua(u.prefixes,i)){Ml(d,s);continue}if(s.appliedBindingSet.has(d))continue;c||(l=s.state[Hn](o),c=!0);const f=u.tail;let h=l,p=!1;for(let e=0;e<f.length;e++){if(null==h){h=void 0;break}if(a&&!(f[e]in Object(h))){p=!0;break}h=h[f[e]]}p?Ml(d,s):(s.appliedBindingSet.add(d),Cl(d,s,h))}}function ha(e,t,n){Fr(e,t);const o=Lr(e),s=aa(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return ca.get(e)??null}(e);if(null!==r)return void fa(r,o,s,t,n)}for(const e of o){if(null===s){$o(wo(e),e)}(null===s||s.shouldApplyState(e))&&Ml(e,n)}e.spreads&&jl(e.spreads,t,s,o,Vr(e))}function pa(e){if(!e.mounted)return;const t=Lr(e),n=aa(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{xo(wo(o),o)}}!function(e){const t=Br(e);for(let e=0;e<t.length;e++)Nt(t[e],null)}(e)}function ga(){return Object.freeze(new Set)}const ma=new WeakMap,ya=ga();function wa(e,t){const n=ma.get(e);n?n.add(t):ma.set(e,new Set([t]))}function ba(e){const t=ma.get(e);return void 0!==t?t:ya}function va(e,t){const n=ma.get(e);n&&(n.delete(t),0===n.size&&ma.delete(e))}const $a=new Set(["if","elseif","else","for"]);class xa{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t;const n=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)n.push(t);this._childNodeArray=n,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];qs(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){qs(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=aa(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(Lr(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Ws(n),n.parentNode.removeChild(n))}const n=Lr(this);for(let e=0;e<n.length;e++){const t=n[e];$a.has(t.bindingType)&&ba(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=aa(this);null!==e&&(e.isRowSession?e.disposeBindings(Lr(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=Lr(this);for(let t=0;t<e.length;t++){const n=e[t];$a.has(n.bindingType)&&ba(n.node).forEach(e=>{e.unmount()}),Co(n),bo(n)}}unmount(){{const e=aa(this);null!==e&&(e.isRowSession?e.disposeBindings(Lr(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Ws(e),e.parentNode.removeChild(e));const e=Lr(this);for(let t=0;t<e.length;t++){const n=e[t];$a.has(n.bindingType)&&ba(n.node).forEach(e=>{e.unmount()}),Co(n),bo(n)}this._mounted=!1}}function Sa(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${s.commentForPrefix}|${s.commentIfPrefix}|${s.commentElseIfPrefix}|${s.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 Ia(e){return 1<<Math.min(e,31)}function Pa(e){let t=e.indexBits;if(void 0===t){t=0;for(const n of e.nodeInfos)for(const e of n.parseBindTextResults)e.statePathName in R&&(t|=Ia(R[e.statePathName])),"string"==typeof e.uuid&&(t|=Pa(nc(e.uuid)));e.indexBits=t}return t}function ka(e){return Pa(nc(e.uuid))}function Aa(e,t){return e.statePathName in R||$a.has(e.bindingType)&&0!==(ka(e)&t)}function Na(e,t){const n=document.createDocumentFragment(),o=new xa(n,t);return o._childNodeArray=e,o._firstNode=e.length>0?e[0]:null,o._lastNode=e.length>0?e[e.length-1]:null,o._mounted=!0,o}function _a(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=dt(o,s[e].nodePath);null===t&&ie(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),St(t),Xe(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,n){let o=Wl.get(n);void 0!==o&&o.currentRowPlan===e||(o=new _r,Wl.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new xa(o);return la(d,c),Wr(d,a),function(e,t){ca.set(e,t)}(d,n),Hr(d,l),zr(d,r),wa(e.node,d),d}function Ta(e){void 0!==e.uuid&&null!==e.uuid||ie("BindingInfo.uuid is null.");const n=nc(e.uuid);n||ie(`Fragment with UUID "${e.uuid}" not found.`);const o=!t()&&Sa(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==s.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=s.enableDirectionalInitialSync,n=[],o=e.nodeInfos;for(let t=0;t<o.length;t++){const s=o[t],r=dt(e.fragment,s.nodePath);if(null===r)return null;for(const e of s.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===_||s===A)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Qe(r))return null;if("prop"===o&&ds(r,e.propName))return null;const i=ft(e);let a;try{a=or({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:t,template:i,isEvent:"event"===o,isIndexBinding:e.statePathName in R,policy:a,authority:a.authority})}}return 0===n.length?null:{directional:t,slots:n}}(n)),null!==r)return _a(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o,s]=function(e,t){const n=[],o=[],s=[];for(const r of t){const t=dt(e,r.nodePath);if(null===t&&ie(`Node not found by path [${r.nodePath.join(", ")}] in fragment.`),bt.has(t))continue;const i=vt(t,r.parseBindTextResults,{allowDeferred:!0});null!==i.deferred&&(s.push(i.deferred),bt.add(t)),o.push(...i.bindings),n.push(t)}return[n,o,s]}(e,t),r=new _r,i=r.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:i,bindingSession:r,spreads:s}}(i,n.nodeInfos);o&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new xa(i,o);a.spreads.length>0&&(l.spreads=a.spreads),la(l,a.bindingSession),Wr(l,a.bindingInfos);const c="for"===e.bindingType?(d=e.statePathInfo.wildcardCount+1,2**Math.min(d,32)-1):-1;var d;const u=[];for(const e of a.bindingInfos)Aa(e,c)&&u.push(e);return Hr(l,u),zr(l,a.nodes),wa(e.node,l),l}const Ea=new WeakSet,Ca=Symbol.for("wcstack.state.view-transition-naming");function Ma(){const e=Yr("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Oa(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||Ea.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[Ca]??={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.`)):(Ea.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 Ra=new WeakMap,ja=new WeakMap,La=new WeakMap,Wa=new WeakMap,Da=new WeakMap,Ba=new WeakMap;function za(e,t,n,o){let s=Ba.get(e);void 0===s&&(s=[document.createComment(""),document.createComment("")],Ba.set(e,s));const[r,i]=s;r.data=`@@wcs-for-start:${o}`,i.data=`@@wcs-for-end:${o}`,e.mounted||(r.remove(),i.remove());const a=null===n?null:n.nextSibling;if(null===r.parentNode)t.insertBefore(r,a),t.insertBefore(i,a),e.mountAfter(r);else if(a!==r){let e=r;for(;e!==i;){const n=e.nextSibling;t.insertBefore(e,a),e=n}t.insertBefore(i,a)}return i}function Fa(e,t,n){!function(e,t,n){let o=ja.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ja.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function qa(e,t){Ra.set(e,t)}function Va(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 Ha(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)}const Ua=new Set(["if","elseif","else","for"]);function Ka(e,t){for(const n of Lr(e))if(t.appliedBindingSet.delete(n),Ua.has(n.bindingType))for(const e of ba(n.node))Ka(e,t)}function Ga(e,t,n){for(const o of Vr(e))if(Ua.has(o.bindingType)){if(o.statePathName in R&&Ml(o,t),0!==(ka(o)&n))for(const e of ba(o.node))e.mounted&&Ga(e,t,n)}else Ml(o,t)}function Ja(e){for(const t of Lr(e)){if(!Ua.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of ba(t.node))Ja(n),e&&n.mounted&&(pa(n),n.unmount(),va(t.node,n),Da.delete(t.node),ja.delete(t.node))}}function Xa(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ya(e,o,r){const i=Boolean(r);let a;const l=ba(e.node);a=0===l.size?Ta(e):l.values().next().value;const c=t(),d=e.uuid??"",u=e.bindingType;if(i||(s.debug&&console.log(`unmount if content : ${Xa(e)}`),c&&a.mounted&&(n.seen=!0),pa(a),a.unmount()),i){s.debug&&console.log(`mount if content : ${Xa(e)}`);const t=At(e.node);if(Fr(a,t),c){if(!a.mounted){const t=document.createComment(`@@wcs-${u}-start:${d}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),a.mountAfter(t);const n=document.createComment(`@@wcs-${u}-end:${d}:${e.statePathName}`),o=a.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}}else a.mountAfter(e.node);ha(a,t,o);const n=Ma();null!==n&&Oa(a,"branch",n)}}const Qa=new WeakMap;function Za(e){return Qa.get(e)??[]}const el=new Set;function tl(){el.clear()}const nl=Symbol.for("wcstack.trustedTypes.policy");function ol(){const e=globalThis[nl];return null===e||"object"!=typeof e?null:e}function sl(e){globalThis[nl]=e}let rl;let il=!1;function al(e,t){if(il)return;if(!function(){if(void 0!==rl)return rl;if(!("trustedTypes"in globalThis))return rl=!1,rl;try{document.createElement("div").innerHTML="<i></i>",rl=!1}catch{rl=!0}return rl}())return;il=!0;const n="function"==typeof ol()?.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 ll={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 cl(e,n,o){if(1===e.propSegments.length){const t=e.propSegments[0];"textContent"===t||"innerText"===t?o=null==o?"":String(o):void 0===o&&"innerHTML"===t&&(o="")}if(void 0===o)return void(s.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!==o){null!==Cr&&null!==d&&"object"==typeof d&&null!==o&&"object"==typeof o&&null!==Qe(r)&&Cr.rememberOverwrittenObject(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=ol(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(o):o,e=!0}catch(e){t&&al(r,c),s.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:o,error:e})}if(e){const e=function(e,t){const n=Qe(e);if(null===n)return null;const o=et(e)?.get(n);if(void 0===o)return null;const s=nt(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,o)}catch(t){s.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:o,error:t})}}};if(s.enablePropagationContext&&ds(r,c)){const t=gs(r,c,e.statePathName),s=ms(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??$s()??ws(t);if(a.visitedEdges.has(s))null!==_t&&_t({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:s,node:r,member:c});else{const e=bs(a,s);xs(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:hs++,writtenValue:n};Ss.push({receipt:i,node:e});try{return r()}finally{Ss.pop()}}(r,c,o,t,e.transactionId,i))}}else i()}if(t()){const e=ll[c];e?e(r,o):(!function(e,t,n){let o=Qa.get(e);o||(o=[],Qa.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,o),a=r,el.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!==o){if(Object.isFrozen(d))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:o}));null!==Cr&&2===i.length&&"object"==typeof d&&null!==d&&null!==Qe(r)&&(u in d?Cr.rememberOverwrittenValue(r,c,u,d[u]):Cr.recordInjectedKey(r,c,u));try{d[u]=o}catch(e){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:o,error:e})}}}const dl=new WeakSet;function ul(e,t,n){}function fl(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)}}const hl=new WeakMap;function pl(e,t,n,o){const s=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+d:"";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(d)&&!hl.has(fl(o,e)?.get)&&s.push(t)}return s}const gl={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},ml={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function yl(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}.${he}`}function wl(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 bl(e,t){return`$setAll("${e}") ${t}`}function vl(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.${he}`}function $l(e,t){const n=Eo(t);if(n.pathInfo.path in R){const e=At(t.node);return null===e&&ie(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&ie("ListIndex not found for loopContext:");const n=R[t];void 0===n&&ie(`Invalid index name: ${t}`);const o=fo(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&ie(vl(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Hn](n)}const xl=new WeakSet;function Sl(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Il=Object.freeze({[T]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?("boolean"!=typeof n&&ie(`Invalid value for class application: expected boolean, got ${typeof n}. Write "|truthy" if you mean to coerce.`),o.classList.toggle(s,n)):o.classList.toggle(s,!1)},[E]:function(e,t,n){const o=e.node,s=e.propSegments[1];if(null==n)return void(o.hasAttribute(s)&&o.removeAttribute(s));const r=String(n);o.getAttribute(s)!==r&&o.setAttribute(s,r)},[C]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[_]:function(e,t,n){Jo(n)||ie("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Rr.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||ie('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Qe(e);if(null===t)return null;const n=et(e)?.get(t);return void 0===n&&ie(`Custom element <${t}> is not defined for command binding.`),nt(e)}(r);null===a&&ie(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||ie(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${fe(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Rr.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 Rr.delete(e);const o=n[i];return"function"!=typeof o&&ie(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),Rr.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Pl={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!dl.has(e.replaceNode)){dl.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,o,s){const r=e.statePathInfo,i=go(e),a=wo(e),l=Tn(a),c=Da.get(e.node);let d,f;const h=void 0!==c&&function(e,t){const n=Nn.get(e);return void 0!==n&&(n===t||mn(t)===mn(n))}(a,s),p=h||void 0===c||c.value===l?null:na(i,l,s);h?(d=c.value,f=sa(mn(d),mn(s))):null!==p&&p.newIndexes.every(e=>e.parentListIndex===i||en(e.parentListIndex)||!sn(s,e.parentListIndex))?(d=c.value,f=sa(mn(d)??[],p.newIndexes)):(d=l.length>0&&!ja.has(e.node)?[]:l,f=na(i,d,s));const g=Array.isArray(s)?s:[];o.newListValueByAbsAddress.set(a,g),Da.set(e.node,xn(g));let m=ja.get(e.node);const y=void 0!==m?function(e,t,n){if(!Qt(t))return null;let o=null;for(let t=0;t<n.newIndexes.length;t++){const s=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(s)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(o??={byAddedIndex:new Map,reused:new Set},o.byAddedIndex.set(s,i),o.reused.add(i))}return o}(m,d,f):null,w=Array.isArray(d)&&d.length===f.deleteIndexSet.size&&f.deleteIndexSet.size>0;if(w&&null===y&&null!==e.node.parentNode){let t=Wa.get(e.node);if(void 0===t){const n=Ra.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Va(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Va(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n.parentNode===e.node.parentNode?n:e.node),Wa.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){Bs.set(e,(Bs.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let b=w?1e3-function(e){return La.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;const v=t();if(void 0!==m){const t=m;f.deleteIndexSet.forEach(o=>{const s=t.get(o);void 0!==s&&(v&&(Ba.get(s)?.forEach(e=>e.remove()),n.seen=!0),null!==y&&y.reused.has(s)?(pa(s),Ja(s),s.unmountInPlace()):b<=0&&s.tryDestroy()?va(e.node,s):(pa(s),s.unmount(),function(e,t){let n=La.get(e.node);void 0===n&&(n=[],La.set(e.node,n)),n.length<1e3?n.push(t):va(e.node,t)}(e,s),b-=1),w||t.delete(o))}),w&&(ja.delete(e.node),m=void 0)}let $=e.node;const x=ce(r.path+"."+u),S=o.stateElement.loopContextStack,I=ra(f);let P=null;f.newIndexes.length==f.addIndexSet.size&&f.newIndexes.length>0&&$.isConnected&&null===y&&(P=document.createDocumentFragment(),ao(P,o.rootNode));const k=v?`${e.uuid}:${r.path}:`:"",A=Ma(),N=La.get(e.node);for(const t of f.newIndexes){let n;if(f.addIndexSet.has(t)){const s=_o(x,t);if(S.createLoopContext(s,s=>{n=y?.byAddedIndex.get(t)??(void 0!==N?N.pop():void 0),void 0===n?n=Ta(e):(Ka(n,o),Fr(n,s)),v?$=null!==P?za(n,P,null,k+t.index):za(n,$.parentNode,$,k+t.index):null!==P?n.appendTo(P):$.nextSibling!==n.firstNode&&n.mountAfter($),ha(n,s,o),null!==A&&Oa(n,"row",A)}),void 0===n&&ie(`Content not found for ListIndex: ${t.index} at path "${r.path}"`),null!==y&&y.reused.has(n)){const e=o.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](o.stateElement,n)}}}else{n=void 0!==m?m.get(t)??null:null,f.changeIndexSet.has(t)&&Ga(n,o,Ia(r.wildcardCount)),null===n&&ie(`Content not found for ListIndex: ${t.index} at path "${r.path}"`);const e=!n.mounted;if(v?$=za(n,$.parentNode,$,k+t.index):null!==I&&I.has(t)&&Ha($,n.firstNode)||$.nextSibling===n.firstNode||n.mountAfter($),e){const e=n,s=_o(x,t);S.createLoopContext(s,t=>{ha(e,t,o)})}}v||($=n.lastNode||$),void 0===m&&(m=new WeakMap,ja.set(e.node,m)),m.set(t,n)}Ra.set(e.node,$),null!==P&&(e.node.parentNode.insertBefore(P,e.node.nextSibling),ao(P,null))},if:Ya,else:Ya,elseif:Ya,radio:function(e,t,n){const o=e.node,s=Mr(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=Mr(o.value,e.inFilters),r=Array.isArray(n)?n:Or;o.checked=r.includes(s)}},kl=new WeakMap,Al=new WeakMap,Nl=new WeakMap;function _l(){}function Tl(e){const t=Cr;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return ul;if(t.isDeclared(n,o))return _l}return cl}function El(e,t){Cl(e,t,$l(t.state,e))}function Cl(e,t,n){const o=Mr(n,e.outFilters);if(!0===Al.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=kl.get(e);if(void 0===s){if(kl.has(e))return s=Tl(e),s===ul&&kl.set(e,s),void s(e,t,o);if(s=Pl[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Il[t],kl.set(e,s),void 0===s){Qe(e.replaceNode)?(s=Tl(e),s===ul&&kl.set(e,s)):(s=cl,kl.set(e,s))}}if(s===cl){if("SELECT"===e.node.tagName){const n=e.propSegments[0];if("value"===n||"selectedIndex"===n)return t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement}),void Al.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function Ml(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=wo(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=Er(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Nl.get(e)){const t=Qe(e.replaceNode);if(t&&(void 0===et(e.replaceNode)?.get(t)||function(e){return"waiting-definition"===fr.get(e)?.phase}(e)))return void function(e,t){if(xl.has(e))return;xl.add(e);const n=()=>{xl.delete(e);const t=Er(e);(null===t||t.shouldApplyState(e))&&Rl([e])},o=n=>{xl.delete(e),Sl(t,n)},s=Er(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{xl.delete(e),r()})||(xl.delete(e),r()))}const r=et(e.replaceNode);if(null===r)return xl.delete(e),void Sl(t,new Error("CustomElementRegistry is unavailable."));Xs(r).wait(t,()=>{e.replaceNode.isConnected?n():xl.delete(e)},o)}(e,t);Nl.set(e,!0)}if(!0===t.sameRootVerified)return void El(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=lo(o),null===o&&ie("Root node for fragment not found for binding.")),o!==t.rootNode){const n=Jl(o);null===n&&ie("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};El(e,r)})}else El(e,t)}function Ol(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!==_t&&_t({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function Rl(e,t,n){let o=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;o<e.length;){let n=e[o];if(!1===n.replaceNode.isConnected){s.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),o++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=lo(d),null===d&&ie("Root node for fragment not found for binding."));const u=Jl(d);null===u&&ie("No state tree found on this root for binding."),u.createState("readonly",s=>{const f={rootNode:d,stateElement:u,state:s,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{Ml(n,f)}catch(e){Ol(n,e,u,c)}o++;const t=e[o];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{cl(e,{propagationContextByBinding:t},n)}catch(t){Ol(e,t,o??null,c)}for(const[e,t]of i.entries())En(e,t),Bn(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Jn](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Xn](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 jl(e,t,n,o,s){for(const r of e)r.cancel?.(),r.cancel=n.deferUntilDefined(r.node,r.tagName,()=>{const i=It(r);if(o&&(e.splice(e.indexOf(r),1),o.push(...i),s.push(...i.filter(e=>e.statePathName in R))),0===i.length)return;Nt(r.node,t);Rl(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1}))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,e)})}function Ll(e,t,n){const[o,s,r]=$t(e,n),i=Tr(e);for(const e of o)Nt(e,t);Rl(i.initialize(s)),jl(r,t,i)}const Wl=new WeakMap;async function Dl(e){const t=e.querySelectorAll(s.tagNames.state),n=[],o=et(e);null===o&&ie(`CustomElementRegistry is unavailable for <${s.tagNames.state}>.`),await o.whenDefined(s.tagNames.state);for(const e of t){if(gt(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function Bl(e){if(e===document)await Dl(document),se(document),$c(document,document),Ll(document.body,null);else{const t=e;t.host.hasAttribute(s.bindAttributeName)&&await Je(t.host),await Dl(t),se(t),$c(t,t),Ll(t,null)}}const zl={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function Fl(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${zl[e]??e}" before the state is defined.`}let ql=null;function Vl(e){return null===ql&&ie(Fl("ssr",e)),ql}const Hl=new WeakMap,Ul=new WeakMap,Kl=new Set,Gl=[];function Jl(e){return Hl.get(e)??null}function Xl(e){return Ul.get(e)??Promise.resolve()}const Yl=new WeakSet;function Ql(e){Yl.add(e)}function Zl(e,n){const o=Hl.get(e);if(null===n){if(void 0===o)return;Hl.delete(e),Kl.delete(o),null!==_t&&_t({type:"state:element-unregistered",rootNode:e,element:o}),s.debug&&console.debug("State element unregistered")}else{if(o===n)return;if(void 0===o){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 Vl('the "enable-ssr" attribute').hydrate(e)||await Bl(e)}else await Bl(e);Ql(e),Ac(),t()}catch(e){n(e)}})});Ul.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await Bl(e),Ql(e),Ac(),t()}catch(e){n(e)}})});Ul.set(e,t)}}void 0!==o&&ie('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="...">.'),Hl.set(e,n),Kl.add(n);for(let t=0;t<Gl.length;t++)Gl[t](e,n);null!==_t&&_t({type:"state:element-registered",rootNode:e,element:n}),s.debug&&console.debug("State element registered",n)}}const ec=new Map;function tc(e,t,n){if(null===n)ec.delete(e);else{ec.set(e,n);const o=Jl(t);null===o&&ie("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 nc(e){return ec.get(e)||null}function oc(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Be(t.getAttribute(s.bindAttributeName)||"");if(t.localName===s.tagNames.state){if(t.hasAttribute("mount"))return n.filter(e=>e.propSegments[0]!==N);const e=n.find(e=>e.propSegments[0]===N);if(void 0!==e){const t=`on a volume element — a <${s.tagNames.state}> with a "mount" attribute`;ie(1===e.propSegments.length?`[wcs/mount-path-invalid] "${e.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${N}.<key>: <path>") ${t}.`:`[wcs/mount-path-invalid] "${e.propName}: ${e.statePathName}" is a volume injection declaration, and it can only be written ${t}. Add mount="<path>", or bind an element property instead.`)}}return n}if(e.nodeType===Node.COMMENT_NODE){const t=Ve(e);null===t&&ie("Comment node binding text not found.");const n=nc(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=He(t),s=null):s=t,[{...o,uuid:s}]}return[]}let sc;function rc(){return sc??={filterName:"not",args:[]}}const ic=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function ac(e,t){const n=t+d+u,o=Ee(e,"|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+d+s.slice(1)}return r.length>0?s+r:s}function lc(e,t){const n=ic.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+ac(s,t)+r}function cc(e,t){const n=Ce(e,";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=Ee(n,":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=ac(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function dc(e,t){return cc(e,t)}function uc(e,t){const n=s.bindAttributeName,o=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const e=o.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=lc(n.data,t);continue}const s=e;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const e=cc(r,t);e!==r&&s.setAttribute(n,e)}}}function fc(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}const hc=new WeakMap;function pc(e){return hc.get(e)??null}function gc(e){const t=[],n=wt(e);for(const e of n){const n=oc(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");hc.set(t,e.data),e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:fc(o),parseBindTextResults:n})}return t}function mc(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 yc=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),wc=rc();function bc(e,t){const n=t.outFilters;return{...t,outFilters:[...n,wc],bindingType:e}}function vc(e,t,n,o,s,r=!0){mc(t),"string"==typeof o&&uc(t,o),$c(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:gc(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 $c(e,t,n,o){const r=s.commentElsePrefix,i=mt(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(s.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(s.bindAttributeName)||"";"string"==typeof n&&(i=dc(i,n));let a=Be(i)[0];const d=yc.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Et();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&ie("'else' binding found without preceding 'if' or 'elseif' binding."),a=bc("else",l.parseBindTextResult),p=vc(e,f,a,g,o,!1),tc(h,e,p);const n=c.at(-1),s=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:fc(s),parseBindTextResults:oc(s)})):t.replaceWith(s)}else if("elseif"===u){null===l&&ie("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=vc(e,f,a,g,o),tc(h,e,p);const n=document.createComment(`@@${d}:${h}`),s=Et(),i={fragment:document.createDocumentFragment(),parseBindTextResult:bc("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:fc(n),parseBindTextResults:oc(n)}),tc(s,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${s}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:fc(m),parseBindTextResults:oc(m)})):t.replaceWith(m)}else{p=vc(e,f,a,g,o),tc(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 xc=()=>`[${s.bindAttributeName}]`;function Sc(e){if(yr(e))return!0;if(!Ic(e))return!1;if(e.hasAttribute(s.bindAttributeName))return!1;const t=e.querySelector(xc());return null!==t&&yr(t)}function Ic(e){return 1===e.nodeType}function Pc(e){if(Sc(e))return;se(e),$c(e.getRootNode(),e);const t=e.hasAttribute(s.bindAttributeName),n=e.parentNode,o=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Ll(t&&o?n:e,null)}const kc=[];function Ac(){const e=kc.splice(0,kc.length);for(const t of e)Pc(t);c()}const Nc={protocol:"wcs-binder",version:1,bind:function(e){var t;Ic(e)&&!Sc(e)&&(t=e.getRootNode(),Yl.has(t)?Pc(e):kc.push(e))}};const _c="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Tc=0;async function Ec(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Tc}\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 Cc(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){ie(`Failed to load script file: ${e}`)}}class Mc{_loopContextStack=Array(h).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&ie("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=h&&ie("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&&ie("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&&ie("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&&ie(`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 Oc={$updatedCallback:W,$streams:K},Rc=new WeakSet;function jc(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function Lc(e){if((null===e||"object"!=typeof e&&"function"!=typeof e)&&ie(`The state must be an object, got ${null===e?"null":typeof e}. Check the source of the state element (json / src / the inline <script>).`),!Rc.has(e)){for(const t of Object.keys(Oc)){if(!(t in e))continue;const n=Oc[t];n in e&&ie(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${he}`),Object.isExtensible(e)||ie(`[wcs/declaration-alias] The state is not extensible, so the old name "${t}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${he}`);const o=jc(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}Rc.add(e)}}const Wc=new WeakMap;function Dc(e,t){let n=Wc.get(e);void 0===n&&(n=new Map,Wc.set(e,n));let o=n.get(t);return void 0===o&&(o=new Go(t,e),n.set(t,o)),o}const Bc=new WeakMap;function zc(e){const t=Bc.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 Dc(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:Dc(e,n)}},set(){ie("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){ie("$command namespace is read-only; deleting from it is not allowed.")}});return Bc.set(e,n),n}const Fc=Symbol("wcs.notHandled"),qc=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Vc=new Map;function Hc(e,t){Vc.set(e,t)}const Uc=new Map;let Kc=[],Gc=[];function Jc(e,t){Uc.set(e,t),Kc=Array.from(Uc.values()).sort((e,t)=>e.order-t.order),Gc=Kc.slice().reverse()}function Xc(e){return Uc.has(e)}function Yc(e,t){for(let n=0;n<Kc.length;n++)Kc[n].activate?.(e,t)}const Qc=new Map;class Zc{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=ce(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 ed(e){let t;return Qc.get(e)??(Qc.set(e,t=new Zc(e)),t)}function td(e){"readonly"===e.mutability&&ie("This state is readonly.")}function nd(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:fo(n.listIndex,o,n.pathInfo.wildcardCount)}function od(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=uo(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?fo(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?fo(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function sd(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function rd(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](e,t,n,o,s);if(a!==Fc)return a}}return Fc}function id(e,t,n,o,s){if(t.pathInfo.segments[0]===V)return function(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}(zc(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=rd(s,t,null,n,o);if(r!==Fc)return r;ie(function(e,t,n){return`[${gl.binding}] Path "${e}" does not exist on the state tree.${fe(e,pl(t,"",n,t))}${he}`}(t.pathInfo.path,e,s.getterPaths))}const r=dd(e,t.parentAddress,n,o);if(null==r)return;const i=t.pathInfo.segments[t.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==u&&!(i in Object(r))){const e=rd(s,t,Object(r),n,o);if(e!==Fc)return e}if(i===u){const e=t.listIndex?.index??ie(vl(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(r,e)}return Reflect.get(r,i)}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 ad(e,t,n,o,s){const r=so(s,t),i=function(e){return Ur.get(e)??null}(r),a=s.stateGeneration,l=t.pathInfo.lastSegment===u?void 0:Bt(t.listIndex);if(null!==i&&!1===i.dirty&&i.generation===a&&i.rowStamp===l)return i.value;const c=id(e,t,n,o,s);"function"!=typeof c&&Gr(r,{value:c,dirty:!1,generation:a,rowStamp:l});const d=i?.value;return Array.isArray(c)&&c!==d&&s.getterPaths.has(t.pathInfo.path)&&function(e,t,n,o,s,r){const{path:i,wildcardCount:a}=t.pathInfo;r.beginUntrack();try{for(const[l,c]of r.stateElement.dynamicDependency){const d=ce(l);if(!c.includes(i)||d.wildcardCount>a)continue;const u=dd(e,_o(d,fo(t.listIndex,d.wildcardCount-1,a)),s,r);u===n?ld.add(t.pathInfo):u===o&&Qi(n,o)}}finally{r.endUntrack()}}(e,t,c,d,n,o),c}const ld=new WeakSet;function cd(e){return ld.has(e)}function dd(e,t,n,o){od(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const e=r.read;for(let r=0;r<e.length;r++){const i=e[r](s,t,n,o);if(i!==Fc)return i}}return sd(s,t)?ad(e,t,n,o,s):id(e,t,n,o,s)}function ud(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=_o(f,r),p=so(n.stateElement,h),g=Dn(p),m=dd(e,h,t,n),y=na(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),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]??ie(`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())Bn(e,Array.isArray(t)?t:[]);return l}function fd(e,t,n){const o=yn(n,t.listIndex);if(null!==o)return o;const s=so(e.stateElement,t),r=na(t.listIndex,Dn(s),n);return Bn(s,Array.isArray(n)?n:[]),r.newIndexes}function hd(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=_o(a,r),c=fd(n,l,dd(e,l,t,n)),d=s[i];r=c[d]??ie(`ListIndex not found at index ${d} of ${a.path}`)}return r}function pd(e,t,n,o){"object"==typeof e&&null!==e||ie(`${Q} 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&&ie(`${Q} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function gd(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&ie(`${Q} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function md(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];pd(a,n,o,i);const l=gd(a,t,n,o,i);r.has(l)&&ie(`${Q} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function yd(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 wd(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=dd(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===u){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const bd=new WeakMap;function vd(e){return bd.get(e)??null}function $d(e,t){null===t?bd.delete(e):(bn(t.listIndexes),bd.set(e,t))}function xd(e,t,n){const o=_o(ce(e.wildcardParentPaths[t]),n),r=so(e.stateElement,o),i=Dn(r),a=e.stateProxy[Hn](o),l=na(o.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 s.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)xd(e,t+1,n)}function Sd(e,t,n,o){n?e.result.has(t)||e.quiet.add(t):e.quiet.delete(t),e.result.add(t),o.push(t)}const Id=[];function Pd(e,t,n){return"full"!==e.listExpansion&&e.listPathSet.has(t)?e.stateElement.crossRowListPaths?.has(t)?{fullRows:n.newIndexes,movedRows:null}:0===n.addIndexSet.size&&0===n.changeIndexSet.size?0===n.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:Id,movedRows:null}:{fullRows:n.newIndexes,movedRows:null}:{fullRows:Id,movedRows:null}:{fullRows:n.addIndexSet,movedRows:n.changeIndexSet}:{fullRows:n.newIndexes,movedRows:null}}const kd=[];function Ad(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return kd;let s=null;const r=t+d;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ce(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??kd}function Nd(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),e.quiet.has(a)?Jr(so(e.stateElement,a)):n(a),i.length=0,_d(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}function _d(e,t,n){const o=t.pathInfo.path,s=e.quiet.has(t),r=e.staticMap.get(o);if(r)for(const i of r){const r=ce(i);if(r.lastSegment===u){const a=e.stateProxy[Hn](t),l=Array.isArray(a)?a:[],c=so(e.stateElement,t),d=Dn(c),u=e.listPathSet.has(o);if(!u&&"diff"===e.listExpansion&&(e.keyedMergePath===o||mn(l)?.length!==l.length&&!ea(d,l)))continue;const f=na(t.listIndex,d,l);e.observedListValueByAbsAddress.set(c,l);const h=Pd(e,o,f);for(const t of h.fullRows)Sd(e,_o(r,t),s||!u,n);for(const t of f.valueChangeIndexes??Id)Sd(e,_o(r,t),s||!u,n);if(null!==h.movedRows){const t=Ad(e,i,r);if(null===t)for(const t of h.movedRows)Sd(e,_o(r,t),s,n);else if(t.length>0)for(const o of h.movedRows)for(const r of t)Sd(e,_o(r,o),s,n)}}else Sd(e,_o(r,t.listIndex),s,n)}const i=e.dynamicMap.get(o);if(i)for(const o of i){const r=ce(o),i=[];if(r.wildcardCount>0){const n=uo(t.pathInfo,r);if(r.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&ie(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=fo(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const s={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:r.wildcardPaths,wildcardParentPaths:r.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};xd(s,n,o),i.push(...s.targetListIndexes)}else{null===t.listIndex&&ie(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=fo(t.listIndex,n-1,t.pathInfo.wildcardCount);i.push(e)}}else i.push(null);for(const t of i)Sd(e,_o(r,t),s,n)}}function Td(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&&ie(`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,quiet:new Set};Nd(u,t,a),function(e,t){for(let n=0;n<1e3;n++){const n=yi(e.stateElement);if(null===n)return;n.forEach(n=>{Nd(e,_o(n.absolutePathInfo.pathInfo,n.listIndex),t)})}}(u,a);for(const[e,t]of u.observedListValueByAbsAddress)Bn(e,t);return Array.from(u.result)}function Ed(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](e,t,n,o,s)}}function Cd(e,t,n){const o=e.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Md(e,t,n){const o=e.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Od(e,t,n,o,s,r){const i=Mi(e,t),a=Wi(e,t);if(!i&&!a)return null;const l=[],c=jd(l);return i&&Li(e,t,n,o,s).forEach(c),a&&Bi(e,t,n?o:r(),s).forEach(c),l}function Rd(){return s.enablePropagationContext?$s()??null:null}function jd(e){const t=ci(),n=Rd();return o=>{Jr(o),t.enqueueAbsoluteAddress(o,n),e.push(o)}}function Ld(e,t,n){if(null===e||0===e.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=ci(),a=Rd();for(let n=0;n<e.length;n++){const l=e[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const d=_o(l.pathInfo,e[n].listIndex);Td(o,d,s,r,o.listPaths,t,"new",e=>{if(e===d)return;const t=so(o,e);Jr(t),i.enqueueAbsoluteAddress(t,a)},{listExpansion:"diff"})}}function Wd(e,t,n,o,r,i,a="diff"){const l=s.enablePropagationContext?$s()??ws(-1):null,c=ci(),f=o.stateElement;c.enqueueAbsoluteAddress(t,l),i&&Jr(t);const h=t=>Td(f,t,f.staticDependency,f.dynamicDependency,f.listPaths,n,"new",t=>{if(t===e)return;const n=so(f,t);Jr(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r});if(h(e),e.pathInfo.lastSegment!==u&&null!==e.listIndex&&null!==e.listIndex.parentListIndex){const t=e.listIndex,o=e.pathInfo.wildcardParentPathInfos[t.position],s=_o(o,t.parentListIndex),r=()=>n[Hn](s),i=e=>{Jr(e),c.enqueueRenderOnlyAddress(e)};for(const n of pn(t,r))i(so(f,_o(e.pathInfo,n)));const a=e.pathInfo.path.slice(e.pathInfo.wildcardPaths[t.position].length);for(const e of Mn(so(f,s),r())){const n=e.absolutePathInfo.pathInfo;n!==o&&n.wildcardCount===o.wildcardCount&&i(ro(f,ce(n.path+d+u+a),t))}}const{path:p,lastSegment:g,wildcardCount:m,wildcardParentPaths:y,wildcardParentPathInfos:w}=e.pathInfo,b=e.listIndex;for(let e=0;b&&e<m;e++){const t=fo(b,e-1,m);for(const o of f.dynamicDependency.get(y[e])??[]){const s=ce(o);if(f.listPaths.has(o)&&s.wildcardCount===e&&cd(s)&&n[Hn](_o(s,t))===n[Hn](_o(w[e],t))){const t=_o(ce(o+p.slice(y[e].length)),b);h(t),g===u&&c.enqueueRenderOnlyAddress(so(f,t.parentAddress))}}}}function Dd(e,t,n,o,s){s&&(e.getterPaths.has(t)?Jr(n):Gr(n,{value:o,dirty:!1,generation:e.stateGeneration,rowStamp:n.absolutePathInfo.pathInfo.lastSegment===u?void 0:Bt(n.listIndex)}))}function Bd(e,t,n,o,s){const r=t.listIndex,i=mn(n);if(i?.[o]!==r||n[o]===s)return t;const a=jt(r.parentListIndex,o,Wt(r));if(function(e){return $n.has(e)}(n)){const e=vd(n)??{value:n.slice(),listIndexes:i};vn(e.value,e.listIndexes),Sn(n,e.value)}const l=function(e){return wn.has(e)}(i)?i:i.slice();l[o]=a,vn(n,l,!0),Ri(i,l),ta([r]);const c=_o(t.pathInfo,a);return Md(e,so(e,c),so(e,t)),c}function zd(e,t,n,o,s,r,i,a,l=!0){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=dd(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===u){const e=t.listIndex?.index??ie(vl(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(i,e,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t),r.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{l&&Wd(t,n,s,r,i,a)}}function Fd(e,t,n,o,s,r,i,a,l){const c=t.parentAddress??ie(`address.parentAddress is undefined path: ${t.pathInfo.path}`),f=dd(e,c,s,r)??[],h=vd(f);if(l)return h&&(h.value[t.listIndex.index]=o),zt(t.listIndex,o),zd(e,t,n,o,s,r,i,a);const p=t.listIndex,g=h??{value:[...f],listIndexes:mn(f)??[],written:new Map};try{return zd(e,t,n,o,s,r,i,a,!1)}finally{const e=function(e,t,n){const{value:o,listIndexes:s}=e,r=new Map;s.forEach((e,n)=>{if(t[n]!==o[n]){const t=r.get(o[n]);t?t.push(e):r.set(o[n],[e])}});let i,a=0;const l=[];for(let e=0;e<s.length;e++){const n=t[e]===o[e]?s[e]:r.get(t[e])?.shift();if(!n&&(a++?(i??=new Set(o)).has(t[e]):o.includes(t[e])))return null;l.push(n)}return l.map((e,t)=>e??jt(n,t))}(g,f,c.listIndex);if(null===e)$d(f,g),zt(p,o),g.written.set(p,Jt),function(e){an.set(e,Jt)}(p),Wd(t,n,s,r,i,a);else{$d(f,null);const t=[p.index];ln(p),g.written.forEach((e,n)=>{ln(n),zt(n,g.value[n.index]),e===Jt&&t.push(n.index)}),g.written.delete(p),e.forEach((e,t)=>{e.index=t}),vn(f,e),Ri(g.listIndexes,e),function(e,t,n,o,s,r,i){const a=r.stateElement,l=ci(),c=so(a,e);vn(t.value,t.listIndexes),Yt(t.value),Sn(n,t.value),Tn(c)===n&&En(c,t.value);l.enqueueRenderOnlyAddress(c);for(const e of Mn(c,n))On(e,n)&&l.enqueueRenderOnlyAddress(e);const f=new Map;t.listIndexes.forEach((e,t)=>f.set(e,t));const h=ce(e.pathInfo.path+d+u);for(let e=0;e<o.length;e++){const n=o[e],i=f.get(n);if(i===e)continue;const c=_o(h,n),d=so(a,c);if(void 0===i){const n=ro(a,h,t.listIndexes[e]);Md(a,d,n),Wd(c,d,s,r,null,sd(a,c),"full");continue}Td(a,c,a.staticDependency,a.dynamicDependency,a.listPaths,s,"new",e=>{const t=so(a,e);Jr(t),l.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}for(const e of i){const n=o[e];if(f.has(n)&&t.written.get(n)!==Jt){const o=_o(h,n),i=so(a,o);Md(a,i,ro(a,h,t.listIndexes[e])),Wd(o,i,s,r,null,sd(a,o))}}}(c,g,f,e,s,r,t)}}}function qd(e,t,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(t.pathInfo.path);if(void 0!==i){const r=dd(e,t,o,s),a=function(e,t,n,o){const s=md(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=md(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,i,r,n);if(null!==a)return function(e,t,n,o,s,r){const i=t.pathInfo.path,a=t.listIndex;null===mn(o)&&na(a,null,o);const l=na(a,o,n.list),c=Vd(e,t,n.list,s,r,i),f=ce(i+d+u);for(const t of n.matched){const n=yd(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?qd(e,_o(ce(f.path+d+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return c}(e,t,a,r,o,s)}}return Vd(e,t,n,o,s,null)}function Vd(e,t,n,o,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let s=0;s<e.length;s++){const i=e[s](a,t,n,o,r);if(i!==Fc)return i}}const d=function(){const e=Is;return Is=0,e}(),f=d>1;if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const d=dd(e,t.parentAddress,o,r);if("object"==typeof d&&null!==d){const e=t.pathInfo.lastSegment,h=e===u?t.listIndex?.index:e;let p,g=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in d,t=void 0!==h?d[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}e===u&&(t=Bd(a,t,d,h,n));const m=Od(a,l,g,p,n,()=>d[h]),y=sd(a,t),w=so(a,t);null!==_t&&_t({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:g}),Ed(a,l,w,p,g);let b=!1;try{if(void 0===h&&ie(vl(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==u&&!(h in d)){const e=c.writeMissing;for(let s=0;s<e.length;s++){b=!0;const i=e[s](a,t,d,h,n,o,r);if(i!==Fc)return i;b=!1}}if(e!==u&&null!==t.listIndex){const o=d[h];o!==n&&(function(e,t,n,o){if(!Zt.has(e))return!1;let s=!1;for(const t in n)s||=t!==o&&n[t]===e;if(!s){let n=tn.get(t);void 0===n&&(n=new WeakSet,tn.set(t,n)),n.add(e)}const r=Zt.get(e),i=on.get(e);if(r[0]?.parentListIndex===t&&(!s||i?.[0]!==t||i[1]!==Jt))for(const n of un.get(e)??[])if(n!==t&&n.position===t.position&&dn(e,n)&&Object(Kt(n))[o]===e){r.forEach(e=>Lt(e,n)),nn.set(e,[t,Jt]);break}return s}(o,t.listIndex,d,e)&&Array.isArray(n)&&Qi(n,o),function(e,t){tn.get(t)?.delete(e);const n=Zt.get(e);if(void 0!==n){on.set(e,[t,Jt]);const o=nn.get(e);o?.[0]===t&&o[1]===Jt&&n.forEach(e=>Lt(e,t))}}(n,t.listIndex))}return Reflect.set(d,h,n)}finally{Wd(t,w,o,r,i,y),Ld(m,o,r),b?Jr(w):Dd(a,l,w,n,y),Cd(a,t.pathInfo,{value:n})}}}let h,p=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=dd(e,t,o,r);if(wd(e,t,o,r)&&Object.is(s,n))return!0;h=s,p=!0}const g=Od(a,l,p,h,n,()=>dd(e,t,o,r)),m=a.elementPaths.has(t.pathInfo.path),y=sd(a,t),w=so(a,t);null!==_t&&_t({type:"state:write",absoluteAddress:w,value:n,oldValue:h,hasOldValue:p}),Ed(a,l,w,h,p);try{return m?Fd(e,t,w,n,o,r,i,y,d):zd(e,t,w,n,o,r,i,y)}finally{Ld(g,o,r),m||Dd(a,l,w,n,y),Cd(a,t.pathInfo,{value:n})}}function Hd(e,t,n,o){return(t,s,...r)=>{Array.isArray(s)||ie(`$resolve("${t}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&ie(`$resolve("${t}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=ce(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&&ie(yl("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=_o(i,hd(e,n,o,i,s));if(0===r.length)return dd(e,a,n,o);td(o),qd(e,a,r[0],n,o)}}function Ud(e,t,n,o){const s=Hd(e,0,n,o);return(t,r)=>{const i=ce(t);if(void 0===r||Array.isArray(r)||ie(`$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&&ie(yl("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=nd(o,i.wildcardPaths[e]);if(t){r=ho(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&&ie(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=ud(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 Kd(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return nd(o,s.wildcardPaths.at(-1)??ie(`lastWildcardPath is null: ${t.pathInfo.path}`))??ie(`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]??ie(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=_o(i,s),l=fd(o,a,dd(e,a,n,o)),c=t.wildcardIndexes[r]??ie(`wildcardIndex is null: ${t.pathInfo.path}`);s=l[c]??ie(`ListIndex not found at index ${c} of ${i.path}`)}return s}case"partial":ie(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Gd(e,t,n,o){const s=o.stateElement;return t=>{const r=ed(t),i=Kd(e,r,n,o),a=_o(r.pathInfo,i),l=so(s,a),c=ci();c.enqueueAbsoluteAddress(l),function(e,t,n,o,s){const r=Mi(e,t),i=Wi(e,t);if(!r&&!i)return;const a=n(),l=[],c=jd(l);r&&Li(e,t,!1,void 0,a).forEach(c),i&&Bi(e,t,void 0,a,!1).forEach(c),Ld(l,o,s)}(s,r.pathInfo.path,()=>dd(e,a,n,o),n,o),Td(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=so(s,e);Jr(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}function Jd(e,t,n,o){return(t,s,r,i)=>{td(o);const a=ce(t);Array.isArray(s)||ie(bl(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&ie(yl("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&ie(bl(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&ie(bl(t,"requires an array as the value when { spread: true } is set."));const d=ud(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&ie(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 f=[];for(let t=0;t<d.length;t++){const s=hd(e,n,o,a,d[t]);f.push(_o(a,s))}const h=a.lastSegment===u;let p=0;for(let t=0;t<f.length;t++){const s=h?_o(a,hd(e,n,o,a,d[t])):f[t];let i;if(c){i=r(dd(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(qd(e,s,i,n,o),p++)}return p}}function Xd(e,t){if("all"===ed(t).wildcardType)return!0;const n=e.getterPaths;if(0===n.size)return!1;for(const e of ce(t).cumulativePaths)if(n.has(e))return!0;return!1}const Yd=/^\$\d+$/,Qd=`${Z}${d}`,Zd=`${ee}${d}`,eu=new WeakMap;function tu(e,t,n,o){const s=R[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&Yd.test(t)&&ie(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${M}1 to ${M}128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&ie(`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 r=e?.listIndex;null==r&&ie(`ListIndex not found: ${t.toString()}`);let i=s;const a=e.pathInfo,l=o.stateElement?.addressHooks;if(l){const t=l.indexShift;for(let n=0;n<t.length;n++)i+=t[n](o,e)}const c=fo(r,i,a.wildcardCount);return c?.index??ie(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,t,n,e);if(i!==Fc)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Ud(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>Jd(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>Gd(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Hd(e,0,n,o)(t,s,...r);case"$dependOn":case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] ${String(t)}("${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&&ie(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??ie("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==e&&s.addDynamicDependency(e,n.path)}}(0,t,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Xd(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ci(o.stateElement,e),Object.is(n[e],t);let r;o.beginUntrack();try{r=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ei(o.stateElement,e,t,so(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Xd(o.stateElement,e);let i,a=r?n[e]:void 0;o.beginUntrack();try{r||(a=n[e]),i=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?Ci(o.stateElement,e):Ei(o.stateElement,e,i,so(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||ie(`$eqIndex("${e}") needs a list row scope.`);const r=fo(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&ie(`$eqIndex("${e}", ${t}): no list index at that level.`),Xd(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&(Ci(o.stateElement,e),o.stateElement.addIndexDependentGetterPath?.(s.pathInfo.path)),Object.is(n[e],r.index);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?mn(l):null;null!==t?function(e,t,n,o,s){pi=!0,Pi(e).lastValue.set(t,s),Ii(e,t);let r=wi.get(e);void 0===r&&wi.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=bi.get(o);if(void 0===l?(bi.set(o,l=[]),bn(o)):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);const n=o[0]?.parentListIndex??null;if(null!==n){let e=$i.get(n);void 0===e&&$i.set(n,e=new Set),e.add(a)}}a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){pi=!0;const r=Pi(e);Ii(e,t),Ti(r,t,s,o,Ni(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,so(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untracked":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 V:return zc(o.stateElement)}if(!t.startsWith(Qd)&&!t.startsWith(Zd))return}const r=ed(t),i=Kd(e,r,n,o),a=_o(r.pathInfo,i);return dd(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=eu.get(e);return void 0===t&&(t=new Map,eu.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Vn:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&ie("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 Hn:i=t=>dd(e,t,n,o);break;case Un:i=t=>wd(e,t,n,o);break;case Kn:i=()=>async function(e,t,n){const o=Reflect.get(e,j);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Gn:i=()=>function(e,t,n){const o=Reflect.get(e,L);"function"==typeof o&&o.call(n)}(e,0,n);break;case Jn:i=t=>function(e,t,n,o){const s=Reflect.get(e,W);let r;if("function"==typeof s){const e=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,s=t.path;if(-1===s.indexOf("#")&&(e.add(s),t.wildcardCount>0)){const e=ho(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}(e.size>0||0===t.length)&&(r=s.call(n,Array.from(e),i))}const i=o.stateElement?.addressHooks;if(i){const e=i.updated;for(let s=0;s<e.length;s++)e[s](o.stateElement,t,n)}return r}(e,t,n,o);break;case Xn:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,D);"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 nu{_stateElement;_addressStack=Array(h).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=Jl(e);null===n&&ie("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&ie("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=h&&(this._hasRepeatedAddress()&&ie(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),ie(`[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&&ie(`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 tu(e,t,n,this)}set(e,t,n,o){return td(this),function(e,t,n,o,s){if("string"==typeof t){const r=ed(t),i=Kd(e,r,o,s);return qd(e,_o(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)}deleteProperty(e,t){return td(this),Reflect.deleteProperty(e,t)}defineProperty(e,t,n){return td(this),Reflect.defineProperty(e,t,n)}}const ou=Promise.resolve(),su=new Map;let ru=[];function iu(e,t){su.set(e,t),ru=Array.from(su.values()).sort((e,t)=>e.order-t.order)}function au(e,t){return ie(Fl(e,t))}const lu="undefined"==typeof HTMLElement?class{}:HTMLElement;function cu(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}let du=null;const uu=new Set(["for","if","elseif","else"]);function fu(e,n,o){const s=new Map;for(const e of o){const t=ce(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=so(e,t);if(i.has(n))return;i.add(n);const o=Io(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(_o(n,t.listIndex))}};zn();try{if(e.createState("readonly",t=>{for(const o of n){const n=_o(ce(o),null);a(n);try{Td(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)uu.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=()=>{Rl(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Qr("state",s);void 0!==i&&i.catch(ii)}finally{Fn()}}const hu=[[G,"watch"],[J,"scan"],[K,"streams"],[X,"recursion"]];class pu extends lu{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Xl(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 Mc}();_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;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=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&&ie(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){Lc(e),function(e){for(let t=0;t<hu.length;t++){const[n,o]=hu[t];n in e&&!Xc(o)&&ie(Fl(o,`"${n}"`))}}(e);const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[q];if(void 0===n)return t;Array.isArray(n)||ie(`${q} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ie(`${q} entries must be non-empty strings.`),e===V&&ie(`${q} entry "${e}" conflicts with the reserved namespace name "${V}".`),t.has(e)&&ie(`${q} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[H];if(void 0===n)return t;Array.isArray(n)||ie(`${H} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ie(`${H} entries must be non-empty strings.`),t.has(e)&&ie(`${H} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[Q];if(void 0===t)return null;"object"==typeof t&&null!==t||ie(`${Q} 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&&ie(`${Q} entry path must be a non-empty string.`);const t=e.split(d);t.some(e=>0===e.length)&&ie(`${Q} entry "${e}" must not contain empty path segments.`),t[t.length-1]===u&&ie(`${Q} entry "${e}" must be the list path itself, not the element path (drop the trailing "${d}${u}").`),-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] ${Q} entry "${e}" uses "${Y}", which ${Q} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${d}${u}${d}children").`),"function"!=typeof o?("string"!=typeof o&&ie(`${Q} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&ie(`${Q} entry "${e}" key field name must be a non-empty string.`),(o.includes(d)||o.includes(u))&&ie(`${Q} entry "${e}" key field name "${o}" must be a flat property name ("${d}" / "${u}" are not allowed).`),o in Object.prototype&&ie(`${Q} 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);var i;n.set("eventTokenNames",s),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&du?.reset(this),this._hasUpdatedCallback=W in e,this._hasErrorCallback=D in e,i=this,Vo.delete(i),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[U];if(void 0!==o){"object"==typeof o&&null!==o||ie(`${U} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||ie(`${U} entry "${t}" is not declared in $eventTokens.${fe(t,n)}`),"function"!=typeof s&&ie(`${U} entry "${t}" must be a function.`),Ho(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const a=function(e){const t=new Set,n=new Set,o=cu(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 a.getterPaths)this._getterPaths.add(e);for(const e of a.setterPaths)this._setterPaths.add(e);!function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].register?.(e,t,n)}(this,e,n),Yc(this,null),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 <${s.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?Vl('the "enable-ssr" attribute').loadState(this):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){ie("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 Ec(e,s.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.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||ie(`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 Cc(e);ie(`Unsupported src file type: ${e}`)}}catch(e){ie(`Failed to initialize state: ${e}`)}}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&&(Zl(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),ie(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${s.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===Jl(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),Ul.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<ru.length;o++)ru[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{j in e&&await e[Kn]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{L in e&&e[Gn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<ru.length;t++)if(!0===ru[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Jl(this._rootNode)===this||Zl(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=function(e){for(let t=0;t<ru.length;t++){const n=ru[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{au("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(te))try{au("dcc",`a <${s.tagNames.state}> inside a [${te}] host`)}catch(e){this._failInitializeLoudly(e)}let n=!1;try{const e=function(e){for(let t=0;t<ru.length;t++){const n=ru[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&au("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let o=!1;try{o=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!o)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 Vl('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}Yc(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<ru.length;t++)if(!0===ru[t].disconnecting?.(e))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(e,t){for(let n=0;n<ru.length;n++)ru[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Zl(this.rootNode,null),e=this,Bc.delete(e),function(e){for(let t=0;t<Gc.length;t++)Gc[t].deactivate?.(e)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(e=>(Lc(e),e))}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}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,this.attachAddressHooks("watch",G)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&ie(`$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 fl(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&&ie("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(e,t){const n=function(e,t){const n=Vc.get(e);return void 0===n&&ie(Fl(e,`"${t}"`)),n}(e,t);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(e,t){for(let n=0;n<qc.length;n++){const o=qc[n],s=t[o];if(void 0===s)continue;const r=e[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(e){this.attachAddressHooks("scopes",e)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e,this.attachAddressHooks("dcc",z)}_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){if(!this._addDependency(this._dynamicDependency,e,t))return!1;const n=ce(e);for(let e=n.parentPathInfo;null!==e&&e.wildcardCount>0&&e.wildcardCount===n.wildcardCount;e=e.parentPathInfo)this._addDependency(this._dynamicDependency,e.path,t);return!0}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+"."+u)),!this._pathSet.has(e)){const t=ce(e);this._pathSet.add(e);const o=function(e,t){const n=ed(t);return"all"===n.wildcardType&&1===n.wildcardIndexes.length&&isNaN(+n.segments[0])&&!t.includes("#")&&Object.isExtensible(e)&&!(t in e)}(this.__state,e);if(du?.check(this,this.__state,e,n,o),o&&function(e,t){const{segments:n,cumulativePaths:o}=ce(t),s=n.length-1,r=(e,r,i)=>{let a,l=!1;for(let c=0;c<=s;c++){const d=n[c];if(l||=!(isNaN(+d)||Array.isArray(a)&&+d in a),r&&c===s)return l?a[d]=i:e[t]=i;a=l?a?.[d]:e[o[c]]}return a},i=function(){return r(this)};hl.set(i,ed(t).pathInfo.path),e.defineTreeAccessor(t,{get:i,set(e){r(this,!0,e)},configurable:!0})}(this,e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ce(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 nu(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&&ie(`<${s.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);!function(e){for(let t=0;t<ru.length;t++)ru[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&ie("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(cu(n)))e.startsWith("$")||e.includes(u)||"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){fu(this,e,this._pathRegistrations.keys())}}const gu=[],mu=[];function yu(){const e=[];let t=0;for(let n=0;n<mu.length;n++){const o=mu[n].deref();void 0!==o&&(e.push(o),mu[t++]=mu[n])}return mu.length=t,e}function wu(e=customElements){yu().includes(e)||mu.push(new WeakRef(e));for(let t=0;t<gu.length;t++)gu[t](e);e.get(s.tagNames.state)||e.define(s.tagNames.state,pu)}function bu(e){if("string"==typeof e?.locale)return 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}}function vu(e,t){const n=bu(e);var s;n&&((s=n).tagNames&&Object.assign(o.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(o.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(o.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(o.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(o.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(o.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(o.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(o.locale=s.locale),"boolean"==typeof s.debug&&(o.debug=s.debug),"boolean"==typeof s.enableMustache&&(o.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(o.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(o.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(o.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(o.sameValueGuard=s.sameValueGuard)),wu(t),function(){const e=globalThis;void 0===e[i]&&(e[i]=Nc)}()}let $u=null;function xu(e){return $u??ie(Fl("watch",`"$watch" in <wcs-state mount="${e}">`))}let Su=null;const Iu=Object.freeze([]);const Pu="3.4.0",ku=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Au(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}}function Nu(e){const t=[],n=new Set,o=new Set,r=e=>{const o=function(e){const t=`${me(e.inFilters)}\0${me(e.outFilters)}`;return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(o.has(e))return;o.add(e);const t=nc(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(Au(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(s.bindAttributeName);if(null===n||0===n.length)continue;try{const e=ct(t,Be(n));for(const o of e)r(Au(t,o,"attribute",n))}catch{}continue}const t=ku.exec(e.data.trim());if(null===t)continue;const n=t[1]||s.commentTextPrefix,o=t[2],a=nc(o);if(null===a){if(n===s.commentTextPrefix)try{r(Au(e,He(o),"comment",o))}catch{}}else r(Au(e,a.parseBindTextResult,"comment",o)),i(o)}return t}function _u(e){const t=function(e){const t=di.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:wi.get(e)}}(e);if(null===t)return[];const n=new Set([...t.byPath.keys(),...t.tracked]);if(void 0!==t.watchers)for(const e of t.watchers.keys())n.add(e);const o=[];for(const e of[...n].sort()){const n=t.byPath.get(e);let s=0;if(void 0!==n)for(const e of n.values())s+=e.size;o.push({path:e,tracked:t.tracked.has(e),rows:s,keys:n?.size??0,lists:t.watchers?.get(e)?.size??0,lastValue:t.lastValue.get(e)})}return o}const Tu="__WCSTACK_DEVTOOLS_HOOK__";function Eu(){const e=globalThis,t=e[Tu];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[Tu]=n,n}const Cu=e=>{null!==_t&&_t({type:"state:update-batch",addresses:e})};function Mu(e){const t=null!==_t;!function(e){_t=e}(e);const n=null!==e;n&&!t?ri(Cu,0):!n&&t&&function(e){const t=Zr.findIndex(t=>t.listener===e);-1!==t&&Zr.splice(t,1)}(Cu)}function Ou(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 Ru(e){return Jl(e)??ie("devtools: no state tree on this root")}let ju=null;function Lu(){if(t())return;if(null!==ju)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Pu,getStateElements(){const e=[];for(const t of Kl)e.push(Ou(t));return e},overlays(e){return t=Ru(e),null===Su?Iu:Su(t);var t},keyedSubscriptions:e=>_u(Ru(e)),keys(e){const t=Ru(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 Ru(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){Ru(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>Nu(e),_setSink:Mu};ju=e,Eu().register(e)}const Wu={name:"devtools",install(){Lu()}},Du=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Bu=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const zu=new WeakMap;const Fu=new WeakMap,qu=new WeakSet,Vu=new WeakMap;function Hu(e,t,n,o){console.warn(`[@wcstack/state] [${gl[n]}] ${ml[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${fe(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${he}`),null!==_t&&_t({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Uu={check:function(e,t,n,o,s){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const r=e.addressHooks;if(r){const t=r.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const i=ce(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=zu.get(e);return void 0===n&&(n=new Set,zu.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,o){if(void 0!==fl(e,t))return Bu;const s=ce(t).segments;let r=e,i="";for(let t=0;t<s.length;t++){const a=o&&Array.isArray(r)&&+s[t]>=0?u:s[t],l=i;i=0===t?a:i+d+a;const c=t>0&&fl(e,i),f=c&&hl.get(c.get);if(c&&(!f||fl(e,f)))return t<s.length-1?Du:Bu;if(Object(r)!==r)return Du;if(a===u){if(!Array.isArray(r)||0===r.length)return Du;r=r[0];continue}const h=fl(r,a);if(void 0===h)return{existence:"missing",missingSegment:a,candidates:pl(r,l,n,e)};if("function"==typeof h.get)return t===s.length-1?Bu:Du;r=h.value}return Bu}(t,n,e.getterPaths,s);"missing"===a.existence&&(function(e,t){return!0===Vu.get(e)?.has(t)}(e,n)||("binding"!==o?Hu(e,n,o,a):function(e,t,n){let o=Fu.get(e);void 0===o&&(o=new Map,Fu.set(e,o));if(o.set(t,n),qu.has(e))return;qu.add(e),setTimeout(()=>function(e){qu.delete(e);const t=Fu.get(e);if(void 0===t)return;Fu.delete(e);for(const[n,o]of t)Hu(e,n,"binding",o)}(e),0)}(e,n,a)))},reset:function(e){zu.delete(e),Fu.delete(e)},markExported:function(e,t){let n=Vu.get(e);void 0===n&&(n=new Set,Vu.set(e,n)),n.add(t),Fu.get(e)?.delete(t)}};let Ku=!1;function Gu(){Ku||(Ku=!0,function(e){du=e}(Uu))}const Ju={name:"diagnostics",install(){Gu()}};function Xu(e){ie(`filter ${e} requires at least one option`)}function Yu(e){ie(`filter ${e} requires a number as option`)}function Qu(e){ie(`filter ${e} requires a number value`)}function Zu(e){ie(`filter ${e} requires a date value`)}const ef={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function tf(e){return!(!e||isNaN(Number(e)))}function nf(e,t){return tf(e)||Yu(t),Number(e)}function of(e,t,n){return nf(e?.[t]??Xu(n),n)}const sf=e=>t=>{const n=e(t);return e=>null==e?e:n(e)},rf={eq:(e,t)=>{const n=e?.[0]??Xu("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e===o:(tf(n)||Yu("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Xu("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e!==o:(tf(n)||Yu("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>!e,lt:e=>{const t=of(e,0,"lt");return e=>("number"!=typeof e&&Qu("lt"),e<t)},le:e=>{const t=of(e,0,"le");return e=>("number"!=typeof e&&Qu("le"),e<=t)},gt:e=>{const t=of(e,0,"gt");return e=>("number"!=typeof e&&Qu("gt"),e>t)},ge:e=>{const t=of(e,0,"ge");return e=>("number"!=typeof e&&Qu("ge"),e>=t)},add:e=>{const t=of(e,0,"add");return e=>("number"!=typeof e&&Qu("add"),e+t)},sub:e=>{const t=of(e,0,"sub");return e=>("number"!=typeof e&&Qu("sub"),e-t)},mul:e=>{const t=of(e,0,"mul");return e=>("number"!=typeof e&&Qu("mul"),e*t)},div:e=>{const t=of(e,0,"div");return e=>("number"!=typeof e&&Qu("div"),e/t)},mod:e=>{const t=of(e,0,"mod");return e=>("number"!=typeof e&&Qu("mod"),e%t)},abs:e=>e=>("number"!=typeof e&&Qu("abs"),Math.abs(e)),clamp:e=>{const t=of(e,0,"clamp"),n=of(e,1,"clamp");return e=>("number"!=typeof e&&Qu("clamp"),Math.min(Math.max(e,t),n))},toFixed:e=>{const t=nf(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&Qu("toFixed"),e.toFixed(t))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Qu("locale"),e.toLocaleString(t??s.locale))},upper:sf(e=>e=>String(e).toUpperCase()),lower:sf(e=>e=>String(e).toLowerCase()),capitalize:sf(e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),trim:sf(e=>e=>String(e).trim()),slice:sf(e=>{const t=[of(e,0,"slice")],n=e?.[1];return void 0!==n&&t.push(nf(n,"slice")),e=>String(e).slice(...t)}),substr:sf(e=>{const t=of(e,0,"substr"),n=of(e,1,"substr");return e=>String(e).substr(t,n)}),padStart:sf(e=>{const t=of(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),padEnd:sf(e=>{const t=of(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),repeat:sf(e=>{const t=of(e,0,"repeat");return e=>String(e).repeat(t)}),reverse:sf(e=>e=>String(e).split("").reverse().join("")),truncate:sf(e=>{const t=of(e,0,"truncate"),n=e?.[1]??"…";return e=>{const o=String(e);return o.length<=t?o:o.slice(0,t)+n}}),join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||ie(`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=Math.pow(10,nf(e?.[0]??"0","round"));return e=>("number"!=typeof e&&Qu("round"),Math.round(e*t)/t)},floor:e=>{const t=Math.pow(10,nf(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&Qu("floor"),Math.floor(e*t)/t)},ceil:e=>{const t=Math.pow(10,nf(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&Qu("ceil"),Math.ceil(e*t)/t)},percent:e=>{const t=nf(e?.[0]??"0","percent");return e=>("number"!=typeof e&&Qu("percent"),`${(100*e).toFixed(t)}%`)},unit:sf(e=>{const t=e?.[0]??Xu("unit");return e=>String(e)+t}),date:e=>{const t=e?.[0];return e=>(e instanceof Date||Zu("date"),e.toLocaleDateString(t??s.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Zu("time"),e.toLocaleTimeString(t??s.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Zu("datetime"),e.toLocaleString(t??s.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Zu("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||Zu("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=>!e,truthy:e=>e=>!!e,defaults:(e,t)=>{const n=e?.[0]??Xu("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Xu("coalesce"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e??o},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),nullIfEmpty:e=>e=>""===e?null:e},af={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[2,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,1],time:[0,1],datetime:[0,1],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},lf=rf,cf=rf;let df=!1;const uf={name:"formats",install(){df||(df=!0,Se("input",cf,af,ef),Se("output",lf,af,ef))}};function ff(e){return-1!==e.indexOf(Y)}function hf(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+d;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(ff(o))return null;const s=o.slice(1).split(d);return s[0]===u||s.some(e=>0===e.length)?null:o}function pf(e){return 0===e.length?e:d+yf(e.slice(1))}function gf(e,t,n){const o=d+e.repeat,s=t.length<=n.length?t:n,r=t.length<=n.length?n:t;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let e=0;e<i.length;e+=o.length)if(!i.startsWith(o,e))return!1;return!0}function mf(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(d,o-1))if(gf(e,t,n.slice(0,o)))return!0;return!1}function yf(e){const t=e.split(d);for(let e=0;e<t.length;e++)t[e]===u||Number.isNaN(Number(t[e]))||(t[e]=u);return t.join(d)}function wf(e,t){const n=e.repeat.split(d),o=d+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===d+e.repeatList+d+"length")return!0;for(let e=1;e<n.length;e++)if(s===d+n.slice(0,e).join(d))return!0;return!1}function bf(e,t,n){n<0&&ie(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=d+e.repeat;const s=o+t;let r=0;for(const e of s.split(d))e===u&&r++;return r>f&&ie(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function vf(e,t){return bf(e,"",t)}function $f(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 s=d+e.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function xf(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=d+n.repeat;let s=0,r=n.anchor.length;for(;t.startsWith(o,r);)r+=o.length,s++;return r!==t.length&&46!==t.charCodeAt(r)?null:s}(t,n.pathInfo.path)}function Sf(e,t,n){const o=e.recursionRegistry,s=hf(o.spec,n);null===s&&ie(wl(n,o.spec.recursiveAnchor));const r=xf(t,o);return null===r&&ie(`[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 If(e,t,n,o,s){const r=o.spec,i=[],a=new Map,l=[],c=r.repeatList,u=r.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void i.push(_o(e,n));const s=g(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function g(o,s,i){const l=_o(o,s),d=so(n.stateElement,l),u=dd(e,l,t,n),h=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&ie(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${r.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)&&ie(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${c}" array.`),o})(o.path,u,i),p=na(s,Dn(d),u);return a.set(d,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=l[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:ce(n),childListPathInfo:ce(r+d+c)};return l[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(_o(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,ce(u),null);for(const[e,t]of a)Bn(e,t);return i}function Pf(e,t,n,o,s,r,i){td(n);const a=n.stateElement.recursionRegistry,l=hf(a.spec,o);null===l&&ie(wl(o,a.spec.recursiveAnchor));const c=pf(l);Array.isArray(s)||ie(bl(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&ie(`[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&&ie(bl(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&ie(bl(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){wf(e,n)&&ie(`[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&&ie(`[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=If(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(qd(e,u[o],r,t,n),f++);return f}const kf={write(e,t){if(!0!==e.hasRecursion)return Fc;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&ie(`[wcs/recursion-readonly] "${t.pathInfo.path}" writes into the recursive getter "${n}" (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.`),Fc},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return Fc;if("$getAll"===t)return(t,s)=>{if(ff(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=hf(r.spec,o);null===i&&ie(wl(o,r.spec.recursiveAnchor)),Array.isArray(s)||ie(`[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&&ie(`[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=If(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(dd(e,a[o],t,n));return l}(o,n,e,t,s);t=Sf(e.stateElement,e,t)}return Ud(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>ff(t)?Pf(o,n,e,t,s,r,i):Jd(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&ff(t)){const s=ed(Sf(e.stateElement,e,t)),r=Kd(o,s,n,e);return dd(o,_o(s.pathInfo,r),n,e)}return Fc}};let Af=!1;function Nf(e,t){"string"==typeof t&&0!==t.length||ie(`[wcs/recursion-declaration-invalid] ${X} ${e} must be a non-empty string.`);const n=t.split(d);n.some(e=>0===e.length)&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain empty path segments.`),n.length<2&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must name a list element: a property path ending with "${d}${u}" (for example "nodes${d}${u}").`),n[n.length-1]!==u&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must end with "${d}${u}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===u&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must have exactly one "${u}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===Y&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain "${Y}" — the declaration is what gives "${Y}" its meaning.`),isNaN(Number(n[o]))||ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const _f=new WeakSet;function Tf(e){return"function"==typeof e.get&&_f.has(e.get)}const Ef="[wcs/recursion-declaration-invalid]";class Cf{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=cu(t);for(const[t,o]of Object.entries(n)){if(!ff(t))continue;"function"==typeof o.set&&ie(`${Ef} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&ie(`${Ef} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=hf(e,t);null===n&&ie(wl(t,e.recursiveAnchor)),0===n.length&&ie(`${Ef} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${d}total"), not the node.`),wf(e,pf(n))&&ie(`${Ef} "${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}${d}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(ff(t)||Tf(n))continue;const e=this._matchExpansion(t);null!==e&&ie(`${Ef} "${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++)gf(this.spec,e[t].suffix,e[n].suffix)&&ie(`${Ef} "${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(mf(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=yf(e),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let e=n.lastIndexOf(d);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(d,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==$f(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=$f(this.spec,e.suffix,t);null!==n&&(null!==o&&ie(`"${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||Tf(s)||ie(`"${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,_f.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(vf(e,o)+d+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 function(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Tf(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))}}}}(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=bf(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 Mf="recursionSpec",Of="recursionRegistry",Rf={order:5,validateEarly(e,t,n){const o=function(e){const t=e[X];if(void 0===t)return null;"object"==typeof t&&null!==t||ie(`[wcs/recursion-declaration-invalid] ${X} 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&&ie(`[wcs/recursion-declaration-invalid] ${X} must declare exactly one anchor; it is empty.`),n.length>1&&ie(`[wcs/recursion-declaration-invalid] ${X} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Nf("anchor",o),"string"!=typeof s&&ie(`[wcs/recursion-declaration-invalid] ${X} entry "${o}" must map to the repeating sub-path as a string (for example "children${d}${u}").`),Nf("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(d)),i=s.slice(0,s.lastIndexOf(d)),a=r+d+Y;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(Mf,o),n.set(Of,null===o?null:new Cf(o,t))},preCommit(e,t,n){const o=e.recursionRegistry;if(null!==o)for(const t of o.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(Of)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",X)},apply(e,t,n){const o=n.get(Mf)??null;null!==o&&e.addListPath(o.anchorList)}};let jf=!1;function Lf(){jf||(jf=!0,Af||(Af=!0,Hc("recursion",kf)),Jc("recursion",Rf))}const Wf={name:"recursion",install(){Lf()}};const Df={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1&&-1===t.path.indexOf("#")?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}))}};let Bf=!1;function zf(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 Ff(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 qf(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 Vf(e){return e.startsWith("$")}function Hf(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 Uf(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||ie(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||ie(`${t} entries must be non-empty strings.`),e.startsWith("$")&&ie(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&ie(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Kf(e){Lc(e);const t=Uf(e,z)??[],n=Uf(e,F)??[],o=cu(e),s=function(e){const t=e[K];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}ie(`${z} entry "${e}" is not declared on the state.${fe(e,Hf(o,"value"))}`)}"function"==typeof t.value&&ie(`${z} entry "${e}" is a method. Declare it in ${F} instead.`)}for(const e of n){const t=o[e];void 0===t&&ie(`${F} entry "${e}" is not declared on the state.${fe(e,Hf(o,"method"))}`),"function"!=typeof t.value&&ie(`${F} entry "${e}" is not a method. Declare it in ${z} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function Gf(e,t,n){const o=e.tagName.toLowerCase();o.includes("-")||ie(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const r=et(e);null!==r&&"function"==typeof r.define||ie(`DCC: CustomElementRegistry is unavailable for "${o}".`),r.get(o)&&ie(`DCC: "${o}" 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}=Kf(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}}(o,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(o,c):{},p=s.tagNames.state,g=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(te))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=et(this._shadow);return null!==e&&tt(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(Bf||(Bf=!0,Hc("dcc",Df)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${z} but its template has no <${s.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=cu(n);for(const[e,t]of Object.entries(m)){if(Vf(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=qf(e,o)}else n.get=zf(e),n.set=Ff(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:zf(e),set:Ff(e)});r.define(o,g)}async function Jf(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&ie(`"bind-component" cannot be used inside a [${te}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){try{if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await Cc(t);ie(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await Ec(n,t.tagName.toLowerCase());ie(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){ie(`DCC: Failed to load state: ${e}`)}}(o,t);Gf(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const Xf={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(te)?Jf(e,t.host,t):null}};let Yf=!1;function Qf(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 Zf(e,t){for(const n of e)if(Qf(t,n.innerSegments))return n;return null}function eh(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+d+n.join(d)}const th=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function nh(e,t,n){const o=th.get(e);return void 0===o?null:(...e)=>{const s=e.slice();for(let e=0;e<o.length;e++){const n=o[e];"string"==typeof s[n]&&(s[n]=t(s[n]))}return n(s)}}const oh=new WeakMap;function sh(e,t,n){let o=oh.get(e);void 0===o&&(o=new Map,oh.set(e,o));const s=o.get(t);null!=s&&ie(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function rh(e,t){if(null===e)return!1;const n=oh.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+d)||e.startsWith(t+d))return!0;return!1}const ih=new WeakMap;const ah=[];function lh(e,t,n,o){if(t.length>0){const s=n.split(d),r=Zf(t,s);if(null!==r)return o&&r.readonly&&ie(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${N}.${r.innerSegments.join(d)}#${b}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${b} from the injection.`),eh(r,s)}return e+d+n}function ch(e,t,n){let o=-1,s=null;for(const e of t){const t=e.outerPathInfo.path;t.length<=o||(n===t?(o=t.length,s=e.innerSegments.join(d)):n.startsWith(t+d)&&(o=t.length,s=e.innerSegments.join(d)+n.slice(t.length)))}if(e.length>o){if(n===e)return"";if(n.startsWith(e+d))return n.slice(e.length+1)}return s}function dh(e,t,n=ah){return new Proxy({},{get(o,s){if("string"==typeof s&&"then"!==s){if("$"===s[0]){if("$postUpdate"===s||"$getAll"===s){const o=s;return(s,...r)=>t[o](lh(e,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>t.$setAll(lh(e,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>t.$resolve(lh(e,n,o,s.length>1),...s);const o=nh(s,t=>lh(e,n,t,!1),e=>t[s](...e));return null!==o?o:t[s]}return t[lh(e,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(t[s]=r,!0):(t[lh(e,n,s,!0)]=r,!0)),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const uh=new WeakMap,fh=[];const hh=new WeakMap,ph=new WeakSet;function gh(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 mh=null;let yh=0;const wh=["$watch",K,"$scan","$listKeys",W,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],bh=new Set;function vh(e,t,n){const o=e.stateObject[t];if("function"==typeof o)try{const s=o.call(n());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 $h(e,t,n,o,s,r=new Set){0===n.length&&ie(`Cannot build a mount record without host bindings for "${t}".`),Lc(s);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(d);a.has(n)&&ie("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(b)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const c=++yh,u=`#m${c}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=cu(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}}(s),p=new Set;for(const e of i)1===e.innerSegments.length&&p.add(e.innerSegments[0]);const g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:c,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?u:l.outerPathInfo.path+d+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(e=>e.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function xh(e){const t=e.indexOf(d);return-1===t?e:e.slice(0,t)}function Sh(e,t){const n=Zf(e.entries,t);return null===n?null:eh(n,t)}function Ih(e,t){return e.markerBasePath+d+t}function Ph(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+d+n;s.set(n,{accessorName:o,indexShift:ce(r).wildcardCount-ce(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function kh(e,t){return!e.injectedKeys.has(t)&&(!e.getterKeys.has(t)&&"function"==typeof e.stateObject[t]||!e.mappedKeys.has(t)&&(Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t)))}function Ah(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(d)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${xh(t)}: path") or declare the key on the component state.`}const Nh=/^\$(\d+)$/;function _h(e,t){if(!e.hasReadonlyEntries)return null;const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=xh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||kh(e,o))return null;const s=function(e,t){return Zf(e.entries,t)}(e,t.split(d));return null!==s&&s.readonly?s:null}function Th(e,t){const n=_h(e,t);if(null!==n){const o=0===n.innerSegments.length?"":d+n.innerSegments.join(d);ie(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${b}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${b} from the mount.`)}return Eh(e,t)}function Eh(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(d);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===u){o=e;break}if(-1===o)return Ph(e,e.markerBasePath,t,t),Ih(e,t);if(kh(e,n[0]))return Ph(e,e.markerBasePath,t,t),Ih(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Sh(e,s);null===i&&ie(Ah(e,t)),0===r.length&&ie(`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 a=i+d+e.marker;return Ph(e,a,r.join(d),t),a+d+r.join(d)}(e,t);const o=xh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return Ih(e,t);if(kh(e,o))return Ih(e,t);const s=Sh(e,t.split(d));if(null!==s)return s;ie(Ah(e,t))}const Ch=new Set(["prop","radio","checkbox"]);function Mh(e,t,n){let o;const s=Nh.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ce(Eh(e,t)).wildcardCount-ce(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Eh(e,t.statePathName),"for"===t.bindingType){const n=ce(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+d+u,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&Ch.has(t.bindingType??"")&&!r.includes(b)&&null!==_h(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ce(o),...i?{propModifiers:[...r,b]}:{}}:t}function Oh(e,t,n,o,s){if(void 0===o)return;const r=ce(n).wildcardCount-ce(t).wildcardCount;return 0===r?o:(s.length<r&&ie(`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])}function Rh(e,t,n){if(-1!==e.indexOf(u))return t;const o=t.split(d);let s=0;for(let e=0;e<o.length&&s<n.length;e++)o[e]===u&&(o[e]=String(n[s++]));return o.join(d)}const jh=new WeakMap,Lh=new WeakMap;const Wh=new WeakMap;const Dh=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)}),Bh=new WeakMap;function zh(e){return Bh.get(e)??null}let Fh=!1;function qh(){Fh||(Fh=!0,kt=e=>jh.has(e)?e.host:null)}function Vh(e){return jh.get(e)??null}function Hh(e){return Uh(e).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join(d),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]}))}function Uh(e){const t=Wh.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 Kh(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Wh.get(e);if(void 0===o)return null;const s=t.indexOf(d,n),r=-1===s?t.slice(n):t.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const Gh=new WeakMap,Jh=new Set;function Xh(e,t,n,o){let s=Gh.get(e);if(void 0===s){if(!o)return null;s=new Map,Gh.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 Yh(e,t){if(!e.component.isConnected)return!1;const n=At(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 Qh(e,t,n,o){const s=Xh(e,t,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&Yh(n,t)?n:null}(r,o);if(null!==e)return{record:e,entry:r.entry}}let i=null,a=null;for(const e of s.holders){const r=e.ref.deref();void 0!==r?Yh(r,o)&&(null!==a&&ie(`[wcs/mount-export-ambiguous] "${t}${d}${n}" is exported by two mounted components on the same instance: <${a.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=e,a=r):s.holders.delete(e)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function Zh(e){const t=e.parentStateElement,n=At(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Vn](n,()=>{e.$postUpdate(o.exportedPath)})})}const ep=new WeakMap,tp=new WeakMap,np=new WeakMap,op=new WeakMap;function sp(e,t){tp.set(e,t);const n=[];for(let e=t?.listIndex.parentListIndex??null;null!==e;e=e.parentListIndex)n.push(e);op.set(e,n)}function rp(e){return At(e.component)??tp.get(e)??null}function ip(e){return rp(e)?.listIndex??null}function ap(e){ie(`The host row of <${e.component.tagName.toLowerCase()}> was removed.`)}function lp(e){for(;null!==e;e=e.parentListIndex)if(en(e))return!0;return!1}function cp(e,t){return!e.component.isConnected&&(lp(t)||!0===op.get(e)?.some(e=>en(e)))}class dp{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(e,t,n,o,s,r,i,a=!1){this.record=e,this.markerParentPath=t,this.listIndex=n,this.hostRow=o,this.isBase=s,this.receiver=r,this.handler=i,this.authorFacing=a}authorThis(e,t){return this.authorFacing?t:new Proxy(e,new dp(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return _o(ce(this.markerParentPath+d+e),this.listIndex)}hostIndexes(){const e=this.listIndex??ip(this.record),t=this.hostRow??e;return(null===this.listIndex?t!==e||cp(this.record,t):lp(t))&&ap(this.record),t?.indexes??[]}resolveTreePath(e,t){return-1===t.indexOf(u)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==ed(t).wildcardType&&!cp(this.record,this.listIndex)?t:Rh(e,t,this.hostIndexes())}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(this.resolveTreePath(e,Eh(this.record,e)))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.hostIndexes(),o=this.receiver,s=this.handler,r=this.listIndex;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Th(e,t):Eh(e,t),a=Oh(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const i=t;return(t,a,...l)=>{const c="$setAll"===i?Th(e,t):Eh(e,t),d=Oh(0,t,c,void 0===a&&"$getAll"===i&&null===r&&null===nd(s,ce(c).wildcardPaths[0])?[]:a,n);return o[i](c,d,...l)}}const e=this.record,n=this.receiver,o=nh(t,t=>this.resolveTreePath(t,Eh(e,t)),e=>n[t](...e));return null!==o?o: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 od(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(this.authorThis(e,n))}return this.receiver[this.resolveTreePath(t,Eh(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)||ie(`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,this.authorThis(e,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(e,t)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress(_o(ce(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+d+t]=n}finally{this.handler.popAddress()}return!0}return e[t]=n,!0}return this.receiver[this.resolveTreePath(t,Th(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 Eh(this.record,t),!0}catch{return!1}}}function up(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=ep.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},ep.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 dp(e,s,t.listIndex,t.listIndex??ip(e),r,n,o))}function fp(e){if(null===ip(e))return e.component[e.stateProp];let t=np.get(e);if(void 0===t){const n={row:null};np.set(e,t=[hp(e,n),n])}return t[0]}function hp(e,t){const n=()=>{const n=rp(e);return void 0!==t&&np.get(e)?.[0]!==i&&n.listIndex!==t.row&&ap(e),n},o=()=>{const t=n();return cp(e,t?.listIndex??null)&&ap(e),t?.listIndex.indexes??[]},s=(t,n)=>-1===n.indexOf(u)?n:"partial"===ed(n).wildcardType?Rh(t,n,o()):-1===n.indexOf("#")&&cp(e,ip(e))?ap(e):n,r=(t,o)=>{let s;const r=n();return e.parentStateElement.createState(t,e=>{s=e[Vn](r,()=>o(e))}),s},i=new Proxy({},{get(t,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(e,t,n,o,s){return"$postUpdate"===t?t=>n("readonly",n=>n.$postUpdate(s(t,Eh(e,t)))):(s,r,...i)=>{const a="$setAll"===t||"$resolve"===t&&i.length>0,l=a?Th(e,s):Eh(e,s),c=Oh(0,s,l,"$resolve"===t?r??[]:r,o());return n(a?"writable":"readonly",e=>e[t](l,c,...i))}}(e,n,r,o,s);const i=nh(n,t=>s(t,Eh(e,t)),e=>r("readonly",t=>t[n](...e)));if(null!==i)return i;const a=t=>t["$"===n[0]?n:s(n,Eh(e,n))],l=r("readonly",a);return"$"===n[0]||e.getterKeys.has(n)||"function"!=typeof e.stateObject[n]?l:function(...e){return r("writable",t=>a(t).apply(this,e))}},set:(t,n,o)=>("string"==typeof n&&r("writable",t=>{t["$"===n[0]?n:s(n,Th(e,n))]=o}),!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 Eh(e,n),!0}catch{return!1}}});return i}function pp(e,t){const n=Vh(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&ie(`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&&Tr(t).dispose(),function(e,t){qh(),jh.set(e,t),Bh.set(t,e);let n=Wh.get(t.parentStateElement);void 0===n&&(n=new Map,Wh.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Lh.get(t.component);void 0===o&&(o=new Map,Lh.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Dh.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=Hl.get(e);if(void 0!==n){if(n===t)return;ie("A state tree is already registered on this root.")}Hl.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Mh(e,t,n);se(t);const o=At(e.component);sp(e,o);$c(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),Ll(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=Eh(e,n)}catch{continue}const o=t.indexOf(d+e.marker);if(-1===o)continue;const s=t.slice(0,o+1+e.marker.length),r=t.slice(s.length+1),i=t.slice(0,o)+d+r,a=ce(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Xh(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),du?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=At(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(Jh.has(s))continue;const r=ce(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Vn](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Jh.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),Zh(e),o=t,s=Promise.resolve(),Ul.set(o,s),s.then(()=>Ql(o),()=>{})}function gp(e,t){Rl(mp(e,t).rebindAddresses()),Zh(e)}function mp(e,t){const n=Tr(t),o=At(e.component);return sp(e,o),n.forEachActiveBindingNode(e=>Nt(e,o)),n}function yp(e){for(let t=e.parentNode;null!==t;t=t.parentNode){const e=Vh(t);if(null!==e)return yp(e.component),void mp(e,t)}}function wp(e,t){if(function(e){const t=Wh.get(e);return void 0!==t&&t.size>0}(t))for(const n of Uh(t)){if(!bp(n.component,e))continue;const t=zh(n);null!==t&&gp(n,t)}}function bp(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 vp={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Kh(e,t.pathInfo.path);if(null!==s)return up(s,t,n,o)}return Fc},readMissing(e,t,n,o,s){if(null===n){if(rh(e.rootNode??null,t.pathInfo.path))return;return Fc}if(!0===e.hasMounts){const n=Qh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=up(e,_o(ce(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return Fc},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=ih.get(e);if(void 0===n||0===n.size)return null;const o=t+d;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&ie(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return Fc},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Qh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=up(e,_o(ce(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return Fc},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Kh(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(d,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const s=-1===o?t:t.slice(0,o),r=-1===o?"":t.slice(o+1),i=e.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:e.delta}(e,o)}return 0},handlerScope(e,t,n,o,s){if(!0!==e.hasMounts)return s;const r=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=jh.get(n);if(void 0!==e)return e;n=n.parentNode}return jh.get(t)??null}(t,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(e,t,n){const o=function(e){return uh.get(e)??fh}(e);for(const s of o){const o=new Set,r={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(-1!==t.indexOf("#"))continue;const i=ch(s.mountPath,s.injections,t);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const e=ho(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(dh(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>rh(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){wp(t,e)}};let $p=!1;function xp(){$p||($p=!0,Hc("scopes",vp),Su=Hh)}const Sp=new WeakMap;function Ip(e){let t=Sp.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Sp.set(e,t)),t}function Pp(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=oh.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function kp(e,t,n){if(t.slotRootNode===n)return!0;const o=t.mountPath;try{sh(n,o,e)}catch{return console.error(`[@wcstack/state] <${s.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return Jl(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Ap(e,t){const n=e,o=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&ie('"mount" requires a non-empty tree path.');const t=ce(e);for(const n of t.segments)0===n.length&&ie(`"mount" path "${e}" has an empty segment.`),n===u&&ie(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&ie(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],o=new Set;let r;try{r=Be(e)}catch(e){ie(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> has an invalid ${s.bindAttributeName}: ${e instanceof Error?e.message:String(e)}`)}for(const e of r){if(e.propSegments[0]!==N)continue;const r=e.propSegments.slice(1),i=e.statePathInfo,a=n=>ie(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> "${e.propName}: ${e.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==u&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${N}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(e.inFilters.length>0||e.outFilters.length>0)&&a("an injection takes no filters."),e.propModifiers.some(e=>e!==b)&&a(`an injection accepts only #${b}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:e.propModifiers.includes(b)})}return n.sort((e,t)=>t.innerSegments.length-e.innerSegments.length),n}(n.getAttribute(s.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&ie('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${s.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),sh(o,r,e),Jl(o)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=o}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===Jl(o)&&function(e,t){const n=()=>{if(null!==Jl(e))return;const n=e.querySelectorAll(s.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${s.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${s.tagNames.state}> to this root node (an empty <${s.tagNames.state}></${s.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=e.ownerDocument??e;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&Pp(e,t),e.settleInitialization()};let l;try{await Promise.resolve(),l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const c=e.connectedRootNode??null;null!==c&&kp(e,t,c)?function(e,t,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};if(null!==t)return void ng(t,a);sg(),function(e,t){if(ph.has(e))return void gh(t);let n=hh.get(e);void 0===n&&(n=[],hh.set(e,n)),n.push(t)}(e,a)}(c,Jl(c),r,l,a,()=>kp(e,t,c),i):a(null)}const Np={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=Ip(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{sh(n,t.mountPath,e),Jl(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,ou}return Ap(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Ip(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&Jl(n)===t.graftInfo.rootStateElement&&Zp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Sp.get(e)?.initializing)return;const t=e.getAttribute("mount");ie(`Cannot replace the state of <${s.tagNames.state} mount="${t}"> 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 "${t}" on the root state instead.`)},initializeFailed(e,t){!function(e){ph.add(e);const t=hh.get(e);if(void 0!==t){hh.delete(e);for(const e of t)gh(e)}}(t)},initializeFailureCleared(e,t){!function(e){ph.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Ip(e);return null!==t.graftInfo&&Zp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,Pp(e,t)),e.clearConnectedRootNode(),!0}};let _p=!1;const Tp=new WeakMap;function Ep(e,t){let n=Tp.get(e);n||(n=new Set,Tp.set(e,n)),n.add(t)}const Cp=new WeakMap;const Mp=new WeakMap,Op=new WeakMap;const Rp=new WeakMap;const jp={isComplete:function(e,t){return!0===Tp.get(e)?.has(t)},isDeclared:function(e,t){return!0===Cp.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=Mp.get(e);o||(o=new Map,Mp.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=Op.get(e);o||(o=new Map,Op.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)},rememberOverwrittenValue:function(e,t,n,o){let s=Rp.get(e);s||(s=new Map,Rp.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function Lp(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 Wp=new WeakMap;class Dp{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=Wp.get(e);return n?n.get(t)??null:null}(e,t)??ie("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 Bp=e=>()=>e;function zp(e,t,n,o){!function(e,t,n){let o=Wp.get(e);o||(o=new Map,Wp.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(Lp(o));const s=function(e,t){const n=new Dp(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Bp(s),enumerable:!0,configurable:!0}),Ep(t,n),Fp(t,n)}function Fp(e,t){if(B in e){const n=e[B];"function"==typeof n?n.call(e,t).catch(e=>{ie(`Error in ${B}: ${e instanceof Error?e.message:String(e)}`)}):ie(`${B} is not a function.`)}}const qp=new Set;function Vp(e,t){qp.has(e)||(qp.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function Hp(e){!function(e){const t=e.component.tagName.toLowerCase(),n=e.stateProp;let o=null;for(const s of e.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=cu(e.stateObject);const i=o[r];let a;if(e.getterKeys.has(r)||e.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)a="an accessor";else if("function"==typeof i?.value)a="a method";else{if(e.mappedKeys.has(r)||e.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(e.stateObject,r))continue;a="an own data key"}const l=s.innerSegments.join(d);Vp(`${t}|${n}|${l}|entry`,`<${t}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${l}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(e);const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=Up(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;Vp(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}function Up(e){const t=e.rootEntry,n=At(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Vn](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Kp=new WeakMap;function Gp(e,t){e.landInitialization(),ie(t)}async function Jp(e,t){const n=e;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?Qe(a):null;null!==a&&null!==l||ie(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(s.bindAttributeName)||Gp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(e=>n.hasAttribute(e));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&ie(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(e,t){let n=Cp.get(e);n||(n=new Set,Cp.set(e,n)),n.add(t)}(a,d);const u=et(a);null===u&&ie(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await Je(a),d in a||ie(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||ie(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=Mp.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==h&&function(e,t){if(!e.hasAttribute(s.bindAttributeName))return!1;const n=pt(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(a,d)&&(a[d]=h,f=h),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(pt(a)??[]).some(e=>e.propSegments[0]===d)||Gp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(s.bindAttributeName)){const s=(pt(a)??[]).filter(e=>e.propSegments[0]===d);if(s.length>0){const c=Jl(a.getRootNode())??Gp(e,`No state tree found on this root for mount host <${l}>.`);let u=(o=a,r=d,Lh.get(o)?.get(r)??null);const h=null!==u;if(null===u&&(!function(e,t,n){const o=Rp.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;Rp.get(e).delete(t)}}(a,d,f),u=$h(a,d,s,c,f,function(e,t){return Op.get(e)?.get(t)}(a,d)),Hp(u)),t.mountRecord=u,n.parentNode!==i)return;try{pp(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=hp(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),Ep(a,d)}return Fp(a,d),function(e){const t=wh.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(Y)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;bh.has(n)||(bh.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.`))}(u),void vh(u,"$connectedCallback",()=>fp(u))}}zp(e,t.boundComponent,t.boundComponentStateProp,f)}var o,r}const Xp={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=Kp.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Kp.set(e,t)),t}(e);return Jp(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Kp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&gp(n,o)}),e.isConnected&&(yp(n.component),mp(n,o)),vh(n,"$connectedCallback",()=>fp(n)),!0},disconnecting(e){const t=Kp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord;return vh(n,"$disconnectedCallback",()=>fp(n)),function(e){const t=np.get(e);void 0!==t&&(t[1].row=ip(e),np.delete(e))}(n),Zh(t.mountRecord),e.clearConnectedRootNode(),!0}};let Yp=!1;function Qp(){Yp||(Yp=!0,iu("bindComponent",Xp),Cr=jp)}function Zp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(dh(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function eg(e,t,n,o){const s=n[G];if(void 0!==s){const n=xu(t),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=lh(t,o,n,!1),c=function(e,n,...s){l.call(dh(t,this,o),e,n,...s)};r.push({path:s,pathInfo:ce(s),handler:c,order:1e6+a++}),i.add(s),e.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(e,r),e.addVolumeWatchPaths?.(i),n.start(e))}const r=n[Q];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(lh(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[W];"function"==typeof i&&(!function(e,t){let n=uh.get(e);void 0===n&&(n=[],uh.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,injections:o,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 tg(e,t,n,o=[]){Lc(n),function(e,t,n,o){const s=0===o.length?null:cu(n);for(const e of o){const n=e.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||ie(`[wcs/mount-path-invalid] Volume "${t}" declares "${n}" as an accessor or a method and also injects it ("${N}.${n}: ${e.outerPathInfo.path}"). Rename one of them.`)}const r=n[G];if(void 0!==r){"object"==typeof r&&null!==r||ie(`${G} must be an object mapping state paths to handler functions.`);const e=xu(t);for(const[t,n]of Object.entries(r))"function"!=typeof n&&ie(`${G} entry "${t}" must be a function.`),e.assertValidPath(t)}const i=n[Q];if(void 0!==i){"object"==typeof i&&null!==i||ie(`${Q} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(i)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&ie(`${Q} entry "${n}" must map a list path to a field name or a key function.`);const r=lh(t,o,n,!1);e.listKeys?.has(r)&&ie(`${Q} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[K]&&ie(`Volume "${t}" declares ${K}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&ie(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[X]&&ie(`Volume "${t}" declares ${X}, 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(cu(n)))-1!==e.indexOf(Y)&&ie(`Volume "${t}" declares "${e}", which uses "${Y}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n,o);const{data:s,accessors:r}=function(e,t){const n={},o=new Map;for(const[s,r]of Object.entries(cu(e)))s.startsWith("$")||t.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(e=>e.innerSegments[0]))),i=ce(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;ie(`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],s=""===n?o in e:void 0!==e[n+d+o];n=""===n?o:n+d+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;ie(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=s}),function(e,t){let n=ih.get(e);void 0===n&&(n=new Set,ih.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+d+n,i=s.get,a=s.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(dh(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(dh(t,this,o),e)}),e.defineTreeAccessor(r,l)}eg(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(dh(t,e,o))}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,injections:o}}function ng(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=tg(e,t.mountPath,t.volumeState,t.injections)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let og=!1;function sg(){var e;og||(og=!0,xp(),_p||(_p=!0,iu("scopes",Np)),Qp(),mh=ng,e=rg,Gl.includes(e)||Gl.push(e))}function rg(e,t){(function(e){const t=oh.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){ph.delete(e);const n=hh.get(e);if(void 0===n||0===n.length||null===mh)return;hh.delete(e);const o=mh;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const ig={name:"scopes",install(){sg(),Yf||(Yf=!0,iu("dcc",Xf))}},ag=/^@@wcs-(?:for|if|elseif|else):[^-]/,lg=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,cg=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,dg=/^@@wcs-text-start:(.+)$/;function ug(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function fg(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const e=n.currentNode;t(e.data)&&o.push(e)}return o}const hg=e=>ag.test(e),pg=e=>lg.test(e),gg=e=>lg.test(e)||cg.test(e);function mg(e){if("else"===e.bindingType)return"else:";let t=`${e.bindingType}: ${e.statePathName}`;for(const n of e.outFilters){const e=n.literals??n.args;t+=`|${n.filterName}`,n.args.length>0&&(t+=`(${n.args.map((t,n)=>"string"==typeof e[n]?`'${t.split("'").join("'\"'\"'")}'`:t).join(",")})`)}return t}function yg(e){const t=e.fragment.cloneNode(!0);for(const n of e.nodeInfos){const o=pc(dt(e.fragment,n.nodePath));if(null===o)continue;const s=dt(t,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return t}class wg extends lu{_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=Pu.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=s.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,o){const r=o??e.ownerDocument;n.seen&&function(e){const t=new Map;for(const n of fg(e,pg)){if(null===n.parentNode)continue;const[,e,o]=lg.exec(n.data),s=o.split(":")[0],r=n.previousSibling?.data,i=`@@wcs-${e}-end:${o}`;if(r!==`@@wcs-${e}:${s}`&&t.get(r)!==s)for(let e=n;null!==e;){const t=e.nextSibling;e.remove(),e=e.data===i?null:t}else"for"===e&&t.set(i,s)}}(r);const i=document.createElement("script");i.setAttribute("type","application/json"),i.textContent=ug(JSON.stringify(t)),e.appendChild(i);for(const[t,n]of function(e){const t=new Map,n=[e];for(;n.length>0;)for(const e of fg(n.shift(),hg)){const o=e.data,s=o.slice(o.indexOf(":")+1);if(t.has(s))continue;const r=nc(s);null!==r&&(t.set(s,r),n.push(r.fragment))}return t}(r)){const o=document.createElement("template");o.setAttribute("id",t),o.setAttribute(s.bindAttributeName,mg(n.parseBindTextResult)),o.content.appendChild(yg(n)),e.appendChild(o)}const a=e.ownerDocument,l=Array.from(el);if(l.length>0){const t={};for(let e=0;e<l.length;e++){const n=l[e];if(!n.isConnected||n.ownerDocument!==a)continue;const o=Za(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const e of o)r[e.propName]=e.value;t[s]=r}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ug(JSON.stringify(t)),e.appendChild(n)}}tl()}static removeBlockBoundaryComments(e){for(const t of fg(e,gg))t.remove()}static removeStructuralComments(e){for(const t of fg(e,hg))t.remove()}static restoreTextBindings(e){for(const t of fg(e,e=>dg.test(e))){const e=dg.exec(t.data)[1],n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;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(s.tagNames.ssr),o=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&o.set(t,e)}}for(const e of fg(t,pg)){const t=lg.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()}wg.restoreTextBindings(t);const r=e=>{for(const t of fg(e,hg)){const e=o.get(t.data.split(":")[1]);if(e){const n=document.createElement("template"),o=e.getAttribute(s.bindAttributeName);o&&n.setAttribute(s.bindAttributeName,o);const i=document.importNode(e.content,!0);if(i.childNodes.length>0)n.content.appendChild(i);else for(const t of Array.from(e.childNodes))n.content.appendChild(document.importNode(t,!0));r(n.content),t.parentNode.replaceChild(n,t)}}};r(t);const i=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of i)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const bg={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=s.tagNames.state,n=s.tagNames.ssr,o=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of o){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Pu),wg.buildContent(o,wg.extractStateData(e),e.getRootNode()),e.parentNode?.insertBefore(o,e)}tl()},reset:function(){ec.clear(),tl(),n.seen=!1}};const vg=new Set(["for","if","elseif","else"]);function $g(e){const[,t,n]=lg.exec(e),[o,...s]=n.split(":");return"for"===t?{type:t,uuid:o,path:s[0],index:parseInt(s[1],10),nodes:[]}:{type:t,uuid:o,path:s.join(":"),index:null,nodes:[]}}function xg(e){const t=[];for(const n of e)if(n.nodeType===Node.ELEMENT_NODE){const e=n;e.hasAttribute(s.bindAttributeName)&&t.push(e),Array.from(e.children).some(e=>e.localName===s.tagNames.state&&gt(e))||t.push(...wt(e))}else null!==Ve(n)&&t.push(n);return t}function Sg(e){const[t,n,o]=xt(e),s=new _r;return{bindingInfos:s.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:t,bindingSession:s,deferredSpreads:o}}const Ig=/^\s*@@\s*(?:wcs-text)?\s*:/;function Pg(e,t){for(const n of t)"event"===n.bindingType||vg.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&Ig.test(n.node.data))&&e.push(n)}function kg(e,t){const n=[];for(let o=0;o<e.nodes.length;o++){const s=t.get(e.nodes[o]);s?o+=s.nodes.length+1:n.push(e.nodes[o])}return n}function Ag(e,t,n,o,s,r){t.length>0&&(e.spreads=t);for(const e of t)St(e.node);jl(t,n,o,s,r)}function Ng(e,t){const n=nc(t),o=Jl(e.getRootNode());let s=null;if(n&&o){const{statePathName:e,outFilters:t}=n.parseBindTextResult;o.createState("readonly",n=>{const o=Mr(n[e],ut(t,"output"));Array.isArray(o)&&(s=o)})}return s}function _g(e,t){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[e]}:${t}`}function Tg(e,t,n){const o=_g(t,n);return fg(e,e=>e===o)[0]??null}function Eg(e,t){const n=e,o=t.templates,r=new Map;for(const[e,t]of o)for(const n of fg(t.content,hg))r.set(n.data.slice(n.data.indexOf(":")+1),e);const i=new Set(mt(e));if(i.size>0)for(const e of fg(n,hg)){const t=e.data.slice(e.data.indexOf(":")+1);let n=e.parentNode;for(;null!==n&&!i.has(n);)n=n.parentNode;null===n||r.has(t)||r.set(t,n)}const a=new Map,l=[];for(const[e,t]of o){let n=Be(t.getAttribute(s.bindAttributeName)||"")[0];const o=n.bindingType,i=r.get(e),c=a.get(i);"else"===o&&c&&(n={...c,outFilters:[...c.outFilters,rc()],bindingType:"else"}),"if"===o||"elseif"===o?a.set(i,n):"else"===o&&a.set(i,null),l.push([e,t,n])}for(const[e,t,o]of l.reverse()){const s=document.importNode(t.content,!0),r="for"===o.bindingType?o.statePathName:void 0;mc(s),"string"==typeof r&&uc(s,r),$c(n,s,r);tc(e,n,{fragment:s,parseBindTextResult:o,nodeInfos:gc(s)})}}const Cg={hydrate:async function(e){await Dl(e);const t=e.querySelectorAll(s.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="${Pu}". Falling back to full render.`),wg.cleanupDom(e),!1}const n=function(e){const t=[];for(const n of fg(e,gg)){if(!pg(n.data)){t.pop();continue}const e=$g(n.data),o=t.at(-1);if("for"===e.type&&o&&o.uuid!==e.uuid)return[e,o];t.push(e)}return null}(document.body);if(null!==n){const[t,o]=n;return console.warn(`[@wcstack/state] SSR: "for: ${t.path}" in "${o.type}: ${o.path}" (known limitation). Falling back to full render.`),wg.cleanupDom(e),!1}for(const n of t)Eg(e,n);wg.restoreTextBindings(document.body);const o=function(e){const t=[];for(const n of fg(e,pg)){const e=$g(n.data);e.start=n;const o=n.data.replace("-start:","-end:");let s=n.nextSibling;for(;s&&(s.nodeType!==Node.COMMENT_NODE||s.data!==o);)e.nodes.push(s),s=s.nextSibling;t.push(e)}return t}(document.body),r=new Map,i=function(e,t,n=new Map){const o=new Map,s=[],r=new Map(t.map(e=>[e.start,e])),i=new Set;for(let e=t.length-1;e>=0;e--){const n=xg(t[e].nodes).filter(e=>!i.has(e));for(const e of n)i.add(e);t[e].subscribers=n}for(const i of t){const t=kg(i,r);if(0===t.length)continue;const a=t.some(e=>hg(e.data));if(a){const e=document.createComment(`wcs-row-end:${i.uuid}`);i.nodes[i.nodes.length-1].after(e),t.push(e)}const{bindingInfos:l,subscriberNodes:c,bindingSession:d,deferredSpreads:f}=Sg(i.subscribers);for(const e of l)if(e.node!==e.replaceNode){const n=t.indexOf(e.node);n>=0&&(t[n]=e.replaceNode)}const h=Na(t,a);la(h,d),Wr(h,l),zr(h,c);const p=l.filter(e=>Aa(e,-1));if(Hr(h,p),"for"===i.type&&null!==i.index){const t=Tg(e,"for",i.uuid);if(t){let e=n.get(i.uuid);if(!e){const s=Ng(t,i.uuid)??i.path;e=o.get(s),e||o.set(s,e=[]),n.set(i.uuid,e)}const r=e[i.index]??=jt(null,i.index);Fa(t,r,h),qa(t,h.lastNode),wa(t,h);const a=_o(ce(i.path+"."+u),r);Fr(h,a),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Pg(s,l),Ag(h,f,a,d,l,p)}}else{const t=i.start.previousSibling,n=t?.data===_g(i.type,i.uuid)?t:Tg(e,i.type,i.uuid);if(n){wa(n,h);const e=At(n);Fr(h,e),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Pg(s,l),Ag(h,f,e,d,l,p)}}}return s}(document.body,o,r);wg.removeBlockBoundaryComments(document.body);const a=[];for(const e of t)e.parentNode&&(a.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());const[,l,c]=$t(document.body),d=[],f=[],h=Tr(document.body),p=h.initialize(l);jl(c,null,h);for(const e of p)if("event"!==e.bindingType)if(vg.has(e.bindingType))f.push(e);else{if(e.statePathName.includes(u))continue;d.push(e)}for(const e of f)if("for"===e.bindingType){const t=wo(e),n=Jl(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=Mr(n[e.statePathName],e.outFilters);if(Array.isArray(o)){const n=r.get(e.uuid);n&&vn(o,n),En(t,o),s=e.node,i=o,Da.set(s,xn(i)),Bn(t,o)}var s,i})}Rl([...d,...i]);for(const{el:e,parent:t,next:n}of a)t.insertBefore(e,n);const g=new Map;for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))g.set(t.getAttribute("data-wcs-ssr-id"),t);for(const t of e.querySelectorAll(s.tagNames.ssr))for(const[e,n]of Object.entries(t.hydrateProps)){const t=g.get(e);if(t)for(const[e,o]of Object.entries(n))Cr?.isDeclared(t,e)||(t[e]=o)}for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))t.removeAttribute("data-wcs-ssr-id");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=wg.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Xl(e.rootNode);const t=wg.extractStateData(e),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",Pu),wg.buildContent(n,t,e.rootNode),e.parentNode?.insertBefore(n,e)}};let Mg=!1;function Og(){Mg||(Mg=!0,ql=Cg,function(e){if(!gu.includes(e)){gu.push(e);for(const t of yu())e(t)}}(e=>{e.get(s.tagNames.ssr)||e.define(s.tagNames.ssr,wg)}),function(){const t=globalThis;void 0===t[e]&&(t[e]=bg)}())}const Rg={name:"ssr",install(){Og()}},jg=new WeakMap,Lg=new Set,Wg=new Set;function Dg(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Bg(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function zg(e){return jg.get(e)}function Fg(e){qg(e),jg.delete(e)}function qg(e){Lg.delete(e),Wg.delete(e)}const Vg=new WeakSet;let Hg=0;function Ug(e){return zg(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Kg(e){if(0===Wg.size)return;if(t=e.absolutePathInfo.stateElement,!Wg.has(t))return;var t;const n=Ug(e);if(void 0!==n)for(const e of n)Gg(e)}function Gg(e){Vg.has(e)||(Vg.add(e),Hg++)}function Jg(e){return!!Vg.delete(e)&&(Hg--,!0)}const Xg=/^(?:0|[1-9]\d*)$/;function Yg(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Qg(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&&Xg.test(t)&&Yg(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Yg(e,t))?"object":null}function Zg(e,t){const n=Qg(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]=Zg(o[e],t);return r}function em(e){return Zg(e,new Map)}function tm(e,t,n){if(Object.is(e,t))return!0;const o=Qg(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(Qg(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(!tm(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&tm(s[e],r[e],n))}function nm(e,t){return tm(e,t,new Map)}const om=new WeakMap;function sm(e,t){if("function"!=typeof t)return;const n=om.get(t);void 0===n?om.set(t,new Set([e])):n.add(e)}function rm(e,t){return"function"==typeof t&&!0===om.get(t)?.has(e)}const im={"read-source":e=>`${J} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-rows":e=>`${J} could not read the rows of "from" for "${e}". Nothing was folded or written.`,"read-output":e=>`${J} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${J} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${J} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${J} could not write the output "${e}".`},am={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function lm(e,t,n){null!==_t&&_t({type:"state:watch-error",phase:t,path:`${J}.${e}`,error:n})}function cm(e,t,n){console.error(`[@wcstack/state] ${im[n](e)}`,t),lm(e,am[n],t)}function dm(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function um(e,t){t.then(void 0,()=>{}),cm(e,new TypeError(`${J} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const fm=new WeakSet;const hm="[wcs/scan-declaration-invalid]",pm=Object.freeze([]);function gm(e){return`${J} entry "${e}"`}function mm(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function ym(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${u}${u}`)?`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.${he}`}function wm(e,t,n){0===n.length&&ie(`${hm} ${e} "${t}" must be a non-empty state path.${he}`),n.startsWith("$")&&ie(`${hm} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${he}`),n.includes("@")&&ie(`${hm} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${he}`),n in Object.prototype&&ie(`${hm} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${he}`);const o=ce(n);for(const s of o.segments)0===s.length&&ie(`${hm} ${e} ${t} "${n}" has an empty path segment.${he}`);return o.wildcardCount>f&&ie(`${hm} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function bm(e,t,n,o){const s=gm(e);0===e.length&&ie(`${hm} ${J} entry name must be a non-empty string.${he}`),(e.includes(d)||e.includes(u))&&ie(`${hm} ${s} must be a flat property name ("${d}" and "${u}" are not allowed). The output is a property the runtime owns.${he}`),e.startsWith("$")&&ie(`${hm} ${s} must not start with "$" (reserved namespace).${he}`),e in Object.prototype&&ie(`${hm} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${he}`),t.has(e)&&ie(`${hm} ${s} conflicts with a getter declared on the state.${he}`),n.has(e)&&ie(`${hm} ${s} conflicts with a setter declared on the state.${he}`),o.has(e)&&ie(`${hm} ${s} conflicts with the ${K} entry of the same name — each output has exactly one owner.${he}`)}function vm(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!rm(e,o)&&ie(`${hm} ${gm(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${he}`)}function $m(e,t,n,o,s,r){const i=gm(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&ie(`${hm} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${he}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||ie(`${hm} ${i} "on" must be a non-empty event-token name.${he}`),n.has(e)||ie(`${hm} ${i} on "${e}" is not declared in ${H}.${fe(e,n)}${he}`),{kind:"event",tokenName:e}}const c=t.from;"string"!=typeof c&&ie(`${hm} ${i} "from" must be a state path string.${he}`);const u=wm(i,"from",c),f=mm(u,o)??r?.recursiveGetterOwning(c)??null;null!==f&&ie(ym(i,"from",c,f));const h=mm(u,s);return null!==h&&ie(function(e,t,n){return`${hm} ${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.${he}`}(i,c,h)),(c===e||c.startsWith(e+d))&&ie(`${hm} ${i} from "${c}" reads the entry's own output — the scan would fold its own writes forever.${he}`),{kind:"path",path:c,pathInfo:u}}function xm(e,t,n,o){if(void 0===t)return pm;const s=gm(e);Array.isArray(t)||ie(`${hm} ${s} "resetOn" must be an array of state paths.${he}`);const r=[];for(const e of t){"string"!=typeof e&&ie(`${hm} ${s} "resetOn" must contain only state path strings.${he}`);const t=wm(s,"resetOn",e);t.wildcardCount>0&&ie(`${hm} ${s} resetOn "${e}" must not contain "${u}" — a reset returns the whole output to "initial".${he}`);const i=mm(t,o);null!==i&&ie(ym(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&ie(`${hm} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${he}`),"path"===n.kind&&e.startsWith(n.path+d)&&ie(`${hm} ${s} 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.${he}`),r.push(e)}return r}function Sm(e,t,n=null){const o=e[J];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&ie(`${hm} ${J} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${he}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(cu(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){Lc(e);const t=e[K];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)){bm(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&ie(`${hm} ${gm(e)} must be an object ({ from | on, initial, fold, resetOn? }).${he}`);const o=u;vm(e,a,o);const f=$m(e,o,t,s,i,n);"initial"in o||ie(`${hm} ${gm(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${he}`),"function"!=typeof o.fold&&ie(`${hm} ${gm(e)} fold must be a function.${he}`);const h=xm(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=ce(e).segments[0];t.has(n)&&ie(`${hm} ${gm(o.name)} resetOn "${e}" reads the ${J} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${he}`)}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&&ie(`${hm} ${J} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${he}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Im(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 Vg.has(e)}(e),l=a&&!nm(n,e.initial)?em(e.initial):n,c=t(l,o,...s);if(dm(c))return void um(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,sm(e.name,c)),a&&Jg(e)}catch(t){cm(e.name,t,i)}}}function Pm(e,t,n){const o=function(e,t){Fg(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Bg(n,e.source.path,e);for(const t of e.resetOn)Bg(o,t,e),"event"===e.source.kind&&Bg(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return jg.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)&&ci().hasQueuedPath(e,n))&&Gg(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}const km="scanEntries",Am={order:8,validate(e,t,n){const o=Sm(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(km,o)},applyEarly(e,t,n){const o=n.get(km)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=em(n.initial);e[n.name]=t,sm(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Ho(e,n.source.tokenName).subscribe(Im(n))}(e,o))},register(e,t,n){const o=n.get(km)??null,s=function(e){const t=new Map,n=zg(e);if(void 0!==n)for(const e of n.entries)Jg(e)&&t.set(e.name,e.resetOn);return Fg(e),t}(e);e.setScanPaths?.(null===o?null:Pm(e,o,s))}};let Nm=!1;const _m=Object.freeze([]),Tm=Object.freeze([]);function Em(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??_m,i=e.dynamicDependency.get(n)??_m,a=t.byFromPath.get(n)??Tm;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Cm=Symbol("wcs-stream-last-notified-uncertain"),Mm=new WeakMap;function Om(e,t){const n=Mm.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Rm(e,t){const n=Mm.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Cm,error:Object.is(o.error,null)?null:Cm})}const jm=new Set;function Lm(e){jm.delete(e)}const Wm=new WeakMap;function Dm(e){return Wm.get(e)??new Map}function Bm(e){Lm(e);const t=Wm.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Rm(e,n.name)}const zm=(e,t)=>t,Fm=new Set;function qm(e,t){Lc(t);const n=t[K];if(void 0===n)return void Om(e,Fm);"object"==typeof n&&null!==n||ie(`${K} must be an object mapping stream names to stream definitions.`);const o=new Map,s=cu(t);for(const[r,i]of Object.entries(n)){0===r.length&&ie(`${K} entry name must be a non-empty string.`),r.includes(d)&&ie(`${K} entry "${r}" must be a flat property name ("${d}" is not allowed).`),r.includes(u)&&ie(`${K} entry "${r}" must be a flat property name ("${u}" is not allowed).`),r.startsWith("$")&&ie(`${K} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&ie(`${K} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(r)&&ie(`${K} entry "${r}" conflicts with a getter declared on the state.`),e.setterPaths.has(r)&&ie(`${K} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||ie(`${K} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||rm(r,a)||ie(`${K} entry "${r}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&ie(`${K} entry "${r}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&ie(`${K} entry "${r}" fold must be a function.`),l&&!("initial"in n)&&ie(`${K} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&ie(`${K} entry "${r}" args must be a function.`);const c={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??zm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in t||(t[r]=c.definition.initial,sm(r,c.definition.initial)),o.set(r,c)}!function(e,t){Wm.set(e,t)}(e,o),Om(e,new Set(o.keys()))}const Vm=new WeakMap,Hm=new WeakMap;function Um(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Dm(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Dm(e).has(n),ownKeys:()=>Array.from(Dm(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Dm(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){ie(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){ie(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Km(e){const t=Vm.get(e);if(void 0!==t)return t;const n=Um(e,Z,e=>e.status);return Vm.set(e,n),n}function Gm(e){const t=Hm.get(e);if(void 0!==t)return t;const n=Um(e,ee,e=>e.error);return Hm.set(e,n),n}function Jm(e){Vm.delete(e),Hm.delete(e)}let Xm=null;function Ym(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}const Qm={read(e,t){!function(e,t){null!==Xm&&Xm.add(so(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===Z?Ym(Km(e),t.pathInfo.segments):n===ee?Ym(Gm(e),t.pathInfo.segments):Fc},get:(e,t)=>t===Z?Km(e.stateElement):t===ee?Gm(e.stateElement):Fc};let Zm=0,ey=null,ty=0;const ny=new WeakMap;function oy(e){Zm=e+1}function sy(){Zm=0}function ry(e){if(Zm>0){const t=ey??=new Map;Zm>(t.get(e)??0)&&t.set(e,Zm),ty=Math.max(ty,Zm)}}function iy(e,t){return ny.get(e)?.get(t)??0}async function ay(e,t,n,o){let s=null;const r=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",r,{once:!0});try{const i=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] ${K}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();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",r)}}function ly(e){gy();const t=Dm(e);if(0!==t.size){!function(e){jm.add(e)}(e);for(const n of t.values())cy(e,n)}}function cy(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=Xm,s=new Set;let r;Xm=s;try{e.createState("readonly",e=>{r=n(e)})}finally{Xm=o}r instanceof Promise&&ie(`${K} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${Z}${d}${t.name}`,a=`${ee}${d}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||ie(`${K} 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&&ie(`${K} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);!function(e,t){const n=zg(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=Em(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&ie(`[wcs/scan-feedback-loop] ${K} entry "${t.name}" args read "${n}", which is derived from the ${J} 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}),sm(t.name,t.definition.initial),dy(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{const o=s.fold(e[t.name],n);e[t.name]=o,sm(t.name,o)})},done(){dy(e,t,"done",null)},fail(o){dy(e,t,"error",o),n.abort()}};ay(s.source,o,n.signal,r)}function dy(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return Mm.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=Mm.get(e);void 0===s&&(s=new Map,Mm.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${Z}${d}${t.name}`),i&&e.$postUpdate(`${ee}${d}${t.name}`)}))}function uy(e){const t=jm;if(0===t.size)return;const n=[];for(const o of t)for(const t of Dm(o).values()){let s=-1;for(const n of t.depAddresses)e.has(n)&&(s=Math.max(s,iy(e,n)));s>=0&&s<=32&&n.push({stateElement:o,entry:t,depth:s})}try{for(const{stateElement:e,entry:o,depth:s}of n)if(t.has(e)&&Dm(e).get(o.name)===o){oy(s);try{cy(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Dm(e).get(o.name)===o&&dy(e,o,"error",n)}}}finally{sy()}}let fy=!1;const hy=new WeakMap,py={order:20,apply(e,t){var n;Jm(e),Bm(n=e),Lm(n),Wm.delete(n),qm(e,t),void 0!==t[K]&&e.attachAddressHooks?.("streams",K)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return ly(e),void hy.set(e,e.connectGeneration??0)}n===e.connectGeneration&&hy.get(e)!==n&&ly(e)}},deactivate(e){Bm(e),Jm(e)}};function gy(){fy||(fy=!0,Hc("streams",Qm),Jc("streams",py),ri(uy,20))}const my=new WeakMap;function yy(e,t,n){let o=my.get(e);void 0===o&&(o=new Map,my.set(e,o)),o.set(t,n)}const wy=new Map;function by(e,t){wy.has(e)||wy.set(e,t)}function vy(e){return wy.get(e)}const $y=new WeakMap,xy=new WeakMap,Sy=new Set,Iy=new Map;function Py(e){return $y.get(e)??Iy}function ky(e){Sy.add(e),function(e){const t=jg.get(e);void 0!==t&&(Dg(t)&&Lg.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Wg.add(e))}(e)}function Ay(){return Sy}function Ny(e,t){let n=xy.get(e);void 0===n&&(n=new Map,xy.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)}}const _y=new Map;function Ty(e){return xy.get(e)??_y}function Ey(e){0===e.length&&ie(`[wcs/watch-declaration-invalid] ${G} entry name must be a non-empty state path.`),e.startsWith("$")&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not start with "$" (reserved namespace).${he}`),e.includes("@")&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${he}`),e in Object.prototype&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ce(e);for(const n of t.segments)0===n.length&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" has an empty path segment.${he}`);return t.wildcardCount>f&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Cy(e,t){const n=t[G];if(void 0===n)return null;"object"==typeof n&&null!==n||ie(`[wcs/watch-declaration-invalid] ${G} must be an object mapping state paths to handler functions.${he}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${t}" must be a function.${he}`);const n=Ey(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){$y.set(e,t)}(e,o),s.size>0?s:null}const My={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||by(n,o)},swapped(e,t,n){var o;o=n,wy.has(o)&&by(t,vy(n))}};function Oy(e){for(let t=e;null!==t;t=t.parentListIndex)if(en(t))return!0;return!1}function Ry(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[Hn](_o(t.wildcardParentPathInfos[i],r)),l=mn(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=fo(o,i,t.wildcardCount);if(l!==c&&!Gt(l,c)){if(en(c))return"gone";s="replaced"}r=l}return s}function jy(e,t,n){const o=new Map;for(const s of n){const n=Ry(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 Ly=Object.freeze([]);function Wy(e,t,n,o){let s=e.get(n);return void 0===s&&(s={stateElement:t,entry:n,rows:[],reset:!1,depth:o},e.set(n,s)),s.depth=Math.max(s.depth,o),s}function Dy(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 By(e,t){return t.has(e.stateElement)&&!0===zg(e.stateElement)?.entries.has(e.entry)}function zy(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Fy(n,e))||Jg(t)}function Fy(e,t){return ci().hasQueuedPath(e,t)}function qy(e,t){!function(e,t,n){if(0!==Hg)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=Ug(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||Jg(t)}}(e,t,Fy)}function Vy(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function Hy(e,t,n){if(!By(e,n))return zy(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(fm.has(e))return;fm.add(e);const o=`[wcs/scan-source-computed] ${J} 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}`),lm(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=Dm(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];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?e.rows:jy(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Dy)){let n;try{n=Vy(t,r,e)}catch(e){cm(s.name,e,"read-source");continue}const o=a(l,n,vy(e.absAddress),...e.indexes);if(dm(o))return void um(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){cm(s.name,e,i.failure)}return i.plan}function Uy(e,t){const{group:n}=e;if(!By(n,t))return void zy(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Jg(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!nm(o,s.initial):!Object.is(o,e.next)){const o=n.reset?em(s.initial):e.next;t[s.name]=o,sm(s.name,o)}})}catch(e){cm(s.name,e,"write")}}function Ky(e,t){if(qy(e,t),0===Lg.size)return Ly;const n=new Map;for(const o of e){const s=o.absolutePathInfo.stateElement;if(!t.has(s))continue;const r=zg(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=iy(e,o),l=r.byFromPath.get(i.path);if(void 0!==l){let e=[];if(i.wildcardCount>0){if(null===o.listIndex)continue;e=ho(o.listIndex,i.wildcardCount)}for(const t of l)Wy(n,s,t,a).rows.push({absAddress:o,indexes:e})}const c=r.byResetPath.get(i.path);if(void 0!==c)for(const e of c)Wy(n,s,e,a).reset=!0}if(0===n.size)return Ly;const o=Array.from(n.values()).sort((e,t)=>e.entry.order-t.entry.order),s=[];try{for(const n of o){oy(n.depth);const o=Hy(n,e,t);null!==o&&s.push(o)}}finally{sy()}return s}function Gy(e){ow(),(0!==Py(e).size||0!==Ty(e).size||function(e){const t=jg.get(e);return void 0!==t&&Dg(t)}(e))&&(ky(e),function(e){const t=[];for(const n of Py(e).values())Jy(e,n)&&t.push(n);for(const n of Ty(e).values())for(const o of n)Jy(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{yy(e,ro(e,o.pathInfo,null),n[o.path])}catch(t){Yy(e,o.path,"prime",t)}})}(e))}function Jy(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Xy={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Yy(e,t,n,o){console.error(`[@wcstack/state] $watch ${Xy[n]} "${t}" threw.`,o),null!==_t&&_t({type:"state:watch-error",phase:n,path:t,error:o})}function Qy(e){const t=Ay(),n=function(e){const t=ty;return t>0&&(ny.set(e,ey),ey=null,ty=0),t}(e);try{if(n>32){qy(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!==_t&&_t({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}if(0===t.size)return void qy(e,t);!function(e,t){if(0!==e.length)try{for(const n of e)oy(n.group.depth),Uy(n,t)}finally{sy()}}(Ky(e,t),t),function(e,t){const n=[],o=new Set;for(const s of e){const e=s.absolutePathInfo.stateElement;if(!t.has(e))continue;const r=s.absolutePathInfo.pathInfo.path;o.add(r);const i=Py(e).get(r),a=Ty(e).get(r);if(void 0===i&&void 0===a)continue;const l=void 0===i?[]:[i];void 0!==a&&l.push(...a);for(const t of l){let o=[];if(t.pathInfo.wildcardCount>0){if(null===s.listIndex)continue;o=ho(s.listIndex,t.pathInfo.wildcardCount)}n.push({stateElement:e,entry:t,absAddress:s,indexes:o})}}if(0===n.length)return;n.sort(ew);const s=function(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(0===s.entry.pathInfo.wildcardCount)continue;const r=e[o-1];(Oy(s.absAddress.listIndex)||r?.entry===s.entry&&Zy(r.indexes,s.indexes)||s.entry.pathInfo.wildcardParentPaths.some(e=>t.has(e)))&&(n??=new Set).add(s.entry)}if(null===n)return e;const o=new Set;for(const t of n){const n=e.filter(e=>e.entry===t),s=n[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(jy(e,t.pathInfo,n));for(const e of n)s.has(e)||o.add(e)})}catch(e){Yy(0,t.path,"evaluate",e);for(const e of n)o.add(e)}}return e.filter(e=>!o.has(e))}(n,o);try{for(const n of s){if(!t.has(n.stateElement))continue;const o=Py(n.stateElement).get(n.entry.path)===n.entry,s=!0===Ty(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(oy(iy(e,n.absAddress)),tw(n))}}finally{sy()}}(e,t)}finally{wy.clear()}}function Zy(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function ew(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 tw(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Jy(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 Yy(0,n.path,"evaluate",e)}const a=r?function(e,t){return my.get(e)?.get(t)}(t,o):vy(o);r&&yy(t,o,i),null!==_t&&_t({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Yy(0,n.path,"handler",e)}}let nw=!1;function ow(){nw||(nw=!0,Hc("watch",My),Jc("watch",sw),ri(Qy,10),si(ry),$u={assertValidPath:Ey,addEntries:Ny,start:Gy})}const sw={order:10,register(e,t){var n;n=e,Sy.delete(n),qg(n),$y.delete(n),function(e){my.delete(e)}(e);const o=Cy(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?G:J)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Gy(e)},deactivate(e){var t;t=e,Sy.delete(t),qg(t)}},rw=[uf,{name:"temporal",install(){ow(),Nm||(Nm=!0,Jc("scan",Am),si(Kg)),gy()}},Wf,ig,Rg,Wu,Ju];function iw(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(rw),vu(e,t)}function aw(e){return e}const lw={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"真偽性を反転(falsy → true)",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},add:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},sub:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},toFixed:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},upper:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lower:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},capitalize:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:2,maxArgs:2,argTypes:["number","number"]},padStart:{description:"先頭を埋める (length[,char]。char の既定は 0 — JS の既定は空白なので注意)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},padEnd:{description:"末尾を埋める (length[,char]。char の既定は空白 — JS と同じ)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},repeat:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},reverse:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix]。suffix の既定は … — U+2026 の 1 文字)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator]。既定はカンマ + 空白)",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},time:{description:"ロケール形式の時刻 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},datetime:{description:"ロケール形式の日時 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},ymd:{description:"YYYY-MM-DD 形式 ([separator]。既定は -)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式 ([separator]。既定は :)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},coalesce:{description:"null / undefined の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},nullIfEmpty:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},cw=2,dw=Object.freeze({$trackDependency:"$dependOn",$untrackDependency:"$untracked"});function uw(){return{version:2,syntax:{bindAttribute:s.bindAttributeName,tagName:s.tagNames.state,pathDelimiter:d,wildcard:u,delimiters:{binding:";",propValue:":",modifier:g,filter:m},structuralDirectives:Array.from(pe),modifiers:{flags:v,keyValue:S,eventNamePrefix:k},indexParam:{prefix:M,maxDepth:f},bindingTypes:{elseKeyword:I,spread:P,eventPropertyPrefix:k,explicitPropertyPrefix:d,propNamespaces:{eventToken:A,command:_,class:T,attr:E,style:C}}},filters:Object.keys(lf),filterMeta:lw,filterAliases:ef,declarationAliases:Oc,apiAliases:dw,reservedLifecycle:[j,L,W,D,B],reservedStateApi:[z,F,q,V,H,U,K,G,J,Q,X,Z,ee]}}const fw=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),hw=Object.freeze([]);function pw(e){if(!s.enableContractAnalyzer)return hw;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))fw.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?gw(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,mw,e=>{t.push(e),null!==_t&&_t(e)}),t}function gw(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function mw(e){const t=et(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{wg as Ssr,nl as TRUSTED_TYPES_POLICY_SLOT,Pu as VERSION,cw as WCS_MANIFEST_VERSION,pw as analyzeContract,iw as bootstrapState,Bl as buildBindings,ef as builtinFilterAliases,lw as builtinFilterMeta,aw as defineState,Xl as getBindingsReady,r as getConfig,ol as getTrustedTypesPolicy,uw as getWcsManifest,sl as setTrustedTypesPolicy};
1
+ const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={seen:!1},o={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},s=o;function r(){return s}const i=Symbol.for("wcstack.binder");const a=Symbol.for("wcstack.binder.pending"),l=Symbol.for("wcstack.binder.taken");function c(){const e=function(){const e=globalThis[i];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[a];return void 0===t&&(t=[],e[a]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[l];return void 0===t&&(t=new WeakSet,e[l]=t),t}();for(const t of n)o.add(t),e.bind(t)}const d=".",u="*",f=128,h=128,p=100,g="#",m="|",y="prevent",w="stop",b="ro",v=Object.freeze([y,w,b]),$="init",x="sync",S=Object.freeze([$,x]),I="else",P="...",k="on",A="eventToken",N="state",_="command",T="class",E="attr",C="style",M="$",O={};for(let e=0;e<f;e++)O[`${M}${e+1}`]=e;const R=Object.freeze(O),j="$connectedCallback",L="$disconnectedCallback",W="$renderedCallback",D="$errorCallback",B="$stateReadyCallback",z="$bindables",F="$commands",q="$commandTokens",V="$command",H="$eventTokens",U="$on",K="$stream",G="$watch",J="$scan",X="$recursion",Y="**",Q="$listKeys",Z="$streamStatus",ee="$streamError",te="data-wc-definition",ne=/\{\{\s*(.+?)\s*\}\}/g,oe=new Set(["SCRIPT","STYLE"]);function se(e){if(!s.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&&oe.has(e.parentElement.tagName)||re(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),se(t.content)}else se(e.content)}function re(e){const t=e.data;if(ne.lastIndex=0,!ne.test(t))return;ne.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=ne.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)}function ie(e){throw new Error(`[@wcstack/state] ${e}`)}const ae=new Map;let le=0;function ce(e){let t=ae.get(e);if(void 0!==t)return t;-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] "${e}" uses "${Y}", 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.`);const n=function(e){let t=1;for(let n=0;n<e.length;n++)e[n]===d&&t++;return t}(e);return n>512&&ie(`[wcs/binding-syntax] "${e}" has ${n} path segments — the limit is 512. Every prefix of a path is interned, so the cost grows with the square of the depth.`),t=Object.freeze(new de(e)),ae.set(e,t),t}class de{id=++le;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:ce(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],d=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===u&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),c.push(t(h)),d.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=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=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=d,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function ue(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 fe(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ue(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const he=" Validate statically: npx @wcstack/lint <file>.",pe=new Set(["if","elseif","else","for"]);function ge(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}function me(e){if(0===e.length)return"";let t="";for(let n=0;n<e.length;n++){const o=e[n];n>0&&(t+="|"),t+=`${o.filterName}(${ge(o.args,o.literals??o.args)})`}return t}let ye=null;const we=new Map([["not",()=>e=>!e]]),be=new Map([["not",[0,0]]]),ve={input:new Map,output:new Map},$e={input:new Map,output:new Map},xe={input:new Map,output:new Map},Se=new Map;function Ie(e,t,n,o){const s=ve[e],r=$e[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}const i=o??{},a=xe[e];for(const[e,n]of[...a])Object.prototype.hasOwnProperty.call(t,n)&&i[e]!==n&&a.delete(e);for(const e of Object.keys(i))a.set(e,i[e]);Se.clear()}function Pe(e,t,n,o=t){const s=xe[n].get(e);void 0!==s&&ye?.renamed(e,s);const r=s??e,i=`${r}${ge(t,o)}:${n}`,a=Se.get(i);if(void 0!==a)return a;const l=ve[n].get(r)??we.get(r);if(void 0===l){const t=0===ve[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";ie(`[wcs/filter-unknown] filter not found: ${e}.${fe(e,function(e){return[...new Set([...we.keys(),...ve[e].keys()])]}(n))}${t}${he}`)}const c=$e[n].get(r)??be.get(r);void 0!==c&&(t.length<c[0]||t.length>c[1])&&ie(t.length<c[0]?`[wcs/filter-arity] filter "${e}" requires at least ${c[0]} argument(s) (${t.length} given).${he}`:`[wcs/filter-arity] filter "${e}" accepts at most ${c[1]} argument(s) (${t.length} given).${he}`);const d=l(t,o);return Se.set(i,d),d}function ke(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const Ae=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function Ne(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:Ae.test(e)?Number(e):e)}function _e(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=ke(o,i,a);t.push(e),n.push(Ne(e,r)),o="",r=!1,i=-1,a=-1};for(let t=0;t<e.length;t++){const n=e[t];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&ie(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${he}`);const c=ke(o,i,a);return(c||r)&&(t.push(c),n.push(Ne(c,r))),{args:t,literals:n}}const Te=e=>e.trim(),Ee=e=>"'"===e||'"'===e;function Ce(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if(Ee(s))n=s;else if(s===t)return o}return-1}function Me(e,t){const n=[];let o=null,s=0;for(let r=0;r<e.length;r++){const i=e[r];null!==o?i===o&&(o=null):Ee(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}function Oe(e,t,n){const o=n??e.join("|");return e.map(e=>{const n=Ce(e,"(");let s=function(e,t){let n=null,o=-1;for(let s=0;s<e.length;s++){const r=e[s];null!==n?r===n&&(n=null):Ee(r)?n=r:r===t&&(o=s)}return o}(e,")");if(-1===s&&(s=e.lastIndexOf(")")),-1!==n&&-1===s&&ie(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${e}".${he}`),-1!==s&&-1===n&&ie(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${e}".${he}`),-1!==s&&s<n&&ie(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${e}".${he}`),-1!==s&&e.slice(s+1).trim().length>0){const t=e.slice(s+1).trim();ie(`[wcs/binding-syntax] "${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,s+1)}|${t}").${he}`)}const r=(-1===n?e:e.substring(0,n)).trim();if(0===r.length&&ie(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${he}`),r.includes(g)){const[e,n]=r.split(g);ie("input"===t?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${g}${n}" comes before the input filters, not inside one — write "<property>${g}${n}|${e}".${he}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${g}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${e}" here.${he}`)}if(-1===n)return{filterName:r,args:[],literals:[]};return{filterName:r,..._e(e.substring(n+1,s))}})}const Re=new Map;function je(e){const t=Ce(e,m);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Re.has(s)?r=Re.get(s):(o=Me(s,m).map(Te),r=Oe(o,"input",e),Re.set(s,r))):n=e.trim();const i=n.split(g).map(Te);i.length>2&&ie(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${g}" — write "${i[0]}${g}${i.slice(1).join(",")}".${he}`);const[a,l]=i,c=a.split(d).map(Te);c.length>1&&""===c[0]||0!==a.length&&!c.some(e=>0===e.length)||ie(`[wcs/binding-syntax] "${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${he}`);return{propName:a,propSegments:c,propModifiers:l?l.split(",").map(Te):[],inFilters:r}}const Le=new Map;function We(e){const t=Ce(e,m);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Le.has(s)?r=Le.get(s):(o=Me(s,m).map(Te),r=Oe(o,"output",e),Le.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&ie(`"${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.`);const i=n,a=i.startsWith(d),l=a?i.slice(1):i;(l.length>0&&l.split(d).some(e=>0===e.length)||!a&&0===l.length)&&ie(`[wcs/binding-syntax] "${e}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).${he}`);return{statePathName:i,statePathInfo:ce(i),outFilters:r}}const De=new Set([I,"if","elseif","for",P]),Be=new Set([T,E,C,_,A,N]);function ze(e){const[...t]=function(e){return Me(e,";")}(e).map(Te).filter(e=>e.length>0),n=t.map(e=>{const t=Ce(e,":");-1===t&&ie(`[wcs/binding-syntax] Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.${he}`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(g)[0].split(m)[0].trim();if(s!==n&&De.has(s)&&ie(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${he}`),n===I){o.length>0&&ie(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${he}`);const t=ce("#else");return{propName:I,propSegments:[I],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===P){0===o.length&&ie(`[wcs/binding-syntax] Invalid spread binding "${e}": spread target path is required.${he}`);const t=We(o);return t.outFilters.length>0&&ie(`[wcs/binding-syntax] Invalid spread binding "${e}": filters are not allowed on spread targets.${he}`),{propName:P,propSegments:[P],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...We(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=We(o);return{...je(n),...e,bindingType:s}}{const e=We(o),t=je(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Be.has(o[0]))&&ie(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Be].join(", ")}).${he}`),{...t,propName:o.join(d),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===A||t.propSegments[0].startsWith(k)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>pe.has(e.bindingType))&&ie(`[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">).${he}`)}return n}const Fe=new WeakMap,qe=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),Ve=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function He(e){const t=Fe.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),o=Ve.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return qe.has(r)?(Fe.set(e,o[2]),o[2]):null}function Ue(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...We(e),bindingType:"text"}}const Ke=new WeakMap,Ge=new WeakSet;let Je=0;async function Xe(e){const t=function(e){let t,n=Ke.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++Je,promise:o,resolve:t},Ke.set(e,n),Ge.has(e)&&n.resolve(),n}(e);await t.promise}function Ye(e){const t=Ke.get(e);void 0===t?Ge.add(e):t.resolve()}const Qe=new WeakMap;function Ze(e){const t=Qe.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{Qe.set(e,n)}}function et(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function tt(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return et(t);if(void 0!==n)return et(n)}return et(globalThis.customElements)}function nt(e,t){e.upgrade?.(t)}function ot(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=at(s.properties,st);if(null===r)return null;const i=void 0===s.inputs?new Map:at(s.inputs,rt);if(null===i)return null;const a=void 0===s.commands?new Map:at(s.commands,it);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function st(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 rt(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 it(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 at(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 lt(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ce(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ct(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function dt(e,t,n={}){const o=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&&ie("Spread binding requires an element node.");const t=e,s=Ze(t);null===s&&ie(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=tt(t);null===a&&ie(`CustomElementRegistry is unavailable for <${s}>.`);if(void 0===a.get(s)){o||ie(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}nt(a,t);const l=ot(t);null===l&&ie(`Spread binding "${n.statePathName}" requires <${s}> 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=lt(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=lt(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=ct(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=ct(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(s.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 ut(e,t){let n=e;for(let e=0;e<t.length;e++){let o=t[e];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function ft(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:Pe(s.filterName,s.args,t,r)})}return n}function ht(e){return{...e,inFilters:ft(e.inFilters,"input"),outFilters:ft(e.outFilters,"output")}}const pt=new WeakMap;function gt(e){return pt.get(e)||null}function mt(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(s.bindAttributeName)}function yt(e){const t=[],n=e.querySelectorAll(`${s.tagNames.state}[bind-component]`);for(const o of n){if(!mt(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function wt(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 bt(e){const t=[],n=yt(e),o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==He(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();){const e=o.currentNode;n.length>0&&wt(e,n)||t.push(e)}return t}const vt=new WeakSet;function $t(e,t,n,o){const s=dt(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ze(e):null;return null===n&&ie("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}vt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=ft(o.inFilters,"input"),s=ft(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:e});else{const r=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:r})}}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){pt.set(e,t)}(e,r),Ye(e),{bindings:r,deferred:null}}function xt(e,t){const n=[],o=[];for(const s of e){if(vt.has(s))continue;const e=$t(s,oc(s),{allowDeferred:!0},t);null===e.deferred?n.push(...e.bindings):o.push(e.deferred)}return[e,n,o]}function St(e){vt.add(e)}function It(e){const{node:t,parseResults:n,transform:o}=e;!function(e){vt.delete(e)}(t);return $t(t,n,{allowDeferred:!1},o).bindings}const Pt=new WeakMap;let kt=null;function At(e){let t=e;for(;t;){const e=Pt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==kt&&t instanceof ShadowRoot&&(n=kt(t)),t=n}return null}function Nt(e,t){null!==t?Pt.set(e,t):Pt.delete(e)}let _t=null;let Tt=0;function Et(){return`u${(Tt++).toString(36)}`}let Ct=0,Mt=0;const Ot=Symbol("wcs.listIndex.noValue");class Rt{uuid=Et();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;cacheStamp=0;ref;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ot,this._index=t,this._version=Ct,this._chainGeneration=Mt}get index(){return this._index}set index(e){this._index=e,this._version=++Ct,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}set homeParentListIndex(e){this._homeParentListIndex=e}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=Ct),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Mt||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Mt),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Ct,Mt++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function jt(e,t,n=e){return new Rt(e,t,n)}function Lt(e,t){e.reparent(t)}function Wt(e){return e.homeParentListIndex}function Dt(e,t){e.homeParentListIndex=t}function Bt(e){return e?.cacheStamp}function zt(e,t){const n=e,o=n.value,s=o!==Ot&&!Object.is(o,t);return o!==t&&(Ft.get(o)?.delete(n.ref),function(e,t){if("object"!=typeof e||null===e||null===t.parentListIndex)return;let n=Ft.get(e);void 0===n?(n=new Set,Ft.set(e,n)):n.size>=(qt.get(n)??8)&&(Vt(n,t,!0),qt.set(n,2*n.size+8));n.add(t.ref??=new WeakRef(t))}(t,n)),n.value=t,s}const Ft=new WeakMap,qt=new WeakMap;function Vt(e,t,n=!1){const o=[];return e?.forEach(s=>{const r=s.deref();void 0===r||n&&Ut(r)?e.delete(s):r!==t&&o.push(r)}),o}const Ht=new WeakSet;function Ut(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ht.has(t))return!0;return!1}function Kt(e){return e.value}function Gt(e,t){const n=e.value;return n!==Ot&&n===t.value}let Jt=0;const Xt=new WeakSet;function Yt(e){Xt.add(e)}function Qt(e){return Xt.has(e)}const Zt=new WeakMap;function en(e){return Ht.has(e)}const tn=new WeakMap;const nn=new WeakMap,on=new WeakMap;function sn(e,t){return!0===tn.get(t)?.has(e)}function rn(e,t){return sn(e,t)||Ut(t)}const an=new WeakMap;function ln(e){an.delete(e)}function cn(e,t,n){const o=Object(Kt(t)),s=Kt(n);for(const t in s)if(s[t]===e&&o[t]!==e)return!1;return!0}function dn(e,t){return!rn(e,t)&&an.get(t)!==Jt}const un=new WeakMap,fn=new WeakMap;const hn=new WeakSet;function pn(e,t){const n=(o=e,Vt(Ft.get(o.value),o));var o;if(0===n.length)return n;const s=new Set(Zt.get(t()));return n.filter(t=>t.position===e.position&&!s.has(t)&&!Ut(t))}function gn(e,t,n){const o=Wt(t),s=t.parentListIndex;return null!==o&&o!==s&&!rn(e,o)&&cn(e,o,s)?o:function(e,t,n,o){return null!==t&&null!==o&&o!==n&&!!Ht.has(t)&&!(!dn(e,o)||o.position!==t.position)&&!sn(e,t)&&Gt(o,t)}(e,o,s,n)||function(e,t,n){return t!==n&&null!==t&&null!==n&&t.position===n.position&&rn(e,t)&&dn(e,n)}(e,s,n)?n:null}function mn(e){const t=Zt.get(e);return void 0===t?null:t}function yn(e,t){const n=Zt.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o&&!Qt(e)){const s=null!==t&&o.parentListIndex!==t&&an.get(t)!==Jt,r=gn(e,o,t);if(null!==r&&hn.has(e)){hn.delete(e);const t=[...e];Yt(t),Zt.set(t,n),Sn(e,t);const o=n.map((t,n)=>{const o=jt(r,n);return zt(o,e[n]),o});return Zt.set(e,o),o}if(null!==r)for(const e of n)Lt(e,r);else if(s){!function(e,t){let n=un.get(e);void 0===n?(n=new Set,un.set(e,n)):n.size>=(fn.get(e)??8)&&(n.forEach(t=>{rn(e,t)&&n.delete(t)}),fn.set(e,2*n.size+8));for(const e of t)n.add(e)}(e,[o.parentListIndex,t]);const s=o.parentListIndex;if(null!==s&&s.position===t.position&&!cn(e,s,t)&&cn(e,t,s))for(const e of n)Lt(e,t)}}return n}const wn=new WeakSet;function bn(e){wn.delete(e)}function vn(e,t,n=!1){null!==t?(n?wn.add(t):bn(t),Zt.set(e,t)):Zt.delete(e)}const $n=new WeakMap;function xn(e){let t=$n.get(e);return void 0===t&&(t={value:e},$n.set(e,t)),t}function Sn(e,t){const n=$n.get(e);void 0!==n&&(n.value=t,$n.delete(e))}const In=new WeakMap,Pn=new WeakMap,kn=new Set,An=new WeakMap,Nn=new WeakMap;function _n(e){const t=e.absolutePathInfo.stateElement;let n=Pn.get(t);return void 0===n&&(n=new WeakMap,Pn.set(t,n)),n}function Tn(e){return In.get(e)??[]}function En(e,t){const n=In.get(e);In.set(e,t),Nn.delete(e);const o=_n(e);n!==t&&void 0!==n&&o.get(n).delete(e);const s=o.get(t);void 0===s?o.set(t,new Set([e])):s.has(e)||(s.size>=(An.get(s)??8)&&(s.forEach(e=>{Cn(e.listIndex)&&s.delete(e)}),An.set(s,Math.max(8,2*s.size))),s.add(e))}function Cn(e){for(let t=e;null!==t;t=t.parentListIndex)if(en(t))return!0;return!1}function Mn(e,t){const n=_n(e).get(t);return void 0===n?kn:(n.forEach(e=>{Cn(e.listIndex)&&n.delete(e)}),n)}function On(e,t){return!Nn.has(e)&&(Nn.set(e,t),!0)}function Rn(e){return In.has(e)}const jn=new WeakMap;let Ln=null,Wn=0;function Dn(e){return jn.get(e)??[]}function Bn(e,t){null===Ln?jn.set(e,t):Ln.set(e,t)}function zn(){Wn++,null===Ln&&(Ln=new Map)}function Fn(){if(0!==Wn&&(Wn--,!(Wn>0||null===Ln))){for(const[e,t]of Ln)jn.set(e,t);Ln=null}}function qn(e){return(Ln?.has(e)??!1)||jn.has(e)}const Vn=Symbol("$$setLoopContext"),Hn=Symbol("$$getByAddress"),Un=Symbol("$$hasByAddress"),Kn=Symbol("$$connectedCallback"),Gn=Symbol("$$disconnectedCallback"),Jn=Symbol("$$updatedCallback"),Xn=Symbol("$$errorCallback"),Yn=new WeakMap,Qn=new WeakMap;class Zn{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function eo(e,t){if(null===t){let t=Qn.get(e);return void 0!==t||(t=new Zn(e,null),Qn.set(e,t)),t}{let n=Yn.get(t);void 0===n&&(n=new WeakMap,Yn.set(t,n));let o=n.get(e);return void 0!==o||(o=new Zn(e,t),n.set(e,o)),o}}const to=new WeakMap;function no(e,t){let n=to.get(e);void 0===n&&(n=new Map,to.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new oo(e,t)),n.set(t,o)),o}class oo{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function so(e,t){return eo(no(e,t.pathInfo),t.listIndex)}function ro(e,t,n){return eo(no(e,t),n)}const io=new WeakMap;function ao(e,t){null===t?io.delete(e):io.set(e,t)}function lo(e){return io.get(e)||null}const co=new Map;function uo(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=co.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,co.set(s,r),r}function fo(e,t,n){return t<0||t>=n?null:e.at(t-n)}function ho(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const po=new WeakMap;function go(e){const t=At(e.node);if(null===t)return null;let n=po.get(t);if(void 0===n)n=new WeakMap,po.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=uo(t.pathInfo,e.statePathInfo);return n>0&&(o=fo(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const mo=new WeakMap;function yo(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=lo(n);null===t?ie(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function wo(e,t){let n=null;if(n=mo.get(e)||null,null!==n)return n;const o=yo(e,t),s=go(e),r=Jl(o);return null===r&&ie("No state tree found on this root for binding."),n=ro(r,e.statePathInfo,s),mo.set(e,n),n}function bo(e){mo.delete(e)}const vo=new WeakMap;function $o(e,t){const n=vo.get(e);void 0===n?vo.set(e,t):n instanceof Set?n.add(t):n!==t&&vo.set(e,new Set([n,t])),null!==_t&&_t({type:"state:binding-added",absoluteAddress:e,binding:t})}function xo(e,t){const n=vo.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&vo.delete(e),null!==_t&&_t({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const So=new WeakMap;function Io(e){const t=vo.get(e);return void 0!==t?t:null!==e.listIndex?So.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const Po=new WeakMap,ko=new WeakMap;class Ao{pathInfo;listIndex;_parentAddress;_rowAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t,this._rowAddress=null!==t&&e.lastSegment===u}get parentAddress(){const e=this._parentAddress;if(void 0!==e&&(!this._rowAddress||e.listIndex===this.listIndex.parentListIndex))return e;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let n=null;n=this.pathInfo.segments[this.pathInfo.segments.length-1]===u?this.listIndex?.parentListIndex??null:this.listIndex;const o=_o(t,n);return void 0!==e&&!No(o,this.listIndex)&&No(e,this.listIndex)?e:this._parentAddress=o}}function No(e,t){const n=e.pathInfo;let o=Kt(e.listIndex);for(const e of n.segments.slice(n.wildcardPositions[n.wildcardCount-1]+1))o=Object(o)[e];return mn(o)?.[t.index]===t}function _o(e,t){if(null===t){let t=ko.get(e);return void 0!==t||(t=new Ao(e,null),ko.set(e,t)),t}{let n=Po.get(t);void 0===n&&(n=new WeakMap,Po.set(t,n));let o=n.get(e);return void 0!==o||(o=new Ao(e,t),n.set(e,o)),o}}const To=new WeakMap;function Eo(e){let t=null;if(t=To.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=go(e);null===n&&ie(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=_o(e.statePathInfo,n)}else t=_o(e.statePathInfo,null);return To.set(e,t),t}function Co(e){To.delete(e)}function Mo(){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 Oo=new Map,Ro=Mo();function jo(e,t){const n=me(e.inFilters);return`${e.statePathName}::${t}::${n}`}function Lo(e){let t="input";for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}function Wo(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const o=Lo(e),s=jo(e,o);let r=Oo.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=Jl(o.getRootNode());null===i&&ie("No state tree found on this root for two-way binding.");const a=At(o);i.createState("writable",e=>{e[Vn](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]:[]})})},Oo.set(s,r)),e.node.addEventListener(o,r),Ro.add(s,e),!0}var t,n;return!1}function Do(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Bo(e,t){console.error(`[wcstack/state] ${t} rejected.`,e)}function zo(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Do(e)&&Promise.resolve(e).catch(e=>Bo(e,t))}class Fo{_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)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,e)}return t}}class qo extends Fo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==_t&&_t({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Vo=new WeakMap;function Ho(e,t){let n=Vo.get(e);void 0===n&&(n=new Map,Vo.set(e,n));let o=n.get(t);return void 0===o&&(o=new qo(t,e),n.set(t,o)),o}const Uo=new WeakMap;function Ko(e){if(e.propSegments[0]!==A)return!1;const t=e.node,n=Ze(t),o=tt(t);if(null!==n&&void 0===o?.get(n))return null===o&&ie(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Uo.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||ie('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Ze(e)?null:ot(e)}(t);null===r&&ie(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&ie(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${fe(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(y)&&e.preventDefault(),c.includes(w)&&e.stopPropagation();const n=Jl(t.getRootNode());null===n&&ie("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||ie(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${fe(l,n.eventTokenNames)}${he}`);const o=At(t);n.createStateAsync("writable",async t=>{zo(t[Vn](o,()=>{const s=null!==o?ho(o.listIndex,o.pathInfo.wildcardCount):[];return Ho(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Uo.set(e,{eventName:a,handler:d}),!0}class Go extends Fo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==_t&&_t({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Jo(e){return e instanceof Go}const Xo=new Map,Yo=Mo();function Qo(e){const t=e.propModifiers.filter(e=>e===y||e===w).sort().join(",");return`${e.statePathName}::${t}`}const Zo=(e,t,n)=>o=>{t.includes(y)&&o.preventDefault(),t.includes(w)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Jl(r);null===i&&ie("No state tree found on this root for event handler.");const a=At(s),l=e.startsWith(V+".");i.createStateAsync("writable",async t=>{const c=t[Vn](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const e=i.addressHooks;if(e){const t=e.handlerScope;for(let e=0;e<t.length;e++)c=t[e](i,s,r,a,c)}}const d=null!==a?ho(a.listIndex,c):[];if(l){const s=t[Hn](_o(n,null));return Jo(s)||ie(`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&&ie(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});zo(c,`"${e}"`)}).catch(t=>Bo(t,`"${e}"`))};function es(e){return"event"===e.bindingType&&e.propName.startsWith(k)}function ts(e){if(!es(e))return!1;const t=Qo(e);let n=Xo.get(t);void 0===n&&(n=Zo(e.statePathName,e.propModifiers,e.statePathInfo),Xo.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Yo.add(t,e),!0}function ns(e){if(!es(e))return!1;const t=Qo(e),n=Xo.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Yo.countOf(t)&&(Yo.remove(t,e)&&Xo.delete(t),!0)}const os=new Map,ss=Mo();function rs(e,t){const n=me(e.inFilters);return`${e.statePathName}::${t}::${n}`}function is(e){let t="input";for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}function as(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const o=is(e),s=rs(e,o);let r=os.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=Jl(o.getRootNode());null===r&&ie("No state tree found on this root for two-way binding.");const i=At(o);r.createState("writable",e=>{e[Vn](i,()=>{e[t]=s})})},os.set(s,r)),e.node.addEventListener(o,r),ss.add(s,e),!0}var t,n;return!1}const ls=new Set(["radio","checkbox"]),cs=new Set(["value","valueAsNumber","valueAsDate"]);function ds(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(ls.has(e)&&"checked"===t)return!0;if(cs.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ze(n);if(null!==s){const e=tt(n)?.get(s);void 0===e&&ie(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=ot(n);if(o?.knownProperties.has(t))return!0}return!1}let us=1,fs=1,hs=1;const ps=new WeakMap;function gs(e,t,n){let o=ps.get(e);void 0===o&&(o=new Map,ps.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=us++,o.set(s,r)),r}function ms(e,t){return"to-element"===t?2*e:2*e+1}const ys=new Set;function ws(e){return{transactionId:fs++,originBindingId:e,visitedEdges:ys,hop:0}}function bs(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 vs=null;function $s(){return vs}function xs(e,t){const n=vs;vs=e;try{return t()}finally{vs=n}}const Ss=[];let Is=0;function Ps(e,t,n,o,s=!1){Is=s?2:1;try{e.createState("writable",e=>{e[Vn](t,()=>{e[n]=o})})}finally{Is=0}}const ks=new Map,As=Mo(),Ns=new WeakMap,_s=e=>e.detail,Ts=new WeakMap;const Es=new WeakMap;let Cs=0;const Ms=new WeakMap;function Os(e,t,n,o){const s=me(e.inFilters);return`${e.propName}::${e.statePathName}::${t}::${s}::${function(e){if(null===e)return"n";let t=Es.get(e);return void 0===t&&Es.set(e,t=++Cs),`g${t}`}(n)}::${o?"o":"s"}`}const Rs=(e,t,n,o,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==o)l=o(i),o!==_s||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=Ts.get(e);void 0===r&&(r=new Set,Ts.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=Ns.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(s.enablePropagationContext){const n=gs(a,e,t),o=function(e,t){for(let n=Ss.length-1;n>=0;n--){const o=Ss[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==o&&Object.is(o.writtenValue,l))return s.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:o.transactionId,coveredBySameValueGuard:s.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==_t&&_t({type:"propagation:suppressed",reason:"confirmation",transactionId:o.transactionId,edgeId:ms(n,"to-state"),node:a,member:e}));const r=ms(n,"to-state"),i=$s();if(null!==i&&i.visitedEdges.has(r))return void(null!==_t&&_t({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=bs(i??ws(n),r)}const f=Jl(a.getRootNode());null===f&&ie("No state tree found on this root for two-way binding.");const h=At(a),p=()=>Ps(f,h,t,c,r);null!==u?xs(u,p):p()};function js(e){const t=Ze(e.node);if(null!==t){const n=tt(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&ie(`CustomElementRegistry is unavailable for <${t}>.`))}if(ds(e.node,e.propName)&&-1===e.propModifiers.indexOf(b)){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ze(e.node);if(null!==n){const o=tt(e.node)?.get(n);void 0===o&&ie(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=ot(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}(e),n=function(e){if(null!==Ze(e.node)){const t=ot(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??_s}return null}(e),o=function(e){if(null===Ze(e.node))return!1;const t=ot(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}(e),s=Os(e,t,n,o);Ms.set(e,{key:s,eventName:t});let r=ks.get(s);void 0===r&&(r=Rs(e.propName,e.statePathName,e.inFilters,n,o),ks.set(s,r)),e.node.addEventListener(t,r),As.add(s,e)}}const Ls=new WeakSet;function Ws(e){Ls.add(e)}function Ds(e){return!!Ls.has(e)&&(Ls.delete(e),!0)}const Bs=new WeakMap;function zs(e,t){const n=Bs.get(e);return!(void 0===n||n<t)&&(n===t?Bs.delete(e):Bs.set(e,n-t),!0)}const Fs=new WeakSet;function qs(e){Fs.add(e)}function Vs(e){return!!Fs.has(e)&&(Fs.delete(e),!0)}let Hs=0;function Us(){Hs--}function Ks(){return Hs>0}class Gs{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 Js=new WeakMap;function Xs(e){let t=Js.get(e);return void 0===t&&(t=new Gs(e),Js.set(e,t)),t}const Ys=new Set([T,E,C,_]);function Qs(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!==$&&s!==x&&ie(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&ie(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Zs(e){return e.propModifiers.some(e=>e.includes("="))}const er=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),tr=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function nr(e,t){return"state"===e&&"call"===t?er:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function or(e){if(!s.enableDirectionalInitialSync)return Zs(e)&&ie("init=/sync= modifiers require enableDirectionalInitialSync."),er;const t=null===(n=Qs(e,$))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:ie(`Invalid init modifier value "${n}".`);var n;const o=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":ie(`Invalid sync modifier value "${e}".`)}(Qs(e,x));if("event"===e.bindingType)return null!==t&&"none"!==t&&ie("Event bindings only allow init=none."),"call"===o?tr:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(Ys.has(e.propSegments[0]))return nr("state",o);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&ie(`Binding type "${e.bindingType}" does not support init=${t}.`),nr(t??"state",o);const r=ot(e.node);if(null===r)return nr(t??"state",o);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||ie(`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)||ie(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==o||i||ie(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:o,observable:i,outputOnly:i&&!a}}function sr(e){let t=e.getRootNode();return t instanceof DocumentFragment&&!(t instanceof ShadowRoot)&&(t=lo(t)),null===t?null:Jl(t)}function rr(e,t){return"auto"!==t?t:function(e){const t=sr(e.replaceNode);null===t&&ie("No state tree found on this root for binding.");const n=Eo(e);let o=!1;return t.createState("readonly",e=>{o=e[Un](n)}),o}(e)?"state":"element"}let ir=0,ar=null,lr=0;const cr=["active","disposed","failed"],dr=new WeakMap,ur=new WeakMap,fr=new WeakMap,hr=new WeakMap,pr=new WeakMap,gr=new WeakMap;function mr(e,t){const n=gr.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):gr.set(e,new Set([n,t]))):gr.set(e,t)}function yr(e){return gr.has(e)}function wr(e,t){const n=gr.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function br(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))br(n,t)}function vr(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class $r{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||!zs(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)Ds(e)||br(e,e=>{wr(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Vs(e)&&!Ks()||br(e,e=>{wr(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&Rl(o)}}const xr=new WeakMap;function Sr(e){let t=xr.get(e);return void 0===t&&(t=new $r(e),xr.set(e,t)),t}function Ir(e){const t=me(e.inFilters),n=me(e.outFilters);return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function Pr(e,t,n){const o=Jl(yo(e,n));null===o&&ie("No state tree found on this root for binding.");const s=no(o,e.statePathInfo);return function(e,t,n){let o=So.get(e);void 0===o&&(o=new WeakMap,So.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!==_t&&_t({type:"state:binding-added",absoluteAddress:eo(e,t),binding:n})}(s,t,e),s}function kr(e,t){const n=wo(e,t);return $o(n,e),n}function Ar(e,t,n,o){null!==t?xo(t,e):function(e,t,n){const o=So.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!==_t&&_t({type:"state:binding-removed",absoluteAddress:eo(e,t),binding:n}))}(n,o,e),Co(e),bo(e)}function Nr(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class _r{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;disposedAt=0;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=this.rowOf(e),i=null===o?-1:o.bindings.indexOf(e);if(null!==o&&0===o.phases[i]){const t=o;this.observe(e.replaceNode),s.registerAddress&&null===t.addresses[i]&&null===t.patternPathInfos[i]&&(t.registered=!0,this.registerRowSlot(t,i));continue}const a=fr.get(e);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(e,s,n),r.push(e)):(this.observe(a.anchor),s.registerAddress&&null===a.address&&null===a.patternListIndex&&(a.options.registerAddress=!0,this.registerAddress(a)),"active"===a.phase&&this.settleInitialRecord(a),this.settleConnectedSnapshot(a))}return r.filter(e=>this.shouldApplyState(e))}activate(e,t){if(vr(t)&&Sr(t),null===this.rowPlan)for(const n of e){const e=fr.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(!s.enableDirectionalInitialSync)return Zs(e)&&or(e),!0;const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0){if(!t.registered)return!0;if(2===t.phases[n])return!1;const e=t.plan.slots[n];return 1&t.flags[n]?"state"===e.authority||!e.policy.outputOnly:(t.flags[n]|=1,"state"===e.authority)}}const n=fr.get(e);return void 0===n||n.session!==this||(!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority)))}getRecord(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0){let o=ur.get(t);void 0===o&&ur.set(t,o=[]);return{id:o[n]??(o[n]=++ir),info:e,generation:t.generation,phase:cr[t.phases[n]],teardowns:null}}const o=fr.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=fr.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(Nr(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=this.deferredByNode.get(e)??new Set,r=()=>s.delete(a)&&this.deferred.delete(a),i=()=>{const s=tt(e);null===s&&ie(`CustomElementRegistry is unavailable for <${t}>.`),a.cancel=Xs(s).wait(t,()=>{if(r())try{nt(s,e),n()}catch(e){o(e)}},e=>{r()&&o(e)})},a={node:e,born:++lr,cancel:null,arm:()=>{if(null===a.cancel&&this.deferred.has(a))try{i()}catch(e){r(),o(e)}}},l=e.getRootNode();if(null!==ar||11===l.nodeType&&!vr(l)){if(null===ar){const e=ar=[];queueMicrotask(()=>{ar=null;for(let t=0;t<e.length;t++)e[t].arm()})}ar.push(a)}else i();return vr(l)&&Sr(l),mr(e,this),this.deferredByNode.set(e,s.add(a)),this.deferred.add(a),()=>{r(),a.cancel?.()}}disposeBinding(e){const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0)return void this.disposeRowSlot(t,n)}const n=fr.get(e);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(e){for(let t=0;t<e.length;t++)this.disposeBinding(e[t]);if(!(this.rows.size>0))for(const e of Array.from(this.deferred))e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}destroyRow(e){const t=e.length>0?this.rowOf(e[0]):null;null!==t?(this.destroyRowRecord(t),this.rows.delete(t)):this.destroyRecords()}destroyRowRecord(e){for(let t=0;t<e.bindings.length;t++){const n=e.addresses[t];null!==n&&(xo(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){this.disposedAt=lr;for(const e of Array.from(this.rows))for(let t=0;t<e.bindings.length;t++)this.disposeRowSlot(e,t);for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))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(){this.disposedAt=lr;for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(xo(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.rows)for(let n=0;n<t.bindings.length;n++)0===t.phases[n]&&e(t.bindings[n].node);for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.rows)for(let n=0;n<t.bindings.length;n++){if(0!==t.phases[n])continue;if(null===t.addresses[n]&&null===t.patternPathInfos[n])continue;const o=t.bindings[n];this.unregisterRowSlot(t,n),this.registerRowSlot(t,n),this.shouldApplyState(o)&&e.push(o)}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?wo(n):null;if(Ar(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=wo(n);e!==o&&Rn(o)&&En(e,Tn(o)),e!==o&&qn(o)&&Bn(e,Dn(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return vr(t)?t:null}(e);null!==t&&Sr(t)}handleMutations(e,t,n){for(const n of t)br(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)br(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&Rl(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);this.deferredByNode.get(e)?.forEach(e=>{e.cancel?.(),e.cancel=null,this.deferred.delete(e)})}handleAddedNode(e,t){this.deferredByNode.get(e)?.forEach(e=>{e.born<=this.disposedAt||(this.deferred.add(e),e.arm())});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=fr.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||n.pendingDefinitions>0&&n.generation>this.disposedAt)&&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=pr.get(t);void 0===e&&(e=Ir(t),pr.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;mr(n,this);const o=this.knownMapFor(n);let s=pr.get(e);void 0===s&&(s=Ir(e),pr.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=e.slots,o=t.length,s={id:++ir,session:this,generation:++lr,plan:e,bindings:t,registered:!1,phases:new Array(o).fill(0),flags:new Array(o).fill(0),addresses:new Array(o).fill(null),patternPathInfos:new Array(o).fill(null),patternListIndexes:new Array(o).fill(null)};this.rows.add(s);for(let e=0;e<o;e++){const o=t[e],r=o.replaceNode;if(mr(r,this),this.addKnownRowBinding(r,o,e),dr.set(o,s),n[e].isEvent){let t=!1;try{t=ts(o)}catch(t){throw s.phases[e]=2,t}t&&(s.flags[e]|=2)}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++lr,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){let n=!1;try{n=ts(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}n&&(o.flags[e]|=2)}this.registerRowSlot(o,e,n)}}rowOf(e){const t=dr.get(e);return void 0!==t&&t.session===this?t:null}registerRowSlot(e,t,n){if(null!==e.addresses[t]||null!==e.patternPathInfos[t])return;const o=e.bindings[t],s=go(o);null!==s?(e.patternPathInfos[t]=Pr(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=kr(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(Ar(e.bindings[t],n,o,e.patternListIndexes[t]),e.addresses[t]=null,e.patternPathInfos[t]=null,e.patternListIndexes[t]=null)}disposeRowSlot(e,t){if(1!==e.phases[t]){e.phases[t]=1,this.runRowSlotTeardowns(e,t);for(let t=0;t<e.phases.length;t++)if(0===e.phases[t])return;this.rows.delete(e)}}runRowSlotTeardowns(e,t){try{this.unregisterRowSlot(e,t)}catch{}if(2&e.flags[t]){e.flags[t]&=-3;try{ns(e.bindings[t])}catch{}}}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:++ir,info:e,generation:++lr,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};fr.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;ts(t)?e.eventAttached=!0:t.propSegments[0]!==A?(as(t)&&Nr(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const t=is(e),n=rs(e,t),o=os.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==ss.countOf(n)&&(ss.remove(n,e)&&os.delete(n),!0))}return!1}(t)),Wo(t)&&Nr(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const t=Lo(e),n=jo(e,t),o=Oo.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Ro.countOf(n)&&(Ro.remove(n,e)&&Oo.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(s.enableDirectionalInitialSync&&ds(t.node,t.propName)&&-1===t.propModifiers.indexOf(b)){const n=function(e,t,n){let o=Ns.get(e);void 0===o&&(o=new Map,Ns.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&&Ns.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});Nr(e,n)}js(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Ko(t)&&Nr(e,()=>function(e){if(e.propSegments[0]!==A)return!1;const t=Uo.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Uo.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Ze(e.info.node);if(null===n)return void t();const o=tt(e.info.node);if(null===o&&ie(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation;Nr(e,this.deferUntilDefined(e.info.node,n,()=>{this.isAlive(e,s)&&(t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e)))},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))}))}settleInitialRecord(e){if(s.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=or(e.info),n=rr(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 Hs++;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,Us()),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=sr(e.node);null===o&&ie("No state tree found on this root for initial binding sync."),Ps(o,At(e.node),e.statePathName,n)}(e.info,r))}settleConnectedSnapshot(e){if(s.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=go(n);if(null!==o?(e.patternPathInfo=Pr(n,o,t),e.patternListIndex=o):e.address=kr(n,t),!e.options.registerPathInfo)return;const s=Jl(n.replaceNode.getRootNode());null===s&&ie("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&&fr.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,Us());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{Ar(t,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=Ms.get(e);if(void 0===t)return;Ms.delete(e);const n=ks.get(t.key);void 0!==n&&(e.node.removeEventListener(t.eventName,n),As.remove(t.key,e)&&ks.delete(t.key))}(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{ns(t)}catch{}}}}function Tr(e){let t=hr.get(e);return void 0===t&&(t=new _r(e),hr.set(e,t)),t}function Er(e){return fr.get(e)?.session??dr.get(e)?.session??null}let Cr=null;function Mr(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const Or=Object.freeze([]);const Rr=new WeakMap;const jr=new WeakMap;function Lr(e){return jr.get(e)??[]}function Wr(e,t){jr.set(e,t)}const Dr=new WeakMap;function Br(e){return Dr.get(e)??[]}function zr(e,t){Dr.set(e,t)}function Fr(e,t){const n=Br(e);for(const e of n)Nt(e,t)}const qr=new WeakMap;function Vr(e){return qr.get(e)??[]}function Hr(e,t){qr.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});const Ur=new WeakMap,Kr=new WeakSet;function Gr(e,t){if(null===t)Ur.delete(e);else{Ur.set(e,t);const{stateElement:n,pathInfo:o}=e.absolutePathInfo;if(o.wildcardCount>0){for(let e=o.parentPathInfo;null!==e&&e.wildcardCount===o.wildcardCount&&!Kr.has(e);e=e.parentPathInfo)Kr.add(e);n.setPathInfo(o.lastWildcardPath,"prop","internal")}}}function Jr(e){const t=Ur.get(e);t&&(t.dirty=!0),null!==e.listIndex&&Kr.has(e.absolutePathInfo.pathInfo)&&e.listIndex.cacheStamp++}const Xr=Symbol.for("wcstack.transition-runner");function Yr(e){const t=globalThis[Xr];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 Qr(e,t,n){const o=Yr(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Zr=[],ei=[];let ti=-1,ni=0,oi=!1;function si(e){ei.includes(e)||ei.push(e)}function ri(e,t=0){const n=Zr.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Zr.push(o):Zr.splice(n,0,o)}function ii(e){queueMicrotask(()=>{throw e})}class ai{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<ei.length;t++)ei[t](e);ti>ni&&(ni=ti),ti<0&&(oi=!0);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(){zn(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],Jt++,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=[]){let o=oi?0:ni;ni=0,oi=!1;const s=new Map,r=new Set;for(let t=0;t<e.length;t++){const n=e[t],o=s.get(n.absoluteAddress);null!==_t&&null!=o&&null!==n.context&&o.transactionId!==n.context.transactionId&&_t({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:o.transactionId,winnerTransactionId:n.context.transactionId}),s.set(n.absoluteAddress,n.context),r.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];s.has(t)||s.set(t,null)}const i=[],a=new Map;s.forEach((e,t)=>{if(null!==e&&e.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),void(null!==_t&&_t({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=Io(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(i.push(t),null!==e&&a.set(t,e));else!1!==n.replaceNode.isConnected&&(i.push(n),null!==e&&a.set(n,e))});try{const e=()=>{ti=o+1;try{a.size>0?Rl(i,a):Rl(i)}finally{ti=-1}};if(o>p&&i.length>0){if(101===o++){const e=[...new Set(Array.from(r,e=>e.absolutePathInfo.pathInfo.path))];console.error("[@wcstack/state] render chain depth limit exceeded; bindings for this batch were not applied.",{maxDepth:p,paths:e}),null!==_t&&_t({type:"state:render-chain-limit",maxDepth:p,paths:e})}}else if(t()||0===i.length)e();else{const t=Qr("state",e);void 0!==t&&t.catch(ii)}}finally{Fn(),ti=o,function(e){for(const t of Zr.slice())t.listener(e)}(r),ti=-1}}}const li=new ai;function ci(){return li}const di=new WeakMap,ui=new WeakMap,fi=new WeakMap,hi=new WeakMap;let pi=!1;const gi=new WeakMap;function mi(e){const t=e.absolutePathInfo.stateElement;let n=gi.get(t);void 0===n&&gi.set(t,n=new Set),n.add(e)}function yi(e){const t=gi.get(e);return void 0===t?null:(gi.delete(e),t)}const wi=new WeakMap,bi=new WeakMap,vi=new WeakMap,$i=new WeakMap,xi=new WeakMap,Si=[];function Ii(e,t){const n=Pi(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ce(t).cumulativePaths;if(o.length<2)return;let s=xi.get(e);void 0===s&&xi.set(e,s=new Map);for(let e=0;e<o.length-1;e++){let n=s.get(o[e]);void 0===n&&s.set(o[e],n=new Set),n.add(t)}}function Pi(e){let t=di.get(e);return void 0===t&&di.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function ki(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function Ai(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function Ni(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=ui.get(o);if(void 0===r&&ui.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(Ai(s,e,o),r.set(t,n),ki(s,n,o)),!1}return r.set(t,n),ki(s,n,o),!0}function _i(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):(o.push(n),!1)}function Ti(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&_i(fi,o.listIndex,r)&&function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){let n=vi.get(t);void 0===n&&vi.set(t,n=new Set),n.add(e)}}(o.listIndex),null!==r.levelListIndex&&_i(hi,r.levelListIndex,r))}function Ei(e,t,n,o,s){pi=!0;const r=Pi(e);Ii(e,t);Ti(r,t,s,o,Ni(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function Ci(e,t){Pi(e).tracked.add(t)}function Mi(e,t){return!0===di.get(e)?.byPath.has(t)||!0===wi.get(e)?.has(t)}function Oi(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(so(e.stateElement,_o(t,o)))}function Ri(e,t){if(!pi||e===t)return;const n=bi.get(e);if(void 0===n)return;bi.delete(e);const o=bi.get(t);bi.set(t,void 0===o?n:o.concat(n)),bn(t);for(const o of n){o.indexes=t;const n=Pi(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&&!en(e))for(const t of o.getters){const n=so(o.stateElement,_o(t,e));Jr(n),ci().enqueueAbsoluteAddress(n,null),mi(n)}}}function ji(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Li(e,t,n,o,s){const r=di.get(e),i=r?.byPath.get(t),a=wi.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return Si;const l=r.lastValue.has(t),c=r.lastValue.get(t);r.lastValue.set(t,s);const d=[],u=!n||!Object.is(o,s),f=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&ji(i.get(o),d),f&&ji(i.get(c),d),u&&ji(i.get(s),d)),void 0!==a)for(const e of a)n&&Oi(e,o,d),f&&Oi(e,c,d),u&&Oi(e,s,d);return d}function Wi(e,t){return!0===xi.get(e)?.has(t)}function Di(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Bi(e,t,n,o,s=!0){const r=ce(t).segments.length,i=[];for(const a of xi.get(e).get(t)){const t=ce(a).segments.slice(r);if(t.includes(u)){zi(e,a,i);continue}const l=s?Di(n,t):void 0;for(const n of Li(e,a,s,l,Di(o,t)))i.push(n)}return i}function zi(e,t,n){const o=di.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())ji(e,n);const s=wi.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)Oi(e,t,n)}function Fi(e){const t=hi.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function qi(e){const t=fi.get(e);if(void 0!==t){fi.delete(e),function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){const n=vi.get(t);void 0!==n&&(n.delete(e),0===n.size&&vi.delete(t))}}(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=ui.get(o),r=s.get(n);s.delete(n),Ai(di.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Fi(e)}}}function Vi(e){const t=$i.get(e);if(void 0!==t){$i.delete(e);for(const e of t){const t=wi.get(e.stateElement),n=t.get(e.path);n.delete(e),0===n.size&&t.delete(e.path);const o=bi.get(e.indexes);o.splice(o.indexOf(e),1),0===o.length&&bi.delete(e.indexes)}}}function Hi(e){if(!pi)return;qi(e),Vi(e);const t=vi.get(e);if(void 0!==t){vi.delete(e);for(const e of t)qi(e),Vi(e),vi.delete(e)}}function Ui(e,t,n){if(!pi)return;const o=hi.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=di.get(e),i=o.byPath.get(s);Ai(i,t,r),ki(i,n,r),ui.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Jr(r),ci().enqueueAbsoluteAddress(r,null),mi(r))}}const Ki=new WeakMap,Gi=Object.freeze([]),Ji=new Set,Xi=new WeakMap,Yi=new WeakMap;function Qi(e,t){Yi.set(e,new WeakRef(Object(t)))}function Zi(e){return Yi.get(e)?.deref()}function ea(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}function ta(e){!function(e){for(const t of e)Ht.add(t)}(e);for(const t of e)Hi(t)}function na(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Gi,s=Array.isArray(n)&&n.length>0?n:Gi,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Gi,o=Array.isArray(t)&&t.length>0?t:Gi;let s=Ki.get(n);return s&&s.get(o)||null}(o,s);if(r&&r.newIndexes===yn(s,e))return r;const i=yn(o,e)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Ji,deleteIndexSet:new Set(i),addIndexSet:Ji};let t=yn(s,e);if(null===t&&null!==e&&function(e,t){const n=un.get(e);for(const o of n??[])if(rn(e,o))n.delete(o);else if(o!==t)return!0;return!1}(o,e)&&Qi(s,o),0===o.length||null===t&&Zi(s)===o){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=jt(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:Ji,deleteIndexSet:new Set(i),addIndexSet:new Set(t)}}if(ea(o,s)&&(t??i)===i)return o!==s&&oa(o,i,e),a={oldIndexes:i,newIndexes:i,changeIndexSet:Ji,deleteIndexSet:Ji,addIndexSet:Ji};if(null!==t)return sa(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,l=new Set;let c=!1;for(let o=0;o<s.length;o++){const a=s[o],d=n.get(a),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=jt(e,o);t.push(n),l.add(n)}else{const e=i[u];c=!0,u!==o&&r.add(e),t.push(e)}}c&&oa(o,t,e);return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:l}}finally{void 0!==a&&(!function(e,t,n){let o=Ki.get(e);o||(o=new WeakMap,Ki.set(e,o)),o.set(t,n)}(o,s,a),bn(i),vn(s,a.newIndexes))}}(e,t,n);return function(e,t){const n=e.newIndexes;let o;for(let e=0;e<n.length;e++){if(n[e].index!==e){const t=n[e].index;n[e].index=e,Ui(n[e],t,e)}zt(n[e],t[e])&&(o??=[]).push(n[e])}const s=Xi.get(t);s?.[0]===Jt&&(o=o?s[1].concat(o):s[1]),o&&Xi.set(t,[Jt,o]),e.valueChangeIndexes=o}(o,Array.isArray(n)&&n.length>0?n:Gi),function(e){for(const t of e)Ht.delete(t)}(o.newIndexes),Zi(n)!==t&&(ta(o.deleteIndexSet),Ri(o.oldIndexes,o.newIndexes)),o}function oa(e,t,n){var o;if(o=e,hn.add(o),null!==n)for(const e of t)Dt(e,n)}function sa(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}}function ra(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 ia=new WeakMap;function aa(e){return ia.get(e)??null}function la(e,t){ia.set(e,t)}const ca=new WeakMap;const da=new WeakMap;function ua(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function fa(e,t,n,o,s){const r=function(e,t,n){let o=da.get(e);void 0===o&&da.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let e=0;e<t.length;e++){const d=t[e];if(!n.shouldApplyState(d))continue;const u=r[e];if(null===u||ua(u.prefixes,i)){Ml(d,s);continue}if(s.appliedBindingSet.has(d))continue;c||(l=s.state[Hn](o),c=!0);const f=u.tail;let h=l,p=!1;for(let e=0;e<f.length;e++){if(null==h){h=void 0;break}if(a&&!(f[e]in Object(h))){p=!0;break}h=h[f[e]]}p?Ml(d,s):(s.appliedBindingSet.add(d),Cl(d,s,h))}}function ha(e,t,n){Fr(e,t);const o=Lr(e),s=aa(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return ca.get(e)??null}(e);if(null!==r)return void fa(r,o,s,t,n)}for(const e of o){if(null===s){$o(wo(e),e)}(null===s||s.shouldApplyState(e))&&Ml(e,n)}e.spreads&&jl(e.spreads,t,s,o,Vr(e))}function pa(e){if(!e.mounted)return;const t=Lr(e),n=aa(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{xo(wo(o),o)}}!function(e){const t=Br(e);for(let e=0;e<t.length;e++)Nt(t[e],null)}(e)}function ga(){return Object.freeze(new Set)}const ma=new WeakMap,ya=ga();function wa(e,t){const n=ma.get(e);n?n.add(t):ma.set(e,new Set([t]))}function ba(e){const t=ma.get(e);return void 0!==t?t:ya}function va(e,t){const n=ma.get(e);n&&(n.delete(t),0===n.size&&ma.delete(e))}const $a=new Set(["if","elseif","else","for"]);class xa{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t;const n=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)n.push(t);this._childNodeArray=n,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];qs(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){qs(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=aa(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(Lr(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Ws(n),n.parentNode.removeChild(n))}const n=Lr(this);for(let e=0;e<n.length;e++){const t=n[e];$a.has(t.bindingType)&&ba(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=aa(this);null!==e&&(e.isRowSession?e.disposeBindings(Lr(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=Lr(this);for(let t=0;t<e.length;t++){const n=e[t];$a.has(n.bindingType)&&ba(n.node).forEach(e=>{e.unmount()}),Co(n),bo(n)}}unmount(){{const e=aa(this);null!==e&&(e.isRowSession?e.disposeBindings(Lr(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Ws(e),e.parentNode.removeChild(e));const e=Lr(this);for(let t=0;t<e.length;t++){const n=e[t];$a.has(n.bindingType)&&ba(n.node).forEach(e=>{e.unmount()}),Co(n),bo(n)}this._mounted=!1}}function Sa(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${s.commentForPrefix}|${s.commentIfPrefix}|${s.commentElseIfPrefix}|${s.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 Ia(e){return 1<<Math.min(e,31)}function Pa(e){let t=e.indexBits;if(void 0===t){t=0;for(const n of e.nodeInfos)for(const e of n.parseBindTextResults)e.statePathName in R&&(t|=Ia(R[e.statePathName])),"string"==typeof e.uuid&&(t|=Pa(nc(e.uuid)));e.indexBits=t}return t}function ka(e){return Pa(nc(e.uuid))}function Aa(e,t){return e.statePathName in R||$a.has(e.bindingType)&&0!==(ka(e)&t)}function Na(e,t){const n=document.createDocumentFragment(),o=new xa(n,t);return o._childNodeArray=e,o._firstNode=e.length>0?e[0]:null,o._lastNode=e.length>0?e[e.length-1]:null,o._mounted=!0,o}function _a(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=ut(o,s[e].nodePath);null===t&&ie(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),St(t),Ye(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,n){let o=Wl.get(n);void 0!==o&&o.currentRowPlan===e||(o=new _r,Wl.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new xa(o);return la(d,c),Wr(d,a),function(e,t){ca.set(e,t)}(d,n),Hr(d,l),zr(d,r),wa(e.node,d),d}function Ta(e){void 0!==e.uuid&&null!==e.uuid||ie("BindingInfo.uuid is null.");const n=nc(e.uuid);n||ie(`Fragment with UUID "${e.uuid}" not found.`);const o=!t()&&Sa(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==s.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=s.enableDirectionalInitialSync,n=[],o=e.nodeInfos;for(let t=0;t<o.length;t++){const s=o[t],r=ut(e.fragment,s.nodePath);if(null===r)return null;for(const e of s.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===_||s===A)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ze(r))return null;if("prop"===o&&ds(r,e.propName))return null;const i=ht(e);let a;try{a=or({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:t,template:i,isEvent:"event"===o,isIndexBinding:e.statePathName in R,policy:a,authority:a.authority})}}return 0===n.length?null:{directional:t,slots:n}}(n)),null!==r)return _a(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o,s]=function(e,t){const n=[],o=[],s=[];for(const r of t){const t=ut(e,r.nodePath);if(null===t&&ie(`Node not found by path [${r.nodePath.join(", ")}] in fragment.`),vt.has(t))continue;const i=$t(t,r.parseBindTextResults,{allowDeferred:!0});null!==i.deferred&&(s.push(i.deferred),vt.add(t)),o.push(...i.bindings),n.push(t)}return[n,o,s]}(e,t),r=new _r,i=r.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:i,bindingSession:r,spreads:s}}(i,n.nodeInfos);o&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new xa(i,o);a.spreads.length>0&&(l.spreads=a.spreads),la(l,a.bindingSession),Wr(l,a.bindingInfos);const c="for"===e.bindingType?(d=e.statePathInfo.wildcardCount+1,2**Math.min(d,32)-1):-1;var d;const u=[];for(const e of a.bindingInfos)Aa(e,c)&&u.push(e);return Hr(l,u),zr(l,a.nodes),wa(e.node,l),l}const Ea=new WeakSet,Ca=Symbol.for("wcstack.state.view-transition-naming");function Ma(){const e=Yr("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Oa(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||Ea.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[Ca]??={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.`)):(Ea.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 Ra=new WeakMap,ja=new WeakMap,La=new WeakMap,Wa=new WeakMap,Da=new WeakMap,Ba=new WeakMap;function za(e,t,n,o){let s=Ba.get(e);void 0===s&&(s=[document.createComment(""),document.createComment("")],Ba.set(e,s));const[r,i]=s;r.data=`@@wcs-for-start:${o}`,i.data=`@@wcs-for-end:${o}`,e.mounted||(r.remove(),i.remove());const a=null===n?null:n.nextSibling;if(null===r.parentNode)t.insertBefore(r,a),t.insertBefore(i,a),e.mountAfter(r);else if(a!==r){let e=r;for(;e!==i;){const n=e.nextSibling;t.insertBefore(e,a),e=n}t.insertBefore(i,a)}return i}function Fa(e,t,n){!function(e,t,n){let o=ja.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ja.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function qa(e,t){Ra.set(e,t)}function Va(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 Ha(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)}const Ua=new Set(["if","elseif","else","for"]);function Ka(e,t){for(const n of Lr(e))if(t.appliedBindingSet.delete(n),Ua.has(n.bindingType))for(const e of ba(n.node))Ka(e,t)}function Ga(e,t,n){for(const o of Vr(e))if(Ua.has(o.bindingType)){if(o.statePathName in R&&Ml(o,t),0!==(ka(o)&n))for(const e of ba(o.node))e.mounted&&Ga(e,t,n)}else Ml(o,t)}function Ja(e){for(const t of Lr(e)){if(!Ua.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of ba(t.node))Ja(n),e&&n.mounted&&(pa(n),n.unmount(),va(t.node,n),Da.delete(t.node),ja.delete(t.node))}}function Xa(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ya(e,o,r){const i=Boolean(r);let a;const l=ba(e.node);a=0===l.size?Ta(e):l.values().next().value;const c=t(),d=e.uuid??"",u=e.bindingType;if(i||(s.debug&&console.log(`unmount if content : ${Xa(e)}`),c&&a.mounted&&(n.seen=!0),pa(a),a.unmount()),i){s.debug&&console.log(`mount if content : ${Xa(e)}`);const t=At(e.node);if(Fr(a,t),c){if(!a.mounted){const t=document.createComment(`@@wcs-${u}-start:${d}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),a.mountAfter(t);const n=document.createComment(`@@wcs-${u}-end:${d}:${e.statePathName}`),o=a.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}}else a.mountAfter(e.node);ha(a,t,o);const n=Ma();null!==n&&Oa(a,"branch",n)}}const Qa=new WeakMap;function Za(e){return Qa.get(e)??[]}const el=new Set;function tl(){el.clear()}const nl=Symbol.for("wcstack.trustedTypes.policy");function ol(){const e=globalThis[nl];return null===e||"object"!=typeof e?null:e}function sl(e){globalThis[nl]=e}let rl;let il=!1;function al(e,t){if(il)return;if(!function(){if(void 0!==rl)return rl;if(!("trustedTypes"in globalThis))return rl=!1,rl;try{document.createElement("div").innerHTML="<i></i>",rl=!1}catch{rl=!0}return rl}())return;il=!0;const n="function"==typeof ol()?.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 ll={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 cl(e,n,o){if(1===e.propSegments.length){const t=e.propSegments[0];"textContent"===t||"innerText"===t?o=null==o?"":String(o):void 0===o&&"innerHTML"===t&&(o="")}if(void 0===o)return void(s.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!==o){null!==Cr&&null!==d&&"object"==typeof d&&null!==o&&"object"==typeof o&&null!==Ze(r)&&Cr.rememberOverwrittenObject(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=ol(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(o):o,e=!0}catch(e){t&&al(r,c),s.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:o,error:e})}if(e){const e=function(e,t){const n=Ze(e);if(null===n)return null;const o=tt(e)?.get(n);if(void 0===o)return null;const s=ot(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,o)}catch(t){s.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:o,error:t})}}};if(s.enablePropagationContext&&ds(r,c)){const t=gs(r,c,e.statePathName),s=ms(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??$s()??ws(t);if(a.visitedEdges.has(s))null!==_t&&_t({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:s,node:r,member:c});else{const e=bs(a,s);xs(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:hs++,writtenValue:n};Ss.push({receipt:i,node:e});try{return r()}finally{Ss.pop()}}(r,c,o,t,e.transactionId,i))}}else i()}if(t()){const e=ll[c];e?e(r,o):(!function(e,t,n){let o=Qa.get(e);o||(o=[],Qa.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,o),a=r,el.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!==o){if(Object.isFrozen(d))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:o}));null!==Cr&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ze(r)&&(u in d?Cr.rememberOverwrittenValue(r,c,u,d[u]):Cr.recordInjectedKey(r,c,u));try{d[u]=o}catch(e){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:o,error:e})}}}const dl=new WeakSet;function ul(e,t,n){}function fl(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)}}const hl=new WeakMap;function pl(e,t,n,o){const s=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+d:"";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(d)&&!hl.has(fl(o,e)?.get)&&s.push(t)}return s}const gl={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},ml={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function yl(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}.${he}`}function wl(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 bl(e,t){return`$setAll("${e}") ${t}`}function vl(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.${he}`}function $l(e,t){const n=Eo(t);if(n.pathInfo.path in R){const e=At(t.node);return null===e&&ie(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&ie("ListIndex not found for loopContext:");const n=R[t];void 0===n&&ie(`Invalid index name: ${t}`);const o=fo(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&ie(vl(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Hn](n)}const xl=new WeakSet;function Sl(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Il=Object.freeze({[T]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?("boolean"!=typeof n&&ie(`Invalid value for class application: expected boolean, got ${typeof n}. Write "|truthy" if you mean to coerce.`),o.classList.toggle(s,n)):o.classList.toggle(s,!1)},[E]:function(e,t,n){const o=e.node,s=e.propSegments[1];if(null==n)return void(o.hasAttribute(s)&&o.removeAttribute(s));const r=String(n);o.getAttribute(s)!==r&&o.setAttribute(s,r)},[C]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[_]:function(e,t,n){Jo(n)||ie("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Rr.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||ie('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Ze(e);if(null===t)return null;const n=tt(e)?.get(t);return void 0===n&&ie(`Custom element <${t}> is not defined for command binding.`),ot(e)}(r);null===a&&ie(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||ie(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${fe(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Rr.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 Rr.delete(e);const o=n[i];return"function"!=typeof o&&ie(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),Rr.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Pl={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!dl.has(e.replaceNode)){dl.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,o,s){const r=e.statePathInfo,i=go(e),a=wo(e),l=Tn(a),c=Da.get(e.node);let d,f;const h=void 0!==c&&function(e,t){const n=Nn.get(e);return void 0!==n&&(n===t||mn(t)===mn(n))}(a,s),p=h||void 0===c||c.value===l?null:na(i,l,s);h?(d=c.value,f=sa(mn(d),mn(s))):null!==p&&p.newIndexes.every(e=>e.parentListIndex===i||en(e.parentListIndex)||!sn(s,e.parentListIndex))?(d=c.value,f=sa(mn(d)??[],p.newIndexes)):(d=l.length>0&&!ja.has(e.node)?[]:l,f=na(i,d,s));const g=Array.isArray(s)?s:[];o.newListValueByAbsAddress.set(a,g),Da.set(e.node,xn(g));let m=ja.get(e.node);const y=void 0!==m?function(e,t,n){if(!Qt(t))return null;let o=null;for(let t=0;t<n.newIndexes.length;t++){const s=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(s)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(o??={byAddedIndex:new Map,reused:new Set},o.byAddedIndex.set(s,i),o.reused.add(i))}return o}(m,d,f):null,w=Array.isArray(d)&&d.length===f.deleteIndexSet.size&&f.deleteIndexSet.size>0;if(w&&null===y&&null!==e.node.parentNode){let t=Wa.get(e.node);if(void 0===t){const n=Ra.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Va(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Va(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n.parentNode===e.node.parentNode?n:e.node),Wa.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){Bs.set(e,(Bs.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let b=w?1e3-function(e){return La.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;const v=t();if(void 0!==m){const t=m;f.deleteIndexSet.forEach(o=>{const s=t.get(o);void 0!==s&&(v&&(Ba.get(s)?.forEach(e=>e.remove()),n.seen=!0),null!==y&&y.reused.has(s)?(pa(s),Ja(s),s.unmountInPlace()):b<=0&&s.tryDestroy()?va(e.node,s):(pa(s),s.unmount(),function(e,t){let n=La.get(e.node);void 0===n&&(n=[],La.set(e.node,n)),n.length<1e3?n.push(t):va(e.node,t)}(e,s),b-=1),w||t.delete(o))}),w&&(ja.delete(e.node),m=void 0)}let $=e.node;const x=ce(r.path+"."+u),S=o.stateElement.loopContextStack,I=ra(f);let P=null;f.newIndexes.length==f.addIndexSet.size&&f.newIndexes.length>0&&$.isConnected&&null===y&&(P=document.createDocumentFragment(),ao(P,o.rootNode));const k=v?`${e.uuid}:${r.path}:`:"",A=Ma(),N=La.get(e.node);for(const t of f.newIndexes){let n;if(f.addIndexSet.has(t)){const s=_o(x,t);if(S.createLoopContext(s,s=>{n=y?.byAddedIndex.get(t)??(void 0!==N?N.pop():void 0),void 0===n?n=Ta(e):(Ka(n,o),Fr(n,s)),v?$=null!==P?za(n,P,null,k+t.index):za(n,$.parentNode,$,k+t.index):null!==P?n.appendTo(P):$.nextSibling!==n.firstNode&&n.mountAfter($),ha(n,s,o),null!==A&&Oa(n,"row",A)}),void 0===n&&ie(`Content not found for ListIndex: ${t.index} at path "${r.path}"`),null!==y&&y.reused.has(n)){const e=o.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](o.stateElement,n)}}}else{n=void 0!==m?m.get(t)??null:null,f.changeIndexSet.has(t)&&Ga(n,o,Ia(r.wildcardCount)),null===n&&ie(`Content not found for ListIndex: ${t.index} at path "${r.path}"`);const e=!n.mounted;if(v?$=za(n,$.parentNode,$,k+t.index):null!==I&&I.has(t)&&Ha($,n.firstNode)||$.nextSibling===n.firstNode||n.mountAfter($),e){const e=n,s=_o(x,t);S.createLoopContext(s,t=>{ha(e,t,o)})}}v||($=n.lastNode||$),void 0===m&&(m=new WeakMap,ja.set(e.node,m)),m.set(t,n)}Ra.set(e.node,$),null!==P&&(e.node.parentNode.insertBefore(P,e.node.nextSibling),ao(P,null))},if:Ya,else:Ya,elseif:Ya,radio:function(e,t,n){const o=e.node,s=Mr(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=Mr(o.value,e.inFilters),r=Array.isArray(n)?n:Or;o.checked=r.includes(s)}},kl=new WeakMap,Al=new WeakMap,Nl=new WeakMap;function _l(){}function Tl(e){const t=Cr;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return ul;if(t.isDeclared(n,o))return _l}return cl}function El(e,t){Cl(e,t,$l(t.state,e))}function Cl(e,t,n){const o=Mr(n,e.outFilters);if(!0===Al.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=kl.get(e);if(void 0===s){if(kl.has(e))return s=Tl(e),s===ul&&kl.set(e,s),void s(e,t,o);if(s=Pl[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Il[t],kl.set(e,s),void 0===s){Ze(e.replaceNode)?(s=Tl(e),s===ul&&kl.set(e,s)):(s=cl,kl.set(e,s))}}if(s===cl){if("SELECT"===e.node.tagName){const n=e.propSegments[0];if("value"===n||"selectedIndex"===n)return t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement}),void Al.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function Ml(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=wo(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=Er(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Nl.get(e)){const t=Ze(e.replaceNode);if(t&&(void 0===tt(e.replaceNode)?.get(t)||function(e){return"waiting-definition"===fr.get(e)?.phase}(e)))return void function(e,t){if(xl.has(e))return;xl.add(e);const n=()=>{xl.delete(e);const t=Er(e);(null===t||t.shouldApplyState(e))&&Rl([e])},o=n=>{xl.delete(e),Sl(t,n)},s=Er(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{xl.delete(e),r()})||(xl.delete(e),r()))}const r=tt(e.replaceNode);if(null===r)return xl.delete(e),void Sl(t,new Error("CustomElementRegistry is unavailable."));Xs(r).wait(t,()=>{e.replaceNode.isConnected?n():xl.delete(e)},o)}(e,t);Nl.set(e,!0)}if(!0===t.sameRootVerified)return void El(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=lo(o),null===o&&ie("Root node for fragment not found for binding.")),o!==t.rootNode){const n=Jl(o);null===n&&ie("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};El(e,r)})}else El(e,t)}function Ol(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!==_t&&_t({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function Rl(e,t,n){let o=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;o<e.length;){let n=e[o];if(!1===n.replaceNode.isConnected){s.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),o++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=lo(d),null===d&&ie("Root node for fragment not found for binding."));const u=Jl(d);null===u&&ie("No state tree found on this root for binding."),u.createState("readonly",s=>{const f={rootNode:d,stateElement:u,state:s,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{Ml(n,f)}catch(e){Ol(n,e,u,c)}o++;const t=e[o];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{cl(e,{propagationContextByBinding:t},n)}catch(t){Ol(e,t,o??null,c)}for(const[e,t]of i.entries())En(e,t),Bn(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Jn](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Xn](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 jl(e,t,n,o,s){for(const r of e)r.cancel?.(),r.cancel=n.deferUntilDefined(r.node,r.tagName,()=>{const i=It(r);if(o&&(e.splice(e.indexOf(r),1),o.push(...i),s.push(...i.filter(e=>e.statePathName in R))),0===i.length)return;Nt(r.node,t);Rl(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1}))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,e)})}function Ll(e,t,n,o=bt(e),s=Tr(e)){const[r,i,a]=xt(function(e){return e.filter(e=>!vt.has(e))}(o),n);for(const e of r)Nt(e,t);Rl(s.initialize(i)),jl(a,t,s)}const Wl=new WeakMap;async function Dl(e){const t=e.querySelectorAll(s.tagNames.state),n=[],o=tt(e);null===o&&ie(`CustomElementRegistry is unavailable for <${s.tagNames.state}>.`),await o.whenDefined(s.tagNames.state);for(const e of t){if(mt(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function Bl(e){if(e===document)await Dl(document),se(document),$c(document,document),Ll(document.body,null);else{const t=e;t.host.hasAttribute(s.bindAttributeName)&&await Xe(t.host),await Dl(t),se(t),$c(t,t),Ll(t,null)}}const zl={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function Fl(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${zl[e]??e}" before the state is defined.`}let ql=null;function Vl(e){return null===ql&&ie(Fl("ssr",e)),ql}const Hl=new WeakMap,Ul=new WeakMap,Kl=new Set,Gl=[];function Jl(e){return Hl.get(e)??null}function Xl(e){return Ul.get(e)??Promise.resolve()}const Yl=new WeakSet;function Ql(e){Yl.add(e)}function Zl(e,n){const o=Hl.get(e);if(null===n){if(void 0===o)return;Hl.delete(e),Kl.delete(o),null!==_t&&_t({type:"state:element-unregistered",rootNode:e,element:o}),s.debug&&console.debug("State element unregistered")}else{if(o===n)return;if(void 0===o){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 Vl('the "enable-ssr" attribute').hydrate(e)||await Bl(e)}else await Bl(e);Ql(e),Ac(),t()}catch(e){n(e)}})});Ul.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await Bl(e),Ql(e),Ac(),t()}catch(e){n(e)}})});Ul.set(e,t)}}void 0!==o&&ie('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="...">.'),Hl.set(e,n),Kl.add(n);for(let t=0;t<Gl.length;t++)Gl[t](e,n);null!==_t&&_t({type:"state:element-registered",rootNode:e,element:n}),s.debug&&console.debug("State element registered",n)}}const ec=new Map;function tc(e,t,n){if(null===n)ec.delete(e);else{ec.set(e,n);const o=Jl(t);null===o&&ie("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 nc(e){return ec.get(e)||null}function oc(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=ze(t.getAttribute(s.bindAttributeName)||"");if(t.localName===s.tagNames.state){if(t.hasAttribute("mount"))return n.filter(e=>e.propSegments[0]!==N);const e=n.find(e=>e.propSegments[0]===N);if(void 0!==e){const t=`on a volume element — a <${s.tagNames.state}> with a "mount" attribute`;ie(1===e.propSegments.length?`[wcs/mount-path-invalid] "${e.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${N}.<key>: <path>") ${t}.`:`[wcs/mount-path-invalid] "${e.propName}: ${e.statePathName}" is a volume injection declaration, and it can only be written ${t}. Add mount="<path>", or bind an element property instead.`)}}return n}if(e.nodeType===Node.COMMENT_NODE){const t=He(e);null===t&&ie("Comment node binding text not found.");const n=nc(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Ue(t),s=null):s=t,[{...o,uuid:s}]}return[]}let sc;function rc(){return sc??={filterName:"not",args:[]}}const ic=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function ac(e,t){const n=t+d+u,o=Ce(e,"|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+d+s.slice(1)}return r.length>0?s+r:s}function lc(e,t){const n=ic.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+ac(s,t)+r}function cc(e,t){const n=Me(e,";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=Ce(n,":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=ac(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function dc(e,t){return cc(e,t)}function uc(e,t){const n=s.bindAttributeName,o=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const e=o.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=lc(n.data,t);continue}const s=e;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const e=cc(r,t);e!==r&&s.setAttribute(n,e)}}}function fc(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}const hc=new WeakMap;function pc(e){return hc.get(e)??null}function gc(e){const t=[],n=bt(e);for(const e of n){const n=oc(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");hc.set(t,e.data),e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:fc(o),parseBindTextResults:n})}return t}function mc(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 yc=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),wc=rc();function bc(e,t){const n=t.outFilters;return{...t,outFilters:[...n,wc],bindingType:e}}function vc(e,t,n,o,s,r=!0){mc(t),"string"==typeof o&&uc(t,o),$c(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:gc(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 $c(e,t,n,o){const r=s.commentElsePrefix,i=yt(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(s.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(s.bindAttributeName)||"";"string"==typeof n&&(i=dc(i,n));let a=ze(i)[0];const d=yc.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Et();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&ie("'else' binding found without preceding 'if' or 'elseif' binding."),a=bc("else",l.parseBindTextResult),p=vc(e,f,a,g,o,!1),tc(h,e,p);const n=c.at(-1),s=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:fc(s),parseBindTextResults:oc(s)})):t.replaceWith(s)}else if("elseif"===u){null===l&&ie("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=vc(e,f,a,g,o),tc(h,e,p);const n=document.createComment(`@@${d}:${h}`),s=Et(),i={fragment:document.createDocumentFragment(),parseBindTextResult:bc("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:fc(n),parseBindTextResults:oc(n)}),tc(s,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${s}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:fc(m),parseBindTextResults:oc(m)})):t.replaceWith(m)}else{p=vc(e,f,a,g,o),tc(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 xc=()=>`[${s.bindAttributeName}]`;function Sc(e){if(yr(e))return!0;if(!Ic(e))return!1;if(e.hasAttribute(s.bindAttributeName))return!1;const t=e.querySelector(xc());return null!==t&&yr(t)}function Ic(e){return 1===e.nodeType}function Pc(e){if(!e.isConnected||Sc(e))return;const t=e.hasAttribute(s.bindAttributeName)?[e]:[];Array.from(e.children).some(e=>e.localName===s.tagNames.state&&mt(e))||(se(e),$c(e.getRootNode(),e),t.push(...bt(e))),Ll(e,null,void 0,t,new _r)}const kc=[];function Ac(){const e=kc.splice(0,kc.length);for(const t of e)Pc(t);c()}const Nc={protocol:"wcs-binder",version:1,bind:function(e){var t;Ic(e)&&e.isConnected&&!Sc(e)&&(t=e.getRootNode(),Yl.has(t)?Pc(e):kc.push(e))}};const _c="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Tc=0;async function Ec(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Tc}\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 await new Promise(e=>setTimeout(e)),new Error(`[@wcstack/state] ${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: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src="./state.js") needs neither. 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 Cc(e){const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}class Mc{_loopContextStack=Array(h).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&ie("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=h&&ie("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&&ie("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&&ie("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&&ie(`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 Oc={$updatedCallback:W,$streams:K},Rc=new WeakSet;function jc(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function Lc(e){if((null===e||"object"!=typeof e&&"function"!=typeof e)&&ie(`The state must be an object, got ${null===e?"null":typeof e}. Check the source of the state element (json / src / the inline <script>).`),!Rc.has(e)){ye?.state(e);for(const t of Object.keys(Oc)){if(!(t in e))continue;const n=Oc[t];n in e&&ie(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${he}`),Object.isExtensible(e)||ie(`[wcs/declaration-alias] The state is not extensible, so the old name "${t}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${he}`);const o=jc(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}Rc.add(e)}}const Wc=new WeakMap;function Dc(e,t){let n=Wc.get(e);void 0===n&&(n=new Map,Wc.set(e,n));let o=n.get(t);return void 0===o&&(o=new Go(t,e),n.set(t,o)),o}const Bc=new WeakMap;function zc(e){const t=Bc.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 Dc(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:Dc(e,n)}},set(){ie("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){ie("$command namespace is read-only; deleting from it is not allowed.")}});return Bc.set(e,n),n}const Fc=Symbol("wcs.notHandled"),qc=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Vc=new Map;function Hc(e,t){Vc.set(e,t)}const Uc=new Map;let Kc=[],Gc=[];function Jc(e,t){Uc.set(e,t),Kc=Array.from(Uc.values()).sort((e,t)=>e.order-t.order),Gc=Kc.slice().reverse()}function Xc(e){return Uc.has(e)}function Yc(e,t){for(let n=0;n<Kc.length;n++)Kc[n].activate?.(e,t)}const Qc=new Map;class Zc{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=ce(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 ed(e){let t;return Qc.get(e)??(Qc.set(e,t=new Zc(e)),t)}function td(e){"readonly"===e.mutability&&ie("This state is readonly.")}function nd(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:fo(n.listIndex,o,n.pathInfo.wildcardCount)}function od(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=uo(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?fo(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?fo(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function sd(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function rd(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](e,t,n,o,s);if(a!==Fc)return a}}return Fc}function id(e,t,n,o,s){if(t.pathInfo.segments[0]===V)return function(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}(zc(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=rd(s,t,null,n,o);if(r!==Fc)return r;ie(function(e,t,n){return`[${gl.binding}] Path "${e}" does not exist on the state tree.${fe(e,pl(t,"",n,t))}${he}`}(t.pathInfo.path,e,s.getterPaths))}const r=dd(e,t.parentAddress,n,o);if(null==r)return;const i=t.pathInfo.segments[t.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==u&&!(i in Object(r))){const e=rd(s,t,Object(r),n,o);if(e!==Fc)return e}if(i===u){const e=t.listIndex?.index??ie(vl(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(r,e)}return Reflect.get(r,i)}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 ad(e,t,n,o,s){const r=so(s,t),i=function(e){return Ur.get(e)??null}(r),a=s.stateGeneration,l=t.pathInfo.lastSegment===u?void 0:Bt(t.listIndex);if(null!==i&&!1===i.dirty&&i.generation===a&&i.rowStamp===l)return i.value;const c=id(e,t,n,o,s);"function"!=typeof c&&Gr(r,{value:c,dirty:!1,generation:a,rowStamp:l});const d=i?.value;return Array.isArray(c)&&c!==d&&s.getterPaths.has(t.pathInfo.path)&&function(e,t,n,o,s,r){const{path:i,wildcardCount:a}=t.pathInfo;r.beginUntrack();try{for(const[l,c]of r.stateElement.dynamicDependency){const d=ce(l);if(!c.includes(i)||d.wildcardCount>a)continue;const u=dd(e,_o(d,fo(t.listIndex,d.wildcardCount-1,a)),s,r);u===n?ld.add(t.pathInfo):u===o&&Qi(n,o)}}finally{r.endUntrack()}}(e,t,c,d,n,o),c}const ld=new WeakSet;function cd(e){return ld.has(e)}function dd(e,t,n,o){od(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const e=r.read;for(let r=0;r<e.length;r++){const i=e[r](s,t,n,o);if(i!==Fc)return i}}return sd(s,t)?ad(e,t,n,o,s):id(e,t,n,o,s)}function ud(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=_o(f,r),p=so(n.stateElement,h),g=Dn(p),m=dd(e,h,t,n),y=na(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),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]??ie(`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())Bn(e,Array.isArray(t)?t:[]);return l}function fd(e,t,n){const o=yn(n,t.listIndex);if(null!==o)return o;const s=so(e.stateElement,t),r=na(t.listIndex,Dn(s),n);return Bn(s,Array.isArray(n)?n:[]),r.newIndexes}function hd(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=_o(a,r),c=fd(n,l,dd(e,l,t,n)),d=s[i];r=c[d]??ie(`ListIndex not found at index ${d} of ${a.path}`)}return r}function pd(e,t,n,o){"object"==typeof e&&null!==e||ie(`${Q} 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&&ie(`${Q} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function gd(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&ie(`${Q} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function md(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];pd(a,n,o,i);const l=gd(a,t,n,o,i);r.has(l)&&ie(`${Q} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function yd(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 wd(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=dd(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===u){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const bd=new WeakMap;function vd(e){return bd.get(e)??null}function $d(e,t){null===t?bd.delete(e):(bn(t.listIndexes),bd.set(e,t))}function xd(e,t,n){const o=_o(ce(e.wildcardParentPaths[t]),n),r=so(e.stateElement,o),i=Dn(r),a=e.stateProxy[Hn](o),l=na(o.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 s.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)xd(e,t+1,n)}function Sd(e,t,n,o){n?e.result.has(t)||e.quiet.add(t):e.quiet.delete(t),e.result.add(t),o.push(t)}const Id=[];function Pd(e,t,n){return"full"!==e.listExpansion&&e.listPathSet.has(t)?e.stateElement.crossRowListPaths?.has(t)?{fullRows:n.newIndexes,movedRows:null}:0===n.addIndexSet.size&&0===n.changeIndexSet.size?0===n.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:Id,movedRows:null}:{fullRows:n.newIndexes,movedRows:null}:{fullRows:Id,movedRows:null}:{fullRows:n.addIndexSet,movedRows:n.changeIndexSet}:{fullRows:n.newIndexes,movedRows:null}}const kd=[];function Ad(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return kd;let s=null;const r=t+d;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ce(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??kd}function Nd(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),e.quiet.has(a)?Jr(so(e.stateElement,a)):n(a),i.length=0,_d(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}function _d(e,t,n){const o=t.pathInfo.path,s=e.quiet.has(t),r=e.staticMap.get(o);if(r)for(const i of r){const r=ce(i);if(r.lastSegment===u){const a=e.stateProxy[Hn](t),l=Array.isArray(a)?a:[],c=so(e.stateElement,t),d=Dn(c),u=e.listPathSet.has(o);if(!u&&"diff"===e.listExpansion&&(e.keyedMergePath===o||mn(l)?.length!==l.length&&!ea(d,l)))continue;const f=na(t.listIndex,d,l);e.observedListValueByAbsAddress.set(c,l);const h=Pd(e,o,f);for(const t of h.fullRows)Sd(e,_o(r,t),s||!u,n);for(const t of f.valueChangeIndexes??Id)Sd(e,_o(r,t),s||!u,n);if(null!==h.movedRows){const t=Ad(e,i,r);if(null===t)for(const t of h.movedRows)Sd(e,_o(r,t),s,n);else if(t.length>0)for(const o of h.movedRows)for(const r of t)Sd(e,_o(r,o),s,n)}}else Sd(e,_o(r,t.listIndex),s,n)}const i=e.dynamicMap.get(o);if(i)for(const o of i){const r=ce(o),i=[];if(r.wildcardCount>0){const n=uo(t.pathInfo,r);if(r.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&ie(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=fo(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const s={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:r.wildcardPaths,wildcardParentPaths:r.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};xd(s,n,o),i.push(...s.targetListIndexes)}else{null===t.listIndex&&ie(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=fo(t.listIndex,n-1,t.pathInfo.wildcardCount);i.push(e)}}else i.push(null);for(const t of i)Sd(e,_o(r,t),s,n)}}function Td(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&&ie(`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,quiet:new Set};Nd(u,t,a),function(e,t){for(let n=0;n<1e3;n++){const n=yi(e.stateElement);if(null===n)return;n.forEach(n=>{Nd(e,_o(n.absolutePathInfo.pathInfo,n.listIndex),t)})}}(u,a);for(const[e,t]of u.observedListValueByAbsAddress)Bn(e,t);return Array.from(u.result)}function Ed(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](e,t,n,o,s)}}function Cd(e,t,n){const o=e.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Md(e,t,n){const o=e.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Od(e,t,n,o,s,r){const i=Mi(e,t),a=Wi(e,t);if(!i&&!a)return null;const l=[],c=jd(l);return i&&Li(e,t,n,o,s).forEach(c),a&&Bi(e,t,n?o:r(),s).forEach(c),l}function Rd(){return s.enablePropagationContext?$s()??null:null}function jd(e){const t=ci(),n=Rd();return o=>{Jr(o),t.enqueueAbsoluteAddress(o,n),e.push(o)}}function Ld(e,t,n){if(null===e||0===e.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=ci(),a=Rd();for(let n=0;n<e.length;n++){const l=e[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const d=_o(l.pathInfo,e[n].listIndex);Td(o,d,s,r,o.listPaths,t,"new",e=>{if(e===d)return;const t=so(o,e);Jr(t),i.enqueueAbsoluteAddress(t,a)},{listExpansion:"diff"})}}function Wd(e,t,n,o,r,i,a="diff"){const l=s.enablePropagationContext?$s()??ws(-1):null,c=ci(),f=o.stateElement;c.enqueueAbsoluteAddress(t,l),i&&Jr(t);const h=t=>Td(f,t,f.staticDependency,f.dynamicDependency,f.listPaths,n,"new",t=>{if(t===e)return;const n=so(f,t);Jr(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r});if(h(e),e.pathInfo.lastSegment!==u&&null!==e.listIndex&&null!==e.listIndex.parentListIndex){const t=e.listIndex,o=e.pathInfo.wildcardParentPathInfos[t.position],s=_o(o,t.parentListIndex),r=()=>n[Hn](s),i=e=>{Jr(e),c.enqueueRenderOnlyAddress(e)};for(const n of pn(t,r))i(so(f,_o(e.pathInfo,n)));const a=e.pathInfo.path.slice(e.pathInfo.wildcardPaths[t.position].length);for(const e of Mn(so(f,s),r())){const n=e.absolutePathInfo.pathInfo;n!==o&&n.wildcardCount===o.wildcardCount&&i(ro(f,ce(n.path+d+u+a),t))}}const{path:p,lastSegment:g,wildcardCount:m,wildcardParentPaths:y,wildcardParentPathInfos:w}=e.pathInfo,b=e.listIndex;for(let e=0;b&&e<m;e++){const t=fo(b,e-1,m);for(const o of f.dynamicDependency.get(y[e])??[]){const s=ce(o);if(f.listPaths.has(o)&&s.wildcardCount===e&&cd(s)&&n[Hn](_o(s,t))===n[Hn](_o(w[e],t))){const t=_o(ce(o+p.slice(y[e].length)),b);h(t),g===u&&c.enqueueRenderOnlyAddress(so(f,t.parentAddress))}}}}function Dd(e,t,n,o,s){s&&(e.getterPaths.has(t)?Jr(n):Gr(n,{value:o,dirty:!1,generation:e.stateGeneration,rowStamp:n.absolutePathInfo.pathInfo.lastSegment===u?void 0:Bt(n.listIndex)}))}function Bd(e,t,n,o,s){const r=t.listIndex,i=mn(n);if(i?.[o]!==r||n[o]===s)return t;const a=jt(r.parentListIndex,o,Wt(r));if(function(e){return $n.has(e)}(n)){const e=vd(n)??{value:n.slice(),listIndexes:i};vn(e.value,e.listIndexes),Sn(n,e.value)}const l=function(e){return wn.has(e)}(i)?i:i.slice();l[o]=a,vn(n,l,!0),Ri(i,l),ta([r]);const c=_o(t.pathInfo,a);return Md(e,so(e,c),so(e,t)),c}function zd(e,t,n,o,s,r,i,a,l=!0){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=dd(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===u){const e=t.listIndex?.index??ie(vl(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(i,e,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t),r.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{l&&Wd(t,n,s,r,i,a)}}function Fd(e,t,n,o,s,r,i,a,l){const c=t.parentAddress??ie(`address.parentAddress is undefined path: ${t.pathInfo.path}`),f=dd(e,c,s,r)??[],h=vd(f);if(l)return h&&(h.value[t.listIndex.index]=o),zt(t.listIndex,o),zd(e,t,n,o,s,r,i,a);const p=t.listIndex,g=h??{value:[...f],listIndexes:mn(f)??[],written:new Map};try{return zd(e,t,n,o,s,r,i,a,!1)}finally{const e=function(e,t,n){const{value:o,listIndexes:s}=e,r=new Map;s.forEach((e,n)=>{if(t[n]!==o[n]){const t=r.get(o[n]);t?t.push(e):r.set(o[n],[e])}});let i,a=0;const l=[];for(let e=0;e<s.length;e++){const n=t[e]===o[e]?s[e]:r.get(t[e])?.shift();if(!n&&(a++?(i??=new Set(o)).has(t[e]):o.includes(t[e])))return null;l.push(n)}return l.map((e,t)=>e??jt(n,t))}(g,f,c.listIndex);if(null===e)$d(f,g),zt(p,o),g.written.set(p,Jt),function(e){an.set(e,Jt)}(p),Wd(t,n,s,r,i,a);else{$d(f,null);const t=[p.index];ln(p),g.written.forEach((e,n)=>{ln(n),zt(n,g.value[n.index]),e===Jt&&t.push(n.index)}),g.written.delete(p),e.forEach((e,t)=>{e.index=t}),vn(f,e),Ri(g.listIndexes,e),function(e,t,n,o,s,r,i){const a=r.stateElement,l=ci(),c=so(a,e);vn(t.value,t.listIndexes),Yt(t.value),Sn(n,t.value),Tn(c)===n&&En(c,t.value);l.enqueueRenderOnlyAddress(c);for(const e of Mn(c,n))On(e,n)&&l.enqueueRenderOnlyAddress(e);const f=new Map;t.listIndexes.forEach((e,t)=>f.set(e,t));const h=ce(e.pathInfo.path+d+u);for(let e=0;e<o.length;e++){const n=o[e],i=f.get(n);if(i===e)continue;const c=_o(h,n),d=so(a,c);if(void 0===i){const n=ro(a,h,t.listIndexes[e]);Md(a,d,n),Wd(c,d,s,r,null,sd(a,c),"full");continue}Td(a,c,a.staticDependency,a.dynamicDependency,a.listPaths,s,"new",e=>{const t=so(a,e);Jr(t),l.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}for(const e of i){const n=o[e];if(f.has(n)&&t.written.get(n)!==Jt){const o=_o(h,n),i=so(a,o);Md(a,i,ro(a,h,t.listIndexes[e])),Wd(o,i,s,r,null,sd(a,o))}}}(c,g,f,e,s,r,t)}}}function qd(e,t,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(t.pathInfo.path);if(void 0!==i){const r=dd(e,t,o,s),a=function(e,t,n,o){const s=md(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=md(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,i,r,n);if(null!==a)return function(e,t,n,o,s,r){const i=t.pathInfo.path,a=t.listIndex;null===mn(o)&&na(a,null,o);const l=na(a,o,n.list),c=Vd(e,t,n.list,s,r,i),f=ce(i+d+u);for(const t of n.matched){const n=yd(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?qd(e,_o(ce(f.path+d+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return c}(e,t,a,r,o,s)}}return Vd(e,t,n,o,s,null)}function Vd(e,t,n,o,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let s=0;s<e.length;s++){const i=e[s](a,t,n,o,r);if(i!==Fc)return i}}const d=function(){const e=Is;return Is=0,e}(),f=d>1;if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const d=dd(e,t.parentAddress,o,r);if("object"==typeof d&&null!==d){const e=t.pathInfo.lastSegment,h=e===u?t.listIndex?.index:e;let p,g=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in d,t=void 0!==h?d[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}e===u&&(t=Bd(a,t,d,h,n));const m=Od(a,l,g,p,n,()=>d[h]),y=sd(a,t),w=so(a,t);null!==_t&&_t({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:g}),Ed(a,l,w,p,g);let b=!1;try{if(void 0===h&&ie(vl(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==u&&!(h in d)){const e=c.writeMissing;for(let s=0;s<e.length;s++){b=!0;const i=e[s](a,t,d,h,n,o,r);if(i!==Fc)return i;b=!1}}if(e!==u&&null!==t.listIndex){const o=d[h];o!==n&&(function(e,t,n,o){if(!Zt.has(e))return!1;let s=!1;for(const t in n)s||=t!==o&&n[t]===e;if(!s){let n=tn.get(t);void 0===n&&(n=new WeakSet,tn.set(t,n)),n.add(e)}const r=Zt.get(e),i=on.get(e);if(r[0]?.parentListIndex===t&&(!s||i?.[0]!==t||i[1]!==Jt))for(const n of un.get(e)??[])if(n!==t&&n.position===t.position&&dn(e,n)&&Object(Kt(n))[o]===e){r.forEach(e=>Lt(e,n)),nn.set(e,[t,Jt]);break}return s}(o,t.listIndex,d,e)&&Array.isArray(n)&&Qi(n,o),function(e,t){tn.get(t)?.delete(e);const n=Zt.get(e);if(void 0!==n){on.set(e,[t,Jt]);const o=nn.get(e);o?.[0]===t&&o[1]===Jt&&n.forEach(e=>Lt(e,t))}}(n,t.listIndex))}return Reflect.set(d,h,n)}finally{Wd(t,w,o,r,i,y),Ld(m,o,r),b?Jr(w):Dd(a,l,w,n,y),Cd(a,t.pathInfo,{value:n})}}}let h,p=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=dd(e,t,o,r);if(wd(e,t,o,r)&&Object.is(s,n))return!0;h=s,p=!0}const g=Od(a,l,p,h,n,()=>dd(e,t,o,r)),m=a.elementPaths.has(t.pathInfo.path),y=sd(a,t),w=so(a,t);null!==_t&&_t({type:"state:write",absoluteAddress:w,value:n,oldValue:h,hasOldValue:p}),Ed(a,l,w,h,p);try{return m?Fd(e,t,w,n,o,r,i,y,d):zd(e,t,w,n,o,r,i,y)}finally{Ld(g,o,r),m||Dd(a,l,w,n,y),Cd(a,t.pathInfo,{value:n})}}function Hd(e,t,n,o){return(t,s,...r)=>{Array.isArray(s)||ie(`$resolve("${t}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&ie(`$resolve("${t}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=ce(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&&ie(yl("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=_o(i,hd(e,n,o,i,s));if(0===r.length)return dd(e,a,n,o);td(o),qd(e,a,r[0],n,o)}}function Ud(e,t,n,o){const s=Hd(e,0,n,o);return(t,r)=>{const i=ce(t);if(void 0===r||Array.isArray(r)||ie(`$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&&ie(yl("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=nd(o,i.wildcardPaths[e]);if(t){r=ho(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&&ie(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=ud(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 Kd(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return nd(o,s.wildcardPaths.at(-1)??ie(`lastWildcardPath is null: ${t.pathInfo.path}`))??ie(`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]??ie(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=_o(i,s),l=fd(o,a,dd(e,a,n,o)),c=t.wildcardIndexes[r]??ie(`wildcardIndex is null: ${t.pathInfo.path}`);s=l[c]??ie(`ListIndex not found at index ${c} of ${i.path}`)}return s}case"partial":ie(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Gd(e,t,n,o){const s=o.stateElement;return t=>{const r=ed(t),i=Kd(e,r,n,o),a=_o(r.pathInfo,i),l=so(s,a),c=ci();c.enqueueAbsoluteAddress(l),function(e,t,n,o,s){const r=Mi(e,t),i=Wi(e,t);if(!r&&!i)return;const a=n(),l=[],c=jd(l);r&&Li(e,t,!1,void 0,a).forEach(c),i&&Bi(e,t,void 0,a,!1).forEach(c),Ld(l,o,s)}(s,r.pathInfo.path,()=>dd(e,a,n,o),n,o),Td(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=so(s,e);Jr(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}function Jd(e,t,n,o){return(t,s,r,i)=>{td(o);const a=ce(t);Array.isArray(s)||ie(bl(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&ie(yl("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&ie(bl(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&ie(bl(t,"requires an array as the value when { spread: true } is set."));const d=ud(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&ie(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 f=[];for(let t=0;t<d.length;t++){const s=hd(e,n,o,a,d[t]);f.push(_o(a,s))}const h=a.lastSegment===u;let p=0;for(let t=0;t<f.length;t++){const s=h?_o(a,hd(e,n,o,a,d[t])):f[t];let i;if(c){i=r(dd(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(qd(e,s,i,n,o),p++)}return p}}function Xd(e,t){if("all"===ed(t).wildcardType)return!0;const n=e.getterPaths;if(0===n.size)return!1;for(const e of ce(t).cumulativePaths)if(n.has(e))return!0;return!1}const Yd=/^\$\d+$/,Qd=`${Z}${d}`,Zd=`${ee}${d}`,eu=new WeakMap;function tu(e,t,n,o){const s=R[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&Yd.test(t)&&ie(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${M}1 to ${M}128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&ie(`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 r=e?.listIndex;null==r&&ie(`ListIndex not found: ${t.toString()}`);let i=s;const a=e.pathInfo,l=o.stateElement?.addressHooks;if(l){const t=l.indexShift;for(let n=0;n<t.length;n++)i+=t[n](o,e)}const c=fo(r,i,a.wildcardCount);return c?.index??ie(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,t,n,e);if(i!==Fc)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Ud(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>Jd(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>Gd(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Hd(e,0,n,o)(t,s,...r);case"$trackDependency":ye?.renamed(t,"$dependOn");case"$dependOn":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] ${String(t)}("${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&&ie(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??ie("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==e&&s.addDynamicDependency(e,n.path)}}(0,t,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Xd(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ci(o.stateElement,e),Object.is(n[e],t);let r;o.beginUntrack();try{r=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ei(o.stateElement,e,t,so(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Xd(o.stateElement,e);let i,a=r?n[e]:void 0;o.beginUntrack();try{r||(a=n[e]),i=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?Ci(o.stateElement,e):Ei(o.stateElement,e,i,so(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||ie(`$eqIndex("${e}") needs a list row scope.`);const r=fo(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&ie(`$eqIndex("${e}", ${t}): no list index at that level.`),Xd(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&(Ci(o.stateElement,e),o.stateElement.addIndexDependentGetterPath?.(s.pathInfo.path)),Object.is(n[e],r.index);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?mn(l):null;null!==t?function(e,t,n,o,s){pi=!0,Pi(e).lastValue.set(t,s),Ii(e,t);let r=wi.get(e);void 0===r&&wi.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=bi.get(o);if(void 0===l?(bi.set(o,l=[]),bn(o)):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);const n=o[0]?.parentListIndex??null;if(null!==n){let e=$i.get(n);void 0===e&&$i.set(n,e=new Set),e.add(a)}}a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){pi=!0;const r=Pi(e);Ii(e,t),Ti(r,t,s,o,Ni(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,so(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":ye?.renamed(t,"$untracked");case"$untracked":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case V:return zc(o.stateElement)}if(!t.startsWith(Qd)&&!t.startsWith(Zd))return}const r=ed(t),i=Kd(e,r,n,o),a=_o(r.pathInfo,i);return dd(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=eu.get(e);return void 0===t&&(t=new Map,eu.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Vn:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&ie("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 Hn:i=t=>dd(e,t,n,o);break;case Un:i=t=>wd(e,t,n,o);break;case Kn:i=()=>async function(e,t,n){const o=Reflect.get(e,j);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Gn:i=()=>function(e,t,n){const o=Reflect.get(e,L);"function"==typeof o&&o.call(n)}(e,0,n);break;case Jn:i=t=>function(e,t,n,o){const s=Reflect.get(e,W);let r;if("function"==typeof s){const e=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,s=t.path;if(-1===s.indexOf("#")&&(e.add(s),t.wildcardCount>0)){const e=ho(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}(e.size>0||0===t.length)&&(r=s.call(n,Array.from(e),i))}const i=o.stateElement?.addressHooks;if(i){const e=i.updated;for(let s=0;s<e.length;s++)e[s](o.stateElement,t,n)}return r}(e,t,n,o);break;case Xn:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,D);"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 nu{_stateElement;_addressStack=Array(h).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=Jl(e);null===n&&ie("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&ie("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=h&&(this._hasRepeatedAddress()&&ie(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),ie(`[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&&ie(`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 tu(e,t,n,this)}set(e,t,n,o){return td(this),function(e,t,n,o,s){if("string"==typeof t){const r=ed(t),i=Kd(e,r,o,s);return qd(e,_o(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)}deleteProperty(e,t){return td(this),Reflect.deleteProperty(e,t)}defineProperty(e,t,n){return td(this),Reflect.defineProperty(e,t,n)}}const ou=Promise.resolve(),su=new Map;let ru=[];function iu(e,t){su.set(e,t),ru=Array.from(su.values()).sort((e,t)=>e.order-t.order)}function au(e,t){return ie(Fl(e,t))}const lu="undefined"==typeof HTMLElement?class{}:HTMLElement;function cu(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}let du=null;const uu=new Set(["for","if","elseif","else"]);function fu(e,n,o){const s=new Map;for(const e of o){const t=ce(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=so(e,t);if(i.has(n))return;i.add(n);const o=Io(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(_o(n,t.listIndex))}};zn();try{if(e.createState("readonly",t=>{for(const o of n){const n=_o(ce(o),null);a(n);try{Td(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)uu.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=()=>{Rl(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Qr("state",s);void 0!==i&&i.catch(ii)}finally{Fn()}}const hu=[[G,"watch"],[J,"scan"],[K,"streams"],[X,"recursion"]];class pu extends lu{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Xl(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 Mc}();_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;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=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&&ie(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){Lc(e),function(e){for(let t=0;t<hu.length;t++){const[n,o]=hu[t];n in e&&!Xc(o)&&ie(Fl(o,`"${n}"`))}}(e);const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[q];if(void 0===n)return t;Array.isArray(n)||ie(`${q} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ie(`${q} entries must be non-empty strings.`),e===V&&ie(`${q} entry "${e}" conflicts with the reserved namespace name "${V}".`),t.has(e)&&ie(`${q} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[H];if(void 0===n)return t;Array.isArray(n)||ie(`${H} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ie(`${H} entries must be non-empty strings.`),t.has(e)&&ie(`${H} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[Q];if(void 0===t)return null;"object"==typeof t&&null!==t||ie(`${Q} 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&&ie(`${Q} entry path must be a non-empty string.`);const t=e.split(d);t.some(e=>0===e.length)&&ie(`${Q} entry "${e}" must not contain empty path segments.`),t[t.length-1]===u&&ie(`${Q} entry "${e}" must be the list path itself, not the element path (drop the trailing "${d}${u}").`),-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] ${Q} entry "${e}" uses "${Y}", which ${Q} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${d}${u}${d}children").`),"function"!=typeof o?("string"!=typeof o&&ie(`${Q} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&ie(`${Q} entry "${e}" key field name must be a non-empty string.`),(o.includes(d)||o.includes(u))&&ie(`${Q} entry "${e}" key field name "${o}" must be a flat property name ("${d}" / "${u}" are not allowed).`),o in Object.prototype&&ie(`${Q} 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);var i;n.set("eventTokenNames",s),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&du?.reset(this),this._hasUpdatedCallback=W in e,this._hasErrorCallback=D in e,i=this,Vo.delete(i),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[U];if(void 0!==o){"object"==typeof o&&null!==o||ie(`${U} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||ie(`${U} entry "${t}" is not declared in $eventTokens.${fe(t,n)}`),"function"!=typeof s&&ie(`${U} entry "${t}" must be a function.`),Ho(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const a=function(e){const t=new Set,n=new Set,o=cu(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 a.getterPaths)this._getterPaths.add(e);for(const e of a.setterPaths)this._setterPaths.add(e);!function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<Kc.length;o++)Kc[o].register?.(e,t,n)}(this,e,n),Yc(this,null),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 <${s.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?Vl('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);return t&&"application/json"===t.type?JSON.parse(t.textContent||"{}"):(console.warn(`[@wcstack/state] state="${e}": no <script type="application/json" id="${e}"> in the document (3.x does not look inside shadow roots), so the state starts empty.`),{})}(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 Ec(e,s.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.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){let t;try{const n=await fetch(e);if(n.ok)return await n.json();t=`HTTP ${n.status} ${n.statusText}`}catch(e){t=e}return console.error(`[@wcstack/state] Failed to load JSON file "${e}", so the state starts empty (4.0 rejects instead):`,t),{}}(e);if(e&&e.endsWith(".js"))return await Cc(e);ie(`Unsupported src file type: ${e}`)}}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&&(Zl(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),ie(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;this._initializeFailed=!0;const n=["state","src"].find(e=>this.hasAttribute(e));throw console.error(`[@wcstack/state] <${s.tagNames.state}${n?` ${n}="${this.getAttribute(n)}"`:""}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===Jl(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),Ul.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<ru.length;o++)ru[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{j in e&&await e[Kn]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{L in e&&e[Gn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<ru.length;t++)if(!0===ru[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Jl(this._rootNode)===this||Zl(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=function(e){for(let t=0;t<ru.length;t++){const n=ru[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{au("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(te))try{au("dcc",`a <${s.tagNames.state}> inside a [${te}] host`)}catch(e){this._failInitializeLoudly(e)}let n=!1;try{const e=function(e){for(let t=0;t<ru.length;t++){const n=ru[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&au("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let o=!1;try{o=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!o)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 Vl('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}Yc(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<ru.length;t++)if(!0===ru[t].disconnecting?.(e))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(e,t){for(let n=0;n<ru.length;n++)ru[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Zl(this.rootNode,null),e=this,Bc.delete(e),function(e){for(let t=0;t<Gc.length;t++)Gc[t].deactivate?.(e)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(e=>(ye?.volumeLoaded(e),Lc(e),e))}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}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,this.attachAddressHooks("watch",G)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&ie(`$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 fl(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&&ie("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(e,t){const n=function(e,t){const n=Vc.get(e);return void 0===n&&ie(Fl(e,`"${t}"`)),n}(e,t);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(e,t){for(let n=0;n<qc.length;n++){const o=qc[n],s=t[o];if(void 0===s)continue;const r=e[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(e){this.attachAddressHooks("scopes",e)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e,this.attachAddressHooks("dcc",z)}_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){if(!this._addDependency(this._dynamicDependency,e,t))return!1;const n=ce(e);for(let e=n.parentPathInfo;null!==e&&e.wildcardCount>0&&e.wildcardCount===n.wildcardCount;e=e.parentPathInfo)this._addDependency(this._dynamicDependency,e.path,t);return!0}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+"."+u)),!this._pathSet.has(e)){const t=ce(e);this._pathSet.add(e);const o=function(e,t){const n=ed(t);return"all"===n.wildcardType&&1===n.wildcardIndexes.length&&isNaN(+n.segments[0])&&!t.includes("#")&&Object.isExtensible(e)&&!(t in e)}(this.__state,e);if(du?.check(this,this.__state,e,n,o),o&&function(e,t){const{segments:n,cumulativePaths:o}=ce(t),s=n.length-1,r=(e,r,i)=>{let a,l=!1;for(let c=0;c<=s;c++){const d=n[c];if(l||=!(isNaN(+d)||Array.isArray(a)&&+d in a),r&&c===s)return l?a[d]=i:e[t]=i;a=l?a?.[d]:e[o[c]]}return a},i=function(){return r(this)};hl.set(i,ed(t).pathInfo.path),e.defineTreeAccessor(t,{get:i,set(e){r(this,!0,e)},configurable:!0})}(this,e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ce(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 nu(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&&ie(`<${s.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);!function(e){for(let t=0;t<ru.length;t++)ru[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&ie("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(cu(n)))e.startsWith("$")||e.includes(u)||"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){fu(this,e,this._pathRegistrations.keys())}}const gu=[],mu=[];function yu(){const e=[];let t=0;for(let n=0;n<mu.length;n++){const o=mu[n].deref();void 0!==o&&(e.push(o),mu[t++]=mu[n])}return mu.length=t,e}function wu(e=customElements){yu().includes(e)||mu.push(new WeakRef(e));for(let t=0;t<gu.length;t++)gu[t](e);e.get(s.tagNames.state)||e.define(s.tagNames.state,pu)}function bu(e){if("string"==typeof e?.locale)return 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}}function vu(e,t){const n=bu(e);var s;n&&((s=n).tagNames&&Object.assign(o.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(o.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(o.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(o.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(o.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(o.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(o.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(o.locale=s.locale),"boolean"==typeof s.debug&&(o.debug=s.debug),"boolean"==typeof s.enableMustache&&(o.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(o.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(o.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(o.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(o.sameValueGuard=s.sameValueGuard)),wu(t),function(){const e=globalThis;void 0===e[i]&&(e[i]=Nc)}()}let $u=null;function xu(e){return $u??ie(Fl("watch",`"$watch" in <wcs-state mount="${e}">`))}let Su=null;const Iu=Object.freeze([]);const Pu="3.5.1",ku=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Au(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}}function Nu(e){const t=[],n=new Set,o=new Set,r=e=>{const o=function(e){const t=`${me(e.inFilters)}\0${me(e.outFilters)}`;return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(o.has(e))return;o.add(e);const t=nc(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(Au(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(s.bindAttributeName);if(null===n||0===n.length)continue;try{const e=dt(t,ze(n));for(const o of e)r(Au(t,o,"attribute",n))}catch{}continue}const t=ku.exec(e.data.trim());if(null===t)continue;const n=t[1]||s.commentTextPrefix,o=t[2],a=nc(o);if(null===a){if(n===s.commentTextPrefix)try{r(Au(e,Ue(o),"comment",o))}catch{}}else r(Au(e,a.parseBindTextResult,"comment",o)),i(o)}return t}function _u(e){const t=function(e){const t=di.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:wi.get(e)}}(e);if(null===t)return[];const n=new Set([...t.byPath.keys(),...t.tracked]);if(void 0!==t.watchers)for(const e of t.watchers.keys())n.add(e);const o=[];for(const e of[...n].sort()){const n=t.byPath.get(e);let s=0;if(void 0!==n)for(const e of n.values())s+=e.size;o.push({path:e,tracked:t.tracked.has(e),rows:s,keys:n?.size??0,lists:t.watchers?.get(e)?.size??0,lastValue:t.lastValue.get(e)})}return o}const Tu="__WCSTACK_DEVTOOLS_HOOK__";function Eu(){const e=globalThis,t=e[Tu];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[Tu]=n,n}const Cu=e=>{null!==_t&&_t({type:"state:update-batch",addresses:e})};function Mu(e){const t=null!==_t;!function(e){_t=e}(e);const n=null!==e;n&&!t?ri(Cu,0):!n&&t&&function(e){const t=Zr.findIndex(t=>t.listener===e);-1!==t&&Zr.splice(t,1)}(Cu)}function Ou(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 Ru(e){return Jl(e)??ie("devtools: no state tree on this root")}let ju=null;function Lu(){if(t())return;if(null!==ju)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Pu,getStateElements(){const e=[];for(const t of Kl)e.push(Ou(t));return e},overlays(e){return t=Ru(e),null===Su?Iu:Su(t);var t},keyedSubscriptions:e=>_u(Ru(e)),keys(e){const t=Ru(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 Ru(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){Ru(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>Nu(e),_setSink:Mu};ju=e,Eu().register(e)}const Wu={name:"devtools",install(){Lu()}},Du=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Bu=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const zu=new WeakMap;const Fu=new WeakMap,qu=new WeakSet,Vu=new WeakMap;function Hu(e,t,n,o){console.warn(`[@wcstack/state] [${gl[n]}] ${ml[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${fe(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${he}`),null!==_t&&_t({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Uu={check:function(e,t,n,o,s){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const r=e.addressHooks;if(r){const t=r.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const i=ce(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=zu.get(e);return void 0===n&&(n=new Set,zu.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,o){if(void 0!==fl(e,t))return Bu;const s=ce(t).segments;let r=e,i="";for(let t=0;t<s.length;t++){const a=o&&Array.isArray(r)&&+s[t]>=0?u:s[t],l=i;i=0===t?a:i+d+a;const c=t>0&&fl(e,i),f=c&&hl.get(c.get);if(c&&(!f||fl(e,f)))return t<s.length-1?Du:Bu;if(Object(r)!==r)return Du;if(a===u){if(!Array.isArray(r)||0===r.length)return Du;r=r[0];continue}const h=fl(r,a);if(void 0===h)return{existence:"missing",missingSegment:a,candidates:pl(r,l,n,e)};if("function"==typeof h.get)return t===s.length-1?Bu:Du;r=h.value}return Bu}(t,n,e.getterPaths,s);"missing"===a.existence&&(function(e,t){return!0===Vu.get(e)?.has(t)}(e,n)||("binding"!==o?Hu(e,n,o,a):function(e,t,n){let o=Fu.get(e);void 0===o&&(o=new Map,Fu.set(e,o));if(o.set(t,n),qu.has(e))return;qu.add(e),setTimeout(()=>function(e){qu.delete(e);const t=Fu.get(e);if(void 0===t)return;Fu.delete(e);for(const[n,o]of t)Hu(e,n,"binding",o)}(e),0)}(e,n,a)))},reset:function(e){zu.delete(e),Fu.delete(e)},markExported:function(e,t){let n=Vu.get(e);void 0===n&&(n=new Set,Vu.set(e,n)),n.add(t),Fu.get(e)?.delete(t)}};let Ku=!1;function Gu(){Ku||(Ku=!0,function(e){du=e}(Uu))}const Ju={name:"diagnostics",install(){Gu()}};function Xu(e){ie(`filter ${e} requires at least one option`)}function Yu(e){ie(`filter ${e} requires a number as option`)}function Qu(e){ie(`filter ${e} requires a number value`)}function Zu(e){ie(`filter ${e} requires a date value`)}const ef={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function tf(e){return!(!e||isNaN(Number(e)))}function nf(e,t){return tf(e)||Yu(t),Number(e)}function of(e,t,n){return nf(e?.[t]??Xu(n),n)}const sf=e=>t=>{const n=e(t);return e=>null==e?e:n(e)},rf={eq:(e,t)=>{const n=e?.[0]??Xu("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e===o:(tf(n)||Yu("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Xu("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e!==o:(tf(n)||Yu("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>!e,lt:e=>{const t=of(e,0,"lt");return e=>("number"!=typeof e&&Qu("lt"),e<t)},le:e=>{const t=of(e,0,"le");return e=>("number"!=typeof e&&Qu("le"),e<=t)},gt:e=>{const t=of(e,0,"gt");return e=>("number"!=typeof e&&Qu("gt"),e>t)},ge:e=>{const t=of(e,0,"ge");return e=>("number"!=typeof e&&Qu("ge"),e>=t)},add:e=>{const t=of(e,0,"add");return e=>("number"!=typeof e&&Qu("add"),e+t)},sub:e=>{const t=of(e,0,"sub");return e=>("number"!=typeof e&&Qu("sub"),e-t)},mul:e=>{const t=of(e,0,"mul");return e=>("number"!=typeof e&&Qu("mul"),e*t)},div:e=>{const t=of(e,0,"div");return e=>("number"!=typeof e&&Qu("div"),e/t)},mod:e=>{const t=of(e,0,"mod");return e=>("number"!=typeof e&&Qu("mod"),e%t)},abs:e=>e=>("number"!=typeof e&&Qu("abs"),Math.abs(e)),clamp:e=>{const t=of(e,0,"clamp"),n=of(e,1,"clamp");return e=>("number"!=typeof e&&Qu("clamp"),Math.min(Math.max(e,t),n))},toFixed:e=>{const t=nf(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&Qu("toFixed"),e.toFixed(t))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Qu("locale"),e.toLocaleString(t??s.locale))},upper:sf(e=>e=>String(e).toUpperCase()),lower:sf(e=>e=>String(e).toLowerCase()),capitalize:sf(e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),trim:sf(e=>e=>String(e).trim()),slice:sf(e=>{const t=[of(e,0,"slice")],n=e?.[1];return void 0!==n&&t.push(nf(n,"slice")),e=>String(e).slice(...t)}),substr:sf(e=>{ye?.removed("substr");const t=of(e,0,"substr"),n=of(e,1,"substr");return e=>String(e).substr(t,n)}),padStart:sf(e=>{const t=of(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),padEnd:sf(e=>{const t=of(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),repeat:sf(e=>{const t=of(e,0,"repeat");return e=>String(e).repeat(t)}),reverse:sf(e=>e=>String(e).split("").reverse().join("")),truncate:sf(e=>{const t=of(e,0,"truncate"),n=e?.[1]??"…";return e=>{const o=String(e);return o.length<=t?o:o.slice(0,t)+n}}),join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||ie(`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=Math.pow(10,nf(e?.[0]??"0","round"));return e=>("number"!=typeof e&&Qu("round"),Math.round(e*t)/t)},floor:e=>{const t=Math.pow(10,nf(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&Qu("floor"),Math.floor(e*t)/t)},ceil:e=>{const t=Math.pow(10,nf(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&Qu("ceil"),Math.ceil(e*t)/t)},percent:e=>{const t=nf(e?.[0]??"0","percent");return e=>("number"!=typeof e&&Qu("percent"),`${(100*e).toFixed(t)}%`)},unit:sf(e=>{const t=e?.[0]??Xu("unit");return e=>String(e)+t}),date:e=>{const t=e?.[0];return e=>(e instanceof Date||Zu("date"),e.toLocaleDateString(t??s.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Zu("time"),e.toLocaleTimeString(t??s.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Zu("datetime"),e.toLocaleString(t??s.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Zu("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||Zu("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=>!e,truthy:e=>e=>!!e,defaults:(e,t)=>{const n=e?.[0]??Xu("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Xu("coalesce"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e??o},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),nullIfEmpty:e=>e=>""===e?null:e},af={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[2,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,1],time:[0,1],datetime:[0,1],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},lf=rf,cf=rf;let df=!1;const uf={name:"formats",install(){df||(df=!0,Ie("input",cf,af,ef),Ie("output",lf,af,ef))}};function ff(e){return-1!==e.indexOf(Y)}function hf(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+d;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(ff(o))return null;const s=o.slice(1).split(d);return s[0]===u||s.some(e=>0===e.length)?null:o}function pf(e){return 0===e.length?e:d+yf(e.slice(1))}function gf(e,t,n){const o=d+e.repeat,s=t.length<=n.length?t:n,r=t.length<=n.length?n:t;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let e=0;e<i.length;e+=o.length)if(!i.startsWith(o,e))return!1;return!0}function mf(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(d,o-1))if(gf(e,t,n.slice(0,o)))return!0;return!1}function yf(e){const t=e.split(d);for(let e=0;e<t.length;e++)t[e]===u||Number.isNaN(Number(t[e]))||(t[e]=u);return t.join(d)}function wf(e,t){const n=e.repeat.split(d),o=d+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===d+e.repeatList+d+"length")return!0;for(let e=1;e<n.length;e++)if(s===d+n.slice(0,e).join(d))return!0;return!1}function bf(e,t,n){n<0&&ie(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=d+e.repeat;const s=o+t;let r=0;for(const e of s.split(d))e===u&&r++;return r>f&&ie(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function vf(e,t){return bf(e,"",t)}function $f(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 s=d+e.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function xf(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=d+n.repeat;let s=0,r=n.anchor.length;for(;t.startsWith(o,r);)r+=o.length,s++;return r!==t.length&&46!==t.charCodeAt(r)?null:s}(t,n.pathInfo.path)}function Sf(e,t,n){const o=e.recursionRegistry,s=hf(o.spec,n);null===s&&ie(wl(n,o.spec.recursiveAnchor));const r=xf(t,o);return null===r&&ie(`[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 If(e,t,n,o,s){const r=o.spec,i=[],a=new Map,l=[],c=r.repeatList,u=r.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void i.push(_o(e,n));const s=g(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function g(o,s,i){const l=_o(o,s),d=so(n.stateElement,l),u=dd(e,l,t,n),h=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&ie(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${r.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)&&ie(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${c}" array.`),o})(o.path,u,i),p=na(s,Dn(d),u);return a.set(d,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=l[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:ce(n),childListPathInfo:ce(r+d+c)};return l[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(_o(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,ce(u),null);for(const[e,t]of a)Bn(e,t);return i}function Pf(e,t,n,o,s,r,i){td(n);const a=n.stateElement.recursionRegistry,l=hf(a.spec,o);null===l&&ie(wl(o,a.spec.recursiveAnchor));const c=pf(l);Array.isArray(s)||ie(bl(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&ie(`[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&&ie(bl(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&ie(bl(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){wf(e,n)&&ie(`[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&&ie(`[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=If(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(qd(e,u[o],r,t,n),f++);return f}const kf={write(e,t){if(!0!==e.hasRecursion)return Fc;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&ie(`[wcs/recursion-readonly] "${t.pathInfo.path}" writes into the recursive getter "${n}" (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.`),Fc},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return Fc;if("$getAll"===t)return(t,s)=>{if(ff(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=hf(r.spec,o);null===i&&ie(wl(o,r.spec.recursiveAnchor)),Array.isArray(s)||ie(`[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&&ie(`[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=If(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(dd(e,a[o],t,n));return l}(o,n,e,t,s);t=Sf(e.stateElement,e,t)}return Ud(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>ff(t)?Pf(o,n,e,t,s,r,i):Jd(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&ff(t)){const s=ed(Sf(e.stateElement,e,t)),r=Kd(o,s,n,e);return dd(o,_o(s.pathInfo,r),n,e)}return Fc}};let Af=!1;function Nf(e,t){"string"==typeof t&&0!==t.length||ie(`[wcs/recursion-declaration-invalid] ${X} ${e} must be a non-empty string.`);const n=t.split(d);n.some(e=>0===e.length)&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain empty path segments.`),n.length<2&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must name a list element: a property path ending with "${d}${u}" (for example "nodes${d}${u}").`),n[n.length-1]!==u&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must end with "${d}${u}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===u&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must have exactly one "${u}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===Y&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain "${Y}" — the declaration is what gives "${Y}" its meaning.`),isNaN(Number(n[o]))||ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const _f=new WeakSet;function Tf(e){return"function"==typeof e.get&&_f.has(e.get)}const Ef="[wcs/recursion-declaration-invalid]";class Cf{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=cu(t);for(const[t,o]of Object.entries(n)){if(!ff(t))continue;"function"==typeof o.set&&ie(`${Ef} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&ie(`${Ef} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=hf(e,t);null===n&&ie(wl(t,e.recursiveAnchor)),0===n.length&&ie(`${Ef} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${d}total"), not the node.`),wf(e,pf(n))&&ie(`${Ef} "${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}${d}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(ff(t)||Tf(n))continue;const e=this._matchExpansion(t);null!==e&&ie(`${Ef} "${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++)gf(this.spec,e[t].suffix,e[n].suffix)&&ie(`${Ef} "${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(mf(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=yf(e),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let e=n.lastIndexOf(d);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(d,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==$f(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=$f(this.spec,e.suffix,t);null!==n&&(null!==o&&ie(`"${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||Tf(s)||ie(`"${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,_f.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(vf(e,o)+d+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 function(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Tf(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))}}}}(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=bf(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 Mf="recursionSpec",Of="recursionRegistry",Rf={order:5,validateEarly(e,t,n){const o=function(e){const t=e[X];if(void 0===t)return null;"object"==typeof t&&null!==t||ie(`[wcs/recursion-declaration-invalid] ${X} 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&&ie(`[wcs/recursion-declaration-invalid] ${X} must declare exactly one anchor; it is empty.`),n.length>1&&ie(`[wcs/recursion-declaration-invalid] ${X} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Nf("anchor",o),"string"!=typeof s&&ie(`[wcs/recursion-declaration-invalid] ${X} entry "${o}" must map to the repeating sub-path as a string (for example "children${d}${u}").`),Nf("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(d)),i=s.slice(0,s.lastIndexOf(d)),a=r+d+Y;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(Mf,o),n.set(Of,null===o?null:new Cf(o,t))},preCommit(e,t,n){const o=e.recursionRegistry;if(null!==o)for(const t of o.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(Of)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",X)},apply(e,t,n){const o=n.get(Mf)??null;null!==o&&e.addListPath(o.anchorList)}};let jf=!1;function Lf(){jf||(jf=!0,Af||(Af=!0,Hc("recursion",kf)),Jc("recursion",Rf))}const Wf={name:"recursion",install(){Lf()}};const Df={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1&&-1===t.path.indexOf("#")?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}))}};let Bf=!1;function zf(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 Ff(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 qf(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 Vf(e){return e.startsWith("$")}function Hf(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 Uf(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||ie(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||ie(`${t} entries must be non-empty strings.`),e.startsWith("$")&&ie(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&ie(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Kf(e){Lc(e);const t=Uf(e,z)??[],n=Uf(e,F)??[],o=cu(e),s=function(e){const t=e[K];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}ie(`${z} entry "${e}" is not declared on the state.${fe(e,Hf(o,"value"))}`)}"function"==typeof t.value&&ie(`${z} entry "${e}" is a method. Declare it in ${F} instead.`)}for(const e of n){const t=o[e];void 0===t&&ie(`${F} entry "${e}" is not declared on the state.${fe(e,Hf(o,"method"))}`),"function"!=typeof t.value&&ie(`${F} entry "${e}" is not a method. Declare it in ${z} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function Gf(e,t,n){const o=e.tagName.toLowerCase();o.includes("-")||ie(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const r=tt(e);null!==r&&"function"==typeof r.define||ie(`DCC: CustomElementRegistry is unavailable for "${o}".`),r.get(o)&&ie(`DCC: "${o}" 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}=Kf(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}}(o,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(o,c):{},p=s.tagNames.state,g=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(te))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=tt(this._shadow);return null!==e&&nt(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(Bf||(Bf=!0,Hc("dcc",Df)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${z} but its template has no <${s.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=cu(n);for(const[e,t]of Object.entries(m)){if(Vf(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=qf(e,o)}else n.get=zf(e),n.set=Ff(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:zf(e),set:Ff(e)});r.define(o,g)}async function Jf(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&ie(`"bind-component" cannot be used inside a [${te}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await Cc(t);ie(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await Ec(n,t.tagName.toLowerCase());ie(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}(o,t);Gf(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const Xf={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(te)?Jf(e,t.host,t):null}};let Yf=!1;function Qf(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 Zf(e,t){for(const n of e)if(Qf(t,n.innerSegments))return n;return null}function eh(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+d+n.join(d)}const th=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function nh(e,t,n){const o=th.get(e);return void 0===o?null:(...e)=>{const s=e.slice();for(let e=0;e<o.length;e++){const n=o[e];"string"==typeof s[n]&&(s[n]=t(s[n]))}return n(s)}}const oh=new WeakMap;function sh(e,t,n){let o=oh.get(e);void 0===o&&(o=new Map,oh.set(e,o));const s=o.get(t);null!=s&&ie(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function rh(e,t){if(null===e)return!1;const n=oh.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+d)||e.startsWith(t+d))return!0;return!1}const ih=new WeakMap;const ah=[];function lh(e,t,n,o){if(t.length>0){const s=n.split(d),r=Zf(t,s);if(null!==r)return o&&r.readonly&&ie(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${N}.${r.innerSegments.join(d)}#${b}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${b} from the injection.`),eh(r,s)}return e+d+n}function ch(e,t,n){let o=-1,s=null;for(const e of t){const t=e.outerPathInfo.path;t.length<=o||(n===t?(o=t.length,s=e.innerSegments.join(d)):n.startsWith(t+d)&&(o=t.length,s=e.innerSegments.join(d)+n.slice(t.length)))}if(e.length>o){if(n===e)return"";if(n.startsWith(e+d))return n.slice(e.length+1)}return s}function dh(e,t,n=ah){return new Proxy({},{get(o,s){if("string"==typeof s&&"then"!==s){if("$"===s[0]){if("$postUpdate"===s||"$getAll"===s){const o=s;return(s,...r)=>t[o](lh(e,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>t.$setAll(lh(e,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>t.$resolve(lh(e,n,o,s.length>1),...s);const o=nh(s,t=>lh(e,n,t,!1),e=>t[s](...e));return null!==o?o:t[s]}return t[lh(e,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(t[s]=r,!0):(t[lh(e,n,s,!0)]=r,!0)),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const uh=new WeakMap,fh=[];const hh=new WeakMap,ph=new WeakSet;function gh(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 mh=null;let yh=0;const wh=["$watch",K,"$scan","$listKeys",W,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],bh=new Set;function vh(e,t,n){const o=e.stateObject[t];if("function"==typeof o)try{const s=o.call(n());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 $h(e,t,n,o,s,r=new Set){0===n.length&&ie(`Cannot build a mount record without host bindings for "${t}".`),Lc(s);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(d);a.has(n)&&ie("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(b)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const c=++yh,u=`#m${c}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=cu(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}}(s),p=new Set;for(const e of i)1===e.innerSegments.length&&p.add(e.innerSegments[0]);const g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:c,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?u:l.outerPathInfo.path+d+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(e=>e.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function xh(e){const t=e.indexOf(d);return-1===t?e:e.slice(0,t)}function Sh(e,t){const n=Zf(e.entries,t);return null===n?null:eh(n,t)}function Ih(e,t){return e.markerBasePath+d+t}function Ph(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+d+n;s.set(n,{accessorName:o,indexShift:ce(r).wildcardCount-ce(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function kh(e,t){return!e.injectedKeys.has(t)&&(!e.getterKeys.has(t)&&"function"==typeof e.stateObject[t]||!e.mappedKeys.has(t)&&(Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t)))}function Ah(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(d)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${xh(t)}: path") or declare the key on the component state.`}const Nh=/^\$(\d+)$/;function _h(e,t){if(!e.hasReadonlyEntries)return null;const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=xh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||kh(e,o))return null;const s=function(e,t){return Zf(e.entries,t)}(e,t.split(d));return null!==s&&s.readonly?s:null}function Th(e,t){const n=_h(e,t);if(null!==n){const o=0===n.innerSegments.length?"":d+n.innerSegments.join(d);ie(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${b}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${b} from the mount.`)}return Eh(e,t)}function Eh(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(d);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===u){o=e;break}if(-1===o)return Ph(e,e.markerBasePath,t,t),Ih(e,t);if(kh(e,n[0]))return Ph(e,e.markerBasePath,t,t),Ih(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Sh(e,s);null===i&&ie(Ah(e,t)),0===r.length&&ie(`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 a=i+d+e.marker;return Ph(e,a,r.join(d),t),a+d+r.join(d)}(e,t);const o=xh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return Ih(e,t);if(kh(e,o))return Ih(e,t);const s=Sh(e,t.split(d));if(null!==s)return s;ie(Ah(e,t))}const Ch=new Set(["prop","radio","checkbox"]);function Mh(e,t,n){let o;const s=Nh.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ce(Eh(e,t)).wildcardCount-ce(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Eh(e,t.statePathName),"for"===t.bindingType){const n=ce(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+d+u,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&Ch.has(t.bindingType??"")&&!r.includes(b)&&null!==_h(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ce(o),...i?{propModifiers:[...r,b]}:{}}:t}function Oh(e,t,n,o,s){if(void 0===o)return;const r=ce(n).wildcardCount-ce(t).wildcardCount;return 0===r?o:(s.length<r&&ie(`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])}function Rh(e,t,n){if(-1!==e.indexOf(u))return t;const o=t.split(d);let s=0;for(let e=0;e<o.length&&s<n.length;e++)o[e]===u&&(o[e]=String(n[s++]));return o.join(d)}const jh=new WeakMap,Lh=new WeakMap;const Wh=new WeakMap;const Dh=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)}),Bh=new WeakMap;function zh(e){return Bh.get(e)??null}let Fh=!1;function qh(){Fh||(Fh=!0,kt=e=>jh.has(e)?e.host:null)}function Vh(e){return jh.get(e)??null}function Hh(e){return Uh(e).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join(d),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]}))}function Uh(e){const t=Wh.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 Kh(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Wh.get(e);if(void 0===o)return null;const s=t.indexOf(d,n),r=-1===s?t.slice(n):t.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const Gh=new WeakMap,Jh=new Set;function Xh(e,t,n,o){let s=Gh.get(e);if(void 0===s){if(!o)return null;s=new Map,Gh.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 Yh(e,t){if(!e.component.isConnected)return!1;const n=At(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 Qh(e,t,n,o){const s=Xh(e,t,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&Yh(n,t)?n:null}(r,o);if(null!==e)return{record:e,entry:r.entry}}let i=null,a=null;for(const e of s.holders){const r=e.ref.deref();void 0!==r?Yh(r,o)&&(null!==a&&ie(`[wcs/mount-export-ambiguous] "${t}${d}${n}" is exported by two mounted components on the same instance: <${a.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=e,a=r):s.holders.delete(e)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function Zh(e){const t=e.parentStateElement,n=At(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Vn](n,()=>{e.$postUpdate(o.exportedPath)})})}const ep=new WeakMap,tp=new WeakMap,np=new WeakMap,op=new WeakMap;function sp(e,t){tp.set(e,t);const n=[];for(let e=t?.listIndex.parentListIndex??null;null!==e;e=e.parentListIndex)n.push(e);op.set(e,n)}function rp(e){return At(e.component)??tp.get(e)??null}function ip(e){return rp(e)?.listIndex??null}function ap(e){ie(`The host row of <${e.component.tagName.toLowerCase()}> was removed.`)}function lp(e){for(;null!==e;e=e.parentListIndex)if(en(e))return!0;return!1}function cp(e,t){return!e.component.isConnected&&(lp(t)||!0===op.get(e)?.some(e=>en(e)))}class dp{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(e,t,n,o,s,r,i,a=!1){this.record=e,this.markerParentPath=t,this.listIndex=n,this.hostRow=o,this.isBase=s,this.receiver=r,this.handler=i,this.authorFacing=a}authorThis(e,t){return this.authorFacing?t:new Proxy(e,new dp(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return _o(ce(this.markerParentPath+d+e),this.listIndex)}hostIndexes(){const e=this.listIndex??ip(this.record),t=this.hostRow??e;return(null===this.listIndex?t!==e||cp(this.record,t):lp(t))&&ap(this.record),t?.indexes??[]}resolveTreePath(e,t){return-1===t.indexOf(u)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==ed(t).wildcardType&&!cp(this.record,this.listIndex)?t:Rh(e,t,this.hostIndexes())}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(this.resolveTreePath(e,Eh(this.record,e)))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.hostIndexes(),o=this.receiver,s=this.handler,r=this.listIndex;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Th(e,t):Eh(e,t),a=Oh(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const i=t;return(t,a,...l)=>{const c="$setAll"===i?Th(e,t):Eh(e,t),d=Oh(0,t,c,void 0===a&&"$getAll"===i&&null===r&&null===nd(s,ce(c).wildcardPaths[0])?[]:a,n);return o[i](c,d,...l)}}const e=this.record,n=this.receiver,o=nh(t,t=>this.resolveTreePath(t,Eh(e,t)),e=>n[t](...e));return null!==o?o: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 od(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(this.authorThis(e,n))}return this.receiver[this.resolveTreePath(t,Eh(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)||ie(`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,this.authorThis(e,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(e,t)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress(_o(ce(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+d+t]=n}finally{this.handler.popAddress()}return!0}return e[t]=n,!0}return this.receiver[this.resolveTreePath(t,Th(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 Eh(this.record,t),!0}catch{return!1}}}function up(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=ep.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},ep.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 dp(e,s,t.listIndex,t.listIndex??ip(e),r,n,o))}function fp(e){if(null===ip(e))return e.component[e.stateProp];let t=np.get(e);if(void 0===t){const n={row:null};np.set(e,t=[hp(e,n),n])}return t[0]}function hp(e,t){const n=()=>{const n=rp(e);return void 0!==t&&np.get(e)?.[0]!==i&&n.listIndex!==t.row&&ap(e),n},o=()=>{const t=n();return cp(e,t?.listIndex??null)&&ap(e),t?.listIndex.indexes??[]},s=(t,n)=>-1===n.indexOf(u)?n:"partial"===ed(n).wildcardType?Rh(t,n,o()):-1===n.indexOf("#")&&cp(e,ip(e))?ap(e):n,r=(t,o)=>{let s;const r=n();return e.parentStateElement.createState(t,e=>{s=e[Vn](r,()=>o(e))}),s},i=new Proxy({},{get(t,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(e,t,n,o,s){return"$postUpdate"===t?t=>n("readonly",n=>n.$postUpdate(s(t,Eh(e,t)))):(s,r,...i)=>{const a="$setAll"===t||"$resolve"===t&&i.length>0,l=a?Th(e,s):Eh(e,s),c=Oh(0,s,l,"$resolve"===t?r??[]:r,o());return n(a?"writable":"readonly",e=>e[t](l,c,...i))}}(e,n,r,o,s);const i=nh(n,t=>s(t,Eh(e,t)),e=>r("readonly",t=>t[n](...e)));if(null!==i)return i;const a=t=>t["$"===n[0]?n:s(n,Eh(e,n))],l=r("readonly",a);return"$"===n[0]||e.getterKeys.has(n)||"function"!=typeof e.stateObject[n]?l:function(...e){return r("writable",t=>a(t).apply(this,e))}},set:(t,n,o)=>("string"==typeof n&&r("writable",t=>{t["$"===n[0]?n:s(n,Th(e,n))]=o}),!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 Eh(e,n),!0}catch{return!1}}});return i}function pp(e,t){const n=Vh(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&ie(`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&&Tr(t).dispose(),function(e,t){qh(),jh.set(e,t),Bh.set(t,e);let n=Wh.get(t.parentStateElement);void 0===n&&(n=new Map,Wh.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Lh.get(t.component);void 0===o&&(o=new Map,Lh.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Dh.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=Hl.get(e);if(void 0!==n){if(n===t)return;ie("A state tree is already registered on this root.")}Hl.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Mh(e,t,n);se(t);const o=At(e.component);sp(e,o);$c(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),Ll(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=Eh(e,n)}catch{continue}const o=t.indexOf(d+e.marker);if(-1===o)continue;const s=t.slice(0,o+1+e.marker.length),r=t.slice(s.length+1),i=t.slice(0,o)+d+r,a=ce(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Xh(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),du?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=At(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(Jh.has(s))continue;const r=ce(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Vn](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Jh.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),Zh(e),o=t,s=Promise.resolve(),Ul.set(o,s),s.then(()=>Ql(o),()=>{})}function gp(e,t){Rl(mp(e,t).rebindAddresses()),Zh(e)}function mp(e,t){const n=Tr(t),o=At(e.component);return sp(e,o),n.forEachActiveBindingNode(e=>Nt(e,o)),n}function yp(e){for(let t=e.parentNode;null!==t;t=t.parentNode){const e=Vh(t);if(null!==e)return yp(e.component),void mp(e,t)}}function wp(e,t){if(function(e){const t=Wh.get(e);return void 0!==t&&t.size>0}(t))for(const n of Uh(t)){if(!bp(n.component,e))continue;const t=zh(n);null!==t&&gp(n,t)}}function bp(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 vp={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Kh(e,t.pathInfo.path);if(null!==s)return up(s,t,n,o)}return Fc},readMissing(e,t,n,o,s){if(null===n){if(rh(e.rootNode??null,t.pathInfo.path))return;return Fc}if(!0===e.hasMounts){const n=Qh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=up(e,_o(ce(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return Fc},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=ih.get(e);if(void 0===n||0===n.size)return null;const o=t+d;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&ie(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return Fc},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Qh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=up(e,_o(ce(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return Fc},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Kh(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(d,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const s=-1===o?t:t.slice(0,o),r=-1===o?"":t.slice(o+1),i=e.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:e.delta}(e,o)}return 0},handlerScope(e,t,n,o,s){if(!0!==e.hasMounts)return s;const r=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=jh.get(n);if(void 0!==e)return e;n=n.parentNode}return jh.get(t)??null}(t,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(e,t,n){const o=function(e){return uh.get(e)??fh}(e);for(const s of o){const o=new Set,r={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(-1!==t.indexOf("#"))continue;const i=ch(s.mountPath,s.injections,t);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const e=ho(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(dh(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>rh(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){wp(t,e)}};let $p=!1;function xp(){$p||($p=!0,Hc("scopes",vp),Su=Hh)}const Sp=new WeakMap;function Ip(e){let t=Sp.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Sp.set(e,t)),t}function Pp(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=oh.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function kp(e,t,n){if(t.slotRootNode===n)return!0;const o=t.mountPath;try{sh(n,o,e)}catch{return console.error(`[@wcstack/state] <${s.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return Jl(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Ap(e,t){const n=e,o=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&ie('"mount" requires a non-empty tree path.');const t=ce(e);for(const n of t.segments)0===n.length&&ie(`"mount" path "${e}" has an empty segment.`),n===u&&ie(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&ie(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],o=new Set;let r;try{r=ze(e)}catch(e){ie(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> has an invalid ${s.bindAttributeName}: ${e instanceof Error?e.message:String(e)}`)}for(const e of r){if(e.propSegments[0]!==N)continue;const r=e.propSegments.slice(1),i=e.statePathInfo,a=n=>ie(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> "${e.propName}: ${e.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==u&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${N}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(e.inFilters.length>0||e.outFilters.length>0)&&a("an injection takes no filters."),e.propModifiers.some(e=>e!==b)&&a(`an injection accepts only #${b}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:e.propModifiers.includes(b)})}return n.sort((e,t)=>t.innerSegments.length-e.innerSegments.length),n}(n.getAttribute(s.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&ie('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${s.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),sh(o,r,e),Jl(o)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=o}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===Jl(o)&&function(e,t){const n=()=>{if(null!==Jl(e))return;const n=e.querySelectorAll(s.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${s.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${s.tagNames.state}> to this root node (an empty <${s.tagNames.state}></${s.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=e.ownerDocument??e;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&Pp(e,t),e.settleInitialization()};let l;try{await Promise.resolve(),l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const c=e.connectedRootNode??null;null!==c&&kp(e,t,c)?function(e,t,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};if(null!==t)return void ng(t,a);sg(),function(e,t){if(ph.has(e))return void gh(t);let n=hh.get(e);void 0===n&&(n=[],hh.set(e,n)),n.push(t)}(e,a)}(c,Jl(c),r,l,a,()=>kp(e,t,c),i):a(null)}const Np={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=Ip(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{sh(n,t.mountPath,e),Jl(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,ou}return Ap(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Ip(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&Jl(n)===t.graftInfo.rootStateElement&&Zp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Sp.get(e)?.initializing)return;const t=e.getAttribute("mount");ie(`Cannot replace the state of <${s.tagNames.state} mount="${t}"> 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 "${t}" on the root state instead.`)},initializeFailed(e,t){!function(e){ph.add(e);const t=hh.get(e);if(void 0!==t){hh.delete(e);for(const e of t)gh(e)}}(t)},initializeFailureCleared(e,t){!function(e){ph.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Ip(e);return null!==t.graftInfo&&Zp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,Pp(e,t)),e.clearConnectedRootNode(),!0}};let _p=!1;const Tp=new WeakMap;function Ep(e,t){let n=Tp.get(e);n||(n=new Set,Tp.set(e,n)),n.add(t)}const Cp=new WeakMap;const Mp=new WeakMap,Op=new WeakMap;const Rp=new WeakMap;const jp={isComplete:function(e,t){return!0===Tp.get(e)?.has(t)},isDeclared:function(e,t){return!0===Cp.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=Mp.get(e);o||(o=new Map,Mp.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=Op.get(e);o||(o=new Map,Op.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)},rememberOverwrittenValue:function(e,t,n,o){let s=Rp.get(e);s||(s=new Map,Rp.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function Lp(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 Wp=new WeakMap;class Dp{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=Wp.get(e);return n?n.get(t)??null:null}(e,t)??ie("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 Bp=e=>()=>e;function zp(e,t,n,o){!function(e,t,n){let o=Wp.get(e);o||(o=new Map,Wp.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(Lp(o));const s=function(e,t){const n=new Dp(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Bp(s),enumerable:!0,configurable:!0}),Ep(t,n),Fp(t,n)}function Fp(e,t){if(B in e){const n=e[B];"function"==typeof n?n.call(e,t).catch(e=>{ie(`Error in ${B}: ${e instanceof Error?e.message:String(e)}`)}):ie(`${B} is not a function.`)}}const qp=new Set;function Vp(e,t){qp.has(e)||(qp.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function Hp(e){!function(e){const t=e.component.tagName.toLowerCase(),n=e.stateProp;let o=null;for(const s of e.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=cu(e.stateObject);const i=o[r];let a;if(e.getterKeys.has(r)||e.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)a="an accessor";else if("function"==typeof i?.value)a="a method";else{if(e.mappedKeys.has(r)||e.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(e.stateObject,r))continue;a="an own data key"}const l=s.innerSegments.join(d);Vp(`${t}|${n}|${l}|entry`,`<${t}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${l}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(e);const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=Up(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;Vp(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}function Up(e){const t=e.rootEntry,n=At(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Vn](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Kp=new WeakMap;function Gp(e,t){e.landInitialization(),ie(t)}async function Jp(e,t){const n=e;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?Ze(a):null;null!==a&&null!==l||ie(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(s.bindAttributeName)||Gp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(e=>n.hasAttribute(e));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&ie(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(e,t){let n=Cp.get(e);n||(n=new Set,Cp.set(e,n)),n.add(t)}(a,d);const u=tt(a);null===u&&ie(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await Xe(a),d in a||ie(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||ie(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=Mp.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==h&&function(e,t){if(!e.hasAttribute(s.bindAttributeName))return!1;const n=gt(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(a,d)&&(a[d]=h,f=h),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(gt(a)??[]).some(e=>e.propSegments[0]===d)||Gp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(s.bindAttributeName)){const s=(gt(a)??[]).filter(e=>e.propSegments[0]===d);if(s.length>0){const c=Jl(a.getRootNode())??Gp(e,`No state tree found on this root for mount host <${l}>.`);let u=(o=a,r=d,Lh.get(o)?.get(r)??null);const h=null!==u;if(null===u&&(!function(e,t,n){const o=Rp.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;Rp.get(e).delete(t)}}(a,d,f),u=$h(a,d,s,c,f,function(e,t){return Op.get(e)?.get(t)}(a,d)),Hp(u)),t.mountRecord=u,n.parentNode!==i)return;try{pp(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=hp(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),Ep(a,d)}return Fp(a,d),function(e){const t=wh.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(Y)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;bh.has(n)||(bh.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.`))}(u),void vh(u,"$connectedCallback",()=>fp(u))}}zp(e,t.boundComponent,t.boundComponentStateProp,f)}var o,r}const Xp={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=Kp.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Kp.set(e,t)),t}(e);return Jp(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Kp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&gp(n,o)}),e.isConnected&&(yp(n.component),mp(n,o)),vh(n,"$connectedCallback",()=>fp(n)),!0},disconnecting(e){const t=Kp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord;return vh(n,"$disconnectedCallback",()=>fp(n)),function(e){const t=np.get(e);void 0!==t&&(t[1].row=ip(e),np.delete(e))}(n),Zh(t.mountRecord),e.clearConnectedRootNode(),!0}};let Yp=!1;function Qp(){Yp||(Yp=!0,iu("bindComponent",Xp),Cr=jp)}function Zp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(dh(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function eg(e,t,n,o){const s=n[G];if(void 0!==s){const n=xu(t),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=lh(t,o,n,!1),c=function(e,n,...s){l.call(dh(t,this,o),e,n,...s)};r.push({path:s,pathInfo:ce(s),handler:c,order:1e6+a++}),i.add(s),e.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(e,r),e.addVolumeWatchPaths?.(i),n.start(e))}const r=n[Q];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(lh(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[W];"function"==typeof i&&(!function(e,t){let n=uh.get(e);void 0===n&&(n=[],uh.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,injections:o,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.`);ye?.volume(t,n,o.length)}function tg(e,t,n,o=[]){Lc(n),function(e,t,n,o){const s=0===o.length?null:cu(n);for(const e of o){const n=e.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||ie(`[wcs/mount-path-invalid] Volume "${t}" declares "${n}" as an accessor or a method and also injects it ("${N}.${n}: ${e.outerPathInfo.path}"). Rename one of them.`)}const r=n[G];if(void 0!==r){"object"==typeof r&&null!==r||ie(`${G} must be an object mapping state paths to handler functions.`);const e=xu(t);for(const[t,n]of Object.entries(r))"function"!=typeof n&&ie(`${G} entry "${t}" must be a function.`),e.assertValidPath(t)}const i=n[Q];if(void 0!==i){"object"==typeof i&&null!==i||ie(`${Q} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(i)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&ie(`${Q} entry "${n}" must map a list path to a field name or a key function.`);const r=lh(t,o,n,!1);e.listKeys?.has(r)&&ie(`${Q} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[K]&&ie(`Volume "${t}" declares ${K}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&ie(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[X]&&ie(`Volume "${t}" declares ${X}, 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(cu(n)))-1!==e.indexOf(Y)&&ie(`Volume "${t}" declares "${e}", which uses "${Y}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n,o);const{data:s,accessors:r}=function(e,t){const n={},o=new Map;for(const[s,r]of Object.entries(cu(e)))s.startsWith("$")||t.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(e=>e.innerSegments[0]))),i=ce(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;ie(`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],s=""===n?o in e:void 0!==e[n+d+o];n=""===n?o:n+d+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;ie(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=s}),function(e,t){let n=ih.get(e);void 0===n&&(n=new Set,ih.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+d+n,i=s.get,a=s.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(dh(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(dh(t,this,o),e)}),e.defineTreeAccessor(r,l)}eg(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(dh(t,e,o))}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,injections:o}}function ng(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=tg(e,t.mountPath,t.volumeState,t.injections)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let og=!1;function sg(){var e;og||(og=!0,xp(),_p||(_p=!0,iu("scopes",Np)),Qp(),mh=ng,e=rg,Gl.includes(e)||Gl.push(e))}function rg(e,t){(function(e){const t=oh.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){ph.delete(e);const n=hh.get(e);if(void 0===n||0===n.length||null===mh)return;hh.delete(e);const o=mh;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const ig={name:"scopes",install(){sg(),Yf||(Yf=!0,iu("dcc",Xf))}},ag=/^@@wcs-(?:for|if|elseif|else):[^-]/,lg=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,cg=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,dg=/^@@wcs-text-start:(.+)$/;function ug(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function fg(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const e=n.currentNode;t(e.data)&&o.push(e)}return o}const hg=e=>ag.test(e),pg=e=>lg.test(e),gg=e=>lg.test(e)||cg.test(e);function mg(e){if("else"===e.bindingType)return"else:";let t=`${e.bindingType}: ${e.statePathName}`;for(const n of e.outFilters){const e=n.literals??n.args;t+=`|${n.filterName}`,n.args.length>0&&(t+=`(${n.args.map((t,n)=>"string"==typeof e[n]?`'${t.split("'").join("'\"'\"'")}'`:t).join(",")})`)}return t}function yg(e){const t=e.fragment.cloneNode(!0);for(const n of e.nodeInfos){const o=pc(ut(e.fragment,n.nodePath));if(null===o)continue;const s=ut(t,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return t}class wg extends lu{_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=Pu.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=s.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,o){const r=o??e.ownerDocument;n.seen&&function(e){const t=new Map;for(const n of fg(e,pg)){if(null===n.parentNode)continue;const[,e,o]=lg.exec(n.data),s=o.split(":")[0],r=n.previousSibling?.data,i=`@@wcs-${e}-end:${o}`;if(r!==`@@wcs-${e}:${s}`&&t.get(r)!==s)for(let e=n;null!==e;){const t=e.nextSibling;e.remove(),e=e.data===i?null:t}else"for"===e&&t.set(i,s)}}(r);const i=document.createElement("script");i.setAttribute("type","application/json"),i.textContent=ug(JSON.stringify(t)),e.appendChild(i);for(const[t,n]of function(e){const t=new Map,n=[e];for(;n.length>0;)for(const e of fg(n.shift(),hg)){const o=e.data,s=o.slice(o.indexOf(":")+1);if(t.has(s))continue;const r=nc(s);null!==r&&(t.set(s,r),n.push(r.fragment))}return t}(r)){const o=document.createElement("template");o.setAttribute("id",t),o.setAttribute(s.bindAttributeName,mg(n.parseBindTextResult)),o.content.appendChild(yg(n)),e.appendChild(o)}const a=e.ownerDocument,l=Array.from(el);if(l.length>0){const t={};for(let e=0;e<l.length;e++){const n=l[e];if(!n.isConnected||n.ownerDocument!==a)continue;const o=Za(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const e of o)r[e.propName]=e.value;t[s]=r}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ug(JSON.stringify(t)),e.appendChild(n)}}tl()}static removeBlockBoundaryComments(e){for(const t of fg(e,gg))t.remove()}static removeStructuralComments(e){for(const t of fg(e,hg))t.remove()}static restoreTextBindings(e){for(const t of fg(e,e=>dg.test(e))){const e=dg.exec(t.data)[1],n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;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(s.tagNames.ssr),o=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&o.set(t,e)}}for(const e of fg(t,pg)){const t=lg.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()}wg.restoreTextBindings(t);const r=e=>{for(const t of fg(e,hg)){const e=o.get(t.data.split(":")[1]);if(e){const n=document.createElement("template"),o=e.getAttribute(s.bindAttributeName);o&&n.setAttribute(s.bindAttributeName,o);const i=document.importNode(e.content,!0);if(i.childNodes.length>0)n.content.appendChild(i);else for(const t of Array.from(e.childNodes))n.content.appendChild(document.importNode(t,!0));r(n.content),t.parentNode.replaceChild(n,t)}}};r(t);const i=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of i)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const bg={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=s.tagNames.state,n=s.tagNames.ssr,o=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of o){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Pu),wg.buildContent(o,wg.extractStateData(e),e.getRootNode()),e.parentNode?.insertBefore(o,e)}tl()},reset:function(){ec.clear(),tl(),n.seen=!1}};const vg=new Set(["for","if","elseif","else"]);function $g(e){const[,t,n]=lg.exec(e),[o,...s]=n.split(":");return"for"===t?{type:t,uuid:o,path:s[0],index:parseInt(s[1],10),nodes:[]}:{type:t,uuid:o,path:s.join(":"),index:null,nodes:[]}}function xg(e){const t=[];for(const n of e)if(n.nodeType===Node.ELEMENT_NODE){const e=n;e.hasAttribute(s.bindAttributeName)&&t.push(e),Array.from(e.children).some(e=>e.localName===s.tagNames.state&&mt(e))||t.push(...bt(e))}else null!==He(n)&&t.push(n);return t}function Sg(e){const[t,n,o]=xt(e),s=new _r;return{bindingInfos:s.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:t,bindingSession:s,deferredSpreads:o}}const Ig=/^\s*@@\s*(?:wcs-text)?\s*:/;function Pg(e,t){for(const n of t)"event"===n.bindingType||vg.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&Ig.test(n.node.data))&&e.push(n)}function kg(e,t){const n=[];for(let o=0;o<e.nodes.length;o++){const s=t.get(e.nodes[o]);s?o+=s.nodes.length+1:n.push(e.nodes[o])}return n}function Ag(e,t,n,o,s,r){t.length>0&&(e.spreads=t);for(const e of t)St(e.node);jl(t,n,o,s,r)}function Ng(e,t){const n=nc(t),o=Jl(e.getRootNode());let s=null;if(n&&o){const{statePathName:e,outFilters:t}=n.parseBindTextResult;o.createState("readonly",n=>{const o=Mr(n[e],ft(t,"output"));Array.isArray(o)&&(s=o)})}return s}function _g(e,t){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[e]}:${t}`}function Tg(e,t,n){const o=_g(t,n);return fg(e,e=>e===o)[0]??null}function Eg(e,t){const n=e,o=t.templates,r=new Map;for(const[e,t]of o)for(const n of fg(t.content,hg))r.set(n.data.slice(n.data.indexOf(":")+1),e);const i=new Set(yt(e));if(i.size>0)for(const e of fg(n,hg)){const t=e.data.slice(e.data.indexOf(":")+1);let n=e.parentNode;for(;null!==n&&!i.has(n);)n=n.parentNode;null===n||r.has(t)||r.set(t,n)}const a=new Map,l=[];for(const[e,t]of o){let n=ze(t.getAttribute(s.bindAttributeName)||"")[0];const o=n.bindingType,i=r.get(e),c=a.get(i);"else"===o&&c&&(n={...c,outFilters:[...c.outFilters,rc()],bindingType:"else"}),"if"===o||"elseif"===o?a.set(i,n):"else"===o&&a.set(i,null),l.push([e,t,n])}for(const[e,t,o]of l.reverse()){const s=document.importNode(t.content,!0),r="for"===o.bindingType?o.statePathName:void 0;mc(s),"string"==typeof r&&uc(s,r),$c(n,s,r);tc(e,n,{fragment:s,parseBindTextResult:o,nodeInfos:gc(s)})}}const Cg={hydrate:async function(e){await Dl(e);const t=e.querySelectorAll(s.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="${Pu}". Falling back to full render.`),wg.cleanupDom(e),!1}const n=function(e){const t=[];for(const n of fg(e,gg)){if(!pg(n.data)){t.pop();continue}const e=$g(n.data),o=t.at(-1);if("for"===e.type&&o&&o.uuid!==e.uuid)return[e,o];t.push(e)}return null}(document.body);if(null!==n){const[t,o]=n;return console.warn(`[@wcstack/state] SSR: "for: ${t.path}" in "${o.type}: ${o.path}" (known limitation). Falling back to full render.`),wg.cleanupDom(e),!1}for(const n of t)Eg(e,n);wg.restoreTextBindings(document.body);const o=function(e){const t=[];for(const n of fg(e,pg)){const e=$g(n.data);e.start=n;const o=n.data.replace("-start:","-end:");let s=n.nextSibling;for(;s&&(s.nodeType!==Node.COMMENT_NODE||s.data!==o);)e.nodes.push(s),s=s.nextSibling;t.push(e)}return t}(document.body),r=new Map,i=function(e,t,n=new Map){const o=new Map,s=[],r=new Map(t.map(e=>[e.start,e])),i=new Set;for(let e=t.length-1;e>=0;e--){const n=xg(t[e].nodes).filter(e=>!i.has(e));for(const e of n)i.add(e);t[e].subscribers=n}for(const i of t){const t=kg(i,r);if(0===t.length)continue;const a=t.some(e=>hg(e.data));if(a){const e=document.createComment(`wcs-row-end:${i.uuid}`);i.nodes[i.nodes.length-1].after(e),t.push(e)}const{bindingInfos:l,subscriberNodes:c,bindingSession:d,deferredSpreads:f}=Sg(i.subscribers);for(const e of l)if(e.node!==e.replaceNode){const n=t.indexOf(e.node);n>=0&&(t[n]=e.replaceNode)}const h=Na(t,a);la(h,d),Wr(h,l),zr(h,c);const p=l.filter(e=>Aa(e,-1));if(Hr(h,p),"for"===i.type&&null!==i.index){const t=Tg(e,"for",i.uuid);if(t){let e=n.get(i.uuid);if(!e){const s=Ng(t,i.uuid)??i.path;e=o.get(s),e||o.set(s,e=[]),n.set(i.uuid,e)}const r=e[i.index]??=jt(null,i.index);Fa(t,r,h),qa(t,h.lastNode),wa(t,h);const a=_o(ce(i.path+"."+u),r);Fr(h,a),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Pg(s,l),Ag(h,f,a,d,l,p)}}else{const t=i.start.previousSibling,n=t?.data===_g(i.type,i.uuid)?t:Tg(e,i.type,i.uuid);if(n){wa(n,h);const e=At(n);Fr(h,e),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Pg(s,l),Ag(h,f,e,d,l,p)}}}return s}(document.body,o,r);wg.removeBlockBoundaryComments(document.body);const a=[];for(const e of t)e.parentNode&&(a.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());const[,l,c]=function(e,t){return xt(bt(e),t)}(document.body),d=[],f=[],h=Tr(document.body),p=h.initialize(l);jl(c,null,h);for(const e of p)if("event"!==e.bindingType)if(vg.has(e.bindingType))f.push(e);else{if(e.statePathName.includes(u))continue;d.push(e)}for(const e of f)if("for"===e.bindingType){const t=wo(e),n=Jl(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=Mr(n[e.statePathName],e.outFilters);if(Array.isArray(o)){const n=r.get(e.uuid);n&&vn(o,n),En(t,o),s=e.node,i=o,Da.set(s,xn(i)),Bn(t,o)}var s,i})}Rl([...d,...i]);for(const{el:e,parent:t,next:n}of a)t.insertBefore(e,n);const g=new Map;for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))g.set(t.getAttribute("data-wcs-ssr-id"),t);for(const t of e.querySelectorAll(s.tagNames.ssr))for(const[e,n]of Object.entries(t.hydrateProps)){const t=g.get(e);if(t)for(const[e,o]of Object.entries(n))Cr?.isDeclared(t,e)||(t[e]=o)}for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))t.removeAttribute("data-wcs-ssr-id");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=wg.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Xl(e.rootNode);const t=wg.extractStateData(e),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",Pu),wg.buildContent(n,t,e.rootNode),e.parentNode?.insertBefore(n,e)}};let Mg=!1;function Og(){Mg||(Mg=!0,ql=Cg,function(e){if(!gu.includes(e)){gu.push(e);for(const t of yu())e(t)}}(e=>{e.get(s.tagNames.ssr)||e.define(s.tagNames.ssr,wg)}),function(){const t=globalThis;void 0===t[e]&&(t[e]=bg)}())}const Rg={name:"ssr",install(){Og()}},jg=new WeakMap,Lg=new Set,Wg=new Set;function Dg(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Bg(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function zg(e){return jg.get(e)}function Fg(e){qg(e),jg.delete(e)}function qg(e){Lg.delete(e),Wg.delete(e)}const Vg=new WeakSet;let Hg=0;function Ug(e){return zg(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Kg(e){if(0===Wg.size)return;if(t=e.absolutePathInfo.stateElement,!Wg.has(t))return;var t;const n=Ug(e);if(void 0!==n)for(const e of n)Gg(e)}function Gg(e){Vg.has(e)||(Vg.add(e),Hg++)}function Jg(e){return!!Vg.delete(e)&&(Hg--,!0)}const Xg=/^(?:0|[1-9]\d*)$/;function Yg(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Qg(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&&Xg.test(t)&&Yg(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Yg(e,t))?"object":null}function Zg(e,t){const n=Qg(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]=Zg(o[e],t);return r}function em(e){return Zg(e,new Map)}function tm(e,t,n){if(Object.is(e,t))return!0;const o=Qg(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(Qg(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(!tm(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&tm(s[e],r[e],n))}function nm(e,t){return tm(e,t,new Map)}const om=new WeakMap;function sm(e,t){if("function"!=typeof t)return;const n=om.get(t);void 0===n?om.set(t,new Set([e])):n.add(e)}function rm(e,t){return"function"==typeof t&&!0===om.get(t)?.has(e)}const im={"read-source":e=>`${J} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-rows":e=>`${J} could not read the rows of "from" for "${e}". Nothing was folded or written.`,"read-output":e=>`${J} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${J} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${J} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${J} could not write the output "${e}".`},am={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function lm(e,t,n){null!==_t&&_t({type:"state:watch-error",phase:t,path:`${J}.${e}`,error:n})}function cm(e,t,n){console.error(`[@wcstack/state] ${im[n](e)}`,t),lm(e,am[n],t)}function dm(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function um(e,t){t.then(void 0,()=>{}),cm(e,new TypeError(`${J} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const fm=new WeakSet;const hm="[wcs/scan-declaration-invalid]",pm=Object.freeze([]);function gm(e){return`${J} entry "${e}"`}function mm(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function ym(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${u}${u}`)?`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.${he}`}function wm(e,t,n){0===n.length&&ie(`${hm} ${e} "${t}" must be a non-empty state path.${he}`),n.startsWith("$")&&ie(`${hm} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${he}`),n.includes("@")&&ie(`${hm} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${he}`),n in Object.prototype&&ie(`${hm} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${he}`);const o=ce(n);for(const s of o.segments)0===s.length&&ie(`${hm} ${e} ${t} "${n}" has an empty path segment.${he}`);return o.wildcardCount>f&&ie(`${hm} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function bm(e,t,n,o){const s=gm(e);0===e.length&&ie(`${hm} ${J} entry name must be a non-empty string.${he}`),(e.includes(d)||e.includes(u))&&ie(`${hm} ${s} must be a flat property name ("${d}" and "${u}" are not allowed). The output is a property the runtime owns.${he}`),e.startsWith("$")&&ie(`${hm} ${s} must not start with "$" (reserved namespace).${he}`),e in Object.prototype&&ie(`${hm} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${he}`),t.has(e)&&ie(`${hm} ${s} conflicts with a getter declared on the state.${he}`),n.has(e)&&ie(`${hm} ${s} conflicts with a setter declared on the state.${he}`),o.has(e)&&ie(`${hm} ${s} conflicts with the ${K} entry of the same name — each output has exactly one owner.${he}`)}function vm(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!rm(e,o)&&ie(`${hm} ${gm(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${he}`)}function $m(e,t,n,o,s,r){const i=gm(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&ie(`${hm} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${he}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||ie(`${hm} ${i} "on" must be a non-empty event-token name.${he}`),n.has(e)||ie(`${hm} ${i} on "${e}" is not declared in ${H}.${fe(e,n)}${he}`),{kind:"event",tokenName:e}}const c=t.from;"string"!=typeof c&&ie(`${hm} ${i} "from" must be a state path string.${he}`);const u=wm(i,"from",c),f=mm(u,o)??r?.recursiveGetterOwning(c)??null;null!==f&&ie(ym(i,"from",c,f));const h=mm(u,s);return null!==h&&ie(function(e,t,n){return`${hm} ${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.${he}`}(i,c,h)),(c===e||c.startsWith(e+d))&&ie(`${hm} ${i} from "${c}" reads the entry's own output — the scan would fold its own writes forever.${he}`),{kind:"path",path:c,pathInfo:u}}function xm(e,t,n,o){if(void 0===t)return pm;const s=gm(e);Array.isArray(t)||ie(`${hm} ${s} "resetOn" must be an array of state paths.${he}`);const r=[];for(const e of t){"string"!=typeof e&&ie(`${hm} ${s} "resetOn" must contain only state path strings.${he}`);const t=wm(s,"resetOn",e);t.wildcardCount>0&&ie(`${hm} ${s} resetOn "${e}" must not contain "${u}" — a reset returns the whole output to "initial".${he}`);const i=mm(t,o);null!==i&&ie(ym(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&ie(`${hm} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${he}`),"path"===n.kind&&e.startsWith(n.path+d)&&ie(`${hm} ${s} 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.${he}`),r.push(e)}return r}function Sm(e,t,n=null){const o=e[J];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&ie(`${hm} ${J} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${he}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(cu(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){Lc(e);const t=e[K];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)){bm(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&ie(`${hm} ${gm(e)} must be an object ({ from | on, initial, fold, resetOn? }).${he}`);const o=u;vm(e,a,o);const f=$m(e,o,t,s,i,n);"initial"in o||ie(`${hm} ${gm(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${he}`),"function"!=typeof o.fold&&ie(`${hm} ${gm(e)} fold must be a function.${he}`);const h=xm(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=ce(e).segments[0];t.has(n)&&ie(`${hm} ${gm(o.name)} resetOn "${e}" reads the ${J} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${he}`)}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&&ie(`${hm} ${J} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${he}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Im(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 Vg.has(e)}(e),l=a&&!nm(n,e.initial)?em(e.initial):n,c=t(l,o,...s);if(dm(c))return void um(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,sm(e.name,c)),a&&Jg(e)}catch(t){cm(e.name,t,i)}}}function Pm(e,t,n){const o=function(e,t){Fg(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Bg(n,e.source.path,e);for(const t of e.resetOn)Bg(o,t,e),"event"===e.source.kind&&Bg(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return jg.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)&&ci().hasQueuedPath(e,n))&&Gg(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}const km="scanEntries",Am={order:8,validate(e,t,n){const o=Sm(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(km,o)},applyEarly(e,t,n){const o=n.get(km)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=em(n.initial);e[n.name]=t,sm(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Ho(e,n.source.tokenName).subscribe(Im(n))}(e,o))},register(e,t,n){const o=n.get(km)??null,s=function(e){const t=new Map,n=zg(e);if(void 0!==n)for(const e of n.entries)Jg(e)&&t.set(e.name,e.resetOn);return Fg(e),t}(e);e.setScanPaths?.(null===o?null:Pm(e,o,s))}};let Nm=!1;const _m=Object.freeze([]),Tm=Object.freeze([]);function Em(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??_m,i=e.dynamicDependency.get(n)??_m,a=t.byFromPath.get(n)??Tm;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Cm=Symbol("wcs-stream-last-notified-uncertain"),Mm=new WeakMap;function Om(e,t){const n=Mm.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Rm(e,t){const n=Mm.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Cm,error:Object.is(o.error,null)?null:Cm})}const jm=new Set;function Lm(e){jm.delete(e)}const Wm=new WeakMap;function Dm(e){return Wm.get(e)??new Map}function Bm(e){Lm(e);const t=Wm.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Rm(e,n.name)}const zm=(e,t)=>t,Fm=new Set;function qm(e,t){Lc(t);const n=t[K];if(void 0===n)return void Om(e,Fm);"object"==typeof n&&null!==n||ie(`${K} must be an object mapping stream names to stream definitions.`);const o=new Map,s=cu(t);for(const[r,i]of Object.entries(n)){0===r.length&&ie(`${K} entry name must be a non-empty string.`),r.includes(d)&&ie(`${K} entry "${r}" must be a flat property name ("${d}" is not allowed).`),r.includes(u)&&ie(`${K} entry "${r}" must be a flat property name ("${u}" is not allowed).`),r.startsWith("$")&&ie(`${K} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&ie(`${K} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(r)&&ie(`${K} entry "${r}" conflicts with a getter declared on the state.`),e.setterPaths.has(r)&&ie(`${K} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||ie(`${K} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||rm(r,a)||ie(`${K} entry "${r}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&ie(`${K} entry "${r}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&ie(`${K} entry "${r}" fold must be a function.`),l&&!("initial"in n)&&ie(`${K} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&ie(`${K} entry "${r}" args must be a function.`);const c={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??zm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in t||(t[r]=c.definition.initial,sm(r,c.definition.initial)),o.set(r,c)}!function(e,t){Wm.set(e,t)}(e,o),Om(e,new Set(o.keys()))}const Vm=new WeakMap,Hm=new WeakMap;function Um(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Dm(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Dm(e).has(n),ownKeys:()=>Array.from(Dm(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Dm(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){ie(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){ie(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Km(e){const t=Vm.get(e);if(void 0!==t)return t;const n=Um(e,Z,e=>e.status);return Vm.set(e,n),n}function Gm(e){const t=Hm.get(e);if(void 0!==t)return t;const n=Um(e,ee,e=>e.error);return Hm.set(e,n),n}function Jm(e){Vm.delete(e),Hm.delete(e)}let Xm=null;function Ym(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}const Qm={read(e,t){!function(e,t){null!==Xm&&Xm.add(so(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===Z?Ym(Km(e),t.pathInfo.segments):n===ee?Ym(Gm(e),t.pathInfo.segments):Fc},get:(e,t)=>t===Z?Km(e.stateElement):t===ee?Gm(e.stateElement):Fc};let Zm=0,ey=null,ty=0;const ny=new WeakMap;function oy(e){Zm=e+1}function sy(){Zm=0}function ry(e){if(Zm>0){const t=ey??=new Map;Zm>(t.get(e)??0)&&t.set(e,Zm),ty=Math.max(ty,Zm)}}function iy(e,t){return ny.get(e)?.get(t)??0}async function ay(e,t,n,o){let s=null;const r=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",r,{once:!0});try{const i=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] ${K}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();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",r)}}function ly(e){gy();const t=Dm(e);if(0!==t.size){!function(e){jm.add(e)}(e);for(const n of t.values())cy(e,n)}}function cy(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=Xm,s=new Set;let r;Xm=s;try{e.createState("readonly",e=>{r=n(e)})}finally{Xm=o}r instanceof Promise&&ie(`${K} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${Z}${d}${t.name}`,a=`${ee}${d}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||ie(`${K} 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&&ie(`${K} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);!function(e,t){const n=zg(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=Em(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&ie(`[wcs/scan-feedback-loop] ${K} entry "${t.name}" args read "${n}", which is derived from the ${J} 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}),sm(t.name,t.definition.initial),dy(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{const o=s.fold(e[t.name],n);e[t.name]=o,sm(t.name,o)})},done(){dy(e,t,"done",null)},fail(o){dy(e,t,"error",o),n.abort()}};ay(s.source,o,n.signal,r)}function dy(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return Mm.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=Mm.get(e);void 0===s&&(s=new Map,Mm.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${Z}${d}${t.name}`),i&&e.$postUpdate(`${ee}${d}${t.name}`)}))}function uy(e){const t=jm;if(0===t.size)return;const n=[];for(const o of t)for(const t of Dm(o).values()){let s=-1;for(const n of t.depAddresses)e.has(n)&&(s=Math.max(s,iy(e,n)));s>=0&&s<=32&&n.push({stateElement:o,entry:t,depth:s})}try{for(const{stateElement:e,entry:o,depth:s}of n)if(t.has(e)&&Dm(e).get(o.name)===o){oy(s);try{cy(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Dm(e).get(o.name)===o&&dy(e,o,"error",n)}}}finally{sy()}}let fy=!1;const hy=new WeakMap,py={order:20,apply(e,t){var n;Jm(e),Bm(n=e),Lm(n),Wm.delete(n),qm(e,t),void 0!==t[K]&&e.attachAddressHooks?.("streams",K)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return ly(e),void hy.set(e,e.connectGeneration??0)}n===e.connectGeneration&&hy.get(e)!==n&&ly(e)}},deactivate(e){Bm(e),Jm(e)}};function gy(){fy||(fy=!0,Hc("streams",Qm),Jc("streams",py),ri(uy,20))}const my=new WeakMap;function yy(e,t,n){let o=my.get(e);void 0===o&&(o=new Map,my.set(e,o)),o.set(t,n)}const wy=new Map;function by(e,t){wy.has(e)||wy.set(e,t)}function vy(e){return wy.get(e)}const $y=new WeakMap,xy=new WeakMap,Sy=new Set,Iy=new Map;function Py(e){return $y.get(e)??Iy}function ky(e){Sy.add(e),function(e){const t=jg.get(e);void 0!==t&&(Dg(t)&&Lg.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Wg.add(e))}(e)}function Ay(){return Sy}function Ny(e,t){let n=xy.get(e);void 0===n&&(n=new Map,xy.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)}}const _y=new Map;function Ty(e){return xy.get(e)??_y}function Ey(e){0===e.length&&ie(`[wcs/watch-declaration-invalid] ${G} entry name must be a non-empty state path.`),e.startsWith("$")&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not start with "$" (reserved namespace).${he}`),e.includes("@")&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${he}`),e in Object.prototype&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ce(e);for(const n of t.segments)0===n.length&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" has an empty path segment.${he}`);return t.wildcardCount>f&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Cy(e,t){const n=t[G];if(void 0===n)return null;"object"==typeof n&&null!==n||ie(`[wcs/watch-declaration-invalid] ${G} must be an object mapping state paths to handler functions.${he}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${t}" must be a function.${he}`);const n=Ey(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){$y.set(e,t)}(e,o),s.size>0?s:null}const My={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||by(n,o)},swapped(e,t,n){var o;o=n,wy.has(o)&&by(t,vy(n))}};function Oy(e){for(let t=e;null!==t;t=t.parentListIndex)if(en(t))return!0;return!1}function Ry(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[Hn](_o(t.wildcardParentPathInfos[i],r)),l=mn(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=fo(o,i,t.wildcardCount);if(l!==c&&!Gt(l,c)){if(en(c))return"gone";s="replaced"}r=l}return s}function jy(e,t,n){const o=new Map;for(const s of n){const n=Ry(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 Ly=Object.freeze([]);function Wy(e,t,n,o){let s=e.get(n);return void 0===s&&(s={stateElement:t,entry:n,rows:[],reset:!1,depth:o},e.set(n,s)),s.depth=Math.max(s.depth,o),s}function Dy(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 By(e,t){return t.has(e.stateElement)&&!0===zg(e.stateElement)?.entries.has(e.entry)}function zy(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Fy(n,e))||Jg(t)}function Fy(e,t){return ci().hasQueuedPath(e,t)}function qy(e,t){!function(e,t,n){if(0!==Hg)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=Ug(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||Jg(t)}}(e,t,Fy)}function Vy(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function Hy(e,t,n){if(!By(e,n))return zy(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(fm.has(e))return;fm.add(e);const o=`[wcs/scan-source-computed] ${J} 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}`),lm(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=Dm(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];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?e.rows:jy(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Dy)){let n;try{n=Vy(t,r,e)}catch(e){cm(s.name,e,"read-source");continue}const o=a(l,n,vy(e.absAddress),...e.indexes);if(dm(o))return void um(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){cm(s.name,e,i.failure)}return i.plan}function Uy(e,t){const{group:n}=e;if(!By(n,t))return void zy(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Jg(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!nm(o,s.initial):!Object.is(o,e.next)){const o=n.reset?em(s.initial):e.next;t[s.name]=o,sm(s.name,o)}})}catch(e){cm(s.name,e,"write")}}function Ky(e,t){if(qy(e,t),0===Lg.size)return Ly;const n=new Map;for(const o of e){const s=o.absolutePathInfo.stateElement;if(!t.has(s))continue;const r=zg(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=iy(e,o),l=r.byFromPath.get(i.path);if(void 0!==l){let e=[];if(i.wildcardCount>0){if(null===o.listIndex)continue;e=ho(o.listIndex,i.wildcardCount)}for(const t of l)Wy(n,s,t,a).rows.push({absAddress:o,indexes:e})}const c=r.byResetPath.get(i.path);if(void 0!==c)for(const e of c)Wy(n,s,e,a).reset=!0}if(0===n.size)return Ly;const o=Array.from(n.values()).sort((e,t)=>e.entry.order-t.entry.order),s=[];try{for(const n of o){oy(n.depth);const o=Hy(n,e,t);null!==o&&s.push(o)}}finally{sy()}return s}function Gy(e){ow(),(0!==Py(e).size||0!==Ty(e).size||function(e){const t=jg.get(e);return void 0!==t&&Dg(t)}(e))&&(ky(e),function(e){const t=[];for(const n of Py(e).values())Jy(e,n)&&t.push(n);for(const n of Ty(e).values())for(const o of n)Jy(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{yy(e,ro(e,o.pathInfo,null),n[o.path])}catch(t){Yy(e,o.path,"prime",t)}})}(e))}function Jy(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Xy={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Yy(e,t,n,o){console.error(`[@wcstack/state] $watch ${Xy[n]} "${t}" threw.`,o),null!==_t&&_t({type:"state:watch-error",phase:n,path:t,error:o})}function Qy(e){const t=Ay(),n=function(e){const t=ty;return t>0&&(ny.set(e,ey),ey=null,ty=0),t}(e);try{if(n>32){qy(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!==_t&&_t({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}if(0===t.size)return void qy(e,t);!function(e,t){if(0!==e.length)try{for(const n of e)oy(n.group.depth),Uy(n,t)}finally{sy()}}(Ky(e,t),t),function(e,t){const n=[],o=new Set;for(const s of e){const e=s.absolutePathInfo.stateElement;if(!t.has(e))continue;const r=s.absolutePathInfo.pathInfo.path;o.add(r);const i=Py(e).get(r),a=Ty(e).get(r);if(void 0===i&&void 0===a)continue;const l=void 0===i?[]:[i];void 0!==a&&l.push(...a);for(const t of l){let o=[];if(t.pathInfo.wildcardCount>0){if(null===s.listIndex)continue;o=ho(s.listIndex,t.pathInfo.wildcardCount)}n.push({stateElement:e,entry:t,absAddress:s,indexes:o})}}if(0===n.length)return;n.sort(ew);const s=function(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(0===s.entry.pathInfo.wildcardCount)continue;const r=e[o-1];(Oy(s.absAddress.listIndex)||r?.entry===s.entry&&Zy(r.indexes,s.indexes)||s.entry.pathInfo.wildcardParentPaths.some(e=>t.has(e)))&&(n??=new Set).add(s.entry)}if(null===n)return e;const o=new Set;for(const t of n){const n=e.filter(e=>e.entry===t),s=n[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(jy(e,t.pathInfo,n));for(const e of n)s.has(e)||o.add(e)})}catch(e){Yy(0,t.path,"evaluate",e);for(const e of n)o.add(e)}}return e.filter(e=>!o.has(e))}(n,o);try{for(const n of s){if(!t.has(n.stateElement))continue;const o=Py(n.stateElement).get(n.entry.path)===n.entry,s=!0===Ty(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(oy(iy(e,n.absAddress)),tw(n))}}finally{sy()}}(e,t)}finally{wy.clear()}}function Zy(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function ew(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 tw(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Jy(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 Yy(0,n.path,"evaluate",e)}const a=r?function(e,t){return my.get(e)?.get(t)}(t,o):vy(o);r&&yy(t,o,i),null!==_t&&_t({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Yy(0,n.path,"handler",e)}}let nw=!1;function ow(){nw||(nw=!0,Hc("watch",My),Jc("watch",sw),ri(Qy,10),si(ry),$u={assertValidPath:Ey,addEntries:Ny,start:Gy})}const sw={order:10,register(e,t){var n;n=e,Sy.delete(n),qg(n),$y.delete(n),function(e){my.delete(e)}(e);const o=Cy(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?G:J)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Gy(e)},deactivate(e){var t;t=e,Sy.delete(t),qg(t)}},rw={name:"temporal",install(){ow(),Nm||(Nm=!0,Jc("scan",Am),si(Kg)),gy()}},iw=new Set,aw=new Set;function lw(e){iw.has(e)||(iw.add(e),console.warn(`[@wcstack/state] [wcs/v4-migration] ${e} See "Preparing for 4.0" in the @wcstack/state README.`))}const cw=["debug","commentTextPrefix","enablePropagationContext"],dw=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],uw={bindAttributeName:"string",commentForPrefix:"string",commentIfPrefix:"string",commentElseIfPrefix:"string",commentElsePrefix:"string",tagNames:"object",locale:"string",enableContractAnalyzer:"boolean"},fw=["state","ssr"],hw=["formats","diagnostics","temporal","list-keys","scopes","recursion","ssr","devtools"],pw=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),gw=(e,t,n)=>lw(`${e}: "${t}" is not one of its options, or not ${n}. 4.0 throws on it.`);function mw(e,t){if(aw.has(e))return;aw.add(e);lw(`${"$"===e[0]?"":"filter "}"${e}" is removed in 4.0: write "${t}" (its name since 3.2).`)}const yw={substr:'filter "substr" is removed in 4.0: write slice(start, start + length) — slice takes the end index, not a length.'},ww={$watch:"Move it to the root state, where its paths are absolute.",$listKeys:"Move it to the root state, where its paths are absolute.",$renderedCallback:"Move it to the root state, where it receives absolute paths.",$behavior:"Declare it on the root state.",$features:"Declare it on the root state."},bw=new WeakSet,vw={state(e){const t=e;for(const e of Object.keys(Oc))void 0!==t[e]&&mw(e,Oc[e]);var n;void 0!==t[J]&&lw(`"${J}" is removed in 4.0: rewrite it with $watch (state paths) or $on (event tokens).`),bw.has(e)||(!function(e){if(null==e)return;if("object"!=typeof e)return void gw("state","$behavior","an object");const t=e;for(const e in t){const n=t[e];dw.includes(e)&&"boolean"==typeof n?n!==s[e]&&lw(`$behavior takes effect in 4.0; 3.x does not read it and runs this state with ${e}: ${!n}. Until you upgrade, pass bootstrapState({ ${e}: ${n} }).`):gw("$behavior",e,"a boolean")}}(t.$behavior),void 0!==(n=t.$features)&&(Array.isArray(n)&&!n.some(e=>!hw.includes(e))||lw(`$features is not an array of add-on names (${hw.join(", ")}). 4.0 throws on it.`)))},volumeLoaded(e){bw.add(e)},renamed:mw,removed(e){lw(yw[e])},volume(e,t,n){n>0&&lw(`volume "${e}" injects root paths (data-wcs="state.<key>: …"): 4.0 does not graft a volume with injections. Read the root path in a root getter instead.`);for(const n of Object.keys(ww))void 0!==t[n]&&lw(`volume "${e}" declares ${n}: 4.0 does not graft a volume that declares it. ${ww[n]}`)}};function $w(e){!function(e){ye=e}(vw),function(e){if("object"==typeof e&&null!==e)for(const[t,n]of Object.entries(e))if(void 0!==n)if(cw.includes(t))lw(`bootstrapState option "${t}" is removed in 4.0, which throws on it. Remove it.`);else if(dw.includes(t)&&"boolean"==typeof n)lw(`bootstrapState option "${t}" moves to the state's $behavior in 4.0, which throws on it here. When you upgrade, write $behavior: { ${t}: ${n} } in the state.`);else if(dw.includes(t)||!pw(uw,t)||null===n||typeof n!==uw[t]||Array.isArray(n))gw("bootstrapState",t,"of the option's type");else if("tagNames"===t)for(const[e,t]of Object.entries(n))void 0===t||fw.includes(e)&&"string"==typeof t||gw("bootstrapState",`tagNames.${e}`,"of the option's type")}(e)}const xw=[uf,rw,Wf,ig,Rg,Wu,Ju];function Sw(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(xw),$w(e),vu(e,t)}function Iw(e){return e}const Pw={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"真偽性を反転(falsy → true)",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},add:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},sub:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},toFixed:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},upper:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lower:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},capitalize:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:2,maxArgs:2,argTypes:["number","number"]},padStart:{description:"先頭を埋める (length[,char]。char の既定は 0 — JS の既定は空白なので注意)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},padEnd:{description:"末尾を埋める (length[,char]。char の既定は空白 — JS と同じ)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},repeat:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},reverse:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix]。suffix の既定は … — U+2026 の 1 文字)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator]。既定はカンマ + 空白)",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},time:{description:"ロケール形式の時刻 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},datetime:{description:"ロケール形式の日時 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},ymd:{description:"YYYY-MM-DD 形式 ([separator]。既定は -)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式 ([separator]。既定は :)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},coalesce:{description:"null / undefined の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},nullIfEmpty:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},kw=2,Aw=Object.freeze({$trackDependency:"$dependOn",$untrackDependency:"$untracked"});function Nw(){return{version:2,syntax:{bindAttribute:s.bindAttributeName,tagName:s.tagNames.state,pathDelimiter:d,wildcard:u,delimiters:{binding:";",propValue:":",modifier:g,filter:m},structuralDirectives:Array.from(pe),modifiers:{flags:v,keyValue:S,eventNamePrefix:k},indexParam:{prefix:M,maxDepth:f},bindingTypes:{elseKeyword:I,spread:P,eventPropertyPrefix:k,explicitPropertyPrefix:d,propNamespaces:{eventToken:A,command:_,class:T,attr:E,style:C}}},filters:Object.keys(lf),filterMeta:Pw,filterAliases:ef,declarationAliases:Oc,apiAliases:Aw,reservedLifecycle:[j,L,W,D,B],reservedStateApi:[z,F,q,V,H,U,K,G,J,Q,X,Z,ee]}}const _w=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),Tw=Object.freeze([]);function Ew(e){if(!s.enableContractAnalyzer)return Tw;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))_w.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?Cw(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,Mw,e=>{t.push(e),null!==_t&&_t(e)}),t}function Cw(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function Mw(e){const t=tt(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{wg as Ssr,nl as TRUSTED_TYPES_POLICY_SLOT,Pu as VERSION,kw as WCS_MANIFEST_VERSION,Ew as analyzeContract,Sw as bootstrapState,Bl as buildBindings,ef as builtinFilterAliases,Pw as builtinFilterMeta,Iw as defineState,Xl as getBindingsReady,r as getConfig,ol as getTrustedTypesPolicy,Nw as getWcsManifest,sl as setTrustedTypesPolicy};
2
2
  //# sourceMappingURL=index.esm.js.map