@wcstack/state 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +47 -17
- package/README.md +47 -17
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/define.d.ts +11 -7
- package/dist/index.d.ts +15 -7
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/manifest.d.ts +14 -1
- package/dist/manifest.esm.js +91 -35
- package/dist/parser.esm.js +25 -0
- package/dist/split/chunks/binder.js +1 -1
- package/dist/split/chunks/binder.js.map +1 -1
- package/dist/split/chunks/checkDependency.js +1 -1
- package/dist/split/chunks/declarationAliases.js +2 -0
- package/dist/split/chunks/declarationAliases.js.map +1 -0
- package/dist/split/chunks/filterRegistry.js +1 -1
- package/dist/split/chunks/filterRegistry.js.map +1 -1
- package/dist/split/chunks/mount.js +1 -1
- package/dist/split/chunks/mount.js.map +1 -1
- package/dist/split/chunks/pathDiagnostics.js +1 -1
- package/dist/split/chunks/pathDiagnostics.js.map +1 -1
- package/dist/split/chunks/registerComponents.js +1 -1
- package/dist/split/chunks/registerComponents.js.map +1 -1
- package/dist/split/chunks/setAll.js +1 -1
- package/dist/split/chunks/version.js +1 -1
- package/dist/split/chunks/watchRuntime.js +1 -1
- package/dist/split/core.d.ts +11 -7
- package/dist/split/core.js +1 -1
- package/dist/split/core.js.map +1 -1
- package/dist/split/features/devtools.js +1 -1
- package/dist/split/features/devtools.js.map +1 -1
- package/dist/split/features/diagnostics.js +1 -1
- package/dist/split/features/formats.js +1 -1
- package/dist/split/features/formats.js.map +1 -1
- package/dist/split/features/recursion.js +1 -1
- package/dist/split/features/scopes.js +1 -1
- package/dist/split/features/scopes.js.map +1 -1
- package/dist/split/features/ssr.js +1 -1
- package/dist/split/features/ssr.js.map +1 -1
- package/dist/split/features/temporal.js +1 -1
- package/dist/split/features/temporal.js.map +1 -1
- package/dist/wcs-manifest.json +65 -25
- package/package.json +1 -1
package/dist/auto.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n;const s=Symbol.for("wcstack.binder");const r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");function a(){const e=function(){const e=globalThis[s];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[r];return void 0===t&&(t=[],e[r]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[i];return void 0===t&&(t=new WeakSet,e[i]=t),t}();for(const t of n)o.add(t),e.bind(t)}const l=".",c="*",d=128,u=128,f="#",h="|",p="prevent",m="stop",g="ro",y="init",w="sync",b="else",v="...",$="on",x="eventToken",S="command",P="class",I="attr",N="style",k={};for(let e=0;e<d;e++)k[`$${e+1}`]=e;const _=Object.freeze(k),A="$connectedCallback",C="$disconnectedCallback",E="$updatedCallback",M="$errorCallback",O="$stateReadyCallback",T="$bindables",R="$commands",j="$commandTokens",L="$command",W="$eventTokens",D="$on",B="$streams",z="$watch",F="$scan",q="$recursion",V="**",H="$listKeys",U="$streamStatus",G="$streamError",K="data-wc-definition",J=/\{\{\s*(.+?)\s*\}\}/g,X=new Set(["SCRIPT","STYLE"]);function Q(e){if(!o.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&X.has(e.parentElement.tagName)||Y(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),Q(t.content)}else Q(e.content)}function Y(e){const t=e.data;if(J.lastIndex=0,!J.test(t))return;J.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=J.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 Z(e){throw new Error(`[@wcstack/state] ${e}`)}const ee=new Map;let te=0;function ne(e){let t=ee.get(e);return void 0!==t||(-1!==e.indexOf(V)&&Z(`[wcs/recursion-unsupported] "${e}" uses "${V}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`),t=Object.freeze(new oe(e)),ee.set(e,t)),t}class oe{id=++te;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:ne(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],d=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===c&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),d.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=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=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=p}}function se(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 re(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=se(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ie=" Validate statically: npx @wcstack/lint <file>.",ae=new Set(["if","elseif","else","for"]),le={not:()=>e=>!e},ce={input:new Map,output:new Map},de={input:new Map,output:new Map},ue=new Map;function fe(e,t,n){const o=ce[e],s=de[e];for(const e of Object.keys(t)){o.set(e,t[e]);const r=n?.[e];void 0===r?s.delete(e):s.set(e,r)}ue.clear()}function he(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=ue.get(s);if(void 0!==r)return r;const i=ce[n].get(e)??le[e];void 0===i&&Z(`[wcs/filter-unknown] filter not found: ${e}.${re(e,function(e){return[...new Set([...Object.keys(le),...ce[e].keys()])]}(n))}${ie}`);const a=de[n].get(e);void 0!==a&&(t.length<a[0]||t.length>a[1])&&Z(t.length<a[0]?`[wcs/filter-arity] filter "${e}" requires at least ${a[0]} argument(s) (${t.length} given).${ie}`:`[wcs/filter-arity] filter "${e}" accepts at most ${a[1]} argument(s) (${t.length} given).${ie}`);const l=i(t,o);return ue.set(s,l),l}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 me=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function ge(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:me.test(e)?Number(e):e)}function ye(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(ge(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&&Z(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ie}`);const c=pe(o,i,a);return(c||r)&&(t.push(c),n.push(ge(c,r))),{args:t,literals:n}}function we(e,t){return e.map(t=>{const n=t.indexOf("("),o=t.lastIndexOf(")");-1!==n&&-1===o&&Z(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==o&&-1===n&&Z(`Invalid filter format: missing opening parenthesis in "${t}"`);const s=(-1===n?t:t.substring(0,n)).trim();if(0===s.length&&Z(`[wcs/binding-syntax] an empty filter in "${e.join("|")}" — remove the extra "|" or name the filter.${ie}`),-1===n)return{filterName:s,args:[],literals:[]};return{filterName:s,...ye(t.substring(n+1,o))}})}const be=e=>e.trim(),ve=e=>"'"===e||'"'===e;function $e(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(ve(s))n=s;else if(s===t)return o}return-1}function xe(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):ve(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const Se=new Map;function Pe(e){const t=$e(e,h);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Se.has(s)?r=Se.get(s):(o=xe(s,h).map(be),r=we(o),Se.set(s,r))):n=e.trim();const i=n.split(f).map(be);i.length>2&&Z(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${f}" — write "${i[0]}${f}${i.slice(1).join(",")}".${ie}`);const[a,c]=i,d=a.split(l).map(be);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map(be):[],inFilters:r}}const Ie=new Map;function Ne(e){const t=$e(e,h);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ie.has(s)?r=Ie.get(s):(o=xe(s,h).map(be),r=we(o),Ie.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&Z(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);return{statePathName:n,statePathInfo:ne(n),outFilters:r}}const ke=new Set([b,"if","elseif","for",v]);function _e(e){const[...t]=function(e){return xe(e,";")}(e).map(be).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&Z(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(f)[0].split(h)[0].trim();if(s!==n&&ke.has(s)&&Z(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ie}`),n===b){o.length>0&&Z(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ie}`);const t=ne("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===v){const t=Ne(o);return t.outFilters.length>0&&Z(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&Z(`Invalid spread binding "${e}": spread target path is required.`),{propName:v,propSegments:[v],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ne(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Ne(o);return{...Pe(n),...e,bindingType:s}}{const e=Ne(o),t=Pe(n);return t.propSegments[0]===x||t.propSegments[0].startsWith($)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>ae.has(e.bindingType))&&Z(`[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">).${ie}`)}return n}const Ae=new WeakMap,Ce=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Ee=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Me(e){const t=Ae.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=Ee.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Ce.has(r)?(Ae.set(e,s[2]),s[2]):null}function Oe(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ne(e),bindingType:"text"}}const Te=new WeakMap,Re=new WeakSet;let je=0;async function Le(e){const t=function(e){let t,n=Te.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++je,promise:o,resolve:t},Te.set(e,n),Re.has(e)&&n.resolve(),n}(e);await t.promise}function We(e){const t=Te.get(e);void 0===t?Re.add(e):t.resolve()}const De=new WeakMap;function Be(e){const t=De.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{De.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 Fe(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 qe(e,t){e.upgrade?.(t)}function Ve(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=Ke(s.properties,He);if(null===r)return null;const i=void 0===s.inputs?new Map:Ke(s.inputs,Ue);if(null===i)return null;const a=void 0===s.commands?new Map:Ke(s.commands,Ge);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function He(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 Ue(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 Ge(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 Ke(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 Je(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ne(n),inFilters:[],outFilters:[],bindingType:"prop"}}function Xe(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function Qe(e,t,n={}){const s=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&Z("Spread binding requires an element node.");const t=e,o=Be(t);null===o&&Z(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Fe(t);null===a&&Z(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||Z(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}qe(a,t);const l=Ve(t);null===l&&Z(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=Je(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=Je(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=Xe(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=Xe(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.debug&&i.has(r[t])){const o=r[a.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[t])}return l}function Ye(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 Ze(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:he(s.filterName,s.args,t,s.literals??s.args)})}return n}const et=new WeakMap;function tt(e){return et.get(e)||null}function nt(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function ot(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!nt(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function st(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 rt(e){const t=[],n=ot(e),s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==Me(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&st(e,n)||t.push(e)}return t}const it=new WeakSet;function at(e,t,n,o){const s=Qe(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Be(e):null;return null===n&&Z("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}it.add(e);const r=function(e,t){const n=[];for(const o of t){const t=Ze(o.inFilters,"input"),s=Ze(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){et.set(e,t)}(e,r),We(e),{bindings:r,deferred:null}}function lt(e,t){const n=rt(e),o=[],s=[];for(const e of n){if(it.has(e))continue;const n=at(e,xa(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function ct(e){it.add(e)}function dt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){it.delete(e)}(t);return at(t,n,{allowDeferred:!1},o).bindings}const ut=new WeakMap;let ft=null;function ht(e){let t=e;for(;t;){const e=ut.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==ft&&t instanceof ShadowRoot&&(n=ft(t)),t=n}return null}function pt(e,t){null!==t?ut.set(e,t):ut.delete(e)}let mt=null;const gt=new WeakMap;function yt(e){return gt.get(e)??[]}function wt(e,t){gt.set(e,t)}function bt(e){return gt.has(e)}const vt=new WeakMap;let $t=null,xt=0;function St(e){return vt.get(e)??[]}function Pt(e,t){null===$t?vt.set(e,t):$t.set(e,t)}function It(){xt++,null===$t&&($t=new Map)}function Nt(){if(0!==xt&&(xt--,!(xt>0||null===$t))){for(const[e,t]of $t)vt.set(e,t);$t=null}}function kt(e){return($t?.has(e)??!1)||vt.has(e)}const _t=Symbol("$$setLoopContext"),At=Symbol("$$getByAddress"),Ct=Symbol("$$hasByAddress"),Et=Symbol("$$setByAddress"),Mt=Symbol("$$connectedCallback"),Ot=Symbol("$$disconnectedCallback"),Tt=Symbol("$$updatedCallback"),Rt=Symbol("$$errorCallback"),jt=new WeakMap,Lt=new WeakMap;class Wt{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Dt(e,t){if(null===t){let t=Lt.get(e);return void 0!==t||(t=new Wt(e,null),Lt.set(e,t)),t}{let n=jt.get(t);void 0===n&&(n=new WeakMap,jt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Wt(e,t),n.set(e,o)),o}}const Bt=new WeakMap;function zt(e,t){let n=Bt.get(e);void 0===n&&(n=new Map,Bt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Ft(e,t)),n.set(t,o)),o}class Ft{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function qt(e,t){return Dt(zt(e,t.pathInfo),t.listIndex)}function Vt(e,t,n){return Dt(zt(e,t),n)}const Ht=new WeakMap;function Ut(e,t){null===t?Ht.delete(e):Ht.set(e,t)}function Gt(e){return Ht.get(e)||null}const Kt=new Map;function Jt(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=Kt.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Kt.set(s,r),r}function Xt(e,t,n){return t<0||t>=n?null:e.at(t-n)}function Qt(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const Yt=new WeakMap;function Zt(e){const t=ht(e.node);if(null===t)return null;let n=Yt.get(t);if(void 0===n)n=new WeakMap,Yt.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=Jt(t.pathInfo,e.statePathInfo);return n>0&&(o=Xt(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const en=new WeakMap;function tn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Gt(n);null===t?Z(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function nn(e,t){let n=null;if(n=en.get(e)||null,null!==n)return n;const o=tn(e,t),s=Zt(e),r=pa(o);return null===r&&Z("No state tree found on this root for binding."),n=Vt(r,e.statePathInfo,s),en.set(e,n),n}function on(e){en.delete(e)}const sn=new WeakMap;function rn(e,t){const n=sn.get(e);void 0===n?sn.set(e,t):n instanceof Set?n.add(t):n!==t&&sn.set(e,new Set([n,t])),null!==mt&&mt({type:"state:binding-added",absoluteAddress:e,binding:t})}function an(e,t){const n=sn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&sn.delete(e),null!==mt&&mt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const ln=new WeakMap;function cn(e){const t=sn.get(e);return void 0!==t?t:null!==e.listIndex?ln.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const dn=new WeakMap,un=new WeakMap;class fn{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===c?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=hn(e,t)}}function hn(e,t){if(null===t){let t=un.get(e);return void 0!==t||(t=new fn(e,null),un.set(e,t)),t}{let n=dn.get(t);void 0===n&&(n=new WeakMap,dn.set(t,n));let o=n.get(e);return void 0!==o||(o=new fn(e,t),n.set(e,o)),o}}const pn=new WeakMap;function mn(e){let t=null;if(t=pn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=Zt(e);null===n&&Z(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=hn(e.statePathInfo,n)}else t=hn(e.statePathInfo,null);return pn.set(e,t),t}function gn(e){pn.delete(e)}function yn(){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 wn=new Map,bn=yn();function vn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function $n(e){let t="input";for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function xn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const o=$n(e),s=vn(e,o);let r=wn.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=pa(o.getRootNode());null===i&&Z("No state tree found on this root for two-way binding.");const a=ht(o);i.createState("writable",e=>{e[_t](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]:[]})})},wn.set(s,r)),e.node.addEventListener(o,r),bn.add(s,e),!0}var t,n;return!1}function Sn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Pn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Sn(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class In{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)t.push(n(...e));return t}}class Nn extends In{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==mt&&mt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const kn=new WeakMap;function _n(e,t){let n=kn.get(e);void 0===n&&(n=new Map,kn.set(e,n));let o=n.get(t);return void 0===o&&(o=new Nn(t,e),n.set(t,o)),o}const An=new WeakMap;function Cn(e){if(e.propSegments[0]!==x)return!1;const t=e.node,n=Be(t),o=Fe(t);if(null!==n&&void 0===o?.get(n))return null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(An.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||Z('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Be(e)?null:Ve(e)}(t);null===r&&Z(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&Z(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${re(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(p)&&e.preventDefault(),c.includes(m)&&e.stopPropagation();const n=pa(t.getRootNode());null===n&&Z("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||Z(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${re(l,n.eventTokenNames)}${ie}`);const o=ht(t);n.createStateAsync("writable",async t=>{Pn(t[_t](o,()=>{const s=null!==o?Qt(o.listIndex,o.pathInfo.wildcardCount):[];return _n(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),An.set(e,{eventName:a,handler:d}),!0}class En extends In{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==mt&&mt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Mn(e){return e instanceof En}const On=new Map,Tn=yn();function Rn(e){const t=e.propModifiers.filter(e=>e===p||e===m).sort().join(",");return`${e.statePathName}::${t}`}const jn=(e,t,n)=>o=>{t.includes(p)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=pa(r);null===i&&Z("No state tree found on this root for event handler.");const a=ht(s),l=e.startsWith(L+".");i.createStateAsync("writable",async t=>{const c=t[_t](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?Qt(a.listIndex,c):[];if(l){const s=t[At](hn(n,null));return Mn(s)||Z(`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&&Z(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Pn(c,`"${e}"`)})};function Ln(e){if(!e.propName.startsWith($))return!1;const t=Rn(e);let n=On.get(t);void 0===n&&(n=jn(e.statePathName,e.propModifiers,e.statePathInfo),On.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Tn.add(t,e),!0}function Wn(e){if(!e.propName.startsWith($))return!1;const t=Rn(e),n=On.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Tn.countOf(t)&&(Tn.remove(t,e)&&On.delete(t),!0)}const Dn=new Map,Bn=yn();function zn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Fn(e){let t="input";for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function qn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const o=Fn(e),s=zn(e,o);let r=Dn.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=pa(o.getRootNode());null===r&&Z("No state tree found on this root for two-way binding.");const i=ht(o);r.createState("writable",e=>{e[_t](i,()=>{e[t]=s})})},Dn.set(s,r)),e.node.addEventListener(o,r),Bn.add(s,e),!0}var t,n;return!1}const Vn=new Set(["radio","checkbox"]),Hn=new Set(["value","valueAsNumber","valueAsDate"]);function Un(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(Vn.has(e)&&"checked"===t)return!0;if(Hn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Be(n);if(null!==s){const e=Fe(n)?.get(s);void 0===e&&Z(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ve(n);if(o?.knownProperties.has(t))return!0}return!1}let Gn=1,Kn=1,Jn=1;const Xn=new WeakMap;function Qn(e,t,n){let o=Xn.get(e);void 0===o&&(o=new Map,Xn.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=Gn++,o.set(s,r)),r}function Yn(e,t){return"to-element"===t?2*e:2*e+1}const Zn=new Set;function eo(e){return{transactionId:Kn++,originBindingId:e,visitedEdges:Zn,hop:0}}function to(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 no=null;function oo(){return no}function so(e,t){const n=no;no=e;try{return t()}finally{no=n}}const ro=[];let io=!1;const ao=new Map,lo=yn(),co=new WeakMap,uo=e=>e.detail,fo=new WeakMap;function ho(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function po(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Be(e.node);if(null!==n){const o=Fe(e.node)?.get(n);void 0===o&&Z(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ve(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function mo(e){if(null!==Be(e.node)){const t=Ve(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??uo}return null}function go(e){if(null===Be(e.node))return!1;const t=Ve(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const yo=(e,t,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==uo||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=fo.get(e);void 0===r&&(r=new Set,fo.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=co.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=Qn(a,e,t),s=function(e,t){for(let n=ro.length-1;n>=0;n--){const o=ro[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==mt&&mt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Yn(n,"to-state"),node:a,member:e}));const r=Yn(n,"to-state"),i=oo();if(null!==i&&i.visitedEdges.has(r))return void(null!==mt&&mt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=to(i??eo(n),r)}const f=pa(a.getRootNode());null===f&&Z("No state tree found on this root for two-way binding.");const h=ht(a),p=()=>{r&&(io=!0);try{f.createState("writable",e=>{e[_t](h,()=>{e[t]=c})})}finally{r&&(io=!1)}};null!==u?so(u,p):p()};const wo=new WeakSet;function bo(e){wo.add(e)}function vo(e){return!!wo.has(e)&&(wo.delete(e),!0)}const $o=new WeakMap;function xo(e,t){const n=$o.get(e);return!(void 0===n||n<t)&&(n===t?$o.delete(e):$o.set(e,n-t),!0)}const So=new WeakSet;function Po(e){So.add(e)}function Io(e){return!!So.has(e)&&(So.delete(e),!0)}let No=0;function ko(){No--}function _o(){return No>0}class Ao{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 Co=new WeakMap;function Eo(e){let t=Co.get(e);return void 0===t&&(t=new Ao(e),Co.set(e,t)),t}function Mo(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!==y&&s!==w&&Z(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&Z(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Oo(e){return e.propModifiers.some(e=>e.includes("="))}const To=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Ro=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function jo(e,t){return"state"===e&&"call"===t?To:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Lo(e){if(!o.enableDirectionalInitialSync)return Oo(e)&&Z("init=/sync= modifiers require enableDirectionalInitialSync."),To;const t=null===(n=Mo(e,y))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:Z(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":Z(`Invalid sync modifier value "${e}".`)}(Mo(e,w));if("event"===e.bindingType)return null!==t&&"none"!==t&&Z("Event bindings only allow init=none."),"call"===s?Ro:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===S)return jo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&Z(`Binding type "${e.bindingType}" does not support init=${t}.`),jo(t??"state",s);const r=Ve(e.node);if(null===r)return jo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||Z(`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)||Z(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||Z(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Wo(e,t){return"auto"!==t?t:function(e){const t=pa(e.replaceNode.getRootNode());null===t&&Z("No state tree found on this root for binding.");const n=mn(e);let o=!1;return t.createState("readonly",e=>{o=e[Ct](n)}),o}(e)?"state":"element"}let Do=0,Bo=0;const zo=["active","disposed","failed"],Fo=new WeakMap,qo=new WeakMap,Vo=new WeakMap,Ho=new WeakMap,Uo=new WeakMap;function Go(e,t){const n=Uo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Uo.set(e,new Set([n,t]))):Uo.set(e,t)}function Ko(e){return Uo.has(e)}function Jo(e,t){const n=Uo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function Xo(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))Xo(n,t)}function Qo(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class Yo{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||!xo(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)vo(e)||Xo(e,e=>{Jo(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Io(e)&&!_o()||Xo(e,e=>{Jo(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&ta(o)}}const Zo=new WeakMap;function es(e){let t=Zo.get(e);return void 0===t&&(t=new Yo(e),Zo.set(e,t)),t}function ts(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function ns(e,t,n){const o=pa(tn(e,n));null===o&&Z("No state tree found on this root for binding.");const s=zt(o,e.statePathInfo);return function(e,t,n){let o=ln.get(e);void 0===o&&(o=new WeakMap,ln.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!==mt&&mt({type:"state:binding-added",absoluteAddress:Dt(e,t),binding:n})}(s,t,e),s}function os(e,t){const n=nn(e,t);return rn(n,e),n}function ss(e,t,n,o){null!==t?an(t,e):function(e,t,n){const o=ln.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!==mt&&mt({type:"state:binding-removed",absoluteAddress:Dt(e,t),binding:n}))}(n,o,e),gn(e),on(e)}function rs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class is{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=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=qo.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(Qo(t)&&es(t),null===this.rowPlan)for(const n of e){const e=qo.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!o.enableDirectionalInitialSync)return Oo(e)&&Lo(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=qo.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)return{id:64*t.id+n,info:e,generation:t.generation,phase:zo[t.phases[n]],teardowns:null};const o=qo.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=qo.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(rs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Fe(e);null===s&&Z(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),Go(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Eo(s).wait(t,()=>{if(a())try{qe(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.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=qo.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.active=!1,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&&(an(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){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.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(an(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?nn(n):null;if(ss(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=nn(n);e!==o&&bt(o)&&wt(e,yt(o)),e!==o&&kt(o)&&Pt(e,St(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return Qo(t)?t:null}(e);null!==t&&es(t)}handleMutations(e,t,n){for(const n of t)Xo(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)Xo(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&ta(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=qo.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Ho.get(t);void 0===e&&(e=ts(t),Ho.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;Go(n,this);const o=this.knownMapFor(n);let s=Ho.get(e);void 0===s&&(s=ts(e),Ho.set(e,s));const r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}initializeRow(e,t){this.rowPlan=e;const n=e.slots,o=t.length,s={id:++Do,session:this,generation:++Bo,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(Go(r,this),this.addKnownRowBinding(r,o,e),Fo.set(o,s),n[e].isEvent){try{Ln(o)}catch(t){throw s.phases[e]=2,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=++Bo,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{Ln(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}o.flags[e]|=2}this.registerRowSlot(o,e,n)}}rowOf(e){const t=Fo.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=Zt(o);null!==s?(e.patternPathInfos[t]=ns(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=os(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(ss(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{Wn(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:++Do,info:e,generation:++Bo,phase:"discovered",teardowns:null,session:this,anchor:e.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};qo.set(e,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;Ln(t)?e.eventAttached=!0:t.propSegments[0]!==x?(qn(t)&&rs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const t=Fn(e),n=zn(e,t),o=Dn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Bn.countOf(n)&&(Bn.remove(n,e)&&Dn.delete(n),!0))}return!1}(t)),xn(t)&&rs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const t=$n(e),n=vn(e,t),o=wn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==bn.countOf(n)&&(bn.remove(n,e)&&wn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Un(t.node,t.propName)&&-1===t.propModifiers.indexOf(g)){const n=function(e,t,n){let o=co.get(e);void 0===o&&(o=new Map,co.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&&co.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});rs(e,n)}!function(e){const t=Be(e.node);if(null!==t){const n=Fe(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&Z(`CustomElementRegistry is unavailable for <${t}>.`))}if(Un(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const t=po(e),n=mo(e),o=go(e),s=ho(e,t,null!==n,o);let r=ao.get(s);void 0===r&&(r=yo(e.propName,e.statePathName,e.inFilters,n,o),ao.set(s,r)),e.node.addEventListener(t,r),lo.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Cn(t)&&rs(e,()=>function(e){if(e.propSegments[0]!==x)return!1;const t=An.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),An.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Be(e.info.node);if(null===n)return void t();const o=Fe(e.info.node);if(null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=Eo(o).wait(n,()=>{if(this.isAlive(e,s))try{qe(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});rs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Lo(e.info),n=Wo(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 No++;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,ko()),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=pa(e.node.getRootNode());null===o&&Z("No state tree found on this root for initial binding sync.");const s=ht(e.node);o.createState("writable",t=>{t[_t](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=Zt(n);if(null!==o?(e.patternPathInfo=ns(n,o,t),e.patternListIndex=o):e.address=os(n,t),!e.options.registerPathInfo)return;const s=pa(n.replaceNode.getRootNode());null===s&&Z("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&qo.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,ko());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{ss(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=Be(e.node);if(null!==t){const n=Fe(e.node),o=n?.get(t);if(void 0===o)return}if(Un(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const t=po(e),n=ho(e,t,null!==mo(e),go(e)),o=ao.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),lo.remove(n,e)&&ao.delete(n)}}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{Wn(t)}catch{}}}}function as(e){let t=Vo.get(e);return void 0===t&&(t=new is(e),Vo.set(e,t)),t}function ls(e){return qo.get(e)?.session??Fo.get(e)?.session??null}let cs=null;function ds(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const us=Object.freeze([]);const fs=new WeakMap;const hs=new WeakMap;function ps(e){return hs.get(e)??[]}function ms(e,t){hs.set(e,t)}const gs=new WeakMap;function ys(e){return gs.get(e)??[]}function ws(e,t){gs.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});let bs=0;function vs(){return`u${(bs++).toString(36)}`}let $s=0,xs=0;const Ss=Symbol("wcs.listIndex.noValue");class Ps{uuid=vs();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ss,this._index=t,this._version=$s,this._chainGeneration=xs}get index(){return this._index}set index(e){this._index=e,this._version=++$s,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(e){this._value=e}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=$s),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===xs||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=xs),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++$s,xs++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Is(e,t,n=e){return new Ps(e,t,n)}function Ns(e,t){e.reparent(t)}function ks(e){return e.homeParentListIndex}function _s(e,t){e.value=t}function As(e,t){const n=e.value;return n!==Ss&&n===t.value}const Cs=new WeakMap,Es=new WeakSet;function Ms(e){return Es.has(e)}function Os(e,t){const n=ks(e),o=e.parentListIndex;return null===n||n===o||Es.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Es.has(e)&&!Es.has(n)&&n.position===e.position&&As(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Es.has(e)&&!Es.has(t)}(o,t)?t:null:n}function Ts(e){const t=Cs.get(e);return void 0===t?null:t}function Rs(e,t){const n=Cs.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Os(o,t);if(null!==e)for(const t of n)Ns(t,e)}return n}function js(e,t){null!==t?Cs.set(e,t):Cs.delete(e)}const Ls=new WeakMap;function Ws(e,t){null===t?Ls.delete(e):Ls.set(e,t)}function Ds(e){const t=Ls.get(e);t&&(t.dirty=!0)}const Bs=Symbol.for("wcstack.transition-runner");function zs(e){const t=globalThis[Bs];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 Fs(e,t,n){const o=zs(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const qs=[],Vs=[];function Hs(e){Vs.includes(e)||Vs.push(e)}function Us(e,t=0){const n=qs.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?qs.push(o):qs.splice(n,0,o)}function Gs(e){queueMicrotask(()=>{throw e})}class Ks{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Vs.length;t++)Vs[t](e);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){It(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){const o=new Map,s=new Set;for(let t=0;t<e.length;t++){const n=e[t],r=o.get(n.absoluteAddress);null!==mt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&mt({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];o.has(t)||o.set(t,null)}const r=[],i=new Map;o.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!==mt&&mt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=cn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(r.push(t),null!==e&&i.set(t,e));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==e&&i.set(n,e))});try{const e=()=>{i.size>0?ta(r,i):ta(r)};if(t()||0===r.length)e();else{const t=Fs("state",e);void 0!==t&&t.catch(Gs)}}finally{Nt(),function(e){for(const t of qs.slice())t.listener(e)}(s)}}}const Js=new Ks;function Xs(){return Js}const Qs=new WeakMap,Ys=new WeakMap,Zs=new WeakMap,er=new WeakMap;let tr=!1;const nr=new WeakMap,or=new WeakMap,sr=new WeakMap,rr=[];function ir(e,t){const n=ar(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ne(t).cumulativePaths;if(o.length<2)return;let s=sr.get(e);void 0===s&&sr.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 ar(e){let t=Qs.get(e);return void 0===t&&Qs.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function lr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function cr(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function dr(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=Ys.get(o);if(void 0===r&&Ys.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(cr(s,e,o),r.set(t,n),lr(s,n,o)),!1}return r.set(t,n),lr(s,n,o),!0}function ur(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function fr(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&ur(Zs,o.listIndex,r),null!==r.levelListIndex&&ur(er,r.levelListIndex,r))}function hr(e,t,n,o,s){tr=!0;const r=ar(e);ir(e,t);fr(r,t,s,o,dr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function pr(e,t){ar(e).tracked.add(t)}function mr(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(qt(e.stateElement,hn(t,o)))}function gr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function yr(e,t,n,o,s){const r=Qs.get(e),i=r?.byPath.get(t),a=nr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return rr;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&&gr(i.get(o),d),f&&gr(i.get(c),d),u&&gr(i.get(s),d)),void 0!==a)for(const e of a)n&&mr(e,o,d),f&&mr(e,c,d),u&&mr(e,s,d);return d}function wr(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function br(e,t,n){const o=Qs.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())gr(e,n);const s=nr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)mr(e,t,n)}function vr(e){const t=er.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function $r(e){if(!tr)return;const t=Zs.get(e);if(void 0!==t){Zs.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=Ys.get(o),r=s.get(n);s.delete(n),cr(Qs.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&vr(e)}}}function xr(e,t,n){if(!tr)return;const o=er.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=Qs.get(e),i=o.byPath.get(s);cr(i,t,r),lr(i,n,r),Ys.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Ds(r),Xs().enqueueAbsoluteAddress(r,null))}}const Sr=new WeakMap,Pr=Object.freeze([]),Ir=new Set;function Nr(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Pr,s=Array.isArray(n)&&n.length>0?n:Pr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Pr,o=Array.isArray(t)&&t.length>0?t:Pr;let s=Sr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Rs(o,e)||[],a=i.length>0?ks(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Ir,deleteIndexSet:new Set(i),addIndexSet:Ir};let t=Rs(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Is(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:Ir,deleteIndexSet:Ir,addIndexSet:new Set(t)}}if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:Ir,deleteIndexSet:Ir,addIndexSet:Ir};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=Is(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=Sr.get(e);o||(o=new WeakMap,Sr.set(e,o)),o.set(t,n)}(o,s,l),js(s,l.newIndexes))}}(e,t,n);!function(e,t){for(let n=0;n<e.length;n++){if(e[n].index!==n){const t=e[n].index;e[n].index=n,xr(e[n],t,n)}_s(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Pr),function(e){for(const t of e)Es.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)$r(e);return function(e){for(const t of e)Es.delete(t)}(o.newIndexes),function(e,t){if(!tr||e===t)return;const n=or.get(e);if(void 0===n)return;or.delete(e);const o=or.get(t);or.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=ar(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&&!Ms(e))for(const t of o.getters){const n=qt(o.stateElement,hn(t,e));Ds(n),Xs().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function kr(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 _r=new WeakSet;const Ar=new WeakMap;function Cr(e){return Ar.get(e)??null}function Er(e,t){Ar.set(e,t)}const Mr=new WeakMap;function Or(e){return Mr.get(e)??[]}function Tr(e,t){Mr.set(e,t)}function Rr(e,t){const n=Or(e);for(const e of n)pt(e,t)}const jr=new WeakMap;const Lr=new WeakMap;function Wr(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function Dr(e,t,n,o,s){const r=function(e,t,n){let o=Lr.get(e);void 0===o&&Lr.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;let a,l=!1;for(let e=0;e<t.length;e++){const c=t[e];if(!n.shouldApplyState(c))continue;const d=r[e];if(null===d||Wr(d.prefixes,i)){Zi(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[At](o),l=!0);const u=d.tail;let f=a;for(let e=0;e<u.length;e++){if(null==f){f=void 0;break}f=f[u[e]]}Yi(c,s,f)}}function Br(e,t,n){Rr(e,t);const o=ps(e),s=Cr(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return jr.get(e)??null}(e);if(null!==r)return void Dr(r,o,s,t,n)}for(const e of o){if(null===s){rn(nn(e),e)}(null===s||s.shouldApplyState(e))&&Zi(e,n)}}function zr(e){if(!e.mounted)return;const t=ps(e),n=Cr(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{an(nn(o),o)}}!function(e){const t=Or(e);for(let e=0;e<t.length;e++)pt(t[e],null)}(e)}function Fr(){return Object.freeze(new Set)}const qr=new WeakMap,Vr=Fr();function Hr(e,t){const n=qr.get(e);n?n.add(t):qr.set(e,new Set([t]))}function Ur(e){const t=qr.get(e);return void 0!==t?t:Vr}function Gr(e,t){const n=qr.get(e);n&&(n.delete(t),0===n.size&&qr.delete(e))}function Kr(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:he(s.filterName,s.args,t,s.literals??s.args)})}return n}function Jr(e){return{...e,inFilters:Kr(e.inFilters,"input"),outFilters:Kr(e.outFilters,"output")}}const Xr=new Set(["if","elseif","else","for"]);class Qr{_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];Po(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){Po(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=Cr(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(ps(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(bo(n),n.parentNode.removeChild(n))}const n=ps(this);for(let e=0;e<n.length;e++){const t=n[e];Xr.has(t.bindingType)&&Ur(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Cr(this);null!==e&&(e.isRowSession?e.disposeBindings(ps(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=ps(this);for(let t=0;t<e.length;t++){const n=e[t];Xr.has(n.bindingType)&&Ur(n.node).forEach(e=>{e.unmount()}),gn(n),on(n)}}unmount(){{const e=Cr(this);null!==e&&(e.isRowSession?e.disposeBindings(ps(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(bo(e),e.parentNode.removeChild(e));const e=ps(this);for(let t=0;t<e.length;t++){const n=e[t];Xr.has(n.bindingType)&&Ur(n.node).forEach(e=>{e.unmount()}),gn(n),on(n)}this._mounted=!1}}function Yr(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function Zr(e){const t=document.createDocumentFragment(),n=new Qr(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function ei(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=Ye(o,s[e].nodePath);null===t&&Z(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),ct(t),We(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=oa.get(n);void 0!==o&&o.currentRowPlan===e||(o=new is,oa.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new Qr(o);return Er(d,c),ms(d,a),function(e,t){jr.set(e,t)}(d,n),ws(d,l),Tr(d,r),Hr(e.node,d),d}function ti(e){void 0!==e.uuid&&null!==e.uuid||Z("BindingInfo.uuid is null.");const n=$a(e.uuid);n||Z(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&Yr(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=Ye(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===S||s===x)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Be(r))return null;if("prop"===o&&Un(r,e.propName))return null;const i=Jr(e);let a;try{a=Lo({...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 _,policy:a,authority:a.authority})}}return{directional:t,slots:n}}(n)),null!==r)return ei(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=Ye(e,s.nodePath);if(null===t&&Z(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),it.has(t))continue;const r=at(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new is,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new Qr(i,s);Er(l,a.bindingSession),ms(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in _&&c.push(e);return ws(l,c),Tr(l,a.nodes),Hr(e.node,l),l}const ni=new WeakSet,oi=Symbol.for("wcstack.state.view-transition-naming");function si(){const e=zs("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function ri(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||ni.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[oi]??={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.`)):(ni.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 ii=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap;function di(e,t,n){!function(e,t,n){let o=ai.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ai.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function ui(e,t){ii.set(e,t)}function fi(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 hi(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function pi(e,t,n){if(o=t,!_r.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const mi=new Set(["if","elseif","else","for"]);function gi(e,t){for(const n of ps(e))if(t.appliedBindingSet.delete(n),mi.has(n.bindingType))for(const e of Ur(n.node))gi(e,t)}function yi(e){for(const t of ps(e)){if(!mi.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Ur(t.node))yi(n),e&&n.mounted&&(zr(n),n.unmount(),Gr(t.node,n))}}function wi(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function bi(e,n,s){const r=Boolean(s);let i;const a=Ur(e.node);i=0===a.size?ti(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${wi(e)}`),zr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${wi(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);Br(i,ht(e.node),n);const t=si();null!==t&&ri(i,"branch",t)}}const vi=new WeakMap;function $i(e){return vi.get(e)??[]}const xi=new Set;const Si=Symbol.for("wcstack.trustedTypes.policy");function Pi(){const e=globalThis[Si];return null===e||"object"!=typeof e?null:e}let Ii;let Ni=!1;function ki(e,t){if(Ni)return;if(!function(){if(void 0!==Ii)return Ii;if(!("trustedTypes"in globalThis))return Ii=!1,Ii;try{document.createElement("div").innerHTML="<i></i>",Ii=!1}catch{Ii=!0}return Ii}())return;Ni=!0;const n="function"==typeof Pi()?.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 _i={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")}},Ai=new Set(["textContent","innerText","innerHTML"]);function Ci(e,n,s){if(void 0===s&&1===e.propSegments.length&&Ai.has(e.propSegments[0])&&(s=""),void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==s){null!==cs&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Be(r)&&cs.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=Pi(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&ki(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=Be(e);if(null===n)return null;const o=Fe(e)?.get(n);if(void 0===o)return null;const s=Ve(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Un(r,c)){const t=Qn(r,c,e.statePathName),o=Yn(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??oo()??eo(t);if(a.visitedEdges.has(o))null!==mt&&mt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=to(a,o);so(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Jn++,writtenValue:n};ro.push({receipt:i,node:e});try{return r()}finally{ro.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=_i[c];e?e(r,s):(!function(e,t,n){let o=vi.get(e);o||(o=[],vi.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,xi.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));null!==cs&&2===i.length&&"object"==typeof d&&null!==d&&null!==Be(r)&&(u in d?cs.rememberOverwrittenValue(r,c,u,d[u]):cs.recordInjectedKey(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const Ei=new WeakSet;function Mi(e,t,n){}function Oi(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}function Ti(e,t,n){const o=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),s=t.length>0?t+l:"";for(const e of n){if(s.length>0&&!e.startsWith(s))continue;const t=e.slice(s.length);t.length>0&&-1===t.indexOf(l)&&o.push(t)}return o}const Ri={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},ji={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Li(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}.${ie}`}function Wi(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 Di(e,t){return`$setAll("${e}") ${t}`}function Bi(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.${ie}`}function zi(e,t){const n=mn(t);if(n.pathInfo.path in _){const e=ht(t.node);return null===e&&Z(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&Z("ListIndex not found for loopContext:");const n=_[t];void 0===n&&Z(`Invalid index name: ${t}`);const o=Xt(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&Z(Bi(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[At](n)}const Fi=new WeakSet;function qi(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Vi=Object.freeze({[P]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&Z("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[I]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[N]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[S]:function(e,t,n){Mn(n)||Z("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=fs.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||Z('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Be(e);if(null===t)return null;const n=Fe(e)?.get(t);return void 0===n&&Z(`Custom element <${t}> is not defined for command binding.`),Ve(e)}(r);null===a&&Z(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||Z(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${re(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),fs.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 fs.delete(e);const o=n[i];return"function"!=typeof o&&Z(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),fs.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Hi={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Ei.has(e.replaceNode)){Ei.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,n,o){const s=e.statePathInfo,r=Zt(e),i=nn(e),a=yt(i),l=a.length>0&&!ai.has(e.node)?[]:a,d=Nr(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=ai.get(e.node);const f=void 0!==u?pi(u,l,d):null,h=Array.isArray(l)&&l.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=ci.get(e.node);if(void 0===t){const n=ii.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(fi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(fi(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),ci.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){$o.set(e,($o.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return li.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;d.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(zr(o),yi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Gr(e.node,o):(zr(o),o.unmount(),function(e,t){let n=li.get(e.node);void 0===n&&(n=[],li.set(e.node,n)),n.length<1e3?n.push(t):Gr(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(ai.delete(e.node),u=void 0)}let m=e.node;const g=ne(s.path+"."+c),y=n.stateElement.loopContextStack,w=kr(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&m.isConnected&&null===f&&(b=document.createDocumentFragment(),Ut(b,n.rootNode));const v=t(),$=si(),x=e.uuid??"",S=li.get(e.node);for(const t of d.newIndexes){let o;if(d.addIndexSet.has(t)){const r=hn(g,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=ti(e):gi(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);m.parentNode.insertBefore(e,m.nextSibling),m=e}o.mountAfter(m)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??m;n.parentNode.insertBefore(e,n.nextSibling)}}Br(o,r,n),null!==$&&ri(o,"row",$)}),void 0===o&&Z(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)){const e=n.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](n.stateElement,o)}}}else{if(o=void 0!==u?u.get(t)??null:null,d.changeIndexSet.has(t)){const e=ys(o);for(const t of e)Zi(t,n)}null===o&&Z(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&hi(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),e){const e=o,s=hn(g,t);y.createLoopContext(s,t=>{Br(e,t,n)})}}m=o.lastNode||m,void 0===u&&(u=new WeakMap,ai.set(e.node,u)),u.set(t,o)}ii.set(e.node,m),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Ut(b,null))},if:bi,else:bi,elseif:bi,radio:function(e,t,n){const o=e.node,s=ds(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=ds(o.value,e.inFilters),r=Array.isArray(n)?n:us;o.checked=r.includes(s)}},Ui=new WeakMap,Gi=new WeakMap,Ki=new WeakMap;function Ji(){}function Xi(e){const t=cs;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Mi;if(t.isDeclared(n,o))return Ji}return Ci}function Qi(e,t){Yi(e,t,zi(t.state,e))}function Yi(e,t,n){const o=ds(n,e.outFilters);if(!0===Gi.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=Ui.get(e);if(void 0===s){if(Ui.has(e))return s=Xi(e),s===Mi&&Ui.set(e,s),void s(e,t,o);if(s=Hi[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Vi[t],Ui.set(e,s),void 0===s){Be(e.replaceNode)?(s=Xi(e),s===Mi&&Ui.set(e,s)):(s=Ci,Ui.set(e,s))}}if(s===Ci){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 Gi.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function Zi(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=nn(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=ls(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Ki.get(e)){const t=Be(e.replaceNode);if(t&&void 0===Fe(e.replaceNode)?.get(t))return void function(e,t){if(Fi.has(e))return;Fi.add(e);const n=()=>{Fi.delete(e);const t=ls(e);(null===t||t.shouldApplyState(e))&&ta([e])},o=n=>{Fi.delete(e),qi(t,n)},s=ls(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Fi.delete(e),r()})||(Fi.delete(e),r()))}const r=Fe(e.replaceNode);if(null===r)return Fi.delete(e),void qi(t,new Error("CustomElementRegistry is unavailable."));Eo(r).wait(t,()=>{e.replaceNode.isConnected?n():Fi.delete(e)},o)}(e,t);Ki.set(e,!0)}if(!0===t.sameRootVerified)return void Qi(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Gt(o),null===o&&Z("Root node for fragment not found for binding.")),o!==t.rootNode){const n=pa(o);null===n&&Z("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};Qi(e,r)})}else Qi(e,t)}function ea(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!==mt&&mt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function ta(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Gt(d),null===d&&Z("Root node for fragment not found for binding."));const u=pa(d);null===u&&Z("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{Zi(n,f)}catch(e){ea(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{Ci(e,{propagationContextByBinding:t},n)}catch(t){ea(e,t,o??null,c)}for(const[e,t]of i.entries())wt(e,t),Pt(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Tt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Rt](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 na(e,t,n){const[o,s,r]=lt(e,n),i=as(e);for(const e of o)pt(e,t);ta(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=dt(o);0!==e.length&&(pt(o.node,t),ta(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const oa=new WeakMap;async function sa(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Fe(e);null===s&&Z(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(nt(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function ra(e){if(e===document)await sa(document),Q(document),Wa(document,document),na(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await Le(t.host),await sa(t),Q(t),Wa(t,t),na(t,null)}}const ia={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function aa(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${ia[e]??e}" before the state is defined.`}let la=null;function ca(e){return null===la&&Z(aa("ssr",e)),la}const da=new WeakMap,ua=new WeakMap,fa=new Set,ha=[];function pa(e){return da.get(e)??null}function ma(e){return ua.get(e)??Promise.resolve()}const ga=new WeakSet;function ya(e){ga.add(e)}function wa(e,n){const s=da.get(e);if(null===n){if(void 0===s)return;da.delete(e),fa.delete(s),null!==mt&&mt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await ca('the "enable-ssr" attribute').hydrate(e)||await ra(e)}else await ra(e);ya(e),Va(),t()}catch(e){n(e)}})});ua.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await ra(e),ya(e),Va(),t()}catch(e){n(e)}})});ua.set(e,t)}}void 0!==s&&Z('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="...">.'),da.set(e,n),fa.add(n);for(let t=0;t<ha.length;t++)ha[t](e,n);null!==mt&&mt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const ba=new Map;function va(e,t,n){if(null===n)ba.delete(e);else{ba.set(e,n);const o=pa(t);null===o&&Z("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 $a(e){return ba.get(e)||null}function xa(e){if(e.nodeType===Node.ELEMENT_NODE){return _e(e.getAttribute(o.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=Me(e);null===t&&Z("Comment node binding text not found.");const n=$a(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Oe(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Sa;function Pa(){return Sa??={filterName:"not",args:[]}}const Ia=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Na(e,t){const n=t+l+c,o=e.indexOf("|");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+l+s.slice(1)}return r.length>0?s+r:s}function ka(e,t){const n=Ia.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Na(s,t)+r}function _a(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Na(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Aa(e,t){return _a(e,t)}function Ca(e,t){const n=o.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=ka(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=_a(r,t);e!==r&&o.setAttribute(n,e)}}}function Ea(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}function Ma(e){const t=[],n=rt(e);for(const e of n){const n=xa(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:Ea(o),parseBindTextResults:n})}return t}function Oa(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 Ta=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Ra=Pa();function ja(e,t){const n=t.outFilters;return{...t,outFilters:[...n,Ra],bindingType:e}}function La(e,t,n,o,s,r=!0){Oa(t),"string"==typeof o&&Ca(t,o),Wa(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ma(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 Wa(e,t,n,s){const r=o.commentElsePrefix,i=ot(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=Aa(i,n));let a=_e(i)[0];const d=Ta.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=vs();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&Z("'else' binding found without preceding 'if' or 'elseif' binding."),a=ja("else",l.parseBindTextResult),p=La(e,f,a,m,s,!1),va(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Ea(o),parseBindTextResults:xa(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&Z("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=La(e,f,a,m,s),va(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=vs(),i={fragment:document.createDocumentFragment(),parseBindTextResult:ja("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Ea(n),parseBindTextResults:xa(n)}),va(o,e,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:Ea(g),parseBindTextResults:xa(g)})):t.replaceWith(g)}else{p=La(e,f,a,m,s),va(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 Da=()=>`[${o.bindAttributeName}]`;function Ba(e){if(Ko(e))return!0;if(!za(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(Da());return null!==t&&Ko(t)}function za(e){return 1===e.nodeType}function Fa(e){if(Ba(e))return;Q(e),Wa(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);na(t&&s?n:e,null)}const qa=[];function Va(){const e=qa.splice(0,qa.length);for(const t of e)Fa(t);a()}const Ha={protocol:"wcs-binder",version:1,bind:function(e){var t;za(e)&&!Ba(e)&&(t=e.getRootNode(),ga.has(t)?Fa(e):qa.push(e))}};const Ua="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ga=0;async function Ka(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Ga}\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 ${Ua}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Ua}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Ja(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){Z(`Failed to load script file: ${e}`)}}class Xa{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&Z("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=u&&Z("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&&Z("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&&Z("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&&Z(`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 Qa=new WeakMap;function Ya(e,t){let n=Qa.get(e);void 0===n&&(n=new Map,Qa.set(e,n));let o=n.get(t);return void 0===o&&(o=new En(t,e),n.set(t,o)),o}const Za=new WeakMap;function el(e){const t=Za.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return Ya(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:Ya(e,n)}},set(){Z("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){Z("$command namespace is read-only; deleting from it is not allowed.")}});return Za.set(e,n),n}const tl=Symbol("wcs.notHandled"),nl=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],ol=new Map;function sl(e,t){ol.set(e,t)}const rl=new Map;let il=[],al=[];function ll(e,t){rl.set(e,t),il=Array.from(rl.values()).sort((e,t)=>e.order-t.order),al=il.slice().reverse()}function cl(e,t){for(let n=0;n<il.length;n++)il[n].activate?.(e,t)}function dl(e){"readonly"===e.mutability&&Z("This state is readonly.")}const ul=new Map;class fl{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=ne(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 hl(e){let t;return ul.get(e)??(ul.set(e,t=new fl(e)),t)}function pl(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:Xt(n.listIndex,o,n.pathInfo.wildcardCount)}function ml(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=Jt(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?Xt(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?Xt(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function gl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function yl(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!==tl)return a}}return tl}function wl(e,t,n,o,s){if(t.pathInfo.segments[0]===L)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}(el(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=yl(s,t,null,n,o);if(r!==tl)return r;Z(function(e,t,n){return`[${Ri.binding}] Path "${e}" does not exist on the state tree.${re(e,Ti(t,"",n))}${ie}`}(t.pathInfo.path,e,s.getterPaths))}const r=vl(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!==c&&!(i in Object(r))){const e=yl(s,t,Object(r),n,o);if(e!==tl)return e}if(i===c){const e=t.listIndex?.index??Z(Bi(`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 bl(e,t,n,o,s){const r=qt(s,t),i=function(e){return Ls.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=wl(e,t,n,o,s);return Ws(r,{value:l,dirty:!1,generation:a}),l}function vl(e,t,n,o){ml(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!==tl)return i}}return gl(s,t)?bl(e,t,n,o,s):wl(e,t,n,o,s)}function $l(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=hn(f,r),p=qt(n.stateElement,h),m=St(p),g=vl(e,h,t,n),y=Nr(r,m,g).newIndexes,w=l[c]??null;if(i.set(p,g),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??Z(`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())Pt(e,Array.isArray(t)?t:[]);return l}function xl(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Rs(vl(e,hn(a,r),t,n),r);null==l&&Z(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??Z(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Sl(e,t,n,o){"object"==typeof e&&null!==e||Z(`${H} 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&&Z(`${H} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Pl(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&Z(`${H} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function Il(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];Sl(a,n,o,i);const l=Pl(a,t,n,o,i);r.has(l)&&Z(`${H} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Nl(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 kl(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=vl(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===c){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const _l=new WeakMap;function Al(e,t){null===t?_l.delete(e):_l.set(e,t)}function Cl(e,t,n){const s=hn(ne(e.wildcardParentPaths[t]),n),r=qt(e.stateElement,s),i=St(r),a=e.stateProxy[At](s),l=Nr(s.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${t}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)Cl(e,t+1,n)}const El=[];function Ml(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:El,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:El,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Ol=[];function Tl(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Ol;let s=null;const r=t+l;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ne(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Ol}function Rl(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=ne(r);if(e.listPathSet.has(o)&&s.lastSegment===c){const i=e.stateProxy[At](t),a=qt(e.stateElement,t),l=St(a),c=Nr(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Ml(e,o,0,0,c);for(const t of d.fullRows){const o=hn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=Tl(e,r,s);if(null===t)for(const t of d.movedRows){const o=hn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=hn(s,o);e.result.add(t),n.push(t)}}}else{const o=hn(s,t.listIndex);e.result.add(o),n.push(o)}}const r=e.dynamicMap.get(o);if(r)for(const o of r){const s=ne(o),r=[];if(s.wildcardCount>0){const n=Jt(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=Xt(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Cl(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=Xt(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=hn(s,t);e.result.add(o),n.push(o)}}}function jl(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&&Z(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),n(a),i.length=0,Rl(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}(u,t,a);for(const[e,t]of u.observedListValueByAbsAddress)Pt(e,t);return Array.from(u.result)}function Ll(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 Wl(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 Dl(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 Bl(e,t,n,s,r,i){const a=function(e,t){return!0===Qs.get(e)?.byPath.has(t)||!0===nr.get(e)?.has(t)}(e,t),l=function(e,t){return!0===sr.get(e)?.has(t)}(e,t);if(!a&&!l)return;const d=Xs(),u=o.enablePropagationContext?oo()??null:null,f=e=>{Ds(e),d.enqueueAbsoluteAddress(e,u)};a&&yr(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=ne(t).segments.length,r=[];for(const i of sr.get(e).get(t)){const t=ne(i).segments.slice(s);if(t.includes(c))br(e,i,r);else for(const s of yr(e,i,!0,wr(n,t),wr(o,t)))r.push(s)}return r}(e,t,n?s:i(),r).forEach(f)}function zl(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?oo()??eo(-1):null,c=Xs();c.enqueueAbsoluteAddress(t,l),i&&Ds(t),jl(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=qt(s.stateElement,t);Ds(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Fl(e,t,n,o,s){s&&(e.getterPaths.has(t)?Ds(n):Ws(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function ql(e,t,n,o,s,r,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=vl(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===c){const e=t.listIndex?.index??Z(Bi(`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{zl(t,n,s,r,i,a)}}function Vl(e,t,n,o,s,r,i,a){const d=t.parentAddress??Z(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=vl(e,d,s,r)??[];let f=(h=u,_l.get(h)??null);var h;if(null===f){const e=Ts(u)??[];f={value:[...u],listIndexes:[...e]},Al(u,f)}try{return ql(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=vl(e,d,s,r)??[],a=Array.isArray(i)?Ts(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:Is(d.listIndex,-1);a[h]=p;if(new Set(i).size===f.value.length){for(let e=0;e<a.length;e++)a[e].index=e;Al(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=Xs(),d=qt(i,e);yt(d)===n&&(js(t.value,t.listIndexes),wt(d,t.value),function(e){_r.add(e)}(t.value));a.enqueueRenderOnlyAddress(d);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=ne(e.pathInfo.path+l+c);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=hn(f,n),d=qt(i,c);if(void 0===l){const n=Vt(i,f,t.listIndexes[e]??null);Dl(i,d,n),zl(c,d,s,r,null,gl(i,c),"full");continue}jl(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=qt(i,e);Ds(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(d,f,i,a,s,r)}}}function Hl(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=vl(e,t,o,s),a=function(e,t,n,o){const s=Il(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Il(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===Ts(o)&&Nr(a,null,o);const d=Nr(a,o,n.list),u=Ul(e,t,n.list,s,r,i),f=ne(i+l+c);for(const t of n.matched){const n=Nl(t.oldRow,t.newRow);if(0===n.length)continue;const o=d.newIndexes[t.position];for(const i of n)void 0!==o?Hl(e,hn(ne(f.path+l+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return Ul(e,t,n,o,s,null)}function Ul(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,d=a.addressHooks;if(d){const e=d.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==tl)return i}}const u=!!io&&(io=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=vl(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===c?t.listIndex?.index:e;let p,m=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in f,t=void 0!==h?f[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,m=!0}Bl(a,l,m,p,n,()=>f[h]);const g=gl(a,t),y=qt(a,t);null!==mt&&mt({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:m}),Ll(a,l,y,p,m);let w=!1;try{if(void 0===h&&Z(Bi(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),d&&0!==d.writeMissing.length&&e!==c&&!(h in f)){const e=d.writeMissing;for(let o=0;o<e.length;o++){w=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==tl)return i;w=!1}}return Reflect.set(f,h,n)}finally{zl(t,y,s,r,i,g),w?Ds(y):Fl(a,l,y,n,g),Wl(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=vl(e,t,s,r);if(kl(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Bl(a,l,h,f,n,()=>vl(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),m=gl(a,t),g=qt(a,t);null!==mt&&mt({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),Ll(a,l,g,f,h);try{return p?Vl(e,t,g,n,s,r,i,m):ql(e,t,g,n,s,r,i,m)}finally{p||Fl(a,l,g,n,m),Wl(a,t.pathInfo,{value:n})}}function Gl(e,t,n,o){return(t,s,...r)=>{const i=ne(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&&Z(Li("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=hn(i,xl(e,n,o,i,s));if(0===r.length)return vl(e,a,n,o);dl(o),Hl(e,a,r[0],n,o)}}function Kl(e,t,n,o){const s=Gl(e,0,n,o);return(t,r)=>{const i=ne(t);if(void 0===r||Array.isArray(r)||Z(`$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&&Z(Li("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=pl(o,i.wildcardPaths[e]);if(t){r=Qt(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&&Z(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=$l(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 Jl(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return pl(o,s.wildcardPaths.at(-1)??Z(`lastWildcardPath is null: ${t.pathInfo.path}`))??Z(`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]??Z(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Rs(vl(e,hn(i,s),n,o),s)??Z(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??Z(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??Z(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":Z(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Xl(e,t,n,o){return(t,s,r,i)=>{dl(o);const a=ne(t);Array.isArray(s)||Z(Di(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&Z(Li("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&Z(Di(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&Z(Di(t,"requires an array as the value when { spread: true } is set."));const d=$l(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&Z(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=xl(e,n,o,a,d[t]);u.push(hn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(vl(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(Hl(e,s,i,n,o),f++)}return f}}function Ql(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of ne(t).cumulativePaths)if(n.has(e))return!0;return!1}const Yl=/^\$\d+$/,Zl=`${U}${l}`,ec=`${G}${l}`,tc=new WeakMap;function nc(e,t,n,o){const s=_[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&Yl.test(t)&&Z(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&Z(`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&&Z(`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=Xt(r,i,a.wildcardCount);return c?.index??Z(`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!==tl)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Kl(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>Xl(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=hl(t),i=Jl(e,r,n,o),a=hn(r.pathInfo,i),l=qt(s,a),c=Xs();c.enqueueAbsoluteAddress(l),jl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=qt(s,e);Ds(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)}}}(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Gl(e,0,n,o)(t,s,...r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(V)&&Z(`[wcs/recursion-unsupported] $trackDependency("${e}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&Z(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??Z("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(t.path)&&t.path!==e&&n.addDynamicDependency(e,t.path)}}(0,0,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Ql(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&pr(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)&&hr(o.stateElement,e,t,qt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Ql(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?pr(o.stateElement,e):hr(o.stateElement,e,i,qt(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||Z(`$eqIndex("${e}") needs a list row scope.`);const r=Xt(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&Z(`$eqIndex("${e}", ${t}): no list index at that level.`),Ql(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&pr(o.stateElement,e),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?Ts(l):null;null!==t?function(e,t,n,o,s){tr=!0,ar(e).lastValue.set(t,s),ir(e,t);let r=nr.get(e);void 0===r&&nr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=or.get(o);void 0===l?or.set(o,l=[]):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a&&(a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a)),a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){tr=!0;const r=ar(e);ir(e,t),fr(r,t,s,o,dr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,qt(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case L:return el(o.stateElement)}if(!t.startsWith(Zl)&&!t.startsWith(ec))return}const r=hl(t),i=Jl(e,r,n,o),a=hn(r.pathInfo,i);return vl(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=tc.get(e);return void 0===t&&(t=new Map,tc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case _t:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&Z("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 At:i=t=>vl(e,t,n,o);break;case Ct:i=t=>kl(e,t,n,o);break;case Et:i=(t,s)=>Hl(e,t,s,n,o);break;case Mt:i=()=>async function(e,t,n){const o=Reflect.get(e,A);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Ot:i=()=>function(e,t,n){const o=Reflect.get(e,C);"function"==typeof o&&o.call(n)}(e,0,n);break;case Tt:i=t=>function(e,t,n,o){const s=Reflect.get(e,E);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=Qt(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}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 Rt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,M);"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 oc{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=pa(e);null===n&&Z("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&&Z("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&Z(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),Z(`[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&&Z(`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 nc(e,t,n,this)}set(e,t,n,o){return dl(this),function(e,t,n,o,s){if("string"==typeof t){const r=hl(t),i=Jl(e,r,o,s);return Hl(e,hn(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)}}const sc=Promise.resolve(),rc=new Map;let ic=[];function ac(e,t){rc.set(e,t),ic=Array.from(rc.values()).sort((e,t)=>e.order-t.order)}function lc(e,t){return Z(aa(e,t))}const cc="undefined"==typeof HTMLElement?class{}:HTMLElement;function dc(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 uc=null;const fc=new Set(["for","if","elseif","else"]);function hc(e,n,o){const s=new Map;for(const e of o){const t=ne(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=qt(e,t);if(i.has(n))return;i.add(n);const o=cn(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(hn(n,t.listIndex))}};It();try{if(e.createState("readonly",t=>{for(const o of n){const n=hn(ne(o),null);a(n);try{jl(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)fc.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=()=>{ta(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Fs("state",s);void 0!==i&&i.catch(Gs)}finally{Nt()}}class pc extends cc{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return ma(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 Xa}();_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&&Z(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(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<il.length;o++)il[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[j];if(void 0===n)return t;Array.isArray(n)||Z(`${j} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||Z(`${j} entries must be non-empty strings.`),e===L&&Z(`${j} entry "${e}" conflicts with the reserved namespace name "${L}".`),t.has(e)&&Z(`${j} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[W];if(void 0===n)return t;Array.isArray(n)||Z(`${W} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||Z(`${W} entries must be non-empty strings.`),t.has(e)&&Z(`${W} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[H];if(void 0===t)return null;"object"==typeof t&&null!==t||Z(`${H} 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&&Z(`${H} entry path must be a non-empty string.`);const t=e.split(l);t.some(e=>0===e.length)&&Z(`${H} entry "${e}" must not contain empty path segments.`),t[t.length-1]===c&&Z(`${H} entry "${e}" must be the list path itself, not the element path (drop the trailing "${l}${c}").`),-1!==e.indexOf(V)&&Z(`[wcs/recursion-unsupported] ${H} entry "${e}" uses "${V}", which ${H} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${l}${c}${l}children").`),"function"!=typeof o?("string"!=typeof o&&Z(`${H} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&Z(`${H} entry "${e}" key field name must be a non-empty string.`),(o.includes(l)||o.includes(c))&&Z(`${H} entry "${e}" key field name "${o}" must be a flat property name ("${l}" / "${c}" are not allowed).`),o in Object.prototype&&Z(`${H} 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<il.length;o++)il[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<il.length;o++)il[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&uc?.reset(this),this._hasUpdatedCallback=E in e,this._hasErrorCallback=M in e,i=this,kn.delete(i),function(e,t,n){for(let o=0;o<il.length;o++)il[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[D];if(void 0!==o){"object"==typeof o&&null!==o||Z(`${D} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||Z(`${D} entry "${t}" is not declared in $eventTokens.${re(t,n)}`),"function"!=typeof s&&Z(`${D} entry "${t}" must be a function.`),_n(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=dc(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<il.length;o++)il[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<il.length;o++)il[o].register?.(e,t,n)}(this,e,n),cl(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 <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?ca('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){Z("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 Ka(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){try{const t=await fetch(e);return t.ok||Z(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e);if(e&&e.endsWith(".js"))return await Ja(e);Z(`Unsupported src file type: ${e}`)}}catch(e){Z(`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&&(wa(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),Z(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===pa(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),ua.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<ic.length;o++)ic[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{A in e&&await e[Mt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{C in e&&e[Ot]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<ic.length;t++)if(!0===ic[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||pa(this._rootNode)===this||wa(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<ic.length;t++){const n=ic[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(K))try{lc("dcc",`a <${o.tagNames.state}> inside a [${K}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{lc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<ic.length;t++){const n=ic[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&lc("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let s=!1;try{s=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!s)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 ca('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}cl(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<ic.length;t++)if(!0===ic[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<ic.length;n++)ic[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{wa(this.rootNode,null),e=this,Za.delete(e),function(e){for(let t=0;t<al.length;t++)al[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()}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",z)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&Z(`$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 Oi(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&&Z("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=ol.get(e);return void 0===n&&Z(aa(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<nl.length;n++){const o=nl[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",T)}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){return this._addDependency(this._dynamicDependency,e,t)}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+c)),!this._pathSet.has(e)){const t=ne(e);if(this._pathSet.add(e),uc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ne(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 oc(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&&Z(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);!function(e){for(let t=0;t<ic.length;t++)ic[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&Z("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(dc(n)))e.startsWith("$")||e.includes(c)||"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){hc(this,e,this._pathRegistrations.keys())}}const mc=[];function gc(e=customElements){for(let t=0;t<mc.length;t++)mc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,pc)}function yc(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 wc(e,t){const o=yc(e);var r;o&&((r=o).tagNames&&Object.assign(n.tagNames,r.tagNames),"string"==typeof r.bindAttributeName&&(n.bindAttributeName=r.bindAttributeName),"string"==typeof r.commentTextPrefix&&(n.commentTextPrefix=r.commentTextPrefix),"string"==typeof r.commentForPrefix&&(n.commentForPrefix=r.commentForPrefix),"string"==typeof r.commentIfPrefix&&(n.commentIfPrefix=r.commentIfPrefix),"string"==typeof r.commentElseIfPrefix&&(n.commentElseIfPrefix=r.commentElseIfPrefix),"string"==typeof r.commentElsePrefix&&(n.commentElsePrefix=r.commentElsePrefix),"string"==typeof r.locale&&(n.locale=r.locale),"boolean"==typeof r.debug&&(n.debug=r.debug),"boolean"==typeof r.enableMustache&&(n.enableMustache=r.enableMustache),"boolean"==typeof r.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=r.enableDirectionalInitialSync),"boolean"==typeof r.enablePropagationContext&&(n.enablePropagationContext=r.enablePropagationContext),"boolean"==typeof r.enableContractAnalyzer&&(n.enableContractAnalyzer=r.enableContractAnalyzer),"boolean"==typeof r.sameValueGuard&&(n.sameValueGuard=r.sameValueGuard)),gc(t),function(){const e=globalThis;void 0===e[s]&&(e[s]=Ha)}()}let bc=0;const vc=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],$c=new Set;function xc(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function Sc(e,t,n,o,s,r=new Set){0===n.length&&Z(`Cannot build a mount record without host bindings for "${t}".`);const i=[],a=new Set;let c=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(l);a.has(n)&&Z("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(g)};i.push(o),0===t.length&&(c=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++bc,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)e.innerSegments.length>0&&p.add(e.innerSegments[0]);const m={};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)||(m[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+l+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,privateSnapshot:m,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function Pc(e){const t=e.indexOf(l);return-1===t?e:e.slice(0,t)}function Ic(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 Nc(e,t){for(const n of e.entries)if(Ic(t,n.innerSegments)){const e=t.slice(n.innerSegments.length);return 0===e.length?n.outerPathInfo.path:n.outerPathInfo.path+l+e.join(l)}return null}function kc(e,t){return e.markerBasePath+l+t}function _c(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+l+n;s.set(n,{accessorName:o,indexShift:ne(r).wildcardCount-ne(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function Ac(e,t){return!e.injectedKeys.has(t)&&!e.mappedKeys.has(t)&&("function"==typeof e.stateObject[t]&&!e.getterKeys.has(t)||Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t))}function Cc(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(l)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${Pc(t)}: path") or declare the key on the component state.`}const Ec=/^\$(\d+)$/;function Mc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=Pc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||Ac(e,o))return null;const s=function(e,t){for(const n of e.entries)if(Ic(t,n.innerSegments))return n;return null}(e,t.split(l));return null!==s&&s.readonly?s:null}function Oc(e,t){const n=Mc(e,t);if(null!==n){const o=0===n.innerSegments.length?"":l+n.innerSegments.join(l);Z(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${g}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${g} from the mount.`)}return Tc(e,t)}function Tc(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(l);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===c){o=e;break}if(-1===o)return _c(e,e.markerBasePath,t,t),kc(e,t);if(Ac(e,n[0]))return _c(e,e.markerBasePath,t,t),kc(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Nc(e,s);null===i&&Z(Cc(e,t)),0===r.length&&Z(`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+l+e.marker;return _c(e,a,r.join(l),t),a+l+r.join(l)}(e,t);const o=Pc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return kc(e,t);if(Ac(e,o))return kc(e,t);const s=Nc(e,t.split(l));if(null!==s)return s;Z(Cc(e,t))}function Rc(e,t,n){let o;const s=Ec.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ne(Tc(e,t)).wildcardCount-ne(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Tc(e,t.statePathName),"for"===t.bindingType){const n=ne(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+l+c,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(g)&&null!==Mc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ne(o),...i?{propModifiers:[...r,g]}:{}}:t}function jc(e,t,n,o,s){if(void 0===o)return;const r=ne(n).wildcardCount-ne(t).wildcardCount;return 0===r?o:(s.length<r&&Z(`Cannot resolve "${t}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const Lc=new WeakMap,Wc=new WeakMap;const Dc=new WeakMap;const Bc=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)}),zc=new WeakMap;function Fc(e){return zc.get(e)??null}let qc=!1;function Vc(){qc||(qc=!0,ft=e=>Lc.has(e)?e.host:null)}function Hc(e){const t=Dc.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 Uc(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Dc.get(e);if(void 0===o)return null;const s=t.indexOf(l,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 Gc="3.0.0",Kc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Jc(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 Xc(e){const t=function(e){const t=Qs.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:nr.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 Qc="__WCSTACK_DEVTOOLS_HOOK__";function Yc(){const e=globalThis,t=e[Qc];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[Qc]=n,n}const Zc=e=>{null!==mt&&mt({type:"state:update-batch",addresses:e})};function ed(e){const t=null!==mt;!function(e){mt=e}(e);const n=null!==e;n&&!t?Us(Zc,0):!n&&t&&function(e){const t=qs.findIndex(t=>t.listener===e);-1!==t&&qs.splice(t,1)}(Zc)}function td(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 nd(e){return pa(e)??Z("devtools: no state tree on this root")}let od=null;function sd(){if(t())return;if(null!==od)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Gc,getStateElements(){const e=[];for(const t of fa)e.push(td(t));return e},overlays:e=>Hc(nd(e)).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join("."),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]})),keyedSubscriptions:e=>Xc(nd(e)),keys(e){const t=nd(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 nd(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){nd(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>function(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=[...e.inFilters,...e.outFilters].map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=$a(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(Jc(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=Qe(t,_e(n));for(const o of e)r(Jc(t,o,"attribute",n))}catch{}continue}const t=Kc.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=$a(s);if(null===a){if(n===o.commentTextPrefix)try{r(Jc(e,Oe(s),"comment",s))}catch{}}else r(Jc(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:ed};od=e,Yc().register(e)}const rd={name:"devtools",install(){sd()}},id=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),ad=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const ld=new WeakMap;const cd=new WeakMap,dd=new WeakSet,ud=new WeakMap;function fd(e,t,n,o){console.warn(`[@wcstack/state] [${Ri[n]}] ${ji[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${re(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ie}`),null!==mt&&mt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const hd={check:function(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=e.addressHooks;if(s){const t=s.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const r=ne(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=ld.get(e);return void 0===n&&(n=new Set,ld.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const i=function(e,t,n){if(void 0!==Oi(e,t))return ad;const o=ne(t).segments;let s=e,r="";for(let t=0;t<o.length;t++){const i=o[t],a=r;if(r=0===t?i:r+l+i,t>0&&t<o.length-1&&void 0!==Oi(e,r))return id;if(Object(s)!==s)return id;if(i===c){if(!Array.isArray(s)||0===s.length)return id;s=s[0];continue}const d=Oi(s,i);if(void 0===d)return{existence:"missing",missingSegment:i,candidates:Ti(s,a,n)};if("function"==typeof d.get)return t===o.length-1?ad:id;s=d.value}return ad}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===ud.get(e)?.has(t)}(e,n)||("binding"!==o?fd(e,n,o,i):function(e,t,n){let o=cd.get(e);void 0===o&&(o=new Map,cd.set(e,o));if(o.set(t,n),dd.has(e))return;dd.add(e),setTimeout(()=>function(e){dd.delete(e);const t=cd.get(e);if(void 0===t)return;cd.delete(e);for(const[n,o]of t)fd(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){ld.delete(e),cd.delete(e)},markExported:function(e,t){let n=ud.get(e);void 0===n&&(n=new Set,ud.set(e,n)),n.add(t),cd.get(e)?.delete(t)}};let pd=!1;function md(){pd||(pd=!0,function(e){uc=e}(hd))}const gd={name:"diagnostics",install(){md()}};function yd(e){Z(`filter ${e} requires at least one option`)}function wd(e){Z(`filter ${e} requires a number as option`)}function bd(e){Z(`filter ${e} requires a number value`)}function vd(e){Z(`filter ${e} requires a date value`)}function $d(e){return!(!e||isNaN(Number(e)))}const xd={eq:(e,t)=>{const n=e?.[0]??yd("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?($d(n)||wd("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??yd("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?($d(n)||wd("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>("boolean"!=typeof e&&Z(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??yd("lt");return $d(t)||wd("lt"),e=>("number"!=typeof e&&bd("lt"),e<Number(t))},le:e=>{const t=e?.[0]??yd("le");return $d(t)||wd("le"),e=>("number"!=typeof e&&bd("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??yd("gt");return $d(t)||wd("gt"),e=>("number"!=typeof e&&bd("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??yd("ge");return $d(t)||wd("ge"),e=>("number"!=typeof e&&bd("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??yd("inc");return $d(t)||wd("inc"),e=>("number"!=typeof e&&bd("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??yd("dec");return $d(t)||wd("dec"),e=>("number"!=typeof e&&bd("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??yd("mul");return $d(t)||wd("mul"),e=>("number"!=typeof e&&bd("mul"),e*Number(t))},div:e=>{const t=e?.[0]??yd("div");return $d(t)||wd("div"),e=>("number"!=typeof e&&bd("div"),e/Number(t))},mod:e=>{const t=e?.[0]??yd("mod");return $d(t)||wd("mod"),e=>("number"!=typeof e&&bd("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&bd("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??yd("clamp");$d(t)||wd("clamp");const n=e?.[1]??yd("clamp");$d(n)||wd("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&bd("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return $d(t)||wd("fix"),e=>("number"!=typeof e&&bd("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&bd("locale"),e.toLocaleString(t??o.locale))},uc:e=>e=>String(e).toUpperCase(),lc:e=>e=>String(e).toLowerCase(),cap:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??yd("slice");$d(n)||wd("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&($d(o)||wd("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??yd("substr");$d(t)||wd("substr");const n=e?.[1]??yd("substr");return $d(n)||wd("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??yd("pad");$d(t)||wd("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??yd("rep");return $d(t)||wd("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??yd("truncate");$d(t)||wd("truncate");const n=Number(t),o=e?.[1]??"…";return e=>{const t=String(e);return t.length<=n?t:t.slice(0,n)+o}},join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||Z(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=e?.[0]??"0";return $d(t)||wd("round"),e=>{"number"!=typeof e&&bd("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return $d(t)||wd("floor"),e=>{"number"!=typeof e&&bd("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return $d(t)||wd("ceil"),e=>{"number"!=typeof e&&bd("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return $d(t)||wd("percent"),e=>("number"!=typeof e&&bd("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??yd("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||vd("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||vd("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||vd("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||vd("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||vd("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]??yd("defaults"),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),null:e=>e=>""===e?null:e},Sd={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],inc:[0,1],dec:[0,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],fix:[0,1],locale:[0,1],uc:[0,0],lc:[0,0],cap:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],pad:[1,2],rep:[1,1],rev:[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,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],boolean:[0,0],number:[0,0],string:[0,0],null:[0,0]},Pd=xd,Id=xd;let Nd=!1;const kd={name:"formats",install(){Nd||(Nd=!0,fe("input",Id,Sd),fe("output",Pd,Sd))}};function _d(e){return-1!==e.indexOf(V)}function Ad(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+l;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(_d(o))return null;const s=o.slice(1).split(l);return s[0]===c||s.some(e=>0===e.length)?null:o}function Cd(e){return 0===e.length?e:l+Od(e.slice(1))}function Ed(e,t,n){const o=l+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 Md(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(l,o-1))if(Ed(e,t,n.slice(0,o)))return!0;return!1}function Od(e){const t=e.split(l);for(let e=0;e<t.length;e++)t[e]===c||Number.isNaN(Number(t[e]))||(t[e]=c);return t.join(l)}function Td(e,t){const n=e.repeat.split(l),o=l+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===l+e.repeatList+l+"length")return!0;for(let e=1;e<n.length;e++)if(s===l+n.slice(0,e).join(l))return!0;return!1}function Rd(e,t,n){n<0&&Z(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=l+e.repeat;const s=o+t;let r=0;for(const e of s.split(l))e===c&&r++;return r>d&&Z(`[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 jd(e,t){return Rd(e,"",t)}function Ld(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=l+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 Wd(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=l+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 Dd(e,t,n){const o=e.recursionRegistry,s=Ad(o.spec,n);null===s&&Z(Wi(n,o.spec.recursiveAnchor));const r=Wd(t,o);return null===r&&Z(`[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 Bd(e,t,n,o,s){const r=o.spec,i=[],a=new Map,c=[],d=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(hn(e,n));const s=m(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function m(o,s,i){const l=hn(o,s),c=qt(n.stateElement,l),u=vl(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)&&Z(`[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)&&Z(`[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 "${d}" array.`),o})(o.path,u,i),p=Nr(s,St(c),u);return a.set(c,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const g=(e,t,n)=>{const{rows:r,tracked:a}=m(t,n,h);if(0===r.length)return;const u=(e=>{const t=c[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:ne(n),childListPathInfo:ne(r+l+d)};return c[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(hn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),g(e+1,u.childListPathInfo,n)}f.delete(y)};g(0,ne(u),null);for(const[e,t]of a)Pt(e,t);return i}function zd(e,t,n,o,s,r,i){dl(n);const a=n.stateElement.recursionRegistry,l=Ad(a.spec,o);null===l&&Z(Wi(o,a.spec.recursiveAnchor));const c=Cd(l);Array.isArray(s)||Z(Di(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&Z(`[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&&Z(Di(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&Z(Di(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){Td(e,n)&&Z(`[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&&Z(`[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=Bd(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Hl(e,u[o],r,t,n),f++);return f}const Fd={write(e,t){if(!0!==e.hasRecursion)return tl;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&Z(`[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.`),tl},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return tl;if("$getAll"===t)return(t,s)=>{if(_d(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Ad(r.spec,o);null===i&&Z(Wi(o,r.spec.recursiveAnchor)),Array.isArray(s)||Z(`[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&&Z(`[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=Bd(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(vl(e,a[o],t,n));return l}(o,n,e,t,s);t=Dd(e.stateElement,e,t)}return Kl(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>_d(t)?zd(o,n,e,t,s,r,i):Xl(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&_d(t)){const s=hl(Dd(e.stateElement,e,t)),r=Jl(o,s,n,e);return vl(o,hn(s.pathInfo,r),n,e)}return tl}};let qd=!1;function Vd(e,t){"string"==typeof t&&0!==t.length||Z(`[wcs/recursion-declaration-invalid] ${q} ${e} must be a non-empty string.`);const n=t.split(l);n.some(e=>0===e.length)&&Z(`[wcs/recursion-declaration-invalid] ${q} ${e} "${t}" must not contain empty path segments.`),n.length<2&&Z(`[wcs/recursion-declaration-invalid] ${q} ${e} "${t}" must name a list element: a property path ending with "${l}${c}" (for example "nodes${l}${c}").`),n[n.length-1]!==c&&Z(`[wcs/recursion-declaration-invalid] ${q} ${e} "${t}" must end with "${l}${c}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&Z(`[wcs/recursion-declaration-invalid] ${q} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&Z(`[wcs/recursion-declaration-invalid] ${q} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===c&&Z(`[wcs/recursion-declaration-invalid] ${q} ${e} "${t}" must have exactly one "${c}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===V&&Z(`[wcs/recursion-declaration-invalid] ${q} ${e} "${t}" must not contain "${V}" — the declaration is what gives "${V}" its meaning.`),isNaN(Number(n[o]))||Z(`[wcs/recursion-declaration-invalid] ${q} ${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 Hd=new WeakSet;function Ud(e){return"function"==typeof e.get&&Hd.has(e.get)}function Gd(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Ud(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}!function(e,t,n){for(const o of n){const n=ne(o),s=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void Ws(Vt(e,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=t;for(const e of s[i].segments.slice(a))l=l?.[e];if(!Array.isArray(l))return;const c=Ts(l);if(null===c)return;const d=Math.min(c.length,l.length);for(let e=0;e<d;e++)r(l[e],c[e],i+1)};r(t,null,0)}}(e,t,n)}}const Kd="[wcs/recursion-declaration-invalid]";class Jd{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=dc(t);for(const[t,o]of Object.entries(n)){if(!_d(t))continue;"function"==typeof o.set&&Z(`${Kd} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&Z(`${Kd} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Ad(e,t);null===n&&Z(Wi(t,e.recursiveAnchor)),0===n.length&&Z(`${Kd} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${l}total"), not the node.`),Td(e,Cd(n))&&Z(`${Kd} "${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}${l}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(_d(t)||Ud(n))continue;const e=this._matchExpansion(t);null!==e&&Z(`${Kd} "${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++)Ed(this.spec,e[t].suffix,e[n].suffix)&&Z(`${Kd} "${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(Md(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=Od(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(l);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(l,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!==Ld(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=Ld(this.spec,e.suffix,t);null!==n&&(null!==o&&Z(`"${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||Ud(s)||Z(`"${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,Hd.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(jd(e,o)+l+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 Gd(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=Rd(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 Xd="recursionSpec",Qd="recursionRegistry",Yd={order:5,validateEarly(e,t,n){const o=function(e){const t=e[q];if(void 0===t)return null;"object"==typeof t&&null!==t||Z(`[wcs/recursion-declaration-invalid] ${q} 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&&Z(`[wcs/recursion-declaration-invalid] ${q} must declare exactly one anchor; it is empty.`),n.length>1&&Z(`[wcs/recursion-declaration-invalid] ${q} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Vd("anchor",o),"string"!=typeof s&&Z(`[wcs/recursion-declaration-invalid] ${q} entry "${o}" must map to the repeating sub-path as a string (for example "children${l}${c}").`),Vd("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(l)),i=s.slice(0,s.lastIndexOf(l)),a=r+l+V;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(Xd,o),n.set(Qd,null===o?null:new Jd(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(Qd)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",q)},apply(e,t,n){const o=n.get(Xd)??null;null!==o&&e.addListPath(o.anchorList)}};let Zd=!1;function eu(){Zd||(Zd=!0,qd||(qd=!0,sl("recursion",Fd)),ll("recursion",Yd))}const tu={name:"recursion",install(){eu()}};const nu={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let ou=!1;function su(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 ru(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 iu(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 au(e){return e.startsWith("$")}function lu(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 cu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||Z(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||Z(`${t} entries must be non-empty strings.`),e.startsWith("$")&&Z(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&Z(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function du(e){const t=cu(e,T)??[],n=cu(e,R)??[],o=dc(e),s=function(e){const t=e[B];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}Z(`${T} entry "${e}" is not declared on the state.${re(e,lu(o,"value"))}`)}"function"==typeof t.value&&Z(`${T} entry "${e}" is a method. Declare it in ${R} instead.`)}for(const e of n){const t=o[e];void 0===t&&Z(`${R} entry "${e}" is not declared on the state.${re(e,lu(o,"method"))}`),"function"!=typeof t.value&&Z(`${R} entry "${e}" is not a method. Declare it in ${T} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function uu(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||Z(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Fe(e);null!==r&&"function"==typeof r.define||Z(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&Z(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=du(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(K))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const e=Fe(this._shadow);return null!==e&&qe(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(m.bindableEventMap).length>0){const t=e.querySelector(p);t?(ou||(ou=!0,sl("dcc",nu)),t.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${T} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=dc(n);for(const[e,t]of Object.entries(g)){if(au(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=iu(e,o)}else n.get=su(e),n.set=ru(e);Object.defineProperty(m.prototype,e,n)}for(const e of u)Object.defineProperty(m.prototype,e,{configurable:!0,enumerable:!0,get:su(e),set:ru(e)});r.define(s,m)}async function fu(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&Z(`"bind-component" cannot be used inside a [${K}] 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 Ja(t);Z(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await Ka(n,t.tagName.toLowerCase());Z(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){Z(`DCC: Failed to load state: ${e}`)}}(o,t);uu(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const hu={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(K)?fu(e,t.host,t):null}};let pu=!1;const mu=new WeakMap;function gu(e,t,n){let o=mu.get(e);void 0===o&&(o=new Map,mu.set(e,o));const s=o.get(t);null!=s&&Z(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function yu(e,t){if(null===e)return!1;const n=mu.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+l)||e.startsWith(t+l))return!0;return!1}const wu=new WeakMap;function bu(e,t){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{t.$postUpdate(e+l+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...s)=>t[n](e+l+o,...s)}return t[o]}return t[e+l+o]}},set:(n,o,s)=>("string"!=typeof o||(t[e+l+o]=s),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const vu=new WeakMap,$u=[];const xu=new WeakMap,Su=new WeakSet;function Pu(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 Iu=null;const Nu=new WeakMap,ku=new Set;function _u(e,t,n,o){let s=Nu.get(e);if(void 0===s){if(!o)return null;s=new Map,Nu.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 Au(e,t){if(!e.component.isConnected)return!1;const n=ht(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 Cu(e,t,n,o){const s=_u(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&&Au(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?Au(r,o)&&(null!==a&&Z(`[wcs/mount-export-ambiguous] "${t}${l}${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 Eu(e){const t=e.parentStateElement,n=ht(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[_t](n,()=>{e.$postUpdate(o.exportedPath)})})}const Mu=new WeakMap;class Ou{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return hn(ne(this.markerParentPath+l+e),this.listIndex)}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(Tc(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Oc(e,t):Tc(e,t),a=jc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Oc(e,t):Tc(e,t),l=jc(0,t,a,r,n);return o[s](a,l,...i)}}return this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return ml(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[Tc(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)||Z(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(t)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(e,t)?(e[t]=n,!0):(this.receiver[Oc(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 Tc(this.record,t),!0}catch{return!1}}}function Tu(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Mu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Mu.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 Ou(e,s,t.listIndex,r,n,o))}function Ru(e){const t=e.parentStateElement,n=(t,n)=>{const o=ht(e.component);let s;return t[_t](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(Tc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Oc(e,n):Tc(e,n),l=ht(e.component)?.listIndex.indexes??[],c=jc(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:Tc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Oc(e,s)]=r})}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return Tc(e,n),!0}catch{return!1}}})}function ju(e,t){const n=function(e){return Lc.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&Z(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&as(t).dispose(),function(e,t){Vc(),Lc.set(e,t),zc.set(t,e);let n=Dc.get(t.parentStateElement);void 0===n&&(n=new Map,Dc.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Wc.get(t.component);void 0===o&&(o=new Map,Wc.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Bc.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=da.get(e);if(void 0!==n){if(n===t)return;Z("A state tree is already registered on this root.")}da.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Rc(e,t,n);Q(t);const o=ht(e.component);Wa(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),na(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=Tc(e,n)}catch{continue}const o=t.indexOf(l+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)+l+r,a=ne(i);if(a.wildcardCount!==e.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,c),_u(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:c}),e.parentStateElement.addDynamicDependency(t,i),uc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=ht(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(ku.has(s))continue;const r=ne(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[_t](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(ku.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),Eu(e),o=t,s=Promise.resolve(),ua.set(o,s),s.then(()=>ya(o),()=>{})}function Lu(e,t){const n=as(t),o=ht(e.component);n.forEachActiveBindingNode(e=>pt(e,o));ta(n.rebindAddresses()),Eu(e)}function Wu(e,t){if(function(e){const t=Dc.get(e);return void 0!==t&&t.size>0}(t))for(const n of Hc(t)){if(!Du(n.component,e))continue;const t=Fc(n);null!==t&&Lu(n,t)}}function Du(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 Bu={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Uc(e,t.pathInfo.path);if(null!==s)return Tu(s,t,n,o)}return tl},readMissing(e,t,n,o,s){if(null===n){if(yu(e.rootNode??null,t.pathInfo.path))return;return tl}if(!0===e.hasMounts){const n=Cu(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Tu(e,hn(ne(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return tl},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=wu.get(e);if(void 0===n||0===n.size)return null;const o=t+l;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&Z(`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 tl},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Cu(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Tu(e,hn(ne(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return tl},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Uc(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(l,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=Lc.get(n);if(void 0!==e)return e;n=n.parentNode}return Lc.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 vu.get(e)??$u}(e);for(const s of o){const o=s.mountPath+l,r=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(t!==s.mountPath&&!t.startsWith(o))continue;if(-1!==t.indexOf("#"))continue;const a=t===s.mountPath?"":t.slice(o.length);if(""===a)continue;r.add(a);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const e=Qt(n.listIndex,l);(i[a]??=[]).push(e)}}if(r.size>0)try{s.callback.call(bu(s.mountPath,n),Array.from(r),i)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>yu(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){Wu(t,e)}};let zu=!1;const Fu=new WeakMap;function qu(e){let t=Fu.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Fu.set(e,t)),t}function Vu(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=mu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function Hu(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{gu(n,s,e)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return pa(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Uu(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");try{!function(e){0===e.length&&Z('"mount" requires a non-empty tree path.');const t=ne(e);for(const n of t.segments)0===n.length&&Z(`"mount" path "${e}" has an empty segment.`),n===c&&Z(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&Z(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),n.hasAttribute("bind-component")&&Z('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),gu(s,r,e),pa(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===pa(s)&&function(e,t){const n=()=>{if(null!==pa(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const i=n=>{t.graftInfo=n,e.markInitialized(),null===n&&Vu(e,t),e.settleInitialization()};let a;try{a=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void i(null)}const l=e.connectedRootNode??null;null!==l&&Hu(e,t,l)?function(e,t,n,o,s,r){const i={mountPath:n,volumeState:o,onGrafted:s,acquireSlot:r};if(null!==t)return void Zh(t,i);tp(),function(e,t){if(Su.has(e))return void Pu(t);let n=xu.get(e);void 0===n&&(n=[],xu.set(e,n)),n.push(t)}(e,i)}(l,pa(l),r,a,i,()=>Hu(e,t,l)):i(null)}const Gu={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=qu(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{gu(n,t.mountPath,e),pa(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,sc}return Uu(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=qu(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&pa(n)===t.graftInfo.rootStateElement&&Xh(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Fu.get(e)?.initializing)return;const t=e.getAttribute("mount");Z(`Cannot replace the state of <${o.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){Su.add(e);const t=xu.get(e);if(void 0!==t){xu.delete(e);for(const e of t)Pu(e)}}(t)},initializeFailureCleared(e,t){!function(e){Su.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=qu(e);return null!==t.graftInfo&&Xh(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,Vu(e,t)),e.clearConnectedRootNode(),!0}};let Ku=!1;const Ju=new WeakMap;function Xu(e,t){let n=Ju.get(e);n||(n=new Set,Ju.set(e,n)),n.add(t)}const Qu=new WeakMap;const Yu=new WeakMap,Zu=new WeakMap;const ef=new WeakMap;const tf={isComplete:function(e,t){return!0===Ju.get(e)?.has(t)},isDeclared:function(e,t){return!0===Qu.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=Yu.get(e);o||(o=new Map,Yu.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=Zu.get(e);o||(o=new Map,Zu.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=ef.get(e);s||(s=new Map,ef.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function nf(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 of=new WeakMap;class sf{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=of.get(e);return n?n.get(t)??null:null}(e,t)??Z("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 rf=e=>()=>e;function af(e,t,n,o){!function(e,t,n){let o=of.get(e);o||(o=new Map,of.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(nf(o));const s=function(e,t){const n=new sf(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:rf(s),enumerable:!0,configurable:!0}),Xu(t,n),lf(t,n)}function lf(e,t){if(O in e){const n=e[O];"function"==typeof n?n.call(e,t).catch(e=>{Z(`Error in ${O}: ${e instanceof Error?e.message:String(e)}`)}):Z(`${O} is not a function.`)}}const cf=new Set;function df(e,t){cf.has(e)||(cf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function uf(e){const t=e.rootEntry,n=ht(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[_t](n,()=>{o=e[t.outerPathInfo.path]})}),o}const ff=new WeakMap;function hf(e,t){e.landInitialization(),Z(t)}async function pf(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?Be(a):null;null!==a&&null!==l||Z(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||hf(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&&Z(`"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=Qu.get(e);n||(n=new Set,Qu.set(e,n)),n.add(t)}(a,d);const u=Fe(a);null===u&&Z(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await Le(a),d in a||Z(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||Z(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=Yu.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(o.bindAttributeName))return!1;const n=tt(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||(tt(a)??[]).some(e=>e.propSegments[0]===d)||hf(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(o.bindAttributeName)){const o=(tt(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=pa(a.getRootNode())??hf(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,Wc.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(function(e,t,n){const o=ef.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;ef.get(e).delete(t)}}(a,d,f),u=Sc(a,d,o,c,f,function(e,t){return Zu.get(e)?.get(t)}(a,d)),function(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=uf(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;df(`${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.`)}}(u)),t.mountRecord=u,n.parentNode!==i)return;try{ju(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Ru(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),Xu(a,d)}return lf(a,d),function(e){const t=vc.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(V)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;$c.has(n)||($c.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 xc(u,"$connectedCallback")}}af(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const mf={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=ff.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},ff.set(e,t)),t}(e);return pf(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=ff.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&Lu(n,o)}),xc(n,"$connectedCallback"),!0},disconnecting(e){const t=ff.get(e);return void 0!==t&&null!==t.mountRecord&&(xc(t.mountRecord,"$disconnectedCallback"),Eu(t.mountRecord),e.clearConnectedRootNode(),!0)}};let gf=!1;function yf(){gf||(gf=!0,ac("bindComponent",mf),cs=tf)}const wf=new WeakMap,bf=new Set,vf=new Set;function $f(e){return e.byFromPath.size>0||e.byResetPath.size>0}function xf(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function Sf(e){return wf.get(e)}function Pf(e){If(e),wf.delete(e)}function If(e){bf.delete(e),vf.delete(e)}const Nf=new WeakMap,kf=new WeakMap,_f=new Set,Af=new Map;function Cf(e){return Nf.get(e)??Af}function Ef(e){_f.add(e),function(e){const t=wf.get(e);void 0!==t&&($f(t)&&bf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&vf.add(e))}(e)}const Mf=new Map;function Of(e){return kf.get(e)??Mf}function Tf(e){0===e.length&&Z(`[wcs/watch-declaration-invalid] ${z} entry name must be a non-empty state path.`),e.startsWith("$")&&Z(`[wcs/watch-declaration-invalid] ${z} entry "${e}" must not start with "$" (reserved namespace).${ie}`),e.includes("@")&&Z(`[wcs/watch-declaration-invalid] ${z} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ie}`),e in Object.prototype&&Z(`[wcs/watch-declaration-invalid] ${z} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ne(e);for(const n of t.segments)0===n.length&&Z(`[wcs/watch-declaration-invalid] ${z} entry "${e}" has an empty path segment.${ie}`);return t.wildcardCount>d&&Z(`[wcs/watch-declaration-invalid] ${z} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Rf(e,t){const n=t[z];if(void 0===n)return null;"object"==typeof n&&null!==n||Z(`[wcs/watch-declaration-invalid] ${z} must be an object mapping state paths to handler functions.${ie}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&Z(`[wcs/watch-declaration-invalid] ${z} entry "${t}" must be a function.${ie}`);const n=Tf(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Nf.set(e,t)}(e,o),s.size>0?s:null}let jf=0,Lf=0;function Wf(e){jf=e+1}function Df(){jf=0}function Bf(){jf>Lf&&(Lf=jf)}const zf=new WeakMap;function Ff(e,t,n){let o=zf.get(e);void 0===o&&(o=new Map,zf.set(e,o)),o.set(t,n)}const qf=new Map;function Vf(e,t){qf.has(e)||qf.set(e,t)}function Hf(e){return qf.get(e)}const Uf={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||Vf(n,o)},swapped(e,t,n){var o;o=n,qf.has(o)&&Vf(t,Hf(n))}};function Gf(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ms(t))return!0;return!1}function Kf(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[At](hn(t.wildcardParentPathInfos[i],r)),l=Ts(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=Xt(o,i,t.wildcardCount);if(l!==c&&!As(l,c)){if(Ms(c))return"gone";s="replaced"}r=l}return s}function Jf(e,t,n){const o=new Map;for(const s of n){const n=Kf(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 Xf=new Set;function Qf(e){Xf.delete(e)}function Yf(){return Xf}const Zf=Symbol("wcs-stream-last-notified-uncertain"),eh=new WeakMap;function th(e,t){const n=eh.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function nh(e,t){const n=eh.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Zf,error:Object.is(o.error,null)?null:Zf})}const oh=new WeakMap;function sh(e){return oh.get(e)??new Map}function rh(e){Qf(e);const t=oh.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,nh(e,n.name)}const ih=new WeakSet;let ah=0;function lh(e){return Sf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function ch(e){if(0===vf.size)return;if(t=e.absolutePathInfo.stateElement,!vf.has(t))return;var t;const n=lh(e);if(void 0!==n)for(const e of n)dh(e)}function dh(e){ih.has(e)||(ih.add(e),ah++)}function uh(e){return!!ih.delete(e)&&(ah--,!0)}const fh=/^(?:0|[1-9]\d*)$/;function hh(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function ph(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&&fh.test(t)&&hh(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&hh(e,t))?"object":null}function mh(e,t){const n=ph(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]=mh(o[e],t);return r}function gh(e){return mh(e,new Map)}function yh(e,t,n){if(Object.is(e,t))return!0;const o=ph(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(ph(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(!yh(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&yh(s[e],r[e],n))}function wh(e,t){return yh(e,t,new Map)}const bh=new WeakMap;function vh(e,t){if("function"!=typeof t)return;const n=bh.get(t);void 0===n?bh.set(t,new Set([e])):n.add(e)}const $h={"read-source":e=>`${F} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${F} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${F} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${F} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${F} could not write the output "${e}".`},xh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Sh(e,t,n){null!==mt&&mt({type:"state:watch-error",phase:t,path:`${F}.${e}`,error:n})}function Ph(e,t,n){console.error(`[@wcstack/state] ${$h[n](e)}`,t),Sh(e,xh[n],t)}function Ih(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Nh(e,t){t.then(void 0,()=>{}),Ph(e,new TypeError(`${F} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const kh=new WeakSet;const _h=Object.freeze([]);function Ah(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function Ch(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 Eh(e,t){return t.has(e.stateElement)&&!0===Sf(e.stateElement)?.entries.has(e.entry)}function Mh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Oh(n,e))||uh(t)}function Oh(e,t){return Xs().hasQueuedPath(e,t)}function Th(e,t){!function(e,t,n){if(0!==ah)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=lh(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||uh(t)}}(e,t,Oh)}function Rh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function jh(e,t,n){if(!Eh(e,n))return Mh(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(kh.has(e))return;kh.add(e);const o=`[wcs/scan-source-computed] ${F} 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}`),Sh(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=sh(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name],o=0===r.pathInfo.wildcardCount?e.rows:Jf(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Ch)){let n;try{n=Rh(t,r,e)}catch(e){Ph(s.name,e,"read-source");continue}const o=a(l,n,Hf(e.absAddress),...e.indexes);if(Ih(o))return void Nh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){Ph(s.name,e,i.failure)}return i.plan}function Lh(e,t){const{group:n}=e;if(!Eh(n,t))return void Mh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||uh(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!wh(o,s.initial):!Object.is(o,e.next)){const o=n.reset?gh(s.initial):e.next;t[s.name]=o,vh(s.name,o)}})}catch(e){Ph(s.name,e,"write")}}function Wh(e,t,n){if(Th(e,t),0===bf.size)return _h;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=Sf(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=Qt(n.listIndex,r.wildcardCount)}for(const s of i)Ah(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)Ah(o,e,t).reset=!0}if(0===o.size)return _h;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];Wf(n);try{for(const n of s){const o=jh(n,e,t);null!==o&&r.push(o)}}finally{Df()}return r}function Dh(e){Kh(),(0!==Cf(e).size||0!==Of(e).size||function(e){const t=wf.get(e);return void 0!==t&&$f(t)}(e))&&(Ef(e),function(e){const t=[];for(const n of Cf(e).values())Bh(e,n)&&t.push(n);for(const n of Of(e).values())for(const o of n)Bh(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{Ff(e,Vt(e,o.pathInfo,null),n[o.path])}catch(t){Fh(e,o.path,"prime",t)}})}(e))}function Bh(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const zh={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Fh(e,t,n,o){console.error(`[@wcstack/state] $watch ${zh[n]} "${t}" threw.`,o),null!==mt&&mt({type:"state:watch-error",phase:n,path:t,error:o})}function qh(e){const t=_f;try{if(0===t.size)return void Th(e,t);const n=function(){const e=Lf;return Lf=0,e}();if(n>32){Th(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!==mt&&mt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){Wf(n);try{for(const n of e)Lh(n,t)}finally{Df()}}}(Wh(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Cf(e).get(s),i=Of(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=Qt(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Hh);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(Gf(o.absAddress.listIndex)||s?.entry===o.entry&&Vh(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(Jf(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){Fh(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);Wf(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Cf(e.stateElement).get(e.entry.path)===e.entry,o=!0===Of(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&Uh(e)}}finally{Df()}}(e,t,n)}finally{qf.clear()}}function Vh(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Hh(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 Uh(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Bh(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 Fh(0,n.path,"evaluate",e)}const a=r?function(e,t){return zf.get(e)?.get(t)}(t,o):Hf(o);r&&Ff(t,o,i),null!==mt&&mt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Fh(0,n.path,"handler",e)}}let Gh=!1;function Kh(){Gh||(Gh=!0,sl("watch",Uf),ll("watch",Jh),Us(qh,10),Hs(Bf))}const Jh={order:10,register(e,t){var n;n=e,_f.delete(n),If(n),Nf.delete(n),function(e){zf.delete(e)}(e);const o=Rf(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?z:F)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Dh(e)},deactivate(e){var t;t=e,_f.delete(t),If(t)}};function Xh(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(bu(e.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function Qh(e,t,n){const o=n[z];if(void 0!==o){const n=[],s=new Set;let r=0;for(const[i,a]of Object.entries(o)){const o=t+l+i,c=function(e,n,...o){a.call(bu(t,this),e,n,...o)};n.push({path:o,pathInfo:ne(o),handler:c,order:1e6+r++}),s.add(o),e.setPathInfo(o,"prop","watch")}n.length>0&&(!function(e,t){let n=kf.get(e);void 0===n&&(n=new Map,kf.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}(e,n),e.addVolumeWatchPaths?.(s),Dh(e))}const s=n[H];if(void 0!==s){const n=new Map;for(const[e,o]of Object.entries(s))n.set(t+l+e,o);e.mergeVolumeListKeys?.(n)}const r=n[E];"function"==typeof r&&(!function(e,t){let n=vu.get(e);void 0===n&&(n=[],vu.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,callback:r}),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 Yh(e,t,n){!function(e,t,n){const o=n[z];if(void 0!==o){"object"==typeof o&&null!==o||Z(`${z} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(o))"function"!=typeof t&&Z(`${z} entry "${e}" must be a function.`),Tf(e)}const s=n[H];if(void 0!==s){"object"==typeof s&&null!==s||Z(`${H} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(s))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&Z(`${H} entry "${n}" must map a list path to a field name or a key function.`),e.listKeys?.has(t+l+n)&&Z(`${H} entry "${t+l+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&Z(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&Z(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[q]&&Z(`Volume "${t}" declares ${q}, 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(dc(n)))-1!==e.indexOf(V)&&Z(`Volume "${t}" declares "${e}", which uses "${V}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n);const{data:o,accessors:s}=function(e){const t={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(e)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(t[o]=s.value):n.set(o,s));return{data:t,accessors:n}}(n),r=ne(t),i=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===r.segments.length&&t in e){if(i)return;Z(`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<r.segments.length-1;t++){const o=r.segments[t],s=""===n?o in e:void 0!==e[n+l+o];n=""===n?o:n+l+o,s||(e[n]={})}if(r.segments.length>1&&void 0!==e[t]){if(i)return;Z(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=o}),function(e,t){let n=wu.get(e);void 0===n&&(n=new Set,wu.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,o]of s){const s=t+l+n,r=o.get,i=o.set,a={enumerable:!1,configurable:!0};"function"==typeof r&&(a.get=function(){return r.call(bu(t,this))}),"function"==typeof i&&(a.set=function(e){i.call(bu(t,this),e)}),e.defineTreeAccessor(s,a)}Qh(e,t,n);const a=n.$connectedCallback;return"function"==typeof a&&e.createState("writable",e=>{let n;try{n=a.call(bu(t,e))}catch(e){return void console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)}n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n}}function Zh(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=Yh(e,t.mountPath,t.volumeState)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let ep=!1;function tp(){var e;ep||(ep=!0,zu||(zu=!0,sl("scopes",Bu)),Ku||(Ku=!0,ac("scopes",Gu)),yf(),Iu=Zh,e=np,ha.includes(e)||ha.push(e))}function np(e,t){(function(e){const t=mu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){Su.delete(e);const n=xu.get(e);if(void 0===n||0===n.length||null===Iu)return;xu.delete(e);const o=Iu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const op={name:"scopes",install(){tp(),pu||(pu=!0,ac("dcc",hu))}},sp=/^@@wcs-(?:for|if|elseif|else):[^-]/,rp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,ip=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,ap=/^@@wcs-text-start:(.+)$/;function lp(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class cp extends cc{_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=Gc.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static find(e){const t=o.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=lp(JSON.stringify(t)),e.appendChild(n);const s=Array.from(ba.keys());for(const t of s){const n=$a(t);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",t);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),e.appendChild(s)}const r=Array.from(xi);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=$i(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=lp(JSON.stringify(t)),e.appendChild(n)}}xi.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(rp.test(e.data)||ip.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;sp.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=ap.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(o.tagNames.ssr),s=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;rp.test(e.data)&&i.push(e)}for(const e of i){const t=rp.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()}cp.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(sp.test(e.data)){const t=e.data.split(":")[1];l.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of l){const n=s.get(t);if(n){const t=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&t.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const c=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of c)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const dp={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Gc),cp.buildContent(o,cp.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const up=new Set(["for","if","elseif","else"]);function fp(e){const t=new is;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=lt(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function hp(e,t,n){for(const o of t)"event"===o.bindingType||up.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in _||ne(o.statePathName).wildcardCount>n||e.push(o)}function pp(e,t,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function mp(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=_e(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,Pa()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;Oa(a),"string"==typeof l&&Ca(a,l),Wa(n,a,l);va(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Ma(a)})}}const gp={hydrate:async function(e){await sa(e);const t=e.querySelectorAll(o.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${Gc}". Falling back to full render.`),cp.cleanupDom(e),!1}for(const n of t)mp(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=rp.exec(e.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let d=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:l,nodes:c})}return t}(document.body),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=Zr(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=fp(s.nodes);Er(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");ms(t,r),Tr(t,i);const l=[];for(const e of r)e.statePathName in _&&l.push(e);if(ws(t,l),"for"===s.type&&null!==s.index){const i=pp(e,"for",s.uuid);if(i){const e=Is(null,s.index);di(i,e,t),ui(i,s.nodes[s.nodes.length-1]),Hr(i,t);const l=ne(s.path+"."+c);Rr(t,hn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),hp(o,r,l.wildcardCount);let d=n.get(s.uuid);d||(d=[],n.set(s.uuid,d)),d.push(e)}}else{const n=pp(e,s.type,s.uuid);n&&(Hr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),hp(o,r,0))}}for(const[t,o]of n){const n=pp(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=$a(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=pa(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&js(t,o)})}return o}(document.body,n);cp.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());cp.restoreTextBindings(document.body);const[i,a]=lt(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(pt(e,null),t.setAttribute("data-wcs-completed",""))}else pt(e,null);const l=[],d=[],u=as(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(up.has(e.bindingType))d.push(e);else{if(e.statePathName.includes(c))continue;l.push(e)}for(const e of d)if("for"===e.bindingType){const t=nn(e),n=pa(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(wt(t,o),Pt(t,o))})}ta([...l,...s]);for(const{el:e,parent:t,next:n}of r)t.insertBefore(e,n);const f=e.querySelectorAll(o.tagNames.ssr);for(const t of f){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=cp.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await ma(e.rootNode);const t=cp.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",Gc),cp.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let yp=!1;function wp(){var t;yp||(yp=!0,la=gp,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,cp)},mc.includes(t)||mc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=dp)}())}const bp={name:"ssr",install(){wp()}},vp="[wcs/scan-declaration-invalid]",$p=Object.freeze([]);function xp(e){return`${F} entry "${e}"`}function Sp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Pp(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${c}${c}`)?`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.${ie}`}function Ip(e,t,n){0===n.length&&Z(`${vp} ${e} "${t}" must be a non-empty state path.${ie}`),n.startsWith("$")&&Z(`${vp} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ie}`),n.includes("@")&&Z(`${vp} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ie}`),n in Object.prototype&&Z(`${vp} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ie}`);const o=ne(n);for(const s of o.segments)0===s.length&&Z(`${vp} ${e} ${t} "${n}" has an empty path segment.${ie}`);return o.wildcardCount>d&&Z(`${vp} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Np(e,t,n,o){const s=xp(e);0===e.length&&Z(`${vp} ${F} entry name must be a non-empty string.${ie}`),(e.includes(l)||e.includes(c))&&Z(`${vp} ${s} must be a flat property name ("${l}" and "${c}" are not allowed). The output is a property the runtime owns.${ie}`),e.startsWith("$")&&Z(`${vp} ${s} must not start with "$" (reserved namespace).${ie}`),e in Object.prototype&&Z(`${vp} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ie}`),t.has(e)&&Z(`${vp} ${s} conflicts with a getter declared on the state.${ie}`),n.has(e)&&Z(`${vp} ${s} conflicts with a setter declared on the state.${ie}`),o.has(e)&&Z(`${vp} ${s} conflicts with the ${B} entry of the same name — each output has exactly one owner.${ie}`)}function kp(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===bh.get(t)?.has(e)}(e,o)&&Z(`${vp} ${xp(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ie}`)}function _p(e,t,n,o,s,r){const i=xp(e),a=void 0!==t.from,c=void 0!==t.on;if(a===c&&Z(`${vp} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ie}`),c){const e=t.on;return"string"==typeof e&&0!==e.length||Z(`${vp} ${i} "on" must be a non-empty event-token name.${ie}`),n.has(e)||Z(`${vp} ${i} on "${e}" is not declared in ${W}.${re(e,n)}${ie}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&Z(`${vp} ${i} "from" must be a state path string.${ie}`);const u=Ip(i,"from",d),f=Sp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&Z(Pp(i,"from",d,f));const h=Sp(u,s);return null!==h&&Z(function(e,t,n){return`${vp} ${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.${ie}`}(i,d,h)),(d===e||d.startsWith(e+l))&&Z(`${vp} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ie}`),{kind:"path",path:d,pathInfo:u}}function Ap(e,t,n,o){if(void 0===t)return $p;const s=xp(e);Array.isArray(t)||Z(`${vp} ${s} "resetOn" must be an array of state paths.${ie}`);const r=[];for(const e of t){"string"!=typeof e&&Z(`${vp} ${s} "resetOn" must contain only state path strings.${ie}`);const t=Ip(s,"resetOn",e);t.wildcardCount>0&&Z(`${vp} ${s} resetOn "${e}" must not contain "${c}" — a reset returns the whole output to "initial".${ie}`);const i=Sp(t,o);null!==i&&Z(Pp(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&Z(`${vp} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ie}`),"path"===n.kind&&e.startsWith(n.path+l)&&Z(`${vp} ${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.${ie}`),r.push(e)}return r}function Cp(e,t,n=null){const o=e[F];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&Z(`${vp} ${F} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ie}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(dc(e)))"function"==typeof n.get?s.add(t):"function"==typeof n.set&&i.add(t),"function"==typeof n.set&&r.add(t),"function"==typeof n.value&&a.set(t,n.value);const l=function(e){const t=e[B];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)){Np(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&Z(`${vp} ${xp(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ie}`);const o=u;kp(e,a,o);const f=_p(e,o,t,s,i,n);"initial"in o||Z(`${vp} ${xp(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ie}`),"function"!=typeof o.fold&&Z(`${vp} ${xp(e)} fold must be a function.${ie}`);const h=Ap(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=ne(e).segments[0];t.has(n)&&Z(`${vp} ${xp(o.name)} resetOn "${e}" reads the ${F} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ie}`)}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&&Z(`${vp} ${F} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ie}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Ep(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 ih.has(e)}(e),l=a&&!wh(n,e.initial)?gh(e.initial):n,c=t(l,o,...s);if(Ih(c))return void Nh(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,vh(e.name,c)),a&&uh(e)}catch(t){Ph(e.name,t,i)}}}function Mp(e,t,n){const o=function(e,t){Pf(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&xf(n,e.source.path,e);for(const t of e.resetOn)xf(o,t,e),"event"===e.source.kind&&xf(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return wf.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)&&Xs().hasQueuedPath(e,n))&&dh(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 Op="scanEntries",Tp={order:8,validate(e,t,n){const o=Cp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Op,o)},applyEarly(e,t,n){const o=n.get(Op)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=gh(n.initial);e[n.name]=t,vh(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&_n(e,n.source.tokenName).subscribe(Ep(n))}(e,o))},register(e,t,n){const o=n.get(Op)??null,s=function(e){const t=new Map,n=Sf(e);if(void 0!==n)for(const e of n.entries)uh(e)&&t.set(e.name,e.resetOn);return Pf(e),t}(e);e.setScanPaths?.(null===o?null:Mp(e,o,s))}};let Rp=!1;const jp=Object.freeze([]),Lp=Object.freeze([]);function Wp(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??jp,i=e.dynamicDependency.get(n)??jp,a=t.byFromPath.get(n)??Lp;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Dp=(e,t)=>t,Bp=new Set;function zp(e,t){const n=t[B];if(void 0===n)return void th(e,Bp);"object"==typeof n&&null!==n||Z(`${B} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&Z(`${B} entry name must be a non-empty string.`),s.includes(l)&&Z(`${B} entry "${s}" must be a flat property name ("${l}" is not allowed).`),s.includes(c)&&Z(`${B} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.startsWith("$")&&Z(`${B} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&Z(`${B} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&Z(`${B} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&Z(`${B} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||Z(`${B} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&Z(`${B} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&Z(`${B} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&Z(`${B} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&Z(`${B} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??Dp,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in t||(t[s]=a.definition.initial),o.set(s,a)}!function(e,t){oh.set(e,t)}(e,o),th(e,new Set(o.keys()))}const Fp=new WeakMap,qp=new WeakMap;function Vp(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=sh(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&sh(e).has(n),ownKeys:()=>Array.from(sh(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=sh(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){Z(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){Z(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Hp(e){const t=Fp.get(e);if(void 0!==t)return t;const n=Vp(e,U,e=>e.status);return Fp.set(e,n),n}function Up(e){const t=qp.get(e);if(void 0!==t)return t;const n=Vp(e,G,e=>e.error);return qp.set(e,n),n}function Gp(e){Fp.delete(e),qp.delete(e)}let Kp=null;function Jp(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 Xp={read(e,t){!function(e,t){null!==Kp&&Kp.add(qt(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===U?Jp(Hp(e),t.pathInfo.segments):n===G?Jp(Up(e),t.pathInfo.segments):tl},get:(e,t)=>t===U?Hp(e.stateElement):t===G?Up(e.stateElement):tl};async function Qp(e,t,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",i)}}function Yp(e){rm();const t=sh(e);if(0!==t.size){!function(e){Xf.add(e)}(e);for(const n of t.values())Zp(e,n)}}function Zp(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=Kp,s=new Set;let r;Kp=s;try{e.createState("readonly",e=>{r=n(e)})}finally{Kp=o}r instanceof Promise&&Z(`${B} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${U}${l}${t.name}`,a=`${G}${l}${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||Z(`${B} 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&&Z(`${B} 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=Sf(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=Wp(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&Z(`[wcs/scan-feedback-loop] ${B} entry "${t.name}" args read "${n}", which is derived from the ${F} 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}),em(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{e[t.name]=s.fold(e[t.name],n)})},done(){em(e,t,"done",null)},fail(o){em(e,t,"error",o),n.abort()}};Qp(s.source,o,n.signal,r)}function em(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return eh.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=eh.get(e);void 0===s&&(s=new Map,eh.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${U}${l}${t.name}`),i&&e.$postUpdate(`${G}${l}${t.name}`)}))}function tm(e){const t=Yf();if(0===t.size)return;const n=[];for(const o of t)for(const t of sh(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&sh(e).get(o.name)===o)try{Zp(e,o)}catch(n){o.controller?.abort(),t.has(e)&&sh(e).get(o.name)===o&&em(e,o,"error",n)}}let nm=!1;const om=new WeakMap,sm={order:20,apply(e,t){var n;Gp(e),rh(n=e),Qf(n),oh.delete(n),zp(e,t),void 0!==t[B]&&e.attachAddressHooks?.("streams",B)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return Yp(e),void om.set(e,e.connectGeneration??0)}n===e.connectGeneration&&om.get(e)!==n&&Yp(e)}},deactivate(e){rh(e),Gp(e)}};function rm(){nm||(nm=!0,sl("streams",Xp),ll("streams",sm),Us(tm,20))}const im=[kd,{name:"temporal",install(){Kh(),Rp||(Rp=!0,ll("scan",Tp),Hs(ch)),rm()}},tu,op,bp,rd,gd];await function(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(im),wc(e,t)}();
|
|
1
|
+
const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n;const s=Symbol.for("wcstack.binder");const r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");function a(){const e=function(){const e=globalThis[s];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[r];return void 0===t&&(t=[],e[r]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[i];return void 0===t&&(t=new WeakSet,e[i]=t),t}();for(const t of n)o.add(t),e.bind(t)}const l=".",c="*",d=128,u=128,f="#",h="|",p="prevent",m="stop",g="ro",y="init",w="sync",b="else",v="...",$="on",S="eventToken",x="state",P="command",I="class",N="attr",k="style",_={};for(let e=0;e<d;e++)_[`$${e+1}`]=e;const A=Object.freeze(_),C="$connectedCallback",E="$disconnectedCallback",M="$renderedCallback",O="$errorCallback",T="$stateReadyCallback",R="$bindables",j="$commands",L="$commandTokens",W="$command",D="$eventTokens",B="$on",z="$stream",F="$watch",q="$scan",V="$recursion",H="**",U="$listKeys",G="$streamStatus",K="$streamError",J="data-wc-definition",X=/\{\{\s*(.+?)\s*\}\}/g,Q=new Set(["SCRIPT","STYLE"]);function Y(e){if(!o.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&Q.has(e.parentElement.tagName)||Z(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),Y(t.content)}else Y(e.content)}function Z(e){const t=e.data;if(X.lastIndex=0,!X.test(t))return;X.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=X.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 ee(e){throw new Error(`[@wcstack/state] ${e}`)}const te=new Map;let ne=0;function oe(e){let t=te.get(e);return void 0!==t||(-1!==e.indexOf(H)&&ee(`[wcs/recursion-unsupported] "${e}" uses "${H}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`),t=Object.freeze(new se(e)),te.set(e,t)),t}class se{id=++ne;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:oe(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],d=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===c&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),d.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=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=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=p}}function re(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 ie(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=re(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ae=" Validate statically: npx @wcstack/lint <file>.",le=new Set(["if","elseif","else","for"]),ce={not:()=>e=>!e},de={input:new Map,output:new Map},ue={input:new Map,output:new Map},fe={input:new Map,output:new Map},he=new Map;function pe(e,t,n,o){const s=de[e],r=ue[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)}for(const t of Object.keys(o??{}))fe[e].set(t,o[t]);he.clear()}function me(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=he.get(s);if(void 0!==r)return r;const i=fe[n].get(e)??e,a=de[n].get(i)??ce[i];void 0===a&&ee(`[wcs/filter-unknown] filter not found: ${e}.${ie(e,function(e){return[...new Set([...Object.keys(ce),...de[e].keys()])]}(n))}${ae}`);const l=ue[n].get(i);void 0!==l&&(t.length<l[0]||t.length>l[1])&&ee(t.length<l[0]?`[wcs/filter-arity] filter "${e}" requires at least ${l[0]} argument(s) (${t.length} given).${ae}`:`[wcs/filter-arity] filter "${e}" accepts at most ${l[1]} argument(s) (${t.length} given).${ae}`);const c=a(t,o);return he.set(s,c),c}function ge(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 ye=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function we(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:ye.test(e)?Number(e):e)}function be(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=ge(o,i,a);t.push(e),n.push(we(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&&ee(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ae}`);const c=ge(o,i,a);return(c||r)&&(t.push(c),n.push(we(c,r))),{args:t,literals:n}}function ve(e,t){return e.map(t=>{const n=t.indexOf("("),o=t.lastIndexOf(")");-1!==n&&-1===o&&ee(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==o&&-1===n&&ee(`Invalid filter format: missing opening parenthesis in "${t}"`);const s=(-1===n?t:t.substring(0,n)).trim();if(0===s.length&&ee(`[wcs/binding-syntax] an empty filter in "${e.join("|")}" — remove the extra "|" or name the filter.${ae}`),-1===n)return{filterName:s,args:[],literals:[]};return{filterName:s,...be(t.substring(n+1,o))}})}const $e=e=>e.trim(),Se=e=>"'"===e||'"'===e;function xe(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(Se(s))n=s;else if(s===t)return o}return-1}function Pe(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):Se(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const Ie=new Map;function Ne(e){const t=xe(e,h);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ie.has(s)?r=Ie.get(s):(o=Pe(s,h).map($e),r=ve(o),Ie.set(s,r))):n=e.trim();const i=n.split(f).map($e);i.length>2&&ee(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${f}" — write "${i[0]}${f}${i.slice(1).join(",")}".${ae}`);const[a,c]=i,d=a.split(l).map($e);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map($e):[],inFilters:r}}const ke=new Map;function _e(e){const t=xe(e,h);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),ke.has(s)?r=ke.get(s):(o=Pe(s,h).map($e),r=ve(o),ke.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&ee(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);return{statePathName:n,statePathInfo:oe(n),outFilters:r}}const Ae=new Set([b,"if","elseif","for",v]),Ce=new Set([I,N,k,P,S]);function Ee(e){const[...t]=function(e){return Pe(e,";")}(e).map($e).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&ee(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(f)[0].split(h)[0].trim();if(s!==n&&Ae.has(s)&&ee(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ae}`),n===b){o.length>0&&ee(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ae}`);const t=oe("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===v){const t=_e(o);return t.outFilters.length>0&&ee(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&ee(`Invalid spread binding "${e}": spread target path is required.`),{propName:v,propSegments:[v],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],..._e(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=_e(o);return{...Ne(n),...e,bindingType:s}}{const e=_e(o),t=Ne(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Ce.has(o[0]))&&ee(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Ce].join(", ")}).${ae}`),{...t,propName:o.join(l),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===S||t.propSegments[0].startsWith($)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>le.has(e.bindingType))&&ee(`[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">).${ae}`)}return n}const Me=new WeakMap,Oe=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Te=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Re(e){const t=Me.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=Te.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Oe.has(r)?(Me.set(e,s[2]),s[2]):null}function je(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],..._e(e),bindingType:"text"}}const Le=new WeakMap,We=new WeakSet;let De=0;async function Be(e){const t=function(e){let t,n=Le.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++De,promise:o,resolve:t},Le.set(e,n),We.has(e)&&n.resolve(),n}(e);await t.promise}function ze(e){const t=Le.get(e);void 0===t?We.add(e):t.resolve()}const Fe=new WeakMap;function qe(e){const t=Fe.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{Fe.set(e,n)}}function Ve(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function He(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Ve(t);if(void 0!==n)return Ve(n)}return Ve(globalThis.customElements)}function Ue(e,t){e.upgrade?.(t)}function Ge(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=Qe(s.properties,Ke);if(null===r)return null;const i=void 0===s.inputs?new Map:Qe(s.inputs,Je);if(null===i)return null;const a=void 0===s.commands?new Map:Qe(s.commands,Xe);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Ke(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 Je(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 Xe(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 Qe(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 Ye(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:oe(n),inFilters:[],outFilters:[],bindingType:"prop"}}function Ze(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function et(e,t,n={}){const s=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&ee("Spread binding requires an element node.");const t=e,o=qe(t);null===o&&ee(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=He(t);null===a&&ee(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||ee(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Ue(a,t);const l=Ge(t);null===l&&ee(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=Ye(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=Ye(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=Ze(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=Ze(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.debug&&i.has(r[t])){const o=r[a.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[t])}return l}function tt(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 nt(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:me(s.filterName,s.args,t,s.literals??s.args)})}return n}const ot=new WeakMap;function st(e){return ot.get(e)||null}function rt(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function it(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!rt(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function at(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 lt(e){const t=[],n=it(e),s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==Re(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&at(e,n)||t.push(e)}return t}const ct=new WeakSet;function dt(e,t,n,o){const s=et(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&&ee("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}ct.add(e);const r=function(e,t){const n=[];for(const o of t){const t=nt(o.inFilters,"input"),s=nt(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){ot.set(e,t)}(e,r),ze(e),{bindings:r,deferred:null}}function ut(e,t){const n=lt(e),o=[],s=[];for(const e of n){if(ct.has(e))continue;const n=dt(e,Ia(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function ft(e){ct.add(e)}function ht(e){const{node:t,parseResults:n,transform:o}=e;!function(e){ct.delete(e)}(t);return dt(t,n,{allowDeferred:!1},o).bindings}const pt=new WeakMap;let mt=null;function gt(e){let t=e;for(;t;){const e=pt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==mt&&t instanceof ShadowRoot&&(n=mt(t)),t=n}return null}function yt(e,t){null!==t?pt.set(e,t):pt.delete(e)}let wt=null;const bt=new WeakMap;function vt(e){return bt.get(e)??[]}function $t(e,t){bt.set(e,t)}function St(e){return bt.has(e)}const xt=new WeakMap;let Pt=null,It=0;function Nt(e){return xt.get(e)??[]}function kt(e,t){null===Pt?xt.set(e,t):Pt.set(e,t)}function _t(){It++,null===Pt&&(Pt=new Map)}function At(){if(0!==It&&(It--,!(It>0||null===Pt))){for(const[e,t]of Pt)xt.set(e,t);Pt=null}}function Ct(e){return(Pt?.has(e)??!1)||xt.has(e)}const Et=Symbol("$$setLoopContext"),Mt=Symbol("$$getByAddress"),Ot=Symbol("$$hasByAddress"),Tt=Symbol("$$setByAddress"),Rt=Symbol("$$connectedCallback"),jt=Symbol("$$disconnectedCallback"),Lt=Symbol("$$updatedCallback"),Wt=Symbol("$$errorCallback"),Dt=new WeakMap,Bt=new WeakMap;class zt{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Ft(e,t){if(null===t){let t=Bt.get(e);return void 0!==t||(t=new zt(e,null),Bt.set(e,t)),t}{let n=Dt.get(t);void 0===n&&(n=new WeakMap,Dt.set(t,n));let o=n.get(e);return void 0!==o||(o=new zt(e,t),n.set(e,o)),o}}const qt=new WeakMap;function Vt(e,t){let n=qt.get(e);void 0===n&&(n=new Map,qt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Ht(e,t)),n.set(t,o)),o}class Ht{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Ut(e,t){return Ft(Vt(e,t.pathInfo),t.listIndex)}function Gt(e,t,n){return Ft(Vt(e,t),n)}const Kt=new WeakMap;function Jt(e,t){null===t?Kt.delete(e):Kt.set(e,t)}function Xt(e){return Kt.get(e)||null}const Qt=new Map;function Yt(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=Qt.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Qt.set(s,r),r}function Zt(e,t,n){return t<0||t>=n?null:e.at(t-n)}function en(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const tn=new WeakMap;function nn(e){const t=gt(e.node);if(null===t)return null;let n=tn.get(t);if(void 0===n)n=new WeakMap,tn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=Yt(t.pathInfo,e.statePathInfo);return n>0&&(o=Zt(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const on=new WeakMap;function sn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Xt(n);null===t?ee(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function rn(e,t){let n=null;if(n=on.get(e)||null,null!==n)return n;const o=sn(e,t),s=nn(e),r=ya(o);return null===r&&ee("No state tree found on this root for binding."),n=Gt(r,e.statePathInfo,s),on.set(e,n),n}function an(e){on.delete(e)}const ln=new WeakMap;function cn(e,t){const n=ln.get(e);void 0===n?ln.set(e,t):n instanceof Set?n.add(t):n!==t&&ln.set(e,new Set([n,t])),null!==wt&&wt({type:"state:binding-added",absoluteAddress:e,binding:t})}function dn(e,t){const n=ln.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&ln.delete(e),null!==wt&&wt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const un=new WeakMap;function fn(e){const t=ln.get(e);return void 0!==t?t:null!==e.listIndex?un.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const hn=new WeakMap,pn=new WeakMap;class mn{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===c?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=gn(e,t)}}function gn(e,t){if(null===t){let t=pn.get(e);return void 0!==t||(t=new mn(e,null),pn.set(e,t)),t}{let n=hn.get(t);void 0===n&&(n=new WeakMap,hn.set(t,n));let o=n.get(e);return void 0!==o||(o=new mn(e,t),n.set(e,o)),o}}const yn=new WeakMap;function wn(e){let t=null;if(t=yn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=nn(e);null===n&&ee(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=gn(e.statePathInfo,n)}else t=gn(e.statePathInfo,null);return yn.set(e,t),t}function bn(e){yn.delete(e)}function vn(){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 $n=new Map,Sn=vn();function xn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Pn(e){let t="input";for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function In(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const o=Pn(e),s=xn(e,o);let r=$n.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=ya(o.getRootNode());null===i&&ee("No state tree found on this root for two-way binding.");const a=gt(o);i.createState("writable",e=>{e[Et](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]:[]})})},$n.set(s,r)),e.node.addEventListener(o,r),Sn.add(s,e),!0}var t,n;return!1}function Nn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function kn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Nn(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class _n{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)t.push(n(...e));return t}}class An extends _n{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==wt&&wt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Cn=new WeakMap;function En(e,t){let n=Cn.get(e);void 0===n&&(n=new Map,Cn.set(e,n));let o=n.get(t);return void 0===o&&(o=new An(t,e),n.set(t,o)),o}const Mn=new WeakMap;function On(e){if(e.propSegments[0]!==S)return!1;const t=e.node,n=qe(t),o=He(t);if(null!==n&&void 0===o?.get(n))return null===o&&ee(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Mn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||ee('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===qe(e)?null:Ge(e)}(t);null===r&&ee(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&ee(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${ie(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(p)&&e.preventDefault(),c.includes(m)&&e.stopPropagation();const n=ya(t.getRootNode());null===n&&ee("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||ee(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${ie(l,n.eventTokenNames)}${ae}`);const o=gt(t);n.createStateAsync("writable",async t=>{kn(t[Et](o,()=>{const s=null!==o?en(o.listIndex,o.pathInfo.wildcardCount):[];return En(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Mn.set(e,{eventName:a,handler:d}),!0}class Tn extends _n{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==wt&&wt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Rn(e){return e instanceof Tn}const jn=new Map,Ln=vn();function Wn(e){const t=e.propModifiers.filter(e=>e===p||e===m).sort().join(",");return`${e.statePathName}::${t}`}const Dn=(e,t,n)=>o=>{t.includes(p)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ya(r);null===i&&ee("No state tree found on this root for event handler.");const a=gt(s),l=e.startsWith(W+".");i.createStateAsync("writable",async t=>{const c=t[Et](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?en(a.listIndex,c):[];if(l){const s=t[Mt](gn(n,null));return Rn(s)||ee(`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&&ee(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});kn(c,`"${e}"`)})};function Bn(e){if(!e.propName.startsWith($))return!1;const t=Wn(e);let n=jn.get(t);void 0===n&&(n=Dn(e.statePathName,e.propModifiers,e.statePathInfo),jn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Ln.add(t,e),!0}function zn(e){if(!e.propName.startsWith($))return!1;const t=Wn(e),n=jn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Ln.countOf(t)&&(Ln.remove(t,e)&&jn.delete(t),!0)}const Fn=new Map,qn=vn();function Vn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Hn(e){let t="input";for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function Un(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const o=Hn(e),s=Vn(e,o);let r=Fn.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=ya(o.getRootNode());null===r&&ee("No state tree found on this root for two-way binding.");const i=gt(o);r.createState("writable",e=>{e[Et](i,()=>{e[t]=s})})},Fn.set(s,r)),e.node.addEventListener(o,r),qn.add(s,e),!0}var t,n;return!1}const Gn=new Set(["radio","checkbox"]),Kn=new Set(["value","valueAsNumber","valueAsDate"]);function Jn(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(Gn.has(e)&&"checked"===t)return!0;if(Kn.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=He(n)?.get(s);void 0===e&&ee(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ge(n);if(o?.knownProperties.has(t))return!0}return!1}let Xn=1,Qn=1,Yn=1;const Zn=new WeakMap;function eo(e,t,n){let o=Zn.get(e);void 0===o&&(o=new Map,Zn.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=Xn++,o.set(s,r)),r}function to(e,t){return"to-element"===t?2*e:2*e+1}const no=new Set;function oo(e){return{transactionId:Qn++,originBindingId:e,visitedEdges:no,hop:0}}function so(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 ro=null;function io(){return ro}function ao(e,t){const n=ro;ro=e;try{return t()}finally{ro=n}}const lo=[];let co=!1;const uo=new Map,fo=vn(),ho=new WeakMap,po=e=>e.detail,mo=new WeakMap;function go(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function yo(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=qe(e.node);if(null!==n){const o=He(e.node)?.get(n);void 0===o&&ee(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ge(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function wo(e){if(null!==qe(e.node)){const t=Ge(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??po}return null}function bo(e){if(null===qe(e.node))return!1;const t=Ge(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const vo=(e,t,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==po||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=mo.get(e);void 0===r&&(r=new Set,mo.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=ho.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=eo(a,e,t),s=function(e,t){for(let n=lo.length-1;n>=0;n--){const o=lo[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==wt&&wt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:to(n,"to-state"),node:a,member:e}));const r=to(n,"to-state"),i=io();if(null!==i&&i.visitedEdges.has(r))return void(null!==wt&&wt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=so(i??oo(n),r)}const f=ya(a.getRootNode());null===f&&ee("No state tree found on this root for two-way binding.");const h=gt(a),p=()=>{r&&(co=!0);try{f.createState("writable",e=>{e[Et](h,()=>{e[t]=c})})}finally{r&&(co=!1)}};null!==u?ao(u,p):p()};const $o=new WeakSet;function So(e){$o.add(e)}function xo(e){return!!$o.has(e)&&($o.delete(e),!0)}const Po=new WeakMap;function Io(e,t){const n=Po.get(e);return!(void 0===n||n<t)&&(n===t?Po.delete(e):Po.set(e,n-t),!0)}const No=new WeakSet;function ko(e){No.add(e)}function _o(e){return!!No.has(e)&&(No.delete(e),!0)}let Ao=0;function Co(){Ao--}function Eo(){return Ao>0}class Mo{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 Oo=new WeakMap;function To(e){let t=Oo.get(e);return void 0===t&&(t=new Mo(e),Oo.set(e,t)),t}function Ro(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!==y&&s!==w&&ee(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&ee(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function jo(e){return e.propModifiers.some(e=>e.includes("="))}const Lo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Wo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Do(e,t){return"state"===e&&"call"===t?Lo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Bo(e){if(!o.enableDirectionalInitialSync)return jo(e)&&ee("init=/sync= modifiers require enableDirectionalInitialSync."),Lo;const t=null===(n=Ro(e,y))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:ee(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":ee(`Invalid sync modifier value "${e}".`)}(Ro(e,w));if("event"===e.bindingType)return null!==t&&"none"!==t&&ee("Event bindings only allow init=none."),"call"===s?Wo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===P)return Do("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&ee(`Binding type "${e.bindingType}" does not support init=${t}.`),Do(t??"state",s);const r=Ge(e.node);if(null===r)return Do(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||ee(`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)||ee(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||ee(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function zo(e,t){return"auto"!==t?t:function(e){const t=ya(e.replaceNode.getRootNode());null===t&&ee("No state tree found on this root for binding.");const n=wn(e);let o=!1;return t.createState("readonly",e=>{o=e[Ot](n)}),o}(e)?"state":"element"}let Fo=0,qo=0;const Vo=["active","disposed","failed"],Ho=new WeakMap,Uo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,Jo=new WeakMap;function Xo(e,t){const n=Jo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Jo.set(e,new Set([n,t]))):Jo.set(e,t)}function Qo(e){return Jo.has(e)}function Yo(e,t){const n=Jo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function Zo(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))Zo(n,t)}function es(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class ts{root;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}handleMutations(e){const t=[],n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.removedNodes;if(0===r.length||!Io(s.target,r.length))for(let e=0;e<r.length;e++)t.push(r[e]);const i=s.addedNodes;for(let e=0;e<i.length;e++)n.push(i[e])}const o=[];for(const e of t)xo(e)||Zo(e,e=>{Yo(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)_o(e)&&!Eo()||Zo(e,e=>{Yo(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&sa(o)}}const ns=new WeakMap;function os(e){let t=ns.get(e);return void 0===t&&(t=new ts(e),ns.set(e,t)),t}function ss(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function rs(e,t,n){const o=ya(sn(e,n));null===o&&ee("No state tree found on this root for binding.");const s=Vt(o,e.statePathInfo);return function(e,t,n){let o=un.get(e);void 0===o&&(o=new WeakMap,un.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!==wt&&wt({type:"state:binding-added",absoluteAddress:Ft(e,t),binding:n})}(s,t,e),s}function is(e,t){const n=rn(e,t);return cn(n,e),n}function as(e,t,n,o){null!==t?dn(t,e):function(e,t,n){const o=un.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!==wt&&wt({type:"state:binding-removed",absoluteAddress:Ft(e,t),binding:n}))}(n,o,e),bn(e),an(e)}function ls(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class cs{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=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=Uo.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(es(t)&&os(t),null===this.rowPlan)for(const n of e){const e=Uo.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!o.enableDirectionalInitialSync)return jo(e)&&Bo(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=Uo.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)return{id:64*t.id+n,info:e,generation:t.generation,phase:Vo[t.phases[n]],teardowns:null};const o=Uo.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=Uo.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(ls(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=He(e);null===s&&ee(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),Xo(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=To(s).wait(t,()=>{if(a())try{Ue(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.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=Uo.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.active=!1,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&&(dn(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){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.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(dn(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?rn(n):null;if(as(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=rn(n);e!==o&&St(o)&&$t(e,vt(o)),e!==o&&Ct(o)&&kt(e,Nt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return es(t)?t:null}(e);null!==t&&os(t)}handleMutations(e,t,n){for(const n of t)Zo(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)Zo(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&sa(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=Uo.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Ko.get(t);void 0===e&&(e=ss(t),Ko.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;Xo(n,this);const o=this.knownMapFor(n);let s=Ko.get(e);void 0===s&&(s=ss(e),Ko.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:++Fo,session:this,generation:++qo,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(Xo(r,this),this.addKnownRowBinding(r,o,e),Ho.set(o,s),n[e].isEvent){try{Bn(o)}catch(t){throw s.phases[e]=2,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=++qo,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{Bn(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}o.flags[e]|=2}this.registerRowSlot(o,e,n)}}rowOf(e){const t=Ho.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=nn(o);null!==s?(e.patternPathInfos[t]=rs(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=is(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(as(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{zn(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:++Fo,info:e,generation:++qo,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};Uo.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;Bn(t)?e.eventAttached=!0:t.propSegments[0]!==S?(Un(t)&&ls(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const t=Hn(e),n=Vn(e,t),o=Fn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==qn.countOf(n)&&(qn.remove(n,e)&&Fn.delete(n),!0))}return!1}(t)),In(t)&&ls(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const t=Pn(e),n=xn(e,t),o=$n.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Sn.countOf(n)&&(Sn.remove(n,e)&&$n.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Jn(t.node,t.propName)&&-1===t.propModifiers.indexOf(g)){const n=function(e,t,n){let o=ho.get(e);void 0===o&&(o=new Map,ho.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&&ho.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});ls(e,n)}!function(e){const t=qe(e.node);if(null!==t){const n=He(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&ee(`CustomElementRegistry is unavailable for <${t}>.`))}if(Jn(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const t=yo(e),n=wo(e),o=bo(e),s=go(e,t,null!==n,o);let r=uo.get(s);void 0===r&&(r=vo(e.propName,e.statePathName,e.inFilters,n,o),uo.set(s,r)),e.node.addEventListener(t,r),fo.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{On(t)&&ls(e,()=>function(e){if(e.propSegments[0]!==S)return!1;const t=Mn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Mn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=qe(e.info.node);if(null===n)return void t();const o=He(e.info.node);if(null===o&&ee(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=To(o).wait(n,()=>{if(this.isAlive(e,s))try{Ue(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});ls(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Bo(e.info),n=zo(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 Ao++;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,Co()),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=ya(e.node.getRootNode());null===o&&ee("No state tree found on this root for initial binding sync.");const s=gt(e.node);o.createState("writable",t=>{t[Et](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=nn(n);if(null!==o?(e.patternPathInfo=rs(n,o,t),e.patternListIndex=o):e.address=is(n,t),!e.options.registerPathInfo)return;const s=ya(n.replaceNode.getRootNode());null===s&&ee("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&&Uo.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,Co());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{as(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=qe(e.node);if(null!==t){const n=He(e.node),o=n?.get(t);if(void 0===o)return}if(Jn(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const t=yo(e),n=go(e,t,null!==wo(e),bo(e)),o=uo.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),fo.remove(n,e)&&uo.delete(n)}}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{zn(t)}catch{}}}}function ds(e){let t=Go.get(e);return void 0===t&&(t=new cs(e),Go.set(e,t)),t}function us(e){return Uo.get(e)?.session??Ho.get(e)?.session??null}let fs=null;function hs(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ps=Object.freeze([]);const ms=new WeakMap;const gs=new WeakMap;function ys(e){return gs.get(e)??[]}function ws(e,t){gs.set(e,t)}const bs=new WeakMap;function vs(e){return bs.get(e)??[]}function $s(e,t){bs.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});let Ss=0;function xs(){return`u${(Ss++).toString(36)}`}let Ps=0,Is=0;const Ns=Symbol("wcs.listIndex.noValue");class ks{uuid=xs();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ns,this._index=t,this._version=Ps,this._chainGeneration=Is}get index(){return this._index}set index(e){this._index=e,this._version=++Ps,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(e){this._value=e}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=Ps),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Is||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Is),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Ps,Is++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function _s(e,t,n=e){return new ks(e,t,n)}function As(e,t){e.reparent(t)}function Cs(e){return e.homeParentListIndex}function Es(e,t){e.value=t}function Ms(e,t){const n=e.value;return n!==Ns&&n===t.value}const Os=new WeakMap,Ts=new WeakSet;function Rs(e){return Ts.has(e)}function js(e,t){const n=Cs(e),o=e.parentListIndex;return null===n||n===o||Ts.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Ts.has(e)&&!Ts.has(n)&&n.position===e.position&&Ms(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Ts.has(e)&&!Ts.has(t)}(o,t)?t:null:n}function Ls(e){const t=Os.get(e);return void 0===t?null:t}function Ws(e,t){const n=Os.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=js(o,t);if(null!==e)for(const t of n)As(t,e)}return n}function Ds(e,t){null!==t?Os.set(e,t):Os.delete(e)}const Bs=new WeakMap;function zs(e,t){null===t?Bs.delete(e):Bs.set(e,t)}function Fs(e){const t=Bs.get(e);t&&(t.dirty=!0)}const qs=Symbol.for("wcstack.transition-runner");function Vs(e){const t=globalThis[qs];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 Hs(e,t,n){const o=Vs(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Us=[],Gs=[];function Ks(e){Gs.includes(e)||Gs.push(e)}function Js(e,t=0){const n=Us.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Us.push(o):Us.splice(n,0,o)}function Xs(e){queueMicrotask(()=>{throw e})}class Qs{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Gs.length;t++)Gs[t](e);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){_t(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){const o=new Map,s=new Set;for(let t=0;t<e.length;t++){const n=e[t],r=o.get(n.absoluteAddress);null!==wt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&wt({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];o.has(t)||o.set(t,null)}const r=[],i=new Map;o.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!==wt&&wt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=fn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(r.push(t),null!==e&&i.set(t,e));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==e&&i.set(n,e))});try{const e=()=>{i.size>0?sa(r,i):sa(r)};if(t()||0===r.length)e();else{const t=Hs("state",e);void 0!==t&&t.catch(Xs)}}finally{At(),function(e){for(const t of Us.slice())t.listener(e)}(s)}}}const Ys=new Qs;function Zs(){return Ys}const er=new WeakMap,tr=new WeakMap,nr=new WeakMap,or=new WeakMap;let sr=!1;const rr=new WeakMap,ir=new WeakMap,ar=new WeakMap,lr=[];function cr(e,t){const n=dr(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=oe(t).cumulativePaths;if(o.length<2)return;let s=ar.get(e);void 0===s&&ar.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 dr(e){let t=er.get(e);return void 0===t&&er.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function ur(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function fr(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function hr(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=tr.get(o);if(void 0===r&&tr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(fr(s,e,o),r.set(t,n),ur(s,n,o)),!1}return r.set(t,n),ur(s,n,o),!0}function pr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function mr(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&pr(nr,o.listIndex,r),null!==r.levelListIndex&&pr(or,r.levelListIndex,r))}function gr(e,t,n,o,s){sr=!0;const r=dr(e);cr(e,t);mr(r,t,s,o,hr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function yr(e,t){dr(e).tracked.add(t)}function wr(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(Ut(e.stateElement,gn(t,o)))}function br(e,t){if(void 0!==e)for(const n of e)t.push(n)}function vr(e,t,n,o,s){const r=er.get(e),i=r?.byPath.get(t),a=rr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return lr;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&&br(i.get(o),d),f&&br(i.get(c),d),u&&br(i.get(s),d)),void 0!==a)for(const e of a)n&&wr(e,o,d),f&&wr(e,c,d),u&&wr(e,s,d);return d}function $r(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Sr(e,t,n){const o=er.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())br(e,n);const s=rr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)wr(e,t,n)}function xr(e){const t=or.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Pr(e){if(!sr)return;const t=nr.get(e);if(void 0!==t){nr.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=tr.get(o),r=s.get(n);s.delete(n),fr(er.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&xr(e)}}}function Ir(e,t,n){if(!sr)return;const o=or.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=er.get(e),i=o.byPath.get(s);fr(i,t,r),ur(i,n,r),tr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Fs(r),Zs().enqueueAbsoluteAddress(r,null))}}const Nr=new WeakMap,kr=Object.freeze([]),_r=new Set;function Ar(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:kr,s=Array.isArray(n)&&n.length>0?n:kr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:kr,o=Array.isArray(t)&&t.length>0?t:kr;let s=Nr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Ws(o,e)||[],a=i.length>0?Cs(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:_r,deleteIndexSet:new Set(i),addIndexSet:_r};let t=Ws(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=_s(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:_r,deleteIndexSet:_r,addIndexSet:new Set(t)}}if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:_r,deleteIndexSet:_r,addIndexSet:_r};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=_s(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=Nr.get(e);o||(o=new WeakMap,Nr.set(e,o)),o.set(t,n)}(o,s,l),Ds(s,l.newIndexes))}}(e,t,n);!function(e,t){for(let n=0;n<e.length;n++){if(e[n].index!==n){const t=e[n].index;e[n].index=n,Ir(e[n],t,n)}Es(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:kr),function(e){for(const t of e)Ts.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)Pr(e);return function(e){for(const t of e)Ts.delete(t)}(o.newIndexes),function(e,t){if(!sr||e===t)return;const n=ir.get(e);if(void 0===n)return;ir.delete(e);const o=ir.get(t);ir.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=dr(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&&!Rs(e))for(const t of o.getters){const n=Ut(o.stateElement,gn(t,e));Fs(n),Zs().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function Cr(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 Er=new WeakSet;const Mr=new WeakMap;function Or(e){return Mr.get(e)??null}function Tr(e,t){Mr.set(e,t)}const Rr=new WeakMap;function jr(e){return Rr.get(e)??[]}function Lr(e,t){Rr.set(e,t)}function Wr(e,t){const n=jr(e);for(const e of n)yt(e,t)}const Dr=new WeakMap;const Br=new WeakMap;function zr(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function Fr(e,t,n,o,s){const r=function(e,t,n){let o=Br.get(e);void 0===o&&Br.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;let a,l=!1;for(let e=0;e<t.length;e++){const c=t[e];if(!n.shouldApplyState(c))continue;const d=r[e];if(null===d||zr(d.prefixes,i)){na(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[Mt](o),l=!0);const u=d.tail;let f=a;for(let e=0;e<u.length;e++){if(null==f){f=void 0;break}f=f[u[e]]}ta(c,s,f)}}function qr(e,t,n){Wr(e,t);const o=ys(e),s=Or(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return Dr.get(e)??null}(e);if(null!==r)return void Fr(r,o,s,t,n)}for(const e of o){if(null===s){cn(rn(e),e)}(null===s||s.shouldApplyState(e))&&na(e,n)}}function Vr(e){if(!e.mounted)return;const t=ys(e),n=Or(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{dn(rn(o),o)}}!function(e){const t=jr(e);for(let e=0;e<t.length;e++)yt(t[e],null)}(e)}function Hr(){return Object.freeze(new Set)}const Ur=new WeakMap,Gr=Hr();function Kr(e,t){const n=Ur.get(e);n?n.add(t):Ur.set(e,new Set([t]))}function Jr(e){const t=Ur.get(e);return void 0!==t?t:Gr}function Xr(e,t){const n=Ur.get(e);n&&(n.delete(t),0===n.size&&Ur.delete(e))}function Qr(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:me(s.filterName,s.args,t,s.literals??s.args)})}return n}function Yr(e){return{...e,inFilters:Qr(e.inFilters,"input"),outFilters:Qr(e.outFilters,"output")}}const Zr=new Set(["if","elseif","else","for"]);class ei{_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];ko(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){ko(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=Or(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(ys(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(So(n),n.parentNode.removeChild(n))}const n=ys(this);for(let e=0;e<n.length;e++){const t=n[e];Zr.has(t.bindingType)&&Jr(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Or(this);null!==e&&(e.isRowSession?e.disposeBindings(ys(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=ys(this);for(let t=0;t<e.length;t++){const n=e[t];Zr.has(n.bindingType)&&Jr(n.node).forEach(e=>{e.unmount()}),bn(n),an(n)}}unmount(){{const e=Or(this);null!==e&&(e.isRowSession?e.disposeBindings(ys(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(So(e),e.parentNode.removeChild(e));const e=ys(this);for(let t=0;t<e.length;t++){const n=e[t];Zr.has(n.bindingType)&&Jr(n.node).forEach(e=>{e.unmount()}),bn(n),an(n)}this._mounted=!1}}function ti(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function ni(e){const t=document.createDocumentFragment(),n=new ei(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function oi(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=tt(o,s[e].nodePath);null===t&&ee(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),ft(t),ze(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=ia.get(n);void 0!==o&&o.currentRowPlan===e||(o=new cs,ia.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new ei(o);return Tr(d,c),ws(d,a),function(e,t){Dr.set(e,t)}(d,n),$s(d,l),Lr(d,r),Kr(e.node,d),d}function si(e){void 0!==e.uuid&&null!==e.uuid||ee("BindingInfo.uuid is null.");const n=Pa(e.uuid);n||ee(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&ti(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=tt(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===P||s===S)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==qe(r))return null;if("prop"===o&&Jn(r,e.propName))return null;const i=Yr(e);let a;try{a=Bo({...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 A,policy:a,authority:a.authority})}}return{directional:t,slots:n}}(n)),null!==r)return oi(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=tt(e,s.nodePath);if(null===t&&ee(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),ct.has(t))continue;const r=dt(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new cs,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new ei(i,s);Tr(l,a.bindingSession),ws(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in A&&c.push(e);return $s(l,c),Lr(l,a.nodes),Kr(e.node,l),l}const ri=new WeakSet,ii=Symbol.for("wcstack.state.view-transition-naming");function ai(){const e=Vs("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function li(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||ri.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[ii]??={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.`)):(ri.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 ci=new WeakMap,di=new WeakMap,ui=new WeakMap,fi=new WeakMap;function hi(e,t,n){!function(e,t,n){let o=di.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,di.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function pi(e,t){ci.set(e,t)}function mi(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 gi(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function yi(e,t,n){if(o=t,!Er.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const wi=new Set(["if","elseif","else","for"]);function bi(e,t){for(const n of ys(e))if(t.appliedBindingSet.delete(n),wi.has(n.bindingType))for(const e of Jr(n.node))bi(e,t)}function vi(e){for(const t of ys(e)){if(!wi.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Jr(t.node))vi(n),e&&n.mounted&&(Vr(n),n.unmount(),Xr(t.node,n))}}function $i(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Si(e,n,s){const r=Boolean(s);let i;const a=Jr(e.node);i=0===a.size?si(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${$i(e)}`),Vr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${$i(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);qr(i,gt(e.node),n);const t=ai();null!==t&&li(i,"branch",t)}}const xi=new WeakMap;function Pi(e){return xi.get(e)??[]}const Ii=new Set;const Ni=Symbol.for("wcstack.trustedTypes.policy");function ki(){const e=globalThis[Ni];return null===e||"object"!=typeof e?null:e}let _i;let Ai=!1;function Ci(e,t){if(Ai)return;if(!function(){if(void 0!==_i)return _i;if(!("trustedTypes"in globalThis))return _i=!1,_i;try{document.createElement("div").innerHTML="<i></i>",_i=!1}catch{_i=!0}return _i}())return;Ai=!0;const n="function"==typeof ki()?.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 Ei={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")}},Mi=new Set(["textContent","innerText","innerHTML"]);function Oi(e,n,s){if(void 0===s&&1===e.propSegments.length&&Mi.has(e.propSegments[0])&&(s=""),void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==s){null!==fs&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==qe(r)&&fs.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=ki(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Ci(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=qe(e);if(null===n)return null;const o=He(e)?.get(n);if(void 0===o)return null;const s=Ge(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Jn(r,c)){const t=eo(r,c,e.statePathName),o=to(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??io()??oo(t);if(a.visitedEdges.has(o))null!==wt&&wt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=so(a,o);ao(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Yn++,writtenValue:n};lo.push({receipt:i,node:e});try{return r()}finally{lo.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=Ei[c];e?e(r,s):(!function(e,t,n){let o=xi.get(e);o||(o=[],xi.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,Ii.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));null!==fs&&2===i.length&&"object"==typeof d&&null!==d&&null!==qe(r)&&(u in d?fs.rememberOverwrittenValue(r,c,u,d[u]):fs.recordInjectedKey(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const Ti=new WeakSet;function Ri(e,t,n){}function ji(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}function Li(e,t,n){const o=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),s=t.length>0?t+l:"";for(const e of n){if(s.length>0&&!e.startsWith(s))continue;const t=e.slice(s.length);t.length>0&&-1===t.indexOf(l)&&o.push(t)}return o}const Wi={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Di={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Bi(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}.${ae}`}function zi(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 Fi(e,t){return`$setAll("${e}") ${t}`}function qi(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.${ae}`}function Vi(e,t){const n=wn(t);if(n.pathInfo.path in A){const e=gt(t.node);return null===e&&ee(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&ee("ListIndex not found for loopContext:");const n=A[t];void 0===n&&ee(`Invalid index name: ${t}`);const o=Zt(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&ee(qi(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Mt](n)}const Hi=new WeakSet;function Ui(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Gi=Object.freeze({[I]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&ee("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[N]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[k]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[P]:function(e,t,n){Rn(n)||ee("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ms.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||ee('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=He(e)?.get(t);return void 0===n&&ee(`Custom element <${t}> is not defined for command binding.`),Ge(e)}(r);null===a&&ee(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||ee(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ie(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ms.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 ms.delete(e);const o=n[i];return"function"!=typeof o&&ee(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),ms.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Ki={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Ti.has(e.replaceNode)){Ti.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,n,o){const s=e.statePathInfo,r=nn(e),i=rn(e),a=vt(i),l=a.length>0&&!di.has(e.node)?[]:a,d=Ar(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=di.get(e.node);const f=void 0!==u?yi(u,l,d):null,h=Array.isArray(l)&&l.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=fi.get(e.node);if(void 0===t){const n=ci.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(mi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(mi(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),fi.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){Po.set(e,(Po.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return ui.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;d.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(Vr(o),vi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Xr(e.node,o):(Vr(o),o.unmount(),function(e,t){let n=ui.get(e.node);void 0===n&&(n=[],ui.set(e.node,n)),n.length<1e3?n.push(t):Xr(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(di.delete(e.node),u=void 0)}let m=e.node;const g=oe(s.path+"."+c),y=n.stateElement.loopContextStack,w=Cr(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&m.isConnected&&null===f&&(b=document.createDocumentFragment(),Jt(b,n.rootNode));const v=t(),$=ai(),S=e.uuid??"",x=ui.get(e.node);for(const t of d.newIndexes){let o;if(d.addIndexSet.has(t)){const r=gn(g,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==x?x.pop():void 0),void 0===o?o=si(e):bi(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${S}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${S}:${s.path}:${t.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${S}:${s.path}:${t.index}`);m.parentNode.insertBefore(e,m.nextSibling),m=e}o.mountAfter(m)}if(v){const e=document.createComment(`@@wcs-for-end:${S}:${s.path}:${t.index}`),n=o.lastNode??m;n.parentNode.insertBefore(e,n.nextSibling)}}qr(o,r,n),null!==$&&li(o,"row",$)}),void 0===o&&ee(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)){const e=n.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](n.stateElement,o)}}}else{if(o=void 0!==u?u.get(t)??null:null,d.changeIndexSet.has(t)){const e=vs(o);for(const t of e)na(t,n)}null===o&&ee(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&gi(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),e){const e=o,s=gn(g,t);y.createLoopContext(s,t=>{qr(e,t,n)})}}m=o.lastNode||m,void 0===u&&(u=new WeakMap,di.set(e.node,u)),u.set(t,o)}ci.set(e.node,m),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Jt(b,null))},if:Si,else:Si,elseif:Si,radio:function(e,t,n){const o=e.node,s=hs(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=hs(o.value,e.inFilters),r=Array.isArray(n)?n:ps;o.checked=r.includes(s)}},Ji=new WeakMap,Xi=new WeakMap,Qi=new WeakMap;function Yi(){}function Zi(e){const t=fs;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Ri;if(t.isDeclared(n,o))return Yi}return Oi}function ea(e,t){ta(e,t,Vi(t.state,e))}function ta(e,t,n){const o=hs(n,e.outFilters);if(!0===Xi.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=Ji.get(e);if(void 0===s){if(Ji.has(e))return s=Zi(e),s===Ri&&Ji.set(e,s),void s(e,t,o);if(s=Ki[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Gi[t],Ji.set(e,s),void 0===s){qe(e.replaceNode)?(s=Zi(e),s===Ri&&Ji.set(e,s)):(s=Oi,Ji.set(e,s))}}if(s===Oi){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 Xi.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function na(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=rn(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=us(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Qi.get(e)){const t=qe(e.replaceNode);if(t&&void 0===He(e.replaceNode)?.get(t))return void function(e,t){if(Hi.has(e))return;Hi.add(e);const n=()=>{Hi.delete(e);const t=us(e);(null===t||t.shouldApplyState(e))&&sa([e])},o=n=>{Hi.delete(e),Ui(t,n)},s=us(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Hi.delete(e),r()})||(Hi.delete(e),r()))}const r=He(e.replaceNode);if(null===r)return Hi.delete(e),void Ui(t,new Error("CustomElementRegistry is unavailable."));To(r).wait(t,()=>{e.replaceNode.isConnected?n():Hi.delete(e)},o)}(e,t);Qi.set(e,!0)}if(!0===t.sameRootVerified)return void ea(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Xt(o),null===o&&ee("Root node for fragment not found for binding.")),o!==t.rootNode){const n=ya(o);null===n&&ee("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};ea(e,r)})}else ea(e,t)}function oa(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!==wt&&wt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function sa(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Xt(d),null===d&&ee("Root node for fragment not found for binding."));const u=ya(d);null===u&&ee("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{na(n,f)}catch(e){oa(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{Oi(e,{propagationContextByBinding:t},n)}catch(t){oa(e,t,o??null,c)}for(const[e,t]of i.entries())$t(e,t),kt(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Lt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Wt](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 ra(e,t,n){const[o,s,r]=ut(e,n),i=ds(e);for(const e of o)yt(e,t);sa(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=ht(o);0!==e.length&&(yt(o.node,t),sa(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const ia=new WeakMap;async function aa(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=He(e);null===s&&ee(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(rt(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function la(e){if(e===document)await aa(document),Y(document),za(document,document),ra(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await Be(t.host),await aa(t),Y(t),za(t,t),ra(t,null)}}const ca={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function da(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${ca[e]??e}" before the state is defined.`}let ua=null;function fa(e){return null===ua&&ee(da("ssr",e)),ua}const ha=new WeakMap,pa=new WeakMap,ma=new Set,ga=[];function ya(e){return ha.get(e)??null}function wa(e){return pa.get(e)??Promise.resolve()}const ba=new WeakSet;function va(e){ba.add(e)}function $a(e,n){const s=ha.get(e);if(null===n){if(void 0===s)return;ha.delete(e),ma.delete(s),null!==wt&&wt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await fa('the "enable-ssr" attribute').hydrate(e)||await la(e)}else await la(e);va(e),Ga(),t()}catch(e){n(e)}})});pa.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await la(e),va(e),Ga(),t()}catch(e){n(e)}})});pa.set(e,t)}}void 0!==s&&ee('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="...">.'),ha.set(e,n),ma.add(n);for(let t=0;t<ga.length;t++)ga[t](e,n);null!==wt&&wt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Sa=new Map;function xa(e,t,n){if(null===n)Sa.delete(e);else{Sa.set(e,n);const o=ya(t);null===o&&ee("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 Pa(e){return Sa.get(e)||null}function Ia(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Ee(t.getAttribute(o.bindAttributeName)||"");return t.localName===o.tagNames.state&&t.hasAttribute("mount")?n.filter(e=>e.propSegments[0]!==x):n}if(e.nodeType===Node.COMMENT_NODE){const t=Re(e);null===t&&ee("Comment node binding text not found.");const n=Pa(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=je(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Na;function ka(){return Na??={filterName:"not",args:[]}}const _a=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Aa(e,t){const n=t+l+c,o=e.indexOf("|");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+l+s.slice(1)}return r.length>0?s+r:s}function Ca(e,t){const n=_a.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Aa(s,t)+r}function Ea(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Aa(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Ma(e,t){return Ea(e,t)}function Oa(e,t){const n=o.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Ca(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Ea(r,t);e!==r&&o.setAttribute(n,e)}}}function Ta(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}function Ra(e){const t=[],n=lt(e);for(const e of n){const n=Ia(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:Ta(o),parseBindTextResults:n})}return t}function ja(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 La=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Wa=ka();function Da(e,t){const n=t.outFilters;return{...t,outFilters:[...n,Wa],bindingType:e}}function Ba(e,t,n,o,s,r=!0){ja(t),"string"==typeof o&&Oa(t,o),za(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ra(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 za(e,t,n,s){const r=o.commentElsePrefix,i=it(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=Ma(i,n));let a=Ee(i)[0];const d=La.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=xs();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&ee("'else' binding found without preceding 'if' or 'elseif' binding."),a=Da("else",l.parseBindTextResult),p=Ba(e,f,a,m,s,!1),xa(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Ta(o),parseBindTextResults:Ia(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&ee("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ba(e,f,a,m,s),xa(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=xs(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Da("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Ta(n),parseBindTextResults:Ia(n)}),xa(o,e,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:Ta(g),parseBindTextResults:Ia(g)})):t.replaceWith(g)}else{p=Ba(e,f,a,m,s),xa(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 Fa=()=>`[${o.bindAttributeName}]`;function qa(e){if(Qo(e))return!0;if(!Va(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(Fa());return null!==t&&Qo(t)}function Va(e){return 1===e.nodeType}function Ha(e){if(qa(e))return;Y(e),za(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);ra(t&&s?n:e,null)}const Ua=[];function Ga(){const e=Ua.splice(0,Ua.length);for(const t of e)Ha(t);a()}const Ka={protocol:"wcs-binder",version:1,bind:function(e){var t;Va(e)&&!qa(e)&&(t=e.getRootNode(),ba.has(t)?Ha(e):Ua.push(e))}};const Ja="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Xa=0;async function Qa(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Xa}\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 ${Ja}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Ja}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Ya(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){ee(`Failed to load script file: ${e}`)}}class Za{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&ee("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=u&&ee("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&&ee("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&&ee("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&&ee(`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 el={$updatedCallback:M,$streams:z},tl=new WeakSet;function nl(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function ol(e){if(!tl.has(e)){for(const t of Object.keys(el)){if(!(t in e))continue;const n=el[t];n in e&&ee(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".`);const o=nl(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}tl.add(e)}}const sl=new WeakMap;function rl(e,t){let n=sl.get(e);void 0===n&&(n=new Map,sl.set(e,n));let o=n.get(t);return void 0===o&&(o=new Tn(t,e),n.set(t,o)),o}const il=new WeakMap;function al(e){const t=il.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 rl(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:rl(e,n)}},set(){ee("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){ee("$command namespace is read-only; deleting from it is not allowed.")}});return il.set(e,n),n}const ll=Symbol("wcs.notHandled"),cl=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],dl=new Map;function ul(e,t){dl.set(e,t)}const fl=new Map;let hl=[],pl=[];function ml(e,t){fl.set(e,t),hl=Array.from(fl.values()).sort((e,t)=>e.order-t.order),pl=hl.slice().reverse()}function gl(e,t){for(let n=0;n<hl.length;n++)hl[n].activate?.(e,t)}function yl(e){"readonly"===e.mutability&&ee("This state is readonly.")}const wl=new Map;class bl{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=oe(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 vl(e){let t;return wl.get(e)??(wl.set(e,t=new bl(e)),t)}function $l(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:Zt(n.listIndex,o,n.pathInfo.wildcardCount)}function Sl(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=Yt(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?Zt(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?Zt(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function xl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function Pl(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!==ll)return a}}return ll}function Il(e,t,n,o,s){if(t.pathInfo.segments[0]===W)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}(al(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=Pl(s,t,null,n,o);if(r!==ll)return r;ee(function(e,t,n){return`[${Wi.binding}] Path "${e}" does not exist on the state tree.${ie(e,Li(t,"",n))}${ae}`}(t.pathInfo.path,e,s.getterPaths))}const r=kl(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!==c&&!(i in Object(r))){const e=Pl(s,t,Object(r),n,o);if(e!==ll)return e}if(i===c){const e=t.listIndex?.index??ee(qi(`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 Nl(e,t,n,o,s){const r=Ut(s,t),i=function(e){return Bs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Il(e,t,n,o,s);return zs(r,{value:l,dirty:!1,generation:a}),l}function kl(e,t,n,o){Sl(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!==ll)return i}}return xl(s,t)?Nl(e,t,n,o,s):Il(e,t,n,o,s)}function _l(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=gn(f,r),p=Ut(n.stateElement,h),m=Nt(p),g=kl(e,h,t,n),y=Ar(r,m,g).newIndexes,w=l[c]??null;if(i.set(p,g),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??ee(`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())kt(e,Array.isArray(t)?t:[]);return l}function Al(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Ws(kl(e,gn(a,r),t,n),r);null==l&&ee(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??ee(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Cl(e,t,n,o){"object"==typeof e&&null!==e||ee(`${U} 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&&ee(`${U} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function El(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&ee(`${U} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function Ml(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];Cl(a,n,o,i);const l=El(a,t,n,o,i);r.has(l)&&ee(`${U} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Ol(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 Tl(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=kl(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===c){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const Rl=new WeakMap;function jl(e,t){null===t?Rl.delete(e):Rl.set(e,t)}function Ll(e,t,n){const s=gn(oe(e.wildcardParentPaths[t]),n),r=Ut(e.stateElement,s),i=Nt(r),a=e.stateProxy[Mt](s),l=Ar(s.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${t}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)Ll(e,t+1,n)}const Wl=[];function Dl(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:Wl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Wl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Bl=[];function zl(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Bl;let s=null;const r=t+l;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=oe(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Bl}function Fl(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=oe(r);if(e.listPathSet.has(o)&&s.lastSegment===c){const i=e.stateProxy[Mt](t),a=Ut(e.stateElement,t),l=Nt(a),c=Ar(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Dl(e,o,0,0,c);for(const t of d.fullRows){const o=gn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=zl(e,r,s);if(null===t)for(const t of d.movedRows){const o=gn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=gn(s,o);e.result.add(t),n.push(t)}}}else{const o=gn(s,t.listIndex);e.result.add(o),n.push(o)}}const r=e.dynamicMap.get(o);if(r)for(const o of r){const s=oe(o),r=[];if(s.wildcardCount>0){const n=Yt(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&ee(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=Zt(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Ll(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&ee(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=Zt(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=gn(s,t);e.result.add(o),n.push(o)}}}function ql(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&&ee(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),n(a),i.length=0,Fl(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}(u,t,a);for(const[e,t]of u.observedListValueByAbsAddress)kt(e,t);return Array.from(u.result)}function Vl(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 Hl(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 Ul(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 Gl(e,t,n,s,r,i){const a=function(e,t){return!0===er.get(e)?.byPath.has(t)||!0===rr.get(e)?.has(t)}(e,t),l=function(e,t){return!0===ar.get(e)?.has(t)}(e,t);if(!a&&!l)return;const d=Zs(),u=o.enablePropagationContext?io()??null:null,f=e=>{Fs(e),d.enqueueAbsoluteAddress(e,u)};a&&vr(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=oe(t).segments.length,r=[];for(const i of ar.get(e).get(t)){const t=oe(i).segments.slice(s);if(t.includes(c))Sr(e,i,r);else for(const s of vr(e,i,!0,$r(n,t),$r(o,t)))r.push(s)}return r}(e,t,n?s:i(),r).forEach(f)}function Kl(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?io()??oo(-1):null,c=Zs();c.enqueueAbsoluteAddress(t,l),i&&Fs(t),ql(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Ut(s.stateElement,t);Fs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Jl(e,t,n,o,s){s&&(e.getterPaths.has(t)?Fs(n):zs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function Xl(e,t,n,o,s,r,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=kl(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===c){const e=t.listIndex?.index??ee(qi(`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{Kl(t,n,s,r,i,a)}}function Ql(e,t,n,o,s,r,i,a){const d=t.parentAddress??ee(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=kl(e,d,s,r)??[];let f=(h=u,Rl.get(h)??null);var h;if(null===f){const e=Ls(u)??[];f={value:[...u],listIndexes:[...e]},jl(u,f)}try{return Xl(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=kl(e,d,s,r)??[],a=Array.isArray(i)?Ls(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:_s(d.listIndex,-1);a[h]=p;if(new Set(i).size===f.value.length){for(let e=0;e<a.length;e++)a[e].index=e;jl(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=Zs(),d=Ut(i,e);vt(d)===n&&(Ds(t.value,t.listIndexes),$t(d,t.value),function(e){Er.add(e)}(t.value));a.enqueueRenderOnlyAddress(d);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=oe(e.pathInfo.path+l+c);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=gn(f,n),d=Ut(i,c);if(void 0===l){const n=Gt(i,f,t.listIndexes[e]??null);Ul(i,d,n),Kl(c,d,s,r,null,xl(i,c),"full");continue}ql(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Ut(i,e);Fs(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(d,f,i,a,s,r)}}}function Yl(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=kl(e,t,o,s),a=function(e,t,n,o){const s=Ml(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Ml(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===Ls(o)&&Ar(a,null,o);const d=Ar(a,o,n.list),u=Zl(e,t,n.list,s,r,i),f=oe(i+l+c);for(const t of n.matched){const n=Ol(t.oldRow,t.newRow);if(0===n.length)continue;const o=d.newIndexes[t.position];for(const i of n)void 0!==o?Yl(e,gn(oe(f.path+l+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return Zl(e,t,n,o,s,null)}function Zl(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,d=a.addressHooks;if(d){const e=d.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==ll)return i}}const u=!!co&&(co=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=kl(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===c?t.listIndex?.index:e;let p,m=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in f,t=void 0!==h?f[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,m=!0}Gl(a,l,m,p,n,()=>f[h]);const g=xl(a,t),y=Ut(a,t);null!==wt&&wt({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:m}),Vl(a,l,y,p,m);let w=!1;try{if(void 0===h&&ee(qi(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),d&&0!==d.writeMissing.length&&e!==c&&!(h in f)){const e=d.writeMissing;for(let o=0;o<e.length;o++){w=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==ll)return i;w=!1}}return Reflect.set(f,h,n)}finally{Kl(t,y,s,r,i,g),w?Fs(y):Jl(a,l,y,n,g),Hl(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=kl(e,t,s,r);if(Tl(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Gl(a,l,h,f,n,()=>kl(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),m=xl(a,t),g=Ut(a,t);null!==wt&&wt({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),Vl(a,l,g,f,h);try{return p?Ql(e,t,g,n,s,r,i,m):Xl(e,t,g,n,s,r,i,m)}finally{p||Jl(a,l,g,n,m),Hl(a,t.pathInfo,{value:n})}}function ec(e,t,n,o){return(t,s,...r)=>{const i=oe(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&&ee(Bi("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=gn(i,Al(e,n,o,i,s));if(0===r.length)return kl(e,a,n,o);yl(o),Yl(e,a,r[0],n,o)}}function tc(e,t,n,o){const s=ec(e,0,n,o);return(t,r)=>{const i=oe(t);if(void 0===r||Array.isArray(r)||ee(`$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&&ee(Bi("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=$l(o,i.wildcardPaths[e]);if(t){r=en(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&&ee(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=_l(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 nc(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return $l(o,s.wildcardPaths.at(-1)??ee(`lastWildcardPath is null: ${t.pathInfo.path}`))??ee(`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]??ee(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Ws(kl(e,gn(i,s),n,o),s)??ee(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??ee(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??ee(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":ee(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function oc(e,t,n,o){return(t,s,r,i)=>{yl(o);const a=oe(t);Array.isArray(s)||ee(Fi(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&ee(Bi("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&ee(Fi(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&ee(Fi(t,"requires an array as the value when { spread: true } is set."));const d=_l(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&ee(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=Al(e,n,o,a,d[t]);u.push(gn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(kl(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(Yl(e,s,i,n,o),f++)}return f}}function sc(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of oe(t).cumulativePaths)if(n.has(e))return!0;return!1}const rc=/^\$\d+$/,ic=`${G}${l}`,ac=`${K}${l}`,lc=new WeakMap;function cc(e,t,n,o){const s=A[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&rc.test(t)&&ee(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&ee(`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&&ee(`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=Zt(r,i,a.wildcardCount);return c?.index??ee(`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!==ll)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>tc(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>oc(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=vl(t),i=nc(e,r,n,o),a=gn(r.pathInfo,i),l=Ut(s,a),c=Zs();c.enqueueAbsoluteAddress(l),ql(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Ut(s,e);Fs(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)}}}(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>ec(e,0,n,o)(t,s,...r);case"$dependOn":case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(H)&&ee(`[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&&ee(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??ee("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(sc(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&yr(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)&&gr(o.stateElement,e,t,Ut(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=sc(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?yr(o.stateElement,e):gr(o.stateElement,e,i,Ut(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||ee(`$eqIndex("${e}") needs a list row scope.`);const r=Zt(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&ee(`$eqIndex("${e}", ${t}): no list index at that level.`),sc(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&yr(o.stateElement,e),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?Ls(l):null;null!==t?function(e,t,n,o,s){sr=!0,dr(e).lastValue.set(t,s),cr(e,t);let r=rr.get(e);void 0===r&&rr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=ir.get(o);void 0===l?ir.set(o,l=[]):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a&&(a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a)),a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){sr=!0;const r=dr(e);cr(e,t),mr(r,t,s,o,hr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Ut(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 W:return al(o.stateElement)}if(!t.startsWith(ic)&&!t.startsWith(ac))return}const r=vl(t),i=nc(e,r,n,o),a=gn(r.pathInfo,i);return kl(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=lc.get(e);return void 0===t&&(t=new Map,lc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Et:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&ee("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 Mt:i=t=>kl(e,t,n,o);break;case Ot:i=t=>Tl(e,t,n,o);break;case Tt:i=(t,s)=>Yl(e,t,s,n,o);break;case Rt:i=()=>async function(e,t,n){const o=Reflect.get(e,C);"function"==typeof o&&await o.call(n)}(e,0,n);break;case jt:i=()=>function(e,t,n){const o=Reflect.get(e,E);"function"==typeof o&&o.call(n)}(e,0,n);break;case Lt:i=t=>function(e,t,n,o){const s=Reflect.get(e,M);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=en(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}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 Wt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,O);"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 dc{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=ya(e);null===n&&ee("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&&ee("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&ee(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),ee(`[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&&ee(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return cc(e,t,n,this)}set(e,t,n,o){return yl(this),function(e,t,n,o,s){if("string"==typeof t){const r=vl(t),i=nc(e,r,o,s);return Yl(e,gn(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)}}const uc=Promise.resolve(),fc=new Map;let hc=[];function pc(e,t){fc.set(e,t),hc=Array.from(fc.values()).sort((e,t)=>e.order-t.order)}function mc(e,t){return ee(da(e,t))}const gc="undefined"==typeof HTMLElement?class{}:HTMLElement;function yc(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 wc=null;const bc=new Set(["for","if","elseif","else"]);function vc(e,n,o){const s=new Map;for(const e of o){const t=oe(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=Ut(e,t);if(i.has(n))return;i.add(n);const o=fn(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(gn(n,t.listIndex))}};_t();try{if(e.createState("readonly",t=>{for(const o of n){const n=gn(oe(o),null);a(n);try{ql(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)bc.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=()=>{sa(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Hs("state",s);void 0!==i&&i.catch(Xs)}finally{At()}}class $c extends gc{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return wa(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 Za}();_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&&ee(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){ol(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<hl.length;o++)hl[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[L];if(void 0===n)return t;Array.isArray(n)||ee(`${L} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ee(`${L} entries must be non-empty strings.`),e===W&&ee(`${L} entry "${e}" conflicts with the reserved namespace name "${W}".`),t.has(e)&&ee(`${L} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[D];if(void 0===n)return t;Array.isArray(n)||ee(`${D} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ee(`${D} entries must be non-empty strings.`),t.has(e)&&ee(`${D} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[U];if(void 0===t)return null;"object"==typeof t&&null!==t||ee(`${U} 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&&ee(`${U} entry path must be a non-empty string.`);const t=e.split(l);t.some(e=>0===e.length)&&ee(`${U} entry "${e}" must not contain empty path segments.`),t[t.length-1]===c&&ee(`${U} entry "${e}" must be the list path itself, not the element path (drop the trailing "${l}${c}").`),-1!==e.indexOf(H)&&ee(`[wcs/recursion-unsupported] ${U} entry "${e}" uses "${H}", which ${U} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${l}${c}${l}children").`),"function"!=typeof o?("string"!=typeof o&&ee(`${U} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&ee(`${U} entry "${e}" key field name must be a non-empty string.`),(o.includes(l)||o.includes(c))&&ee(`${U} entry "${e}" key field name "${o}" must be a flat property name ("${l}" / "${c}" are not allowed).`),o in Object.prototype&&ee(`${U} 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<hl.length;o++)hl[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<hl.length;o++)hl[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&wc?.reset(this),this._hasUpdatedCallback=M in e,this._hasErrorCallback=O in e,i=this,Cn.delete(i),function(e,t,n){for(let o=0;o<hl.length;o++)hl[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[B];if(void 0!==o){"object"==typeof o&&null!==o||ee(`${B} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||ee(`${B} entry "${t}" is not declared in $eventTokens.${ie(t,n)}`),"function"!=typeof s&&ee(`${B} entry "${t}" must be a function.`),En(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=yc(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<hl.length;o++)hl[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<hl.length;o++)hl[o].register?.(e,t,n)}(this,e,n),gl(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 <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?fa('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){ee("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 Qa(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){try{const t=await fetch(e);return t.ok||ee(`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 Ya(e);ee(`Unsupported src file type: ${e}`)}}catch(e){ee(`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&&($a(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),ee(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===ya(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),pa.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<hc.length;o++)hc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{C in e&&await e[Rt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{E in e&&e[jt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<hc.length;t++)if(!0===hc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||ya(this._rootNode)===this||$a(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<hc.length;t++){const n=hc[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(J))try{mc("dcc",`a <${o.tagNames.state}> inside a [${J}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{mc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<hc.length;t++){const n=hc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&mc("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let s=!1;try{s=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!s)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 fa('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}gl(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<hc.length;t++)if(!0===hc[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<hc.length;n++)hc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{$a(this.rootNode,null),e=this,il.delete(e),function(e){for(let t=0;t<pl.length;t++)pl[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=>(ol(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",F)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&ee(`$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 ji(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&&ee("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=dl.get(e);return void 0===n&&ee(da(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<cl.length;n++){const o=cl[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",R)}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){return this._addDependency(this._dynamicDependency,e,t)}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+c)),!this._pathSet.has(e)){const t=oe(e);if(this._pathSet.add(e),wc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=oe(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 dc(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&&ee(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);!function(e){for(let t=0;t<hc.length;t++)hc[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&ee("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(yc(n)))e.startsWith("$")||e.includes(c)||"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){vc(this,e,this._pathRegistrations.keys())}}const Sc=[];function xc(e=customElements){for(let t=0;t<Sc.length;t++)Sc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,$c)}function Pc(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 Ic(e,t){const o=Pc(e);var r;o&&((r=o).tagNames&&Object.assign(n.tagNames,r.tagNames),"string"==typeof r.bindAttributeName&&(n.bindAttributeName=r.bindAttributeName),"string"==typeof r.commentTextPrefix&&(n.commentTextPrefix=r.commentTextPrefix),"string"==typeof r.commentForPrefix&&(n.commentForPrefix=r.commentForPrefix),"string"==typeof r.commentIfPrefix&&(n.commentIfPrefix=r.commentIfPrefix),"string"==typeof r.commentElseIfPrefix&&(n.commentElseIfPrefix=r.commentElseIfPrefix),"string"==typeof r.commentElsePrefix&&(n.commentElsePrefix=r.commentElsePrefix),"string"==typeof r.locale&&(n.locale=r.locale),"boolean"==typeof r.debug&&(n.debug=r.debug),"boolean"==typeof r.enableMustache&&(n.enableMustache=r.enableMustache),"boolean"==typeof r.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=r.enableDirectionalInitialSync),"boolean"==typeof r.enablePropagationContext&&(n.enablePropagationContext=r.enablePropagationContext),"boolean"==typeof r.enableContractAnalyzer&&(n.enableContractAnalyzer=r.enableContractAnalyzer),"boolean"==typeof r.sameValueGuard&&(n.sameValueGuard=r.sameValueGuard)),xc(t),function(){const e=globalThis;void 0===e[s]&&(e[s]=Ka)}()}function Nc(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 kc(e,t){for(const n of e)if(Nc(t,n.innerSegments))return n;return null}function _c(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+l+n.join(l)}let Ac=0;const Cc=["$watch",z,"$scan","$listKeys",M,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Ec=new Set;function Mc(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function Oc(e,t,n,o,s,r=new Set){0===n.length&&ee(`Cannot build a mount record without host bindings for "${t}".`),ol(s);const i=[],a=new Set;let c=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(l);a.has(n)&&ee("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(g)};i.push(o),0===t.length&&(c=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++Ac,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)e.innerSegments.length>0&&p.add(e.innerSegments[0]);const m={};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)||(m[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+l+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,privateSnapshot:m,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function Tc(e){const t=e.indexOf(l);return-1===t?e:e.slice(0,t)}function Rc(e,t){const n=kc(e.entries,t);return null===n?null:_c(n,t)}function jc(e,t){return e.markerBasePath+l+t}function Lc(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+l+n;s.set(n,{accessorName:o,indexShift:oe(r).wildcardCount-oe(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function Wc(e,t){return!e.injectedKeys.has(t)&&!e.mappedKeys.has(t)&&("function"==typeof e.stateObject[t]&&!e.getterKeys.has(t)||Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t))}function Dc(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(l)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${Tc(t)}: path") or declare the key on the component state.`}const Bc=/^\$(\d+)$/;function zc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=Tc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||Wc(e,o))return null;const s=function(e,t){return kc(e.entries,t)}(e,t.split(l));return null!==s&&s.readonly?s:null}function Fc(e,t){const n=zc(e,t);if(null!==n){const o=0===n.innerSegments.length?"":l+n.innerSegments.join(l);ee(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${g}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${g} from the mount.`)}return qc(e,t)}function qc(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(l);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===c){o=e;break}if(-1===o)return Lc(e,e.markerBasePath,t,t),jc(e,t);if(Wc(e,n[0]))return Lc(e,e.markerBasePath,t,t),jc(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Rc(e,s);null===i&&ee(Dc(e,t)),0===r.length&&ee(`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+l+e.marker;return Lc(e,a,r.join(l),t),a+l+r.join(l)}(e,t);const o=Tc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return jc(e,t);if(Wc(e,o))return jc(e,t);const s=Rc(e,t.split(l));if(null!==s)return s;ee(Dc(e,t))}function Vc(e,t,n){let o;const s=Bc.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:oe(qc(e,t)).wildcardCount-oe(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=qc(e,t.statePathName),"for"===t.bindingType){const n=oe(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+l+c,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(g)&&null!==zc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:oe(o),...i?{propModifiers:[...r,g]}:{}}:t}function Hc(e,t,n,o,s){if(void 0===o)return;const r=oe(n).wildcardCount-oe(t).wildcardCount;return 0===r?o:(s.length<r&&ee(`Cannot resolve "${t}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const Uc=new WeakMap,Gc=new WeakMap;const Kc=new WeakMap;const Jc=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)}),Xc=new WeakMap;function Qc(e){return Xc.get(e)??null}let Yc=!1;function Zc(){Yc||(Yc=!0,mt=e=>Uc.has(e)?e.host:null)}function ed(e){const t=Kc.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 td(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Kc.get(e);if(void 0===o)return null;const s=t.indexOf(l,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 nd="3.2.0",od=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function sd(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 rd(e){const t=function(e){const t=er.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:rr.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 id="__WCSTACK_DEVTOOLS_HOOK__";function ad(){const e=globalThis,t=e[id];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[id]=n,n}const ld=e=>{null!==wt&&wt({type:"state:update-batch",addresses:e})};function cd(e){const t=null!==wt;!function(e){wt=e}(e);const n=null!==e;n&&!t?Js(ld,0):!n&&t&&function(e){const t=Us.findIndex(t=>t.listener===e);-1!==t&&Us.splice(t,1)}(ld)}function dd(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 ud(e){return ya(e)??ee("devtools: no state tree on this root")}let fd=null;function hd(){if(t())return;if(null!==fd)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:nd,getStateElements(){const e=[];for(const t of ma)e.push(dd(t));return e},overlays:e=>ed(ud(e)).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join("."),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]})),keyedSubscriptions:e=>rd(ud(e)),keys(e){const t=ud(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 ud(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){ud(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>function(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=[...e.inFilters,...e.outFilters].map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=Pa(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(sd(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=et(t,Ee(n));for(const o of e)r(sd(t,o,"attribute",n))}catch{}continue}const t=od.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=Pa(s);if(null===a){if(n===o.commentTextPrefix)try{r(sd(e,je(s),"comment",s))}catch{}}else r(sd(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:cd};fd=e,ad().register(e)}const pd={name:"devtools",install(){hd()}},md=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),gd=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const yd=new WeakMap;const wd=new WeakMap,bd=new WeakSet,vd=new WeakMap;function $d(e,t,n,o){console.warn(`[@wcstack/state] [${Wi[n]}] ${Di[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ie(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ae}`),null!==wt&&wt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Sd={check:function(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=e.addressHooks;if(s){const t=s.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const r=oe(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=yd.get(e);return void 0===n&&(n=new Set,yd.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const i=function(e,t,n){if(void 0!==ji(e,t))return gd;const o=oe(t).segments;let s=e,r="";for(let t=0;t<o.length;t++){const i=o[t],a=r;if(r=0===t?i:r+l+i,t>0&&t<o.length-1&&void 0!==ji(e,r))return md;if(Object(s)!==s)return md;if(i===c){if(!Array.isArray(s)||0===s.length)return md;s=s[0];continue}const d=ji(s,i);if(void 0===d)return{existence:"missing",missingSegment:i,candidates:Li(s,a,n)};if("function"==typeof d.get)return t===o.length-1?gd:md;s=d.value}return gd}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===vd.get(e)?.has(t)}(e,n)||("binding"!==o?$d(e,n,o,i):function(e,t,n){let o=wd.get(e);void 0===o&&(o=new Map,wd.set(e,o));if(o.set(t,n),bd.has(e))return;bd.add(e),setTimeout(()=>function(e){bd.delete(e);const t=wd.get(e);if(void 0===t)return;wd.delete(e);for(const[n,o]of t)$d(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){yd.delete(e),wd.delete(e)},markExported:function(e,t){let n=vd.get(e);void 0===n&&(n=new Set,vd.set(e,n)),n.add(t),wd.get(e)?.delete(t)}};let xd=!1;function Pd(){xd||(xd=!0,function(e){wc=e}(Sd))}const Id={name:"diagnostics",install(){Pd()}};function Nd(e){ee(`filter ${e} requires at least one option`)}function kd(e){ee(`filter ${e} requires a number as option`)}function _d(e){ee(`filter ${e} requires a number value`)}function Ad(e){ee(`filter ${e} requires a date value`)}const Cd={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function Ed(e){return!(!e||isNaN(Number(e)))}const Md={eq:(e,t)=>{const n=e?.[0]??Nd("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Ed(n)||kd("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Nd("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Ed(n)||kd("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>("boolean"!=typeof e&&ee(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??Nd("lt");return Ed(t)||kd("lt"),e=>("number"!=typeof e&&_d("lt"),e<Number(t))},le:e=>{const t=e?.[0]??Nd("le");return Ed(t)||kd("le"),e=>("number"!=typeof e&&_d("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??Nd("gt");return Ed(t)||kd("gt"),e=>("number"!=typeof e&&_d("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??Nd("ge");return Ed(t)||kd("ge"),e=>("number"!=typeof e&&_d("ge"),e>=Number(t))},add:e=>{const t=e?.[0]??Nd("add");return Ed(t)||kd("add"),e=>("number"!=typeof e&&_d("add"),e+Number(t))},sub:e=>{const t=e?.[0]??Nd("sub");return Ed(t)||kd("sub"),e=>("number"!=typeof e&&_d("sub"),e-Number(t))},mul:e=>{const t=e?.[0]??Nd("mul");return Ed(t)||kd("mul"),e=>("number"!=typeof e&&_d("mul"),e*Number(t))},div:e=>{const t=e?.[0]??Nd("div");return Ed(t)||kd("div"),e=>("number"!=typeof e&&_d("div"),e/Number(t))},mod:e=>{const t=e?.[0]??Nd("mod");return Ed(t)||kd("mod"),e=>("number"!=typeof e&&_d("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&_d("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??Nd("clamp");Ed(t)||kd("clamp");const n=e?.[1]??Nd("clamp");Ed(n)||kd("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&_d("clamp"),Math.min(Math.max(e,o),s))},toFixed:e=>{const t=e?.[0]??"0";return Ed(t)||kd("toFixed"),e=>("number"!=typeof e&&_d("toFixed"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&_d("locale"),e.toLocaleString(t??o.locale))},upper:e=>e=>String(e).toUpperCase(),lower:e=>e=>String(e).toLowerCase(),capitalize:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??Nd("slice");Ed(n)||kd("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Ed(o)||kd("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??Nd("substr");Ed(t)||kd("substr");const n=e?.[1]??Nd("substr");return Ed(n)||kd("substr"),e=>String(e).substr(Number(t),Number(n))},padStart:e=>{const t=e?.[0]??Nd("padStart");Ed(t)||kd("padStart");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},padEnd:e=>{const t=e?.[0]??Nd("padEnd");Ed(t)||kd("padEnd");const n=e?.[1]??" ";return e=>String(e).padEnd(Number(t),n)},repeat:e=>{const t=e?.[0]??Nd("repeat");return Ed(t)||kd("repeat"),e=>String(e).repeat(Number(t))},reverse:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??Nd("truncate");Ed(t)||kd("truncate");const n=Number(t),o=e?.[1]??"…";return e=>{const t=String(e);return t.length<=n?t:t.slice(0,n)+o}},join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||ee(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=e?.[0]??"0";return Ed(t)||kd("round"),e=>{"number"!=typeof e&&_d("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Ed(t)||kd("floor"),e=>{"number"!=typeof e&&_d("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Ed(t)||kd("ceil"),e=>{"number"!=typeof e&&_d("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Ed(t)||kd("percent"),e=>("number"!=typeof e&&_d("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??Nd("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Ad("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Ad("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Ad("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Ad("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||Ad("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]??Nd("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Nd("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},Od={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:[1,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,0],time:[0,0],datetime:[0,0],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]},Td=Md,Rd=Md;let jd=!1;const Ld={name:"formats",install(){jd||(jd=!0,pe("input",Rd,Od,Cd),pe("output",Td,Od,Cd))}};function Wd(e){return-1!==e.indexOf(H)}function Dd(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+l;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(Wd(o))return null;const s=o.slice(1).split(l);return s[0]===c||s.some(e=>0===e.length)?null:o}function Bd(e){return 0===e.length?e:l+qd(e.slice(1))}function zd(e,t,n){const o=l+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 Fd(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(l,o-1))if(zd(e,t,n.slice(0,o)))return!0;return!1}function qd(e){const t=e.split(l);for(let e=0;e<t.length;e++)t[e]===c||Number.isNaN(Number(t[e]))||(t[e]=c);return t.join(l)}function Vd(e,t){const n=e.repeat.split(l),o=l+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===l+e.repeatList+l+"length")return!0;for(let e=1;e<n.length;e++)if(s===l+n.slice(0,e).join(l))return!0;return!1}function Hd(e,t,n){n<0&&ee(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=l+e.repeat;const s=o+t;let r=0;for(const e of s.split(l))e===c&&r++;return r>d&&ee(`[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 Ud(e,t){return Hd(e,"",t)}function Gd(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=l+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 Kd(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=l+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 Jd(e,t,n){const o=e.recursionRegistry,s=Dd(o.spec,n);null===s&&ee(zi(n,o.spec.recursiveAnchor));const r=Kd(t,o);return null===r&&ee(`[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 Xd(e,t,n,o,s){const r=o.spec,i=[],a=new Map,c=[],d=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(gn(e,n));const s=m(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function m(o,s,i){const l=gn(o,s),c=Ut(n.stateElement,l),u=kl(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)&&ee(`[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)&&ee(`[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 "${d}" array.`),o})(o.path,u,i),p=Ar(s,Nt(c),u);return a.set(c,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const g=(e,t,n)=>{const{rows:r,tracked:a}=m(t,n,h);if(0===r.length)return;const u=(e=>{const t=c[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:oe(n),childListPathInfo:oe(r+l+d)};return c[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(gn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),g(e+1,u.childListPathInfo,n)}f.delete(y)};g(0,oe(u),null);for(const[e,t]of a)kt(e,t);return i}function Qd(e,t,n,o,s,r,i){yl(n);const a=n.stateElement.recursionRegistry,l=Dd(a.spec,o);null===l&&ee(zi(o,a.spec.recursiveAnchor));const c=Bd(l);Array.isArray(s)||ee(Fi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&ee(`[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&&ee(Fi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&ee(Fi(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){Vd(e,n)&&ee(`[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&&ee(`[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=Xd(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Yl(e,u[o],r,t,n),f++);return f}const Yd={write(e,t){if(!0!==e.hasRecursion)return ll;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&ee(`[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.`),ll},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return ll;if("$getAll"===t)return(t,s)=>{if(Wd(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Dd(r.spec,o);null===i&&ee(zi(o,r.spec.recursiveAnchor)),Array.isArray(s)||ee(`[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&&ee(`[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=Xd(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(kl(e,a[o],t,n));return l}(o,n,e,t,s);t=Jd(e.stateElement,e,t)}return tc(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>Wd(t)?Qd(o,n,e,t,s,r,i):oc(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&Wd(t)){const s=vl(Jd(e.stateElement,e,t)),r=nc(o,s,n,e);return kl(o,gn(s.pathInfo,r),n,e)}return ll}};let Zd=!1;function eu(e,t){"string"==typeof t&&0!==t.length||ee(`[wcs/recursion-declaration-invalid] ${V} ${e} must be a non-empty string.`);const n=t.split(l);n.some(e=>0===e.length)&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain empty path segments.`),n.length<2&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must name a list element: a property path ending with "${l}${c}" (for example "nodes${l}${c}").`),n[n.length-1]!==c&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must end with "${l}${c}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===c&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must have exactly one "${c}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===H&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain "${H}" — the declaration is what gives "${H}" its meaning.`),isNaN(Number(n[o]))||ee(`[wcs/recursion-declaration-invalid] ${V} ${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 tu=new WeakSet;function nu(e){return"function"==typeof e.get&&tu.has(e.get)}function ou(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&nu(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}!function(e,t,n){for(const o of n){const n=oe(o),s=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void zs(Gt(e,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=t;for(const e of s[i].segments.slice(a))l=l?.[e];if(!Array.isArray(l))return;const c=Ls(l);if(null===c)return;const d=Math.min(c.length,l.length);for(let e=0;e<d;e++)r(l[e],c[e],i+1)};r(t,null,0)}}(e,t,n)}}const su="[wcs/recursion-declaration-invalid]";class ru{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=yc(t);for(const[t,o]of Object.entries(n)){if(!Wd(t))continue;"function"==typeof o.set&&ee(`${su} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&ee(`${su} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Dd(e,t);null===n&&ee(zi(t,e.recursiveAnchor)),0===n.length&&ee(`${su} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${l}total"), not the node.`),Vd(e,Bd(n))&&ee(`${su} "${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}${l}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(Wd(t)||nu(n))continue;const e=this._matchExpansion(t);null!==e&&ee(`${su} "${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++)zd(this.spec,e[t].suffix,e[n].suffix)&&ee(`${su} "${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(Fd(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=qd(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(l);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(l,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!==Gd(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=Gd(this.spec,e.suffix,t);null!==n&&(null!==o&&ee(`"${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||nu(s)||ee(`"${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,tu.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(Ud(e,o)+l+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 ou(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=Hd(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 iu="recursionSpec",au="recursionRegistry",lu={order:5,validateEarly(e,t,n){const o=function(e){const t=e[V];if(void 0===t)return null;"object"==typeof t&&null!==t||ee(`[wcs/recursion-declaration-invalid] ${V} 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&&ee(`[wcs/recursion-declaration-invalid] ${V} must declare exactly one anchor; it is empty.`),n.length>1&&ee(`[wcs/recursion-declaration-invalid] ${V} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];eu("anchor",o),"string"!=typeof s&&ee(`[wcs/recursion-declaration-invalid] ${V} entry "${o}" must map to the repeating sub-path as a string (for example "children${l}${c}").`),eu("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(l)),i=s.slice(0,s.lastIndexOf(l)),a=r+l+H;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(iu,o),n.set(au,null===o?null:new ru(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(au)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",V)},apply(e,t,n){const o=n.get(iu)??null;null!==o&&e.addListPath(o.anchorList)}};let cu=!1;function du(){cu||(cu=!0,Zd||(Zd=!0,ul("recursion",Yd)),ml("recursion",lu))}const uu={name:"recursion",install(){du()}};const fu={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let hu=!1;function pu(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 mu(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 gu(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 yu(e){return e.startsWith("$")}function wu(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 bu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||ee(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||ee(`${t} entries must be non-empty strings.`),e.startsWith("$")&&ee(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&ee(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function vu(e){ol(e);const t=bu(e,R)??[],n=bu(e,j)??[],o=yc(e),s=function(e){const t=e[z];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}ee(`${R} entry "${e}" is not declared on the state.${ie(e,wu(o,"value"))}`)}"function"==typeof t.value&&ee(`${R} entry "${e}" is a method. Declare it in ${j} instead.`)}for(const e of n){const t=o[e];void 0===t&&ee(`${j} entry "${e}" is not declared on the state.${ie(e,wu(o,"method"))}`),"function"!=typeof t.value&&ee(`${j} entry "${e}" is not a method. Declare it in ${R} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function $u(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||ee(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=He(e);null!==r&&"function"==typeof r.define||ee(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&ee(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=vu(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(J))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const e=He(this._shadow);return null!==e&&Ue(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(m.bindableEventMap).length>0){const t=e.querySelector(p);t?(hu||(hu=!0,ul("dcc",fu)),t.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${R} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=yc(n);for(const[e,t]of Object.entries(g)){if(yu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=gu(e,o)}else n.get=pu(e),n.set=mu(e);Object.defineProperty(m.prototype,e,n)}for(const e of u)Object.defineProperty(m.prototype,e,{configurable:!0,enumerable:!0,get:pu(e),set:mu(e)});r.define(s,m)}async function Su(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&ee(`"bind-component" cannot be used inside a [${J}] 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 Ya(t);ee(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await Qa(n,t.tagName.toLowerCase());ee(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){ee(`DCC: Failed to load state: ${e}`)}}(o,t);$u(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const xu={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(J)?Su(e,t.host,t):null}};let Pu=!1;const Iu=new WeakMap;function Nu(e,t,n){let o=Iu.get(e);void 0===o&&(o=new Map,Iu.set(e,o));const s=o.get(t);null!=s&&ee(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function ku(e,t){if(null===e)return!1;const n=Iu.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+l)||e.startsWith(t+l))return!0;return!1}const _u=new WeakMap;const Au=[];function Cu(e,t,n,o){if(t.length>0){const s=n.split(l),r=kc(t,s);if(null!==r)return o&&r.readonly&&ee(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${x}.${r.innerSegments.join(l)}#${g}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${g} from the injection.`),_c(r,s)}return e+l+n}function Eu(e,t,n){for(const e of t){const t=e.outerPathInfo.path;if(n===t)return e.innerSegments.join(l);if(n.startsWith(t+l))return e.innerSegments.join(l)+n.slice(t.length)}return n===e?"":n.startsWith(e+l)?n.slice(e.length+1):null}function Mu(e,t,n=Au){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](Cu(e,n,s,!1),...r)}return"$setAll"===s?(o,...s)=>t.$setAll(Cu(e,n,o,!0),...s):"$resolve"===s?(o,...s)=>t.$resolve(Cu(e,n,o,s.length>1),...s):t[s]}return t[Cu(e,n,s,!1)]}},set:(o,s,r)=>("string"!=typeof s||(t[Cu(e,n,s,!0)]=r),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Ou=new WeakMap,Tu=[];const Ru=new WeakMap,ju=new WeakSet;function Lu(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 Wu=null;const Du=new WeakMap,Bu=new Set;function zu(e,t,n,o){let s=Du.get(e);if(void 0===s){if(!o)return null;s=new Map,Du.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 Fu(e,t){if(!e.component.isConnected)return!1;const n=gt(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 qu(e,t,n,o){const s=zu(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&&Fu(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?Fu(r,o)&&(null!==a&&ee(`[wcs/mount-export-ambiguous] "${t}${l}${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 Vu(e){const t=e.parentStateElement,n=gt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Et](n,()=>{e.$postUpdate(o.exportedPath)})})}const Hu=new WeakMap;class Uu{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return gn(oe(this.markerParentPath+l+e),this.listIndex)}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(qc(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Fc(e,t):qc(e,t),a=Hc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Fc(e,t):qc(e,t),l=Hc(0,t,a,r,n);return o[s](a,l,...i)}}return this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return Sl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[qc(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)||ee(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(t)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(e,t)?(e[t]=n,!0):(this.receiver[Fc(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 qc(this.record,t),!0}catch{return!1}}}function Gu(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Hu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Hu.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 Uu(e,s,t.listIndex,r,n,o))}function Ku(e){const t=e.parentStateElement,n=(t,n)=>{const o=gt(e.component);let s;return t[Et](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(qc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Fc(e,n):qc(e,n),l=gt(e.component)?.listIndex.indexes??[],c=Hc(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:qc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Fc(e,s)]=r})}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return qc(e,n),!0}catch{return!1}}})}function Ju(e,t){const n=function(e){return Uc.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&ee(`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&&ds(t).dispose(),function(e,t){Zc(),Uc.set(e,t),Xc.set(t,e);let n=Kc.get(t.parentStateElement);void 0===n&&(n=new Map,Kc.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Gc.get(t.component);void 0===o&&(o=new Map,Gc.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Jc.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=ha.get(e);if(void 0!==n){if(n===t)return;ee("A state tree is already registered on this root.")}ha.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Vc(e,t,n);Y(t);const o=gt(e.component);za(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),ra(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=qc(e,n)}catch{continue}const o=t.indexOf(l+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)+l+r,a=oe(i);if(a.wildcardCount!==e.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,c),zu(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:c}),e.parentStateElement.addDynamicDependency(t,i),wc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=gt(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(Bu.has(s))continue;const r=oe(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Et](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Bu.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),Vu(e),o=t,s=Promise.resolve(),pa.set(o,s),s.then(()=>va(o),()=>{})}function Xu(e,t){const n=ds(t),o=gt(e.component);n.forEachActiveBindingNode(e=>yt(e,o));sa(n.rebindAddresses()),Vu(e)}function Qu(e,t){if(function(e){const t=Kc.get(e);return void 0!==t&&t.size>0}(t))for(const n of ed(t)){if(!Yu(n.component,e))continue;const t=Qc(n);null!==t&&Xu(n,t)}}function Yu(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 Zu={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=td(e,t.pathInfo.path);if(null!==s)return Gu(s,t,n,o)}return ll},readMissing(e,t,n,o,s){if(null===n){if(ku(e.rootNode??null,t.pathInfo.path))return;return ll}if(!0===e.hasMounts){const n=qu(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Gu(e,gn(oe(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return ll},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=_u.get(e);if(void 0===n||0===n.size)return null;const o=t+l;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&ee(`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 ll},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=qu(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Gu(e,gn(oe(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return ll},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=td(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(l,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=Uc.get(n);if(void 0!==e)return e;n=n.parentNode}return Uc.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 Ou.get(e)??Tu}(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=Eu(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=en(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(Mu(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>ku(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){Qu(t,e)}};let ef=!1;const tf=new WeakMap;function nf(e){let t=tf.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},tf.set(e,t)),t}function of(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Iu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function sf(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{Nu(n,s,e)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return ya(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function rf(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&ee('"mount" requires a non-empty tree path.');const t=oe(e);for(const n of t.segments)0===n.length&&ee(`"mount" path "${e}" has an empty segment.`),n===c&&ee(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&ee(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],s=new Set;for(const r of Ee(e)){if(r.propSegments[0]!==x)continue;const e=r.propSegments.slice(1),i=r.statePathInfo,a=e=>ee(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> "${r.propName}: ${r.statePathName}": ${e}`);1===e.length&&e[0]&&e[0]!==c&&"$"!==e[0][0]&&"#"!==e[0][0]||a(`inject one key at a time ("${x}.<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)."),(r.inFilters.length>0||r.outFilters.length>0)&&a("an injection takes no filters."),r.propModifiers.some(e=>e!==g)&&a(`an injection accepts only #${g}.`),s.has(e[0])&&a(`"${e[0]}" is injected twice.`),s.add(e[0]),n.push({innerSegments:e,outerPathInfo:i,readonly:r.propModifiers.includes(g)})}return n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&ee('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),Nu(s,r,e),ya(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===ya(s)&&function(e,t){const n=()=>{if(null!==ya(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&of(e,t),e.settleInitialization()};let l;try{l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const d=e.connectedRootNode??null;null!==d&&sf(e,t,d)?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 fp(t,a);pp(),function(e,t){if(ju.has(e))return void Lu(t);let n=Ru.get(e);void 0===n&&(n=[],Ru.set(e,n)),n.push(t)}(e,a)}(d,ya(d),r,l,a,()=>sf(e,t,d),i):a(null)}const af={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=nf(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{Nu(n,t.mountPath,e),ya(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,uc}return rf(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=nf(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&ya(n)===t.graftInfo.rootStateElement&&cp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==tf.get(e)?.initializing)return;const t=e.getAttribute("mount");ee(`Cannot replace the state of <${o.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){ju.add(e);const t=Ru.get(e);if(void 0!==t){Ru.delete(e);for(const e of t)Lu(e)}}(t)},initializeFailureCleared(e,t){!function(e){ju.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=nf(e);return null!==t.graftInfo&&cp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,of(e,t)),e.clearConnectedRootNode(),!0}};let lf=!1;const cf=new WeakMap;function df(e,t){let n=cf.get(e);n||(n=new Set,cf.set(e,n)),n.add(t)}const uf=new WeakMap;const ff=new WeakMap,hf=new WeakMap;const pf=new WeakMap;const mf={isComplete:function(e,t){return!0===cf.get(e)?.has(t)},isDeclared:function(e,t){return!0===uf.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=ff.get(e);o||(o=new Map,ff.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=hf.get(e);o||(o=new Map,hf.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=pf.get(e);s||(s=new Map,pf.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function gf(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),o=Object.getOwnPropertyDescriptors(e);for(const e in o){const t=o[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,o),n}(e)}const yf=new WeakMap;class wf{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=yf.get(e);return n?n.get(t)??null:null}(e,t)??ee("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 bf=e=>()=>e;function vf(e,t,n,o){!function(e,t,n){let o=yf.get(e);o||(o=new Map,yf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(gf(o));const s=function(e,t){const n=new wf(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:bf(s),enumerable:!0,configurable:!0}),df(t,n),$f(t,n)}function $f(e,t){if(T in e){const n=e[T];"function"==typeof n?n.call(e,t).catch(e=>{ee(`Error in ${T}: ${e instanceof Error?e.message:String(e)}`)}):ee(`${T} is not a function.`)}}const Sf=new Set;function xf(e,t){Sf.has(e)||(Sf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function Pf(e){const t=e.rootEntry,n=gt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Et](n,()=>{o=e[t.outerPathInfo.path]})}),o}const If=new WeakMap;function Nf(e,t){e.landInitialization(),ee(t)}async function kf(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||ee(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||Nf(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&&ee(`"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=uf.get(e);n||(n=new Set,uf.set(e,n)),n.add(t)}(a,d);const u=He(a);null===u&&ee(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await Be(a),d in a||ee(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||ee(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=ff.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(o.bindAttributeName))return!1;const n=st(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||(st(a)??[]).some(e=>e.propSegments[0]===d)||Nf(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(o.bindAttributeName)){const o=(st(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=ya(a.getRootNode())??Nf(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,Gc.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(function(e,t,n){const o=pf.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;pf.get(e).delete(t)}}(a,d,f),u=Oc(a,d,o,c,f,function(e,t){return hf.get(e)?.get(t)}(a,d)),function(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=Pf(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;xf(`${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.`)}}(u)),t.mountRecord=u,n.parentNode!==i)return;try{Ju(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Ku(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),df(a,d)}return $f(a,d),function(e){const t=Cc.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(H)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;Ec.has(n)||(Ec.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 Mc(u,"$connectedCallback")}}vf(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const _f={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=If.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},If.set(e,t)),t}(e);return kf(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=If.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&Xu(n,o)}),Mc(n,"$connectedCallback"),!0},disconnecting(e){const t=If.get(e);return void 0!==t&&null!==t.mountRecord&&(Mc(t.mountRecord,"$disconnectedCallback"),Vu(t.mountRecord),e.clearConnectedRootNode(),!0)}};let Af=!1;function Cf(){Af||(Af=!0,pc("bindComponent",_f),fs=mf)}const Ef=new WeakMap,Mf=new Set,Of=new Set;function Tf(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Rf(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function jf(e){return Ef.get(e)}function Lf(e){Wf(e),Ef.delete(e)}function Wf(e){Mf.delete(e),Of.delete(e)}const Df=new WeakMap,Bf=new WeakMap,zf=new Set,Ff=new Map;function qf(e){return Df.get(e)??Ff}function Vf(e){zf.add(e),function(e){const t=Ef.get(e);void 0!==t&&(Tf(t)&&Mf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Of.add(e))}(e)}const Hf=new Map;function Uf(e){return Bf.get(e)??Hf}function Gf(e){0===e.length&&ee(`[wcs/watch-declaration-invalid] ${F} entry name must be a non-empty state path.`),e.startsWith("$")&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not start with "$" (reserved namespace).${ae}`),e.includes("@")&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ae}`),e in Object.prototype&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=oe(e);for(const n of t.segments)0===n.length&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" has an empty path segment.${ae}`);return t.wildcardCount>d&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Kf(e,t){const n=t[F];if(void 0===n)return null;"object"==typeof n&&null!==n||ee(`[wcs/watch-declaration-invalid] ${F} must be an object mapping state paths to handler functions.${ae}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must be a function.${ae}`);const n=Gf(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Df.set(e,t)}(e,o),s.size>0?s:null}let Jf=0,Xf=0;function Qf(e){Jf=e+1}function Yf(){Jf=0}function Zf(){Jf>Xf&&(Xf=Jf)}const eh=new WeakMap;function th(e,t,n){let o=eh.get(e);void 0===o&&(o=new Map,eh.set(e,o)),o.set(t,n)}const nh=new Map;function oh(e,t){nh.has(e)||nh.set(e,t)}function sh(e){return nh.get(e)}const rh={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||oh(n,o)},swapped(e,t,n){var o;o=n,nh.has(o)&&oh(t,sh(n))}};function ih(e){for(let t=e;null!==t;t=t.parentListIndex)if(Rs(t))return!0;return!1}function ah(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[Mt](gn(t.wildcardParentPathInfos[i],r)),l=Ls(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=Zt(o,i,t.wildcardCount);if(l!==c&&!Ms(l,c)){if(Rs(c))return"gone";s="replaced"}r=l}return s}function lh(e,t,n){const o=new Map;for(const s of n){const n=ah(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 ch=new Set;function dh(e){ch.delete(e)}function uh(){return ch}const fh=Symbol("wcs-stream-last-notified-uncertain"),hh=new WeakMap;function ph(e,t){const n=hh.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function mh(e,t){const n=hh.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:fh,error:Object.is(o.error,null)?null:fh})}const gh=new WeakMap;function yh(e){return gh.get(e)??new Map}function wh(e){dh(e);const t=gh.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,mh(e,n.name)}const bh=new WeakSet;let vh=0;function $h(e){return jf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Sh(e){if(0===Of.size)return;if(t=e.absolutePathInfo.stateElement,!Of.has(t))return;var t;const n=$h(e);if(void 0!==n)for(const e of n)xh(e)}function xh(e){bh.has(e)||(bh.add(e),vh++)}function Ph(e){return!!bh.delete(e)&&(vh--,!0)}const Ih=/^(?:0|[1-9]\d*)$/;function Nh(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function kh(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&&Ih.test(t)&&Nh(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Nh(e,t))?"object":null}function _h(e,t){const n=kh(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]=_h(o[e],t);return r}function Ah(e){return _h(e,new Map)}function Ch(e,t,n){if(Object.is(e,t))return!0;const o=kh(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(kh(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(!Ch(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&Ch(s[e],r[e],n))}function Eh(e,t){return Ch(e,t,new Map)}const Mh=new WeakMap;function Oh(e,t){if("function"!=typeof t)return;const n=Mh.get(t);void 0===n?Mh.set(t,new Set([e])):n.add(e)}const Th={"read-source":e=>`${q} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${q} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${q} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${q} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${q} could not write the output "${e}".`},Rh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function jh(e,t,n){null!==wt&&wt({type:"state:watch-error",phase:t,path:`${q}.${e}`,error:n})}function Lh(e,t,n){console.error(`[@wcstack/state] ${Th[n](e)}`,t),jh(e,Rh[n],t)}function Wh(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Dh(e,t){t.then(void 0,()=>{}),Lh(e,new TypeError(`${q} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Bh=new WeakSet;const zh=Object.freeze([]);function Fh(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function qh(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 Vh(e,t){return t.has(e.stateElement)&&!0===jf(e.stateElement)?.entries.has(e.entry)}function Hh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Uh(n,e))||Ph(t)}function Uh(e,t){return Zs().hasQueuedPath(e,t)}function Gh(e,t){!function(e,t,n){if(0!==vh)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=$h(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||Ph(t)}}(e,t,Uh)}function Kh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function Jh(e,t,n){if(!Vh(e,n))return Hh(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(Bh.has(e))return;Bh.add(e);const o=`[wcs/scan-source-computed] ${q} 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}`),jh(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=yh(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name],o=0===r.pathInfo.wildcardCount?e.rows:lh(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(qh)){let n;try{n=Kh(t,r,e)}catch(e){Lh(s.name,e,"read-source");continue}const o=a(l,n,sh(e.absAddress),...e.indexes);if(Wh(o))return void Dh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){Lh(s.name,e,i.failure)}return i.plan}function Xh(e,t){const{group:n}=e;if(!Vh(n,t))return void Hh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Ph(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!Eh(o,s.initial):!Object.is(o,e.next)){const o=n.reset?Ah(s.initial):e.next;t[s.name]=o,Oh(s.name,o)}})}catch(e){Lh(s.name,e,"write")}}function Qh(e,t,n){if(Gh(e,t),0===Mf.size)return zh;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=jf(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=en(n.listIndex,r.wildcardCount)}for(const s of i)Fh(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)Fh(o,e,t).reset=!0}if(0===o.size)return zh;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];Qf(n);try{for(const n of s){const o=Jh(n,e,t);null!==o&&r.push(o)}}finally{Yf()}return r}function Yh(e){ap(),(0!==qf(e).size||0!==Uf(e).size||function(e){const t=Ef.get(e);return void 0!==t&&Tf(t)}(e))&&(Vf(e),function(e){const t=[];for(const n of qf(e).values())Zh(e,n)&&t.push(n);for(const n of Uf(e).values())for(const o of n)Zh(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{th(e,Gt(e,o.pathInfo,null),n[o.path])}catch(t){tp(e,o.path,"prime",t)}})}(e))}function Zh(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const ep={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function tp(e,t,n,o){console.error(`[@wcstack/state] $watch ${ep[n]} "${t}" threw.`,o),null!==wt&&wt({type:"state:watch-error",phase:n,path:t,error:o})}function np(e){const t=zf;try{if(0===t.size)return void Gh(e,t);const n=function(){const e=Xf;return Xf=0,e}();if(n>32){Gh(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!==wt&&wt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){Qf(n);try{for(const n of e)Xh(n,t)}finally{Yf()}}}(Qh(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=qf(e).get(s),i=Uf(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=en(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(sp);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(ih(o.absAddress.listIndex)||s?.entry===o.entry&&op(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(lh(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){tp(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);Qf(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=qf(e.stateElement).get(e.entry.path)===e.entry,o=!0===Uf(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&rp(e)}}finally{Yf()}}(e,t,n)}finally{nh.clear()}}function op(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function sp(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 rp(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Zh(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 tp(0,n.path,"evaluate",e)}const a=r?function(e,t){return eh.get(e)?.get(t)}(t,o):sh(o);r&&th(t,o,i),null!==wt&&wt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){tp(0,n.path,"handler",e)}}let ip=!1;function ap(){ip||(ip=!0,ul("watch",rh),ml("watch",lp),Js(np,10),Ks(Zf))}const lp={order:10,register(e,t){var n;n=e,zf.delete(n),Wf(n),Df.delete(n),function(e){eh.delete(e)}(e);const o=Kf(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?F:q)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Yh(e)},deactivate(e){var t;t=e,zf.delete(t),Wf(t)}};function cp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Mu(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function dp(e,t,n,o){const s=n[F];if(void 0!==s){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(s)){const s=Cu(t,o,a,!1),c=function(e,n,...s){l.call(Mu(t,this,o),e,n,...s)};n.push({path:s,pathInfo:oe(s),handler:c,order:1e6+i++}),r.add(s),e.setPathInfo(s,"prop","watch")}n.length>0&&(!function(e,t){let n=Bf.get(e);void 0===n&&(n=new Map,Bf.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}(e,n),e.addVolumeWatchPaths?.(r),Yh(e))}const r=n[U];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(Cu(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[M];"function"==typeof i&&(!function(e,t){let n=Ou.get(e);void 0===n&&(n=[],Ou.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 up(e,t,n,o=[]){ol(n),function(e,t,n,o){for(const e of o){const o=e.innerSegments[0],s=Object.getOwnPropertyDescriptor(n,o);void 0===s||"function"!=typeof s.get&&"function"!=typeof s.set&&"function"!=typeof s.value||ee(`Volume "${t}" declares "${o}" as an accessor or a method and also injects it ("${x}.${o}: ${e.outerPathInfo.path}"). Rename one of them.`)}const s=n[F];if(void 0!==s){"object"==typeof s&&null!==s||ee(`${F} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(s))"function"!=typeof t&&ee(`${F} entry "${e}" must be a function.`),Gf(e)}const r=n[U];if(void 0!==r){"object"==typeof r&&null!==r||ee(`${U} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(r)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&ee(`${U} entry "${n}" must map a list path to a field name or a key function.`);const r=Cu(t,o,n,!1);e.listKeys?.has(r)&&ee(`${U} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[z]&&ee(`Volume "${t}" declares ${z}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&ee(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[V]&&ee(`Volume "${t}" declares ${V}, 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(yc(n)))-1!==e.indexOf(H)&&ee(`Volume "${t}" declares "${e}", which uses "${H}". 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(Object.getOwnPropertyDescriptors(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=oe(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;ee(`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+l+o];n=""===n?o:n+l+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;ee(`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=_u.get(e);void 0===n&&(n=new Set,_u.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+l+n,i=s.get,a=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(Mu(t,this,o))}),"function"==typeof a&&(c.set=function(e){a.call(Mu(t,this,o),e)}),e.defineTreeAccessor(r,c)}dp(e,t,n,o);const c=n.$connectedCallback;return"function"==typeof c&&e.createState("writable",e=>{let n;try{n=c.call(Mu(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 fp(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=up(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 hp=!1;function pp(){var e;hp||(hp=!0,ef||(ef=!0,ul("scopes",Zu)),lf||(lf=!0,pc("scopes",af)),Cf(),Wu=fp,e=mp,ga.includes(e)||ga.push(e))}function mp(e,t){(function(e){const t=Iu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){ju.delete(e);const n=Ru.get(e);if(void 0===n||0===n.length||null===Wu)return;Ru.delete(e);const o=Wu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const gp={name:"scopes",install(){pp(),Pu||(Pu=!0,pc("dcc",xu))}},yp=/^@@wcs-(?:for|if|elseif|else):[^-]/,wp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,bp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,vp=/^@@wcs-text-start:(.+)$/;function $p(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Sp extends gc{_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=nd.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static find(e){const t=o.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=$p(JSON.stringify(t)),e.appendChild(n);const s=Array.from(Sa.keys());for(const t of s){const n=Pa(t);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",t);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),e.appendChild(s)}const r=Array.from(Ii);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=Pi(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=$p(JSON.stringify(t)),e.appendChild(n)}}Ii.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(wp.test(e.data)||bp.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;yp.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=vp.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(o.tagNames.ssr),s=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;wp.test(e.data)&&i.push(e)}for(const e of i){const t=wp.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()}Sp.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(yp.test(e.data)){const t=e.data.split(":")[1];l.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of l){const n=s.get(t);if(n){const t=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&t.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const c=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of c)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const xp={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",nd),Sp.buildContent(o,Sp.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const Pp=new Set(["for","if","elseif","else"]);function Ip(e){const t=new cs;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=ut(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function Np(e,t,n){for(const o of t)"event"===o.bindingType||Pp.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in A||oe(o.statePathName).wildcardCount>n||e.push(o)}function kp(e,t,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function _p(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Ee(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,ka()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;ja(a),"string"==typeof l&&Oa(a,l),za(n,a,l);xa(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Ra(a)})}}const Ap={hydrate:async function(e){await aa(e);const t=e.querySelectorAll(o.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${nd}". Falling back to full render.`),Sp.cleanupDom(e),!1}for(const n of t)_p(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=wp.exec(e.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let d=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:l,nodes:c})}return t}(document.body),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=ni(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=Ip(s.nodes);Tr(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");ws(t,r),Lr(t,i);const l=[];for(const e of r)e.statePathName in A&&l.push(e);if($s(t,l),"for"===s.type&&null!==s.index){const i=kp(e,"for",s.uuid);if(i){const e=_s(null,s.index);hi(i,e,t),pi(i,s.nodes[s.nodes.length-1]),Kr(i,t);const l=oe(s.path+"."+c);Wr(t,gn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Np(o,r,l.wildcardCount);let d=n.get(s.uuid);d||(d=[],n.set(s.uuid,d)),d.push(e)}}else{const n=kp(e,s.type,s.uuid);n&&(Kr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Np(o,r,0))}}for(const[t,o]of n){const n=kp(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=Pa(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ya(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&Ds(t,o)})}return o}(document.body,n);Sp.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());Sp.restoreTextBindings(document.body);const[i,a]=ut(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(yt(e,null),t.setAttribute("data-wcs-completed",""))}else yt(e,null);const l=[],d=[],u=ds(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(Pp.has(e.bindingType))d.push(e);else{if(e.statePathName.includes(c))continue;l.push(e)}for(const e of d)if("for"===e.bindingType){const t=rn(e),n=ya(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&($t(t,o),kt(t,o))})}sa([...l,...s]);for(const{el:e,parent:t,next:n}of r)t.insertBefore(e,n);const f=e.querySelectorAll(o.tagNames.ssr);for(const t of f){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=Sp.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await wa(e.rootNode);const t=Sp.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",nd),Sp.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let Cp=!1;function Ep(){var t;Cp||(Cp=!0,ua=Ap,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Sp)},Sc.includes(t)||Sc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=xp)}())}const Mp={name:"ssr",install(){Ep()}},Op="[wcs/scan-declaration-invalid]",Tp=Object.freeze([]);function Rp(e){return`${q} entry "${e}"`}function jp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Lp(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${c}${c}`)?`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.${ae}`}function Wp(e,t,n){0===n.length&&ee(`${Op} ${e} "${t}" must be a non-empty state path.${ae}`),n.startsWith("$")&&ee(`${Op} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ae}`),n.includes("@")&&ee(`${Op} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ae}`),n in Object.prototype&&ee(`${Op} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ae}`);const o=oe(n);for(const s of o.segments)0===s.length&&ee(`${Op} ${e} ${t} "${n}" has an empty path segment.${ae}`);return o.wildcardCount>d&&ee(`${Op} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Dp(e,t,n,o){const s=Rp(e);0===e.length&&ee(`${Op} ${q} entry name must be a non-empty string.${ae}`),(e.includes(l)||e.includes(c))&&ee(`${Op} ${s} must be a flat property name ("${l}" and "${c}" are not allowed). The output is a property the runtime owns.${ae}`),e.startsWith("$")&&ee(`${Op} ${s} must not start with "$" (reserved namespace).${ae}`),e in Object.prototype&&ee(`${Op} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ae}`),t.has(e)&&ee(`${Op} ${s} conflicts with a getter declared on the state.${ae}`),n.has(e)&&ee(`${Op} ${s} conflicts with a setter declared on the state.${ae}`),o.has(e)&&ee(`${Op} ${s} conflicts with the ${z} entry of the same name — each output has exactly one owner.${ae}`)}function Bp(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Mh.get(t)?.has(e)}(e,o)&&ee(`${Op} ${Rp(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ae}`)}function zp(e,t,n,o,s,r){const i=Rp(e),a=void 0!==t.from,c=void 0!==t.on;if(a===c&&ee(`${Op} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ae}`),c){const e=t.on;return"string"==typeof e&&0!==e.length||ee(`${Op} ${i} "on" must be a non-empty event-token name.${ae}`),n.has(e)||ee(`${Op} ${i} on "${e}" is not declared in ${D}.${ie(e,n)}${ae}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&ee(`${Op} ${i} "from" must be a state path string.${ae}`);const u=Wp(i,"from",d),f=jp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&ee(Lp(i,"from",d,f));const h=jp(u,s);return null!==h&&ee(function(e,t,n){return`${Op} ${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.${ae}`}(i,d,h)),(d===e||d.startsWith(e+l))&&ee(`${Op} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ae}`),{kind:"path",path:d,pathInfo:u}}function Fp(e,t,n,o){if(void 0===t)return Tp;const s=Rp(e);Array.isArray(t)||ee(`${Op} ${s} "resetOn" must be an array of state paths.${ae}`);const r=[];for(const e of t){"string"!=typeof e&&ee(`${Op} ${s} "resetOn" must contain only state path strings.${ae}`);const t=Wp(s,"resetOn",e);t.wildcardCount>0&&ee(`${Op} ${s} resetOn "${e}" must not contain "${c}" — a reset returns the whole output to "initial".${ae}`);const i=jp(t,o);null!==i&&ee(Lp(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&ee(`${Op} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ae}`),"path"===n.kind&&e.startsWith(n.path+l)&&ee(`${Op} ${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.${ae}`),r.push(e)}return r}function qp(e,t,n=null){const o=e[q];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&ee(`${Op} ${q} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ae}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(yc(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){ol(e);const t=e[z];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)){Dp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&ee(`${Op} ${Rp(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ae}`);const o=u;Bp(e,a,o);const f=zp(e,o,t,s,i,n);"initial"in o||ee(`${Op} ${Rp(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ae}`),"function"!=typeof o.fold&&ee(`${Op} ${Rp(e)} fold must be a function.${ae}`);const h=Fp(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=oe(e).segments[0];t.has(n)&&ee(`${Op} ${Rp(o.name)} resetOn "${e}" reads the ${q} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ae}`)}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&&ee(`${Op} ${q} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ae}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Vp(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 bh.has(e)}(e),l=a&&!Eh(n,e.initial)?Ah(e.initial):n,c=t(l,o,...s);if(Wh(c))return void Dh(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Oh(e.name,c)),a&&Ph(e)}catch(t){Lh(e.name,t,i)}}}function Hp(e,t,n){const o=function(e,t){Lf(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Rf(n,e.source.path,e);for(const t of e.resetOn)Rf(o,t,e),"event"===e.source.kind&&Rf(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Ef.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)&&Zs().hasQueuedPath(e,n))&&xh(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 Up="scanEntries",Gp={order:8,validate(e,t,n){const o=qp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Up,o)},applyEarly(e,t,n){const o=n.get(Up)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=Ah(n.initial);e[n.name]=t,Oh(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&En(e,n.source.tokenName).subscribe(Vp(n))}(e,o))},register(e,t,n){const o=n.get(Up)??null,s=function(e){const t=new Map,n=jf(e);if(void 0!==n)for(const e of n.entries)Ph(e)&&t.set(e.name,e.resetOn);return Lf(e),t}(e);e.setScanPaths?.(null===o?null:Hp(e,o,s))}};let Kp=!1;const Jp=Object.freeze([]),Xp=Object.freeze([]);function Qp(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??Jp,i=e.dynamicDependency.get(n)??Jp,a=t.byFromPath.get(n)??Xp;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Yp=(e,t)=>t,Zp=new Set;function em(e,t){ol(t);const n=t[z];if(void 0===n)return void ph(e,Zp);"object"==typeof n&&null!==n||ee(`${z} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&ee(`${z} entry name must be a non-empty string.`),s.includes(l)&&ee(`${z} entry "${s}" must be a flat property name ("${l}" is not allowed).`),s.includes(c)&&ee(`${z} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.startsWith("$")&&ee(`${z} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&ee(`${z} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&ee(`${z} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&ee(`${z} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||ee(`${z} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&ee(`${z} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&ee(`${z} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&ee(`${z} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&ee(`${z} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??Yp,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in t||(t[s]=a.definition.initial),o.set(s,a)}!function(e,t){gh.set(e,t)}(e,o),ph(e,new Set(o.keys()))}const tm=new WeakMap,nm=new WeakMap;function om(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=yh(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&yh(e).has(n),ownKeys:()=>Array.from(yh(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=yh(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){ee(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){ee(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function sm(e){const t=tm.get(e);if(void 0!==t)return t;const n=om(e,G,e=>e.status);return tm.set(e,n),n}function rm(e){const t=nm.get(e);if(void 0!==t)return t;const n=om(e,K,e=>e.error);return nm.set(e,n),n}function im(e){tm.delete(e),nm.delete(e)}let am=null;function lm(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 cm={read(e,t){!function(e,t){null!==am&&am.add(Ut(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===G?lm(sm(e),t.pathInfo.segments):n===K?lm(rm(e),t.pathInfo.segments):ll},get:(e,t)=>t===G?sm(e.stateElement):t===K?rm(e.stateElement):ll};async function dm(e,t,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",i)}}function um(e){wm();const t=yh(e);if(0!==t.size){!function(e){ch.add(e)}(e);for(const n of t.values())fm(e,n)}}function fm(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=am,s=new Set;let r;am=s;try{e.createState("readonly",e=>{r=n(e)})}finally{am=o}r instanceof Promise&&ee(`${z} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${G}${l}${t.name}`,a=`${K}${l}${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||ee(`${z} 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&&ee(`${z} 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=jf(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=Qp(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&ee(`[wcs/scan-feedback-loop] ${z} entry "${t.name}" args read "${n}", which is derived from the ${q} 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}),hm(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{e[t.name]=s.fold(e[t.name],n)})},done(){hm(e,t,"done",null)},fail(o){hm(e,t,"error",o),n.abort()}};dm(s.source,o,n.signal,r)}function hm(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return hh.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=hh.get(e);void 0===s&&(s=new Map,hh.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${G}${l}${t.name}`),i&&e.$postUpdate(`${K}${l}${t.name}`)}))}function pm(e){const t=uh();if(0===t.size)return;const n=[];for(const o of t)for(const t of yh(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&yh(e).get(o.name)===o)try{fm(e,o)}catch(n){o.controller?.abort(),t.has(e)&&yh(e).get(o.name)===o&&hm(e,o,"error",n)}}let mm=!1;const gm=new WeakMap,ym={order:20,apply(e,t){var n;im(e),wh(n=e),dh(n),gh.delete(n),em(e,t),void 0!==t[z]&&e.attachAddressHooks?.("streams",z)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return um(e),void gm.set(e,e.connectGeneration??0)}n===e.connectGeneration&&gm.get(e)!==n&&um(e)}},deactivate(e){wh(e),im(e)}};function wm(){mm||(mm=!0,ul("streams",cm),ml("streams",ym),Js(pm,20))}const bm=[Ld,{name:"temporal",install(){ap(),Kp||(Kp=!0,ml("scan",Gp),Ks(Sh)),wm()}},uu,gp,Mp,pd,Id];await function(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(bm),Ic(e,t)}();
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|