@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.
Files changed (44) hide show
  1. package/README.ja.md +47 -17
  2. package/README.md +47 -17
  3. package/dist/auto.min.js +1 -1
  4. package/dist/auto.min.js.map +1 -1
  5. package/dist/define.d.ts +11 -7
  6. package/dist/index.d.ts +15 -7
  7. package/dist/index.esm.js +1 -1
  8. package/dist/index.esm.js.map +1 -1
  9. package/dist/manifest.d.ts +14 -1
  10. package/dist/manifest.esm.js +91 -35
  11. package/dist/parser.esm.js +25 -0
  12. package/dist/split/chunks/binder.js +1 -1
  13. package/dist/split/chunks/binder.js.map +1 -1
  14. package/dist/split/chunks/checkDependency.js +1 -1
  15. package/dist/split/chunks/declarationAliases.js +2 -0
  16. package/dist/split/chunks/declarationAliases.js.map +1 -0
  17. package/dist/split/chunks/filterRegistry.js +1 -1
  18. package/dist/split/chunks/filterRegistry.js.map +1 -1
  19. package/dist/split/chunks/mount.js +1 -1
  20. package/dist/split/chunks/mount.js.map +1 -1
  21. package/dist/split/chunks/pathDiagnostics.js +1 -1
  22. package/dist/split/chunks/pathDiagnostics.js.map +1 -1
  23. package/dist/split/chunks/registerComponents.js +1 -1
  24. package/dist/split/chunks/registerComponents.js.map +1 -1
  25. package/dist/split/chunks/setAll.js +1 -1
  26. package/dist/split/chunks/version.js +1 -1
  27. package/dist/split/chunks/watchRuntime.js +1 -1
  28. package/dist/split/core.d.ts +11 -7
  29. package/dist/split/core.js +1 -1
  30. package/dist/split/core.js.map +1 -1
  31. package/dist/split/features/devtools.js +1 -1
  32. package/dist/split/features/devtools.js.map +1 -1
  33. package/dist/split/features/diagnostics.js +1 -1
  34. package/dist/split/features/formats.js +1 -1
  35. package/dist/split/features/formats.js.map +1 -1
  36. package/dist/split/features/recursion.js +1 -1
  37. package/dist/split/features/scopes.js +1 -1
  38. package/dist/split/features/scopes.js.map +1 -1
  39. package/dist/split/features/ssr.js +1 -1
  40. package/dist/split/features/ssr.js.map +1 -1
  41. package/dist/split/features/temporal.js +1 -1
  42. package/dist/split/features/temporal.js.map +1 -1
  43. package/dist/wcs-manifest.json +65 -25
  44. package/package.json +1 -1
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={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;function s(){return o}const r=Symbol.for("wcstack.binder");const i=Symbol.for("wcstack.binder.pending"),a=Symbol.for("wcstack.binder.taken");function l(){const e=function(){const e=globalThis[r];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[i];return void 0===t&&(t=[],e[i]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[a];return void 0===t&&(t=new WeakSet,e[a]=t),t}();for(const t of n)o.add(t),e.bind(t)}const c=".",d="*",u=128,f=128,h="#",p="|",g="prevent",m="stop",y="ro",w=Object.freeze([g,m,y]),b="init",v="sync",$=Object.freeze([b,v]),x="else",S="...",P="on",I="eventToken",A="command",N="class",k="attr",_="style",T="$",C={};for(let e=0;e<u;e++)C[`${T}${e+1}`]=e;const E=Object.freeze(C),M="$connectedCallback",O="$disconnectedCallback",R="$updatedCallback",j="$errorCallback",L="$stateReadyCallback",W="$bindables",D="$commands",B="$commandTokens",z="$command",F="$eventTokens",q="$on",V="$streams",H="$watch",U="$scan",G="$recursion",K="**",J="$listKeys",X="$streamStatus",Y="$streamError",Q="data-wc-definition",Z=/\{\{\s*(.+?)\s*\}\}/g,ee=new Set(["SCRIPT","STYLE"]);function te(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&&ee.has(e.parentElement.tagName)||ne(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),te(t.content)}else te(e.content)}function ne(e){const t=e.data;if(Z.lastIndex=0,!Z.test(t))return;Z.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Z.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 oe(e){throw new Error(`[@wcstack/state] ${e}`)}const se=new Map;let re=0;function ie(e){let t=se.get(e);return void 0!==t||(-1!==e.indexOf(K)&&oe(`[wcs/recursion-unsupported] "${e}" uses "${K}", 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 ae(e)),se.set(e,t)),t}class ae{id=++re;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:ie(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===d&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),c.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=u,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function le(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 ce(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=le(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const de=" Validate statically: npx @wcstack/lint <file>.",ue=new Set(["if","elseif","else","for"]),fe={not:()=>e=>!e},he={input:new Map,output:new Map},pe={input:new Map,output:new Map},ge=new Map;function me(e,t,n){const o=he[e],s=pe[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)}ge.clear()}function ye(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=ge.get(s);if(void 0!==r)return r;const i=he[n].get(e)??fe[e];void 0===i&&oe(`[wcs/filter-unknown] filter not found: ${e}.${ce(e,function(e){return[...new Set([...Object.keys(fe),...he[e].keys()])]}(n))}${de}`);const a=pe[n].get(e);void 0!==a&&(t.length<a[0]||t.length>a[1])&&oe(t.length<a[0]?`[wcs/filter-arity] filter "${e}" requires at least ${a[0]} argument(s) (${t.length} given).${de}`:`[wcs/filter-arity] filter "${e}" accepts at most ${a[1]} argument(s) (${t.length} given).${de}`);const l=i(t,o);return ge.set(s,l),l}function we(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 be=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function ve(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:be.test(e)?Number(e):e)}function $e(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=we(o,i,a);t.push(e),n.push(ve(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&&oe(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${de}`);const c=we(o,i,a);return(c||r)&&(t.push(c),n.push(ve(c,r))),{args:t,literals:n}}function xe(e,t){return e.map(t=>{const n=t.indexOf("("),o=t.lastIndexOf(")");-1!==n&&-1===o&&oe(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==o&&-1===n&&oe(`Invalid filter format: missing opening parenthesis in "${t}"`);const s=(-1===n?t:t.substring(0,n)).trim();if(0===s.length&&oe(`[wcs/binding-syntax] an empty filter in "${e.join("|")}" — remove the extra "|" or name the filter.${de}`),-1===n)return{filterName:s,args:[],literals:[]};return{filterName:s,...$e(t.substring(n+1,o))}})}const Se=e=>e.trim(),Pe=e=>"'"===e||'"'===e;function Ie(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(Pe(s))n=s;else if(s===t)return o}return-1}function Ae(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):Pe(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const Ne=new Map;function ke(e){const t=Ie(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ne.has(s)?r=Ne.get(s):(o=Ae(s,p).map(Se),r=xe(o),Ne.set(s,r))):n=e.trim();const i=n.split(h).map(Se);i.length>2&&oe(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${h}" — write "${i[0]}${h}${i.slice(1).join(",")}".${de}`);const[a,l]=i,d=a.split(c).map(Se);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(Se):[],inFilters:r}}const _e=new Map;function Te(e){const t=Ie(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),_e.has(s)?r=_e.get(s):(o=Ae(s,p).map(Se),r=xe(o),_e.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&oe(`"${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:ie(n),outFilters:r}}const Ce=new Set([x,"if","elseif","for",S]);function Ee(e){const[...t]=function(e){return Ae(e,";")}(e).map(Se).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&oe(`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(h)[0].split(p)[0].trim();if(s!==n&&Ce.has(s)&&oe(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${de}`),n===x){o.length>0&&oe(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${de}`);const t=ie("#else");return{propName:x,propSegments:[x],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===S){const t=Te(o);return t.outFilters.length>0&&oe(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&oe(`Invalid spread binding "${e}": spread target path is required.`),{propName:S,propSegments:[S],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Te(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Te(o);return{...ke(n),...e,bindingType:s}}{const e=Te(o),t=ke(n);return t.propSegments[0]===I||t.propSegments[0].startsWith(P)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>ue.has(e.bindingType))&&oe(`[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">).${de}`)}return n}const Me=new WeakMap,Oe=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Re=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function je(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=Re.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 Le(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Te(e),bindingType:"text"}}const We=new WeakMap,De=new WeakSet;let Be=0;async function ze(e){const t=function(e){let t,n=We.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++Be,promise:o,resolve:t},We.set(e,n),De.has(e)&&n.resolve(),n}(e);await t.promise}function Fe(e){const t=We.get(e);void 0===t?De.add(e):t.resolve()}const qe=new WeakMap;function Ve(e){const t=qe.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{qe.set(e,n)}}function He(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Ue(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return He(t);if(void 0!==n)return He(n)}return He(globalThis.customElements)}function Ge(e,t){e.upgrade?.(t)}function Ke(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,Je);if(null===r)return null;const i=void 0===s.inputs?new Map:Qe(s.inputs,Xe);if(null===i)return null;const a=void 0===s.commands?new Map:Qe(s.commands,Ye);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Je(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 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.attribute||"string"==typeof t.attribute)}function Ye(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 Ze(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ie(n),inFilters:[],outFilters:[],bindingType:"prop"}}function et(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function tt(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&&oe("Spread binding requires an element node.");const t=e,o=Ve(t);null===o&&oe(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Ue(t);null===a&&oe(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||oe(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Ge(a,t);const l=Ke(t);null===l&&oe(`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=Ze(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=Ze(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=et(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=et(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 nt(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 ot(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:ye(s.filterName,s.args,t,s.literals??s.args)})}return n}const st=new WeakMap;function rt(e){return st.get(e)||null}function it(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function at(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!it(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function lt(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 ct(e){const t=[],n=at(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!==je(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&lt(e,n)||t.push(e)}return t}const dt=new WeakSet;function ut(e,t,n,o){const s=tt(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ve(e):null;return null===n&&oe("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}dt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=ot(o.inFilters,"input"),s=ot(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){st.set(e,t)}(e,r),Fe(e),{bindings:r,deferred:null}}function ft(e,t){const n=ct(e),o=[],s=[];for(const e of n){if(dt.has(e))continue;const n=ut(e,Na(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function ht(e){dt.add(e)}function pt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){dt.delete(e)}(t);return ut(t,n,{allowDeferred:!1},o).bindings}const gt=new WeakMap;let mt=null;function yt(e){let t=e;for(;t;){const e=gt.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 wt(e,t){null!==t?gt.set(e,t):gt.delete(e)}let bt=null;const vt=new WeakMap;function $t(e){return vt.get(e)??[]}function xt(e,t){vt.set(e,t)}function St(e){return vt.has(e)}const Pt=new WeakMap;let It=null,At=0;function Nt(e){return Pt.get(e)??[]}function kt(e,t){null===It?Pt.set(e,t):It.set(e,t)}function _t(){At++,null===It&&(It=new Map)}function Tt(){if(0!==At&&(At--,!(At>0||null===It))){for(const[e,t]of It)Pt.set(e,t);It=null}}function Ct(e){return(It?.has(e)??!1)||Pt.has(e)}const Et=Symbol("$$setLoopContext"),Mt=Symbol("$$getByAddress"),Ot=Symbol("$$hasByAddress"),Rt=Symbol("$$setByAddress"),jt=Symbol("$$connectedCallback"),Lt=Symbol("$$disconnectedCallback"),Wt=Symbol("$$updatedCallback"),Dt=Symbol("$$errorCallback"),Bt=new WeakMap,zt=new WeakMap;class Ft{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function qt(e,t){if(null===t){let t=zt.get(e);return void 0!==t||(t=new Ft(e,null),zt.set(e,t)),t}{let n=Bt.get(t);void 0===n&&(n=new WeakMap,Bt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Ft(e,t),n.set(e,o)),o}}const Vt=new WeakMap;function Ht(e,t){let n=Vt.get(e);void 0===n&&(n=new Map,Vt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Ut(e,t)),n.set(t,o)),o}class Ut{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Gt(e,t){return qt(Ht(e,t.pathInfo),t.listIndex)}function Kt(e,t,n){return qt(Ht(e,t),n)}const Jt=new WeakMap;function Xt(e,t){null===t?Jt.delete(e):Jt.set(e,t)}function Yt(e){return Jt.get(e)||null}const Qt=new Map;function Zt(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 en(e,t,n){return t<0||t>=n?null:e.at(t-n)}function tn(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const nn=new WeakMap;function on(e){const t=yt(e.node);if(null===t)return null;let n=nn.get(t);if(void 0===n)n=new WeakMap,nn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=Zt(t.pathInfo,e.statePathInfo);return n>0&&(o=en(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const sn=new WeakMap;function rn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Yt(n);null===t?oe(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function an(e,t){let n=null;if(n=sn.get(e)||null,null!==n)return n;const o=rn(e,t),s=on(e),r=ba(o);return null===r&&oe("No state tree found on this root for binding."),n=Kt(r,e.statePathInfo,s),sn.set(e,n),n}function ln(e){sn.delete(e)}const cn=new WeakMap;function dn(e,t){const n=cn.get(e);void 0===n?cn.set(e,t):n instanceof Set?n.add(t):n!==t&&cn.set(e,new Set([n,t])),null!==bt&&bt({type:"state:binding-added",absoluteAddress:e,binding:t})}function un(e,t){const n=cn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&cn.delete(e),null!==bt&&bt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const fn=new WeakMap;function hn(e){const t=cn.get(e);return void 0!==t?t:null!==e.listIndex?fn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const pn=new WeakMap,gn=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]===d?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=yn(e,t)}}function yn(e,t){if(null===t){let t=gn.get(e);return void 0!==t||(t=new mn(e,null),gn.set(e,t)),t}{let n=pn.get(t);void 0===n&&(n=new WeakMap,pn.set(t,n));let o=n.get(e);return void 0!==o||(o=new mn(e,t),n.set(e,o)),o}}const wn=new WeakMap;function bn(e){let t=null;if(t=wn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=on(e);null===n&&oe(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=yn(e.statePathInfo,n)}else t=yn(e.statePathInfo,null);return wn.set(e,t),t}function vn(e){wn.delete(e)}function $n(){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 xn=new Map,Sn=$n();function Pn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function In(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function An(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=In(e),s=Pn(e,o);let r=xn.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=ba(o.getRootNode());null===i&&oe("No state tree found on this root for two-way binding.");const a=yt(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]:[]})})},xn.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 Tn extends _n{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==bt&&bt({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 Tn(t,e),n.set(t,o)),o}const Mn=new WeakMap;function On(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Ve(t),o=Ue(t);if(null!==n&&void 0===o?.get(n))return null===o&&oe(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Mn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||oe('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Ve(e)?null:Ke(e)}(t);null===r&&oe(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&oe(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${ce(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(g)&&e.preventDefault(),c.includes(m)&&e.stopPropagation();const n=ba(t.getRootNode());null===n&&oe("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||oe(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${ce(l,n.eventTokenNames)}${de}`);const o=yt(t);n.createStateAsync("writable",async t=>{kn(t[Et](o,()=>{const s=null!==o?tn(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 Rn extends _n{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==bt&&bt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function jn(e){return e instanceof Rn}const Ln=new Map,Wn=$n();function Dn(e){const t=e.propModifiers.filter(e=>e===g||e===m).sort().join(",");return`${e.statePathName}::${t}`}const Bn=(e,t,n)=>o=>{t.includes(g)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ba(r);null===i&&oe("No state tree found on this root for event handler.");const a=yt(s),l=e.startsWith(z+".");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?tn(a.listIndex,c):[];if(l){const s=t[Mt](yn(n,null));return jn(s)||oe(`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&&oe(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});kn(c,`"${e}"`)})};function zn(e){if(!e.propName.startsWith(P))return!1;const t=Dn(e);let n=Ln.get(t);void 0===n&&(n=Bn(e.statePathName,e.propModifiers,e.statePathInfo),Ln.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Wn.add(t,e),!0}function Fn(e){if(!e.propName.startsWith(P))return!1;const t=Dn(e),n=Ln.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Wn.countOf(t)&&(Wn.remove(t,e)&&Ln.delete(t),!0)}const qn=new Map,Vn=$n();function Hn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Un(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function Gn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=Un(e),s=Hn(e,o);let r=qn.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const e of n)s=e.filterFn(s);const r=ba(o.getRootNode());null===r&&oe("No state tree found on this root for two-way binding.");const i=yt(o);r.createState("writable",e=>{e[Et](i,()=>{e[t]=s})})},qn.set(s,r)),e.node.addEventListener(o,r),Vn.add(s,e),!0}var t,n;return!1}const Kn=new Set(["radio","checkbox"]),Jn=new Set(["value","valueAsNumber","valueAsDate"]);function Xn(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(Kn.has(e)&&"checked"===t)return!0;if(Jn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ve(n);if(null!==s){const e=Ue(n)?.get(s);void 0===e&&oe(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ke(n);if(o?.knownProperties.has(t))return!0}return!1}let Yn=1,Qn=1,Zn=1;const eo=new WeakMap;function to(e,t,n){let o=eo.get(e);void 0===o&&(o=new Map,eo.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=Yn++,o.set(s,r)),r}function no(e,t){return"to-element"===t?2*e:2*e+1}const oo=new Set;function so(e){return{transactionId:Qn++,originBindingId:e,visitedEdges:oo,hop:0}}function ro(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 io=null;function ao(){return io}function lo(e,t){const n=io;io=e;try{return t()}finally{io=n}}const co=[];let uo=!1;const fo=new Map,ho=$n(),po=new WeakMap,go=e=>e.detail,mo=new WeakMap;function yo(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 wo(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ve(e.node);if(null!==n){const o=Ue(e.node)?.get(n);void 0===o&&oe(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ke(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function bo(e){if(null!==Ve(e.node)){const t=Ke(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??go}return null}function vo(e){if(null===Ve(e.node))return!1;const t=Ke(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const $o=(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!==go||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=po.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=to(a,e,t),s=function(e,t){for(let n=co.length-1;n>=0;n--){const o=co[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!==bt&&bt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:no(n,"to-state"),node:a,member:e}));const r=no(n,"to-state"),i=ao();if(null!==i&&i.visitedEdges.has(r))return void(null!==bt&&bt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=ro(i??so(n),r)}const f=ba(a.getRootNode());null===f&&oe("No state tree found on this root for two-way binding.");const h=yt(a),p=()=>{r&&(uo=!0);try{f.createState("writable",e=>{e[Et](h,()=>{e[t]=c})})}finally{r&&(uo=!1)}};null!==u?lo(u,p):p()};const xo=new WeakSet;function So(e){xo.add(e)}function Po(e){return!!xo.has(e)&&(xo.delete(e),!0)}const Io=new WeakMap;function Ao(e,t){const n=Io.get(e);return!(void 0===n||n<t)&&(n===t?Io.delete(e):Io.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 To=0;function Co(){To--}function Eo(){return To>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 Ro(e){let t=Oo.get(e);return void 0===t&&(t=new Mo(e),Oo.set(e,t)),t}function jo(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==b&&s!==v&&oe(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&oe(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Lo(e){return e.propModifiers.some(e=>e.includes("="))}const Wo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Do=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Bo(e,t){return"state"===e&&"call"===t?Wo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function zo(e){if(!o.enableDirectionalInitialSync)return Lo(e)&&oe("init=/sync= modifiers require enableDirectionalInitialSync."),Wo;const t=null===(n=jo(e,b))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:oe(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":oe(`Invalid sync modifier value "${e}".`)}(jo(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&oe("Event bindings only allow init=none."),"call"===s?Do:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===A)return Bo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&oe(`Binding type "${e.bindingType}" does not support init=${t}.`),Bo(t??"state",s);const r=Ke(e.node);if(null===r)return Bo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||oe(`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)||oe(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||oe(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Fo(e,t){return"auto"!==t?t:function(e){const t=ba(e.replaceNode.getRootNode());null===t&&oe("No state tree found on this root for binding.");const n=bn(e);let o=!1;return t.createState("readonly",e=>{o=e[Ot](n)}),o}(e)?"state":"element"}let qo=0,Vo=0;const Ho=["active","disposed","failed"],Uo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,Jo=new WeakMap,Xo=new WeakMap;function Yo(e,t){const n=Xo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Xo.set(e,new Set([n,t]))):Xo.set(e,t)}function Qo(e){return Xo.has(e)}function Zo(e,t){const n=Xo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function es(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))es(n,t)}function ts(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class ns{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||!Ao(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)Po(e)||es(e,e=>{Zo(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)_o(e)&&!Eo()||es(e,e=>{Zo(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&ia(o)}}const os=new WeakMap;function ss(e){let t=os.get(e);return void 0===t&&(t=new ns(e),os.set(e,t)),t}function rs(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 is(e,t,n){const o=ba(rn(e,n));null===o&&oe("No state tree found on this root for binding.");const s=Ht(o,e.statePathInfo);return function(e,t,n){let o=fn.get(e);void 0===o&&(o=new WeakMap,fn.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!==bt&&bt({type:"state:binding-added",absoluteAddress:qt(e,t),binding:n})}(s,t,e),s}function as(e,t){const n=an(e,t);return dn(n,e),n}function ls(e,t,n,o){null!==t?un(t,e):function(e,t,n){const o=fn.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!==bt&&bt({type:"state:binding-removed",absoluteAddress:qt(e,t),binding:n}))}(n,o,e),vn(e),ln(e)}function cs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class ds{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=Go.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(ts(t)&&ss(t),null===this.rowPlan)for(const n of e){const e=Go.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!o.enableDirectionalInitialSync)return Lo(e)&&zo(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=Go.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:Ho[t.phases[n]],teardowns:null};const o=Go.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=Go.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(cs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Ue(e);null===s&&oe(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),Yo(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=Ro(s).wait(t,()=>{if(a())try{Ge(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=Go.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&&(un(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&&(un(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?an(n):null;if(ls(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=an(n);e!==o&&St(o)&&xt(e,$t(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 ts(t)?t:null}(e);null!==t&&ss(t)}handleMutations(e,t,n){for(const n of t)es(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)es(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&ia(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=Go.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Jo.get(t);void 0===e&&(e=rs(t),Jo.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;Yo(n,this);const o=this.knownMapFor(n);let s=Jo.get(e);void 0===s&&(s=rs(e),Jo.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:++qo,session:this,generation:++Vo,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(Yo(r,this),this.addKnownRowBinding(r,o,e),Uo.set(o,s),n[e].isEvent){try{zn(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=++Vo,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{zn(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=Uo.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=on(o);null!==s?(e.patternPathInfos[t]=is(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=as(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(ls(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{Fn(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:++qo,info:e,generation:++Vo,phase:"discovered",teardowns:null,session:this,anchor:e.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Go.set(e,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;zn(t)?e.eventAttached=!0:t.propSegments[0]!==I?(Gn(t)&&cs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=Un(e),n=Hn(e,t),o=qn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Vn.countOf(n)&&(Vn.remove(n,e)&&qn.delete(n),!0))}return!1}(t)),An(t)&&cs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=In(e),n=Pn(e,t),o=xn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Sn.countOf(n)&&(Sn.remove(n,e)&&xn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Xn(t.node,t.propName)&&-1===t.propModifiers.indexOf(y)){const n=function(e,t,n){let o=po.get(e);void 0===o&&(o=new Map,po.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&&po.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});cs(e,n)}!function(e){const t=Ve(e.node);if(null!==t){const n=Ue(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&oe(`CustomElementRegistry is unavailable for <${t}>.`))}if(Xn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=wo(e),n=bo(e),o=vo(e),s=yo(e,t,null!==n,o);let r=fo.get(s);void 0===r&&(r=$o(e.propName,e.statePathName,e.inFilters,n,o),fo.set(s,r)),e.node.addEventListener(t,r),ho.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{On(t)&&cs(e,()=>function(e){if(e.propSegments[0]!==I)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=Ve(e.info.node);if(null===n)return void t();const o=Ue(e.info.node);if(null===o&&oe(`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=Ro(o).wait(n,()=>{if(this.isAlive(e,s))try{Ge(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});cs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=zo(e.info),n=Fo(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 To++;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=ba(e.node.getRootNode());null===o&&oe("No state tree found on this root for initial binding sync.");const s=yt(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=on(n);if(null!==o?(e.patternPathInfo=is(n,o,t),e.patternListIndex=o):e.address=as(n,t),!e.options.registerPathInfo)return;const s=ba(n.replaceNode.getRootNode());null===s&&oe("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&Go.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,Co());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{ls(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=Ve(e.node);if(null!==t){const n=Ue(e.node),o=n?.get(t);if(void 0===o)return}if(Xn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=wo(e),n=yo(e,t,null!==bo(e),vo(e)),o=fo.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),ho.remove(n,e)&&fo.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{Fn(t)}catch{}}}}function us(e){let t=Ko.get(e);return void 0===t&&(t=new ds(e),Ko.set(e,t)),t}function fs(e){return Go.get(e)?.session??Uo.get(e)?.session??null}let hs=null;function ps(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const gs=Object.freeze([]);const ms=new WeakMap;const ys=new WeakMap;function ws(e){return ys.get(e)??[]}function bs(e,t){ys.set(e,t)}const vs=new WeakMap;function $s(e){return vs.get(e)??[]}function xs(e,t){vs.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 Ps(){return`u${(Ss++).toString(36)}`}let Is=0,As=0;const Ns=Symbol("wcs.listIndex.noValue");class ks{uuid=Ps();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=Is,this._chainGeneration=As}get index(){return this._index}set index(e){this._index=e,this._version=++Is,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=Is),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===As||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=As),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Is,As++}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 Ts(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,Rs=new WeakSet;function js(e){return Rs.has(e)}function Ls(e,t){const n=Cs(e),o=e.parentListIndex;return null===n||n===o||Rs.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Rs.has(e)&&!Rs.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&&Rs.has(e)&&!Rs.has(t)}(o,t)?t:null:n}function Ws(e){const t=Os.get(e);return void 0===t?null:t}function Ds(e,t){const n=Os.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Ls(o,t);if(null!==e)for(const t of n)Ts(t,e)}return n}function Bs(e,t){null!==t?Os.set(e,t):Os.delete(e)}const zs=new WeakMap;function Fs(e,t){null===t?zs.delete(e):zs.set(e,t)}function qs(e){const t=zs.get(e);t&&(t.dirty=!0)}const Vs=Symbol.for("wcstack.transition-runner");function Hs(e){const t=globalThis[Vs];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 Us(e,t,n){const o=Hs(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Gs=[],Ks=[];function Js(e){Ks.includes(e)||Ks.push(e)}function Xs(e,t=0){const n=Gs.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Gs.push(o):Gs.splice(n,0,o)}function Ys(e){queueMicrotask(()=>{throw e})}class Qs{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Ks.length;t++)Ks[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!==bt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&bt({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!==bt&&bt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=hn(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?ia(r,i):ia(r)};if(t()||0===r.length)e();else{const t=Us("state",e);void 0!==t&&t.catch(Ys)}}finally{Tt(),function(e){for(const t of Gs.slice())t.listener(e)}(s)}}}const Zs=new Qs;function er(){return Zs}const tr=new WeakMap,nr=new WeakMap,or=new WeakMap,sr=new WeakMap;let rr=!1;const ir=new WeakMap,ar=new WeakMap,lr=new WeakMap,cr=[];function dr(e,t){const n=ur(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ie(t).cumulativePaths;if(o.length<2)return;let s=lr.get(e);void 0===s&&lr.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 ur(e){let t=tr.get(e);return void 0===t&&tr.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function fr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function hr(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function pr(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=nr.get(o);if(void 0===r&&nr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(hr(s,e,o),r.set(t,n),fr(s,n,o)),!1}return r.set(t,n),fr(s,n,o),!0}function gr(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&&gr(or,o.listIndex,r),null!==r.levelListIndex&&gr(sr,r.levelListIndex,r))}function yr(e,t,n,o,s){rr=!0;const r=ur(e);dr(e,t);mr(r,t,s,o,pr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function wr(e,t){ur(e).tracked.add(t)}function br(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(Gt(e.stateElement,yn(t,o)))}function vr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function $r(e,t,n,o,s){const r=tr.get(e),i=r?.byPath.get(t),a=ir.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return cr;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&&vr(i.get(o),d),f&&vr(i.get(c),d),u&&vr(i.get(s),d)),void 0!==a)for(const e of a)n&&br(e,o,d),f&&br(e,c,d),u&&br(e,s,d);return d}function xr(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=tr.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())vr(e,n);const s=ir.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)br(e,t,n)}function Pr(e){const t=sr.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Ir(e){if(!rr)return;const t=or.get(e);if(void 0!==t){or.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=nr.get(o),r=s.get(n);s.delete(n),hr(tr.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Pr(e)}}}function Ar(e,t,n){if(!rr)return;const o=sr.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=tr.get(e),i=o.byPath.get(s);hr(i,t,r),fr(i,n,r),nr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(qs(r),er().enqueueAbsoluteAddress(r,null))}}const Nr=new WeakMap,kr=Object.freeze([]),_r=new Set;function Tr(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=Ds(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=Ds(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),Bs(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,Ar(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)Rs.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)Ir(e);return function(e){for(const t of e)Rs.delete(t)}(o.newIndexes),function(e,t){if(!rr||e===t)return;const n=ar.get(e);if(void 0===n)return;ar.delete(e);const o=ar.get(t);ar.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=ur(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&&!js(e))for(const t of o.getters){const n=Gt(o.stateElement,yn(t,e));qs(n),er().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 Rr(e,t){Mr.set(e,t)}const jr=new WeakMap;function Lr(e){return jr.get(e)??[]}function Wr(e,t){jr.set(e,t)}function Dr(e,t){const n=Lr(e);for(const e of n)wt(e,t)}const Br=new WeakMap;const zr=new WeakMap;function Fr(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function qr(e,t,n,o,s){const r=function(e,t,n){let o=zr.get(e);void 0===o&&zr.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||Fr(d.prefixes,i)){sa(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]]}oa(c,s,f)}}function Vr(e,t,n){Dr(e,t);const o=ws(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 Br.get(e)??null}(e);if(null!==r)return void qr(r,o,s,t,n)}for(const e of o){if(null===s){dn(an(e),e)}(null===s||s.shouldApplyState(e))&&sa(e,n)}}function Hr(e){if(!e.mounted)return;const t=ws(e),n=Or(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{un(an(o),o)}}!function(e){const t=Lr(e);for(let e=0;e<t.length;e++)wt(t[e],null)}(e)}function Ur(){return Object.freeze(new Set)}const Gr=new WeakMap,Kr=Ur();function Jr(e,t){const n=Gr.get(e);n?n.add(t):Gr.set(e,new Set([t]))}function Xr(e){const t=Gr.get(e);return void 0!==t?t:Kr}function Yr(e,t){const n=Gr.get(e);n&&(n.delete(t),0===n.size&&Gr.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:ye(s.filterName,s.args,t,s.literals??s.args)})}return n}function Zr(e){return{...e,inFilters:Qr(e.inFilters,"input"),outFilters:Qr(e.outFilters,"output")}}const ei=new Set(["if","elseif","else","for"]);class ti{_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(ws(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=ws(this);for(let e=0;e<n.length;e++){const t=n[e];ei.has(t.bindingType)&&Xr(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Or(this);null!==e&&(e.isRowSession?e.disposeBindings(ws(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=ws(this);for(let t=0;t<e.length;t++){const n=e[t];ei.has(n.bindingType)&&Xr(n.node).forEach(e=>{e.unmount()}),vn(n),ln(n)}}unmount(){{const e=Or(this);null!==e&&(e.isRowSession?e.disposeBindings(ws(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(So(e),e.parentNode.removeChild(e));const e=ws(this);for(let t=0;t<e.length;t++){const n=e[t];ei.has(n.bindingType)&&Xr(n.node).forEach(e=>{e.unmount()}),vn(n),ln(n)}this._mounted=!1}}function ni(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 oi(e){const t=document.createDocumentFragment(),n=new ti(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 si(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=nt(o,s[e].nodePath);null===t&&oe(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),ht(t),Fe(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=la.get(n);void 0!==o&&o.currentRowPlan===e||(o=new ds,la.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new ti(o);return Rr(d,c),bs(d,a),function(e,t){Br.set(e,t)}(d,n),xs(d,l),Wr(d,r),Jr(e.node,d),d}function ri(e){void 0!==e.uuid&&null!==e.uuid||oe("BindingInfo.uuid is null.");const n=Aa(e.uuid);n||oe(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&ni(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=nt(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===A||s===I)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ve(r))return null;if("prop"===o&&Xn(r,e.propName))return null;const i=Zr(e);let a;try{a=zo({...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 E,policy:a,authority:a.authority})}}return{directional:t,slots:n}}(n)),null!==r)return si(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=nt(e,s.nodePath);if(null===t&&oe(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),dt.has(t))continue;const r=ut(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new ds,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 ti(i,s);Rr(l,a.bindingSession),bs(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in E&&c.push(e);return xs(l,c),Wr(l,a.nodes),Jr(e.node,l),l}const ii=new WeakSet,ai=Symbol.for("wcstack.state.view-transition-naming");function li(){const e=Hs("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function ci(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||ii.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[ai]??={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.`)):(ii.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 di=new WeakMap,ui=new WeakMap,fi=new WeakMap,hi=new WeakMap;function pi(e,t,n){!function(e,t,n){let o=ui.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ui.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function gi(e,t){di.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 yi(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 wi(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 bi=new Set(["if","elseif","else","for"]);function vi(e,t){for(const n of ws(e))if(t.appliedBindingSet.delete(n),bi.has(n.bindingType))for(const e of Xr(n.node))vi(e,t)}function $i(e){for(const t of ws(e)){if(!bi.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Xr(t.node))$i(n),e&&n.mounted&&(Hr(n),n.unmount(),Yr(t.node,n))}}function xi(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=Xr(e.node);i=0===a.size?ri(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${xi(e)}`),Hr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${xi(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);Vr(i,yt(e.node),n);const t=li();null!==t&&ci(i,"branch",t)}}const Pi=new WeakMap;function Ii(e){return Pi.get(e)??[]}const Ai=new Set;const Ni=Symbol.for("wcstack.trustedTypes.policy");function ki(){const e=globalThis[Ni];return null===e||"object"!=typeof e?null:e}function _i(e){globalThis[Ni]=e}let Ti;let Ci=!1;function Ei(e,t){if(Ci)return;if(!function(){if(void 0!==Ti)return Ti;if(!("trustedTypes"in globalThis))return Ti=!1,Ti;try{document.createElement("div").innerHTML="<i></i>",Ti=!1}catch{Ti=!0}return Ti}())return;Ci=!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 Mi={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")}},Oi=new Set(["textContent","innerText","innerHTML"]);function Ri(e,n,s){if(void 0===s&&1===e.propSegments.length&&Oi.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!==hs&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Ve(r)&&hs.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&&Ei(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=Ve(e);if(null===n)return null;const o=Ue(e)?.get(n);if(void 0===o)return null;const s=Ke(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&&Xn(r,c)){const t=to(r,c,e.statePathName),o=no(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??ao()??so(t);if(a.visitedEdges.has(o))null!==bt&&bt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=ro(a,o);lo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Zn++,writtenValue:n};co.push({receipt:i,node:e});try{return r()}finally{co.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=Mi[c];e?e(r,s):(!function(e,t,n){let o=Pi.get(e);o||(o=[],Pi.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,Ai.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!==hs&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ve(r)&&(u in d?hs.rememberOverwrittenValue(r,c,u,d[u]):hs.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 ji=new WeakSet;function Li(e,t,n){}function Wi(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 Di(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+c:"";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(c)&&o.push(t)}return o}const Bi={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},zi={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Fi(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}.${de}`}function qi(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 Vi(e,t){return`$setAll("${e}") ${t}`}function Hi(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.${de}`}function Ui(e,t){const n=bn(t);if(n.pathInfo.path in E){const e=yt(t.node);return null===e&&oe(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&oe("ListIndex not found for loopContext:");const n=E[t];void 0===n&&oe(`Invalid index name: ${t}`);const o=en(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&oe(Hi(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Mt](n)}const Gi=new WeakSet;function Ki(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Ji=Object.freeze({[N]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&oe("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[k]: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)},[_]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[A]:function(e,t,n){jn(n)||oe("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||oe('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Ve(e);if(null===t)return null;const n=Ue(e)?.get(t);return void 0===n&&oe(`Custom element <${t}> is not defined for command binding.`),Ke(e)}(r);null===a&&oe(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||oe(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ce(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&&oe(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),ms.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Xi={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!ji.has(e.replaceNode)){ji.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=on(e),i=an(e),a=$t(i),l=a.length>0&&!ui.has(e.node)?[]:a,c=Tr(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=ui.get(e.node);const f=void 0!==u?wi(u,l,c):null,h=Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=hi.get(e.node);if(void 0===t){const n=di.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),hi.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){Io.set(e,(Io.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return fi.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;c.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(Hr(o),$i(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Yr(e.node,o):(Hr(o),o.unmount(),function(e,t){let n=fi.get(e.node);void 0===n&&(n=[],fi.set(e.node,n)),n.length<1e3?n.push(t):Yr(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(ui.delete(e.node),u=void 0)}let g=e.node;const m=ie(s.path+"."+d),y=n.stateElement.loopContextStack,w=Cr(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&g.isConnected&&null===f&&(b=document.createDocumentFragment(),Xt(b,n.rootNode));const v=t(),$=li(),x=e.uuid??"",S=fi.get(e.node);for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const r=yn(m,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=ri(e):vi(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(g.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);g.parentNode.insertBefore(e,g.nextSibling),g=e}o.mountAfter(g)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??g;n.parentNode.insertBefore(e,n.nextSibling)}}Vr(o,r,n),null!==$&&ci(o,"row",$)}),void 0===o&&oe(`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,c.changeIndexSet.has(t)){const e=$s(o);for(const t of e)sa(t,n)}null===o&&oe(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&yi(g,o.firstNode)||g.nextSibling===o.firstNode||o.mountAfter(g),e){const e=o,s=yn(m,t);y.createLoopContext(s,t=>{Vr(e,t,n)})}}g=o.lastNode||g,void 0===u&&(u=new WeakMap,ui.set(e.node,u)),u.set(t,o)}di.set(e.node,g),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Xt(b,null))},if:Si,else:Si,elseif:Si,radio:function(e,t,n){const o=e.node,s=ps(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=ps(o.value,e.inFilters),r=Array.isArray(n)?n:gs;o.checked=r.includes(s)}},Yi=new WeakMap,Qi=new WeakMap,Zi=new WeakMap;function ea(){}function ta(e){const t=hs;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Li;if(t.isDeclared(n,o))return ea}return Ri}function na(e,t){oa(e,t,Ui(t.state,e))}function oa(e,t,n){const o=ps(n,e.outFilters);if(!0===Qi.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=Yi.get(e);if(void 0===s){if(Yi.has(e))return s=ta(e),s===Li&&Yi.set(e,s),void s(e,t,o);if(s=Xi[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Ji[t],Yi.set(e,s),void 0===s){Ve(e.replaceNode)?(s=ta(e),s===Li&&Yi.set(e,s)):(s=Ri,Yi.set(e,s))}}if(s===Ri){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 Qi.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function sa(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=an(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=fs(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Zi.get(e)){const t=Ve(e.replaceNode);if(t&&void 0===Ue(e.replaceNode)?.get(t))return void function(e,t){if(Gi.has(e))return;Gi.add(e);const n=()=>{Gi.delete(e);const t=fs(e);(null===t||t.shouldApplyState(e))&&ia([e])},o=n=>{Gi.delete(e),Ki(t,n)},s=fs(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Gi.delete(e),r()})||(Gi.delete(e),r()))}const r=Ue(e.replaceNode);if(null===r)return Gi.delete(e),void Ki(t,new Error("CustomElementRegistry is unavailable."));Ro(r).wait(t,()=>{e.replaceNode.isConnected?n():Gi.delete(e)},o)}(e,t);Zi.set(e,!0)}if(!0===t.sameRootVerified)return void na(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Yt(o),null===o&&oe("Root node for fragment not found for binding.")),o!==t.rootNode){const n=ba(o);null===n&&oe("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};na(e,r)})}else na(e,t)}function ra(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!==bt&&bt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function ia(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=Yt(d),null===d&&oe("Root node for fragment not found for binding."));const u=ba(d);null===u&&oe("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{sa(n,f)}catch(e){ra(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{Ri(e,{propagationContextByBinding:t},n)}catch(t){ra(e,t,o??null,c)}for(const[e,t]of i.entries())xt(e,t),kt(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Wt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Dt](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 aa(e,t,n){const[o,s,r]=ft(e,n),i=us(e);for(const e of o)wt(e,t);ia(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=pt(o);0!==e.length&&(wt(o.node,t),ia(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const la=new WeakMap;async function ca(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Ue(e);null===s&&oe(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(it(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function da(e){if(e===document)await ca(document),te(document),qa(document,document),aa(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await ze(t.host),await ca(t),te(t),qa(t,t),aa(t,null)}}const ua={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function fa(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${ua[e]??e}" before the state is defined.`}let ha=null;function pa(e){return null===ha&&oe(fa("ssr",e)),ha}const ga=new WeakMap,ma=new WeakMap,ya=new Set,wa=[];function ba(e){return ga.get(e)??null}function va(e){return ma.get(e)??Promise.resolve()}const $a=new WeakSet;function xa(e){$a.add(e)}function Sa(e,n){const s=ga.get(e);if(null===n){if(void 0===s)return;ga.delete(e),ya.delete(s),null!==bt&&bt({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 pa('the "enable-ssr" attribute').hydrate(e)||await da(e)}else await da(e);xa(e),Ja(),t()}catch(e){n(e)}})});ma.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await da(e),xa(e),Ja(),t()}catch(e){n(e)}})});ma.set(e,t)}}void 0!==s&&oe('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="...">.'),ga.set(e,n),ya.add(n);for(let t=0;t<wa.length;t++)wa[t](e,n);null!==bt&&bt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Pa=new Map;function Ia(e,t,n){if(null===n)Pa.delete(e);else{Pa.set(e,n);const o=ba(t);null===o&&oe("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 Aa(e){return Pa.get(e)||null}function Na(e){if(e.nodeType===Node.ELEMENT_NODE){return Ee(e.getAttribute(o.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=je(e);null===t&&oe("Comment node binding text not found.");const n=Aa(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Le(t),s=null):s=t,[{...o,uuid:s}]}return[]}let ka;function _a(){return ka??={filterName:"not",args:[]}}const Ta=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Ca(e,t){const n=t+c+d,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+c+s.slice(1)}return r.length>0?s+r:s}function Ea(e,t){const n=Ta.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Ca(s,t)+r}function Ma(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=Ca(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Oa(e,t){return Ma(e,t)}function Ra(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=Ea(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Ma(r,t);e!==r&&o.setAttribute(n,e)}}}function ja(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 La(e){const t=[],n=ct(e);for(const e of n){const n=Na(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:ja(o),parseBindTextResults:n})}return t}function Wa(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 Da=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Ba=_a();function za(e,t){const n=t.outFilters;return{...t,outFilters:[...n,Ba],bindingType:e}}function Fa(e,t,n,o,s,r=!0){Wa(t),"string"==typeof o&&Ra(t,o),qa(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:La(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 qa(e,t,n,s){const r=o.commentElsePrefix,i=at(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=Oa(i,n));let a=Ee(i)[0];const d=Da.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Ps();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&oe("'else' binding found without preceding 'if' or 'elseif' binding."),a=za("else",l.parseBindTextResult),p=Fa(e,f,a,g,s,!1),Ia(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:ja(o),parseBindTextResults:Na(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&oe("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Fa(e,f,a,g,s),Ia(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=Ps(),i={fragment:document.createDocumentFragment(),parseBindTextResult:za("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ja(n),parseBindTextResults:Na(n)}),Ia(o,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:ja(m),parseBindTextResults:Na(m)})):t.replaceWith(m)}else{p=Fa(e,f,a,g,s),Ia(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 Va=()=>`[${o.bindAttributeName}]`;function Ha(e){if(Qo(e))return!0;if(!Ua(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(Va());return null!==t&&Qo(t)}function Ua(e){return 1===e.nodeType}function Ga(e){if(Ha(e))return;te(e),qa(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);aa(t&&s?n:e,null)}const Ka=[];function Ja(){const e=Ka.splice(0,Ka.length);for(const t of e)Ga(t);l()}const Xa={protocol:"wcs-binder",version:1,bind:function(e){var t;Ua(e)&&!Ha(e)&&(t=e.getRootNode(),$a.has(t)?Ga(e):Ka.push(e))}};const Ya="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Qa=0;async function Za(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Qa}\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 ${Ya}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Ya}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function el(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){oe(`Failed to load script file: ${e}`)}}class tl{_loopContextStack=Array(f).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&oe("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=f&&oe("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&&oe("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&&oe("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&&oe(`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 nl=new WeakMap;function ol(e,t){let n=nl.get(e);void 0===n&&(n=new Map,nl.set(e,n));let o=n.get(t);return void 0===o&&(o=new Rn(t,e),n.set(t,o)),o}const sl=new WeakMap;function rl(e){const t=sl.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 ol(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:ol(e,n)}},set(){oe("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){oe("$command namespace is read-only; deleting from it is not allowed.")}});return sl.set(e,n),n}const il=Symbol("wcs.notHandled"),al=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],ll=new Map;function cl(e,t){ll.set(e,t)}const dl=new Map;let ul=[],fl=[];function hl(e,t){dl.set(e,t),ul=Array.from(dl.values()).sort((e,t)=>e.order-t.order),fl=ul.slice().reverse()}function pl(e,t){for(let n=0;n<ul.length;n++)ul[n].activate?.(e,t)}function gl(e){"readonly"===e.mutability&&oe("This state is readonly.")}const ml=new Map;class yl{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=ie(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 wl(e){let t;return ml.get(e)??(ml.set(e,t=new yl(e)),t)}function bl(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:en(n.listIndex,o,n.pathInfo.wildcardCount)}function vl(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=Zt(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?en(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?en(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function $l(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function xl(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!==il)return a}}return il}function Sl(e,t,n,o,s){if(t.pathInfo.segments[0]===z)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}(rl(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=xl(s,t,null,n,o);if(r!==il)return r;oe(function(e,t,n){return`[${Bi.binding}] Path "${e}" does not exist on the state tree.${ce(e,Di(t,"",n))}${de}`}(t.pathInfo.path,e,s.getterPaths))}const r=Il(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!==d&&!(i in Object(r))){const e=xl(s,t,Object(r),n,o);if(e!==il)return e}if(i===d){const e=t.listIndex?.index??oe(Hi(`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 Pl(e,t,n,o,s){const r=Gt(s,t),i=function(e){return zs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Sl(e,t,n,o,s);return Fs(r,{value:l,dirty:!1,generation:a}),l}function Il(e,t,n,o){vl(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!==il)return i}}return $l(s,t)?Pl(e,t,n,o,s):Sl(e,t,n,o,s)}function Al(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=yn(f,r),p=Gt(n.stateElement,h),g=Nt(p),m=Il(e,h,t,n),y=Tr(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??oe(`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 Nl(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Ds(Il(e,yn(a,r),t,n),r);null==l&&oe(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??oe(`ListIndex not found at index ${c} of ${a.path}`)}return r}function kl(e,t,n,o){"object"==typeof e&&null!==e||oe(`${J} 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&&oe(`${J} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function _l(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&oe(`${J} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function Tl(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];kl(a,n,o,i);const l=_l(a,t,n,o,i);r.has(l)&&oe(`${J} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Cl(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 El(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=Il(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===d){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const Ml=new WeakMap;function Ol(e,t){null===t?Ml.delete(e):Ml.set(e,t)}function Rl(e,t,n){const s=yn(ie(e.wildcardParentPaths[t]),n),r=Gt(e.stateElement,s),i=Nt(r),a=e.stateProxy[Mt](s),l=Tr(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)Rl(e,t+1,n)}const jl=[];function Ll(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:jl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:jl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Wl=[];function Dl(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Wl;let s=null;const r=t+c;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ie(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Wl}function Bl(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=ie(r);if(e.listPathSet.has(o)&&s.lastSegment===d){const i=e.stateProxy[Mt](t),a=Gt(e.stateElement,t),l=Nt(a),c=Tr(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Ll(e,o,0,0,c);for(const t of d.fullRows){const o=yn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=Dl(e,r,s);if(null===t)for(const t of d.movedRows){const o=yn(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=yn(s,o);e.result.add(t),n.push(t)}}}else{const o=yn(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=ie(o),r=[];if(s.wildcardCount>0){const n=Zt(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&oe(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=en(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};Rl(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&oe(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=en(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=yn(s,t);e.result.add(o),n.push(o)}}}function zl(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&&oe(`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,Bl(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 Fl(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 ql(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 Vl(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 Hl(e,t,n,s,r,i){const a=function(e,t){return!0===tr.get(e)?.byPath.has(t)||!0===ir.get(e)?.has(t)}(e,t),l=function(e,t){return!0===lr.get(e)?.has(t)}(e,t);if(!a&&!l)return;const c=er(),u=o.enablePropagationContext?ao()??null:null,f=e=>{qs(e),c.enqueueAbsoluteAddress(e,u)};a&&$r(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=ie(t).segments.length,r=[];for(const i of lr.get(e).get(t)){const t=ie(i).segments.slice(s);if(t.includes(d))Sr(e,i,r);else for(const s of $r(e,i,!0,xr(n,t),xr(o,t)))r.push(s)}return r}(e,t,n?s:i(),r).forEach(f)}function Ul(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?ao()??so(-1):null,c=er();c.enqueueAbsoluteAddress(t,l),i&&qs(t),zl(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Gt(s.stateElement,t);qs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Gl(e,t,n,o,s){s&&(e.getterPaths.has(t)?qs(n):Fs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function Kl(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=Il(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??oe(Hi(`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{Ul(t,n,s,r,i,a)}}function Jl(e,t,n,o,s,r,i,a){const l=t.parentAddress??oe(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=Il(e,l,s,r)??[];let f=(h=u,Ml.get(h)??null);var h;if(null===f){const e=Ws(u)??[];f={value:[...u],listIndexes:[...e]},Ol(u,f)}try{return Kl(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=Il(e,l,s,r)??[],a=Array.isArray(i)?Ws(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:_s(l.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;Ol(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=er(),l=Gt(i,e);$t(l)===n&&(Bs(t.value,t.listIndexes),xt(l,t.value),function(e){Er.add(e)}(t.value));a.enqueueRenderOnlyAddress(l);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=ie(e.pathInfo.path+c+d);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=yn(f,n),d=Gt(i,c);if(void 0===l){const n=Kt(i,f,t.listIndexes[e]??null);Vl(i,d,n),Ul(c,d,s,r,null,$l(i,c),"full");continue}zl(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Gt(i,e);qs(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(l,f,i,a,s,r)}}}function Xl(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=Il(e,t,o,s),a=function(e,t,n,o){const s=Tl(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Tl(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===Ws(o)&&Tr(a,null,o);const l=Tr(a,o,n.list),u=Yl(e,t,n.list,s,r,i),f=ie(i+c+d);for(const t of n.matched){const n=Cl(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?Xl(e,yn(ie(f.path+c+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return Yl(e,t,n,o,s,null)}function Yl(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==il)return i}}const u=!!uo&&(uo=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=Il(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===d?t.listIndex?.index:e;let p,g=!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,g=!0}Hl(a,l,g,p,n,()=>f[h]);const m=$l(a,t),y=Gt(a,t);null!==bt&&bt({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:g}),Fl(a,l,y,p,g);let w=!1;try{if(void 0===h&&oe(Hi(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==d&&!(h in f)){const e=c.writeMissing;for(let o=0;o<e.length;o++){w=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==il)return i;w=!1}}return Reflect.set(f,h,n)}finally{Ul(t,y,s,r,i,m),w?qs(y):Gl(a,l,y,n,m),ql(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Il(e,t,s,r);if(El(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Hl(a,l,h,f,n,()=>Il(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),g=$l(a,t),m=Gt(a,t);null!==bt&&bt({type:"state:write",absoluteAddress:m,value:n,oldValue:f,hasOldValue:h}),Fl(a,l,m,f,h);try{return p?Jl(e,t,m,n,s,r,i,g):Kl(e,t,m,n,s,r,i,g)}finally{p||Gl(a,l,m,n,g),ql(a,t.pathInfo,{value:n})}}function Ql(e,t,n,o){return(t,s,...r)=>{const i=ie(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&&oe(Fi("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=yn(i,Nl(e,n,o,i,s));if(0===r.length)return Il(e,a,n,o);gl(o),Xl(e,a,r[0],n,o)}}function Zl(e,t,n,o){const s=Ql(e,0,n,o);return(t,r)=>{const i=ie(t);if(void 0===r||Array.isArray(r)||oe(`$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&&oe(Fi("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=bl(o,i.wildcardPaths[e]);if(t){r=tn(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&&oe(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=Al(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 ec(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return bl(o,s.wildcardPaths.at(-1)??oe(`lastWildcardPath is null: ${t.pathInfo.path}`))??oe(`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]??oe(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Ds(Il(e,yn(i,s),n,o),s)??oe(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??oe(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??oe(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":oe(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function tc(e,t,n,o){return(t,s,r,i)=>{gl(o);const a=ie(t);Array.isArray(s)||oe(Vi(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&oe(Fi("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&oe(Vi(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&oe(Vi(t,"requires an array as the value when { spread: true } is set."));const d=Al(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&oe(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=Nl(e,n,o,a,d[t]);u.push(yn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(Il(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(Xl(e,s,i,n,o),f++)}return f}}function nc(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of ie(t).cumulativePaths)if(n.has(e))return!0;return!1}const oc=/^\$\d+$/,sc=`${X}${c}`,rc=`${Y}${c}`,ic=new WeakMap;function ac(e,t,n,o){const s=E[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&oc.test(t)&&oe(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${T}1 to ${T}128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&oe(`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&&oe(`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=en(r,i,a.wildcardCount);return c?.index??oe(`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!==il)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Zl(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>tc(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=wl(t),i=ec(e,r,n,o),a=yn(r.pathInfo,i),l=Gt(s,a),c=er();c.enqueueAbsoluteAddress(l),zl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Gt(s,e);qs(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)=>Ql(e,0,n,o)(t,s,...r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(K)&&oe(`[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&&oe(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??oe("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(nc(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&wr(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)&&yr(o.stateElement,e,t,Gt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=nc(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?wr(o.stateElement,e):yr(o.stateElement,e,i,Gt(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||oe(`$eqIndex("${e}") needs a list row scope.`);const r=en(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&oe(`$eqIndex("${e}", ${t}): no list index at that level.`),nc(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&wr(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?Ws(l):null;null!==t?function(e,t,n,o,s){rr=!0,ur(e).lastValue.set(t,s),dr(e,t);let r=ir.get(e);void 0===r&&ir.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=ar.get(o);void 0===l?ar.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){rr=!0;const r=ur(e);dr(e,t),mr(r,t,s,o,pr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Gt(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 z:return rl(o.stateElement)}if(!t.startsWith(sc)&&!t.startsWith(rc))return}const r=wl(t),i=ec(e,r,n,o),a=yn(r.pathInfo,i);return Il(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=ic.get(e);return void 0===t&&(t=new Map,ic.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&&oe("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=>Il(e,t,n,o);break;case Ot:i=t=>El(e,t,n,o);break;case Rt:i=(t,s)=>Xl(e,t,s,n,o);break;case jt:i=()=>async function(e,t,n){const o=Reflect.get(e,M);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Lt:i=()=>function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&o.call(n)}(e,0,n);break;case Wt:i=t=>function(e,t,n,o){const s=Reflect.get(e,R);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=tn(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 Dt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,j);"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 lc{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=ba(e);null===n&&oe("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&&oe("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=f&&(this._hasRepeatedAddress()&&oe(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),oe(`[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&&oe(`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 ac(e,t,n,this)}set(e,t,n,o){return gl(this),function(e,t,n,o,s){if("string"==typeof t){const r=wl(t),i=ec(e,r,o,s);return Xl(e,yn(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 cc=Promise.resolve(),dc=new Map;let uc=[];function fc(e,t){dc.set(e,t),uc=Array.from(dc.values()).sort((e,t)=>e.order-t.order)}function hc(e,t){return oe(fa(e,t))}const pc="undefined"==typeof HTMLElement?class{}:HTMLElement;function gc(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 mc=null;const yc=new Set(["for","if","elseif","else"]);function wc(e,n,o){const s=new Map;for(const e of o){const t=ie(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=Gt(e,t);if(i.has(n))return;i.add(n);const o=hn(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(yn(n,t.listIndex))}};_t();try{if(e.createState("readonly",t=>{for(const o of n){const n=yn(ie(o),null);a(n);try{zl(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)yc.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=()=>{ia(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Us("state",s);void 0!==i&&i.catch(Ys)}finally{Tt()}}class bc extends pc{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return va(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 tl}();_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&&oe(`${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<ul.length;o++)ul[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[B];if(void 0===n)return t;Array.isArray(n)||oe(`${B} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||oe(`${B} entries must be non-empty strings.`),e===z&&oe(`${B} entry "${e}" conflicts with the reserved namespace name "${z}".`),t.has(e)&&oe(`${B} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[F];if(void 0===n)return t;Array.isArray(n)||oe(`${F} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||oe(`${F} entries must be non-empty strings.`),t.has(e)&&oe(`${F} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[J];if(void 0===t)return null;"object"==typeof t&&null!==t||oe(`${J} 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&&oe(`${J} entry path must be a non-empty string.`);const t=e.split(c);t.some(e=>0===e.length)&&oe(`${J} entry "${e}" must not contain empty path segments.`),t[t.length-1]===d&&oe(`${J} entry "${e}" must be the list path itself, not the element path (drop the trailing "${c}${d}").`),-1!==e.indexOf(K)&&oe(`[wcs/recursion-unsupported] ${J} entry "${e}" uses "${K}", which ${J} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${c}${d}${c}children").`),"function"!=typeof o?("string"!=typeof o&&oe(`${J} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&oe(`${J} entry "${e}" key field name must be a non-empty string.`),(o.includes(c)||o.includes(d))&&oe(`${J} entry "${e}" key field name "${o}" must be a flat property name ("${c}" / "${d}" are not allowed).`),o in Object.prototype&&oe(`${J} 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<ul.length;o++)ul[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<ul.length;o++)ul[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&mc?.reset(this),this._hasUpdatedCallback=R in e,this._hasErrorCallback=j in e,i=this,Cn.delete(i),function(e,t,n){for(let o=0;o<ul.length;o++)ul[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[q];if(void 0!==o){"object"==typeof o&&null!==o||oe(`${q} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||oe(`${q} entry "${t}" is not declared in $eventTokens.${ce(t,n)}`),"function"!=typeof s&&oe(`${q} 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=gc(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<ul.length;o++)ul[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<ul.length;o++)ul[o].register?.(e,t,n)}(this,e,n),pl(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")?pa('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){oe("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 Za(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||oe(`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 el(e);oe(`Unsupported src file type: ${e}`)}}catch(e){oe(`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&&(Sa(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),oe(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===ba(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),ma.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<uc.length;o++)uc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{M in e&&await e[jt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{O in e&&e[Lt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<uc.length;t++)if(!0===uc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||ba(this._rootNode)===this||Sa(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<uc.length;t++){const n=uc[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(Q))try{hc("dcc",`a <${o.tagNames.state}> inside a [${Q}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{hc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<uc.length;t++){const n=uc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&hc("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 pa('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}pl(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<uc.length;t++)if(!0===uc[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<uc.length;n++)uc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Sa(this.rootNode,null),e=this,sl.delete(e),function(e){for(let t=0;t<fl.length;t++)fl[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",H)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&oe(`$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 Wi(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&&oe("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=ll.get(e);return void 0===n&&oe(fa(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<al.length;n++){const o=al[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",W)}_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+"."+d)),!this._pathSet.has(e)){const t=ie(e);if(this._pathSet.add(e),mc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ie(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 lc(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&&oe(`<${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<uc.length;t++)uc[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&oe("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(gc(n)))e.startsWith("$")||e.includes(d)||"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){wc(this,e,this._pathRegistrations.keys())}}const vc=[];function $c(e=customElements){for(let t=0;t<vc.length;t++)vc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,bc)}function xc(e){if("string"==typeof e?.locale)return e;const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}function Sc(e,t){const o=xc(e);var s;o&&((s=o).tagNames&&Object.assign(n.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(n.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(n.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(n.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(n.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(n.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(n.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(n.locale=s.locale),"boolean"==typeof s.debug&&(n.debug=s.debug),"boolean"==typeof s.enableMustache&&(n.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(n.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(n.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(n.sameValueGuard=s.sameValueGuard)),$c(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=Xa)}()}let Pc=0;const Ic=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Ac=new Set;function Nc(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 kc(e,t,n,o,s,r=new Set){0===n.length&&oe(`Cannot build a mount record without host bindings for "${t}".`);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(c);a.has(n)&&oe("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(y)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++Pc,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 g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?u:l.outerPathInfo.path+c+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function _c(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function Tc(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 Cc(e,t){for(const n of e.entries)if(Tc(t,n.innerSegments)){const e=t.slice(n.innerSegments.length);return 0===e.length?n.outerPathInfo.path:n.outerPathInfo.path+c+e.join(c)}return null}function Ec(e,t){return e.markerBasePath+c+t}function Mc(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+c+n;s.set(n,{accessorName:o,indexShift:ie(r).wildcardCount-ie(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function Oc(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 Rc(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(c)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${_c(t)}: path") or declare the key on the component state.`}const jc=/^\$(\d+)$/;function Lc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=_c(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||Oc(e,o))return null;const s=function(e,t){for(const n of e.entries)if(Tc(t,n.innerSegments))return n;return null}(e,t.split(c));return null!==s&&s.readonly?s:null}function Wc(e,t){const n=Lc(e,t);if(null!==n){const o=0===n.innerSegments.length?"":c+n.innerSegments.join(c);oe(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${y}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${y} from the mount.`)}return Dc(e,t)}function Dc(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(c);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===d){o=e;break}if(-1===o)return Mc(e,e.markerBasePath,t,t),Ec(e,t);if(Oc(e,n[0]))return Mc(e,e.markerBasePath,t,t),Ec(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Cc(e,s);null===i&&oe(Rc(e,t)),0===r.length&&oe(`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+c+e.marker;return Mc(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=_c(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return Ec(e,t);if(Oc(e,o))return Ec(e,t);const s=Cc(e,t.split(c));if(null!==s)return s;oe(Rc(e,t))}function Bc(e,t,n){let o;const s=jc.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ie(Dc(e,t)).wildcardCount-ie(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Dc(e,t.statePathName),"for"===t.bindingType){const n=ie(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+c+d,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(y)&&null!==Lc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ie(o),...i?{propModifiers:[...r,y]}:{}}:t}function zc(e,t,n,o,s){if(void 0===o)return;const r=ie(n).wildcardCount-ie(t).wildcardCount;return 0===r?o:(s.length<r&&oe(`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 Fc=new WeakMap,qc=new WeakMap;const Vc=new WeakMap;const Hc=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)}),Uc=new WeakMap;function Gc(e){return Uc.get(e)??null}let Kc=!1;function Jc(){Kc||(Kc=!0,mt=e=>Fc.has(e)?e.host:null)}function Xc(e){const t=Vc.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 Yc(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Vc.get(e);if(void 0===o)return null;const s=t.indexOf(c,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 Qc="3.0.0",Zc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function ed(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 td(e){const t=function(e){const t=tr.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:ir.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 nd="__WCSTACK_DEVTOOLS_HOOK__";function od(){const e=globalThis,t=e[nd];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[nd]=n,n}const sd=e=>{null!==bt&&bt({type:"state:update-batch",addresses:e})};function rd(e){const t=null!==bt;!function(e){bt=e}(e);const n=null!==e;n&&!t?Xs(sd,0):!n&&t&&function(e){const t=Gs.findIndex(t=>t.listener===e);-1!==t&&Gs.splice(t,1)}(sd)}function id(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 ad(e){return ba(e)??oe("devtools: no state tree on this root")}let ld=null;function cd(){if(t())return;if(null!==ld)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Qc,getStateElements(){const e=[];for(const t of ya)e.push(id(t));return e},overlays:e=>Xc(ad(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=>td(ad(e)),keys(e){const t=ad(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 ad(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){ad(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=Aa(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(ed(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=tt(t,Ee(n));for(const o of e)r(ed(t,o,"attribute",n))}catch{}continue}const t=Zc.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=Aa(s);if(null===a){if(n===o.commentTextPrefix)try{r(ed(e,Le(s),"comment",s))}catch{}}else r(ed(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:rd};ld=e,od().register(e)}const dd={name:"devtools",install(){cd()}},ud=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),fd=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const hd=new WeakMap;const pd=new WeakMap,gd=new WeakSet,md=new WeakMap;function yd(e,t,n,o){console.warn(`[@wcstack/state] [${Bi[n]}] ${zi[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ce(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${de}`),null!==bt&&bt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const wd={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=ie(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=hd.get(e);return void 0===n&&(n=new Set,hd.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!==Wi(e,t))return fd;const o=ie(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+c+i,t>0&&t<o.length-1&&void 0!==Wi(e,r))return ud;if(Object(s)!==s)return ud;if(i===d){if(!Array.isArray(s)||0===s.length)return ud;s=s[0];continue}const l=Wi(s,i);if(void 0===l)return{existence:"missing",missingSegment:i,candidates:Di(s,a,n)};if("function"==typeof l.get)return t===o.length-1?fd:ud;s=l.value}return fd}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===md.get(e)?.has(t)}(e,n)||("binding"!==o?yd(e,n,o,i):function(e,t,n){let o=pd.get(e);void 0===o&&(o=new Map,pd.set(e,o));if(o.set(t,n),gd.has(e))return;gd.add(e),setTimeout(()=>function(e){gd.delete(e);const t=pd.get(e);if(void 0===t)return;pd.delete(e);for(const[n,o]of t)yd(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){hd.delete(e),pd.delete(e)},markExported:function(e,t){let n=md.get(e);void 0===n&&(n=new Set,md.set(e,n)),n.add(t),pd.get(e)?.delete(t)}};let bd=!1;function vd(){bd||(bd=!0,function(e){mc=e}(wd))}const $d={name:"diagnostics",install(){vd()}};function xd(e){oe(`filter ${e} requires at least one option`)}function Sd(e){oe(`filter ${e} requires a number as option`)}function Pd(e){oe(`filter ${e} requires a number value`)}function Id(e){oe(`filter ${e} requires a date value`)}function Ad(e){return!(!e||isNaN(Number(e)))}const Nd={eq:(e,t)=>{const n=e?.[0]??xd("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Ad(n)||Sd("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??xd("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Ad(n)||Sd("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>("boolean"!=typeof e&&oe(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??xd("lt");return Ad(t)||Sd("lt"),e=>("number"!=typeof e&&Pd("lt"),e<Number(t))},le:e=>{const t=e?.[0]??xd("le");return Ad(t)||Sd("le"),e=>("number"!=typeof e&&Pd("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??xd("gt");return Ad(t)||Sd("gt"),e=>("number"!=typeof e&&Pd("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??xd("ge");return Ad(t)||Sd("ge"),e=>("number"!=typeof e&&Pd("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??xd("inc");return Ad(t)||Sd("inc"),e=>("number"!=typeof e&&Pd("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??xd("dec");return Ad(t)||Sd("dec"),e=>("number"!=typeof e&&Pd("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??xd("mul");return Ad(t)||Sd("mul"),e=>("number"!=typeof e&&Pd("mul"),e*Number(t))},div:e=>{const t=e?.[0]??xd("div");return Ad(t)||Sd("div"),e=>("number"!=typeof e&&Pd("div"),e/Number(t))},mod:e=>{const t=e?.[0]??xd("mod");return Ad(t)||Sd("mod"),e=>("number"!=typeof e&&Pd("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&Pd("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??xd("clamp");Ad(t)||Sd("clamp");const n=e?.[1]??xd("clamp");Ad(n)||Sd("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&Pd("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return Ad(t)||Sd("fix"),e=>("number"!=typeof e&&Pd("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Pd("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]??xd("slice");Ad(n)||Sd("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Ad(o)||Sd("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??xd("substr");Ad(t)||Sd("substr");const n=e?.[1]??xd("substr");return Ad(n)||Sd("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??xd("pad");Ad(t)||Sd("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??xd("rep");return Ad(t)||Sd("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??xd("truncate");Ad(t)||Sd("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)||oe(`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 Ad(t)||Sd("round"),e=>{"number"!=typeof e&&Pd("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Ad(t)||Sd("floor"),e=>{"number"!=typeof e&&Pd("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Ad(t)||Sd("ceil"),e=>{"number"!=typeof e&&Pd("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Ad(t)||Sd("percent"),e=>("number"!=typeof e&&Pd("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??xd("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Id("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Id("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Id("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Id("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||Id("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]??xd("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},kd={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]},_d=Nd,Td=Nd;let Cd=!1;const Ed={name:"formats",install(){Cd||(Cd=!0,me("input",Td,kd),me("output",_d,kd))}};function Md(e){return-1!==e.indexOf(K)}function Od(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+c;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(Md(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function Rd(e){return 0===e.length?e:c+Wd(e.slice(1))}function jd(e,t,n){const o=c+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 Ld(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(jd(e,t,n.slice(0,o)))return!0;return!1}function Wd(e){const t=e.split(c);for(let e=0;e<t.length;e++)t[e]===d||Number.isNaN(Number(t[e]))||(t[e]=d);return t.join(c)}function Dd(e,t){const n=e.repeat.split(c),o=c+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===c+e.repeatList+c+"length")return!0;for(let e=1;e<n.length;e++)if(s===c+n.slice(0,e).join(c))return!0;return!1}function Bd(e,t,n){n<0&&oe(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=c+e.repeat;const s=o+t;let r=0;for(const e of s.split(c))e===d&&r++;return r>u&&oe(`[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 zd(e,t){return Bd(e,"",t)}function Fd(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=c+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 qd(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=c+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 Vd(e,t,n){const o=e.recursionRegistry,s=Od(o.spec,n);null===s&&oe(qi(n,o.spec.recursiveAnchor));const r=qd(t,o);return null===r&&oe(`[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 Hd(e,t,n,o,s){const r=o.spec,i=[],a=new Map,l=[],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(yn(e,n));const s=g(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function g(o,s,i){const l=yn(o,s),c=Gt(n.stateElement,l),u=Il(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)&&oe(`[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)&&oe(`[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=Tr(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 m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=l[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:ie(n),childListPathInfo:ie(r+c+d)};return l[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(yn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,ie(u),null);for(const[e,t]of a)kt(e,t);return i}function Ud(e,t,n,o,s,r,i){gl(n);const a=n.stateElement.recursionRegistry,l=Od(a.spec,o);null===l&&oe(qi(o,a.spec.recursiveAnchor));const c=Rd(l);Array.isArray(s)||oe(Vi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&oe(`[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&&oe(Vi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&oe(Vi(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){Dd(e,n)&&oe(`[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&&oe(`[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=Hd(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Xl(e,u[o],r,t,n),f++);return f}const Gd={write(e,t){if(!0!==e.hasRecursion)return il;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&oe(`[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.`),il},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return il;if("$getAll"===t)return(t,s)=>{if(Md(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Od(r.spec,o);null===i&&oe(qi(o,r.spec.recursiveAnchor)),Array.isArray(s)||oe(`[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&&oe(`[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=Hd(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Il(e,a[o],t,n));return l}(o,n,e,t,s);t=Vd(e.stateElement,e,t)}return Zl(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>Md(t)?Ud(o,n,e,t,s,r,i):tc(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&Md(t)){const s=wl(Vd(e.stateElement,e,t)),r=ec(o,s,n,e);return Il(o,yn(s.pathInfo,r),n,e)}return il}};let Kd=!1;function Jd(e,t){"string"==typeof t&&0!==t.length||oe(`[wcs/recursion-declaration-invalid] ${G} ${e} must be a non-empty string.`);const n=t.split(c);n.some(e=>0===e.length)&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not contain empty path segments.`),n.length<2&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must name a list element: a property path ending with "${c}${d}" (for example "nodes${c}${d}").`),n[n.length-1]!==d&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must end with "${c}${d}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===d&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must have exactly one "${d}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===K&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not contain "${K}" — the declaration is what gives "${K}" its meaning.`),isNaN(Number(n[o]))||oe(`[wcs/recursion-declaration-invalid] ${G} ${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 Xd=new WeakSet;function Yd(e){return"function"==typeof e.get&&Xd.has(e.get)}function Qd(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Yd(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=ie(o),s=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void Fs(Kt(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=Ws(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 Zd="[wcs/recursion-declaration-invalid]";class eu{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=gc(t);for(const[t,o]of Object.entries(n)){if(!Md(t))continue;"function"==typeof o.set&&oe(`${Zd} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&oe(`${Zd} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Od(e,t);null===n&&oe(qi(t,e.recursiveAnchor)),0===n.length&&oe(`${Zd} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),Dd(e,Rd(n))&&oe(`${Zd} "${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}${c}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(Md(t)||Yd(n))continue;const e=this._matchExpansion(t);null!==e&&oe(`${Zd} "${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++)jd(this.spec,e[t].suffix,e[n].suffix)&&oe(`${Zd} "${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(Ld(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=Wd(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(c);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(c,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!==Fd(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=Fd(this.spec,e.suffix,t);null!==n&&(null!==o&&oe(`"${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||Yd(s)||oe(`"${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,Xd.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(zd(e,o)+c+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 Qd(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=Bd(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 tu="recursionSpec",nu="recursionRegistry",ou={order:5,validateEarly(e,t,n){const o=function(e){const t=e[G];if(void 0===t)return null;"object"==typeof t&&null!==t||oe(`[wcs/recursion-declaration-invalid] ${G} 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&&oe(`[wcs/recursion-declaration-invalid] ${G} must declare exactly one anchor; it is empty.`),n.length>1&&oe(`[wcs/recursion-declaration-invalid] ${G} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Jd("anchor",o),"string"!=typeof s&&oe(`[wcs/recursion-declaration-invalid] ${G} entry "${o}" must map to the repeating sub-path as a string (for example "children${c}${d}").`),Jd("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(c)),i=s.slice(0,s.lastIndexOf(c)),a=r+c+K;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(tu,o),n.set(nu,null===o?null:new eu(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(nu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",G)},apply(e,t,n){const o=n.get(tu)??null;null!==o&&e.addListPath(o.anchorList)}};let su=!1;function ru(){su||(su=!0,Kd||(Kd=!0,cl("recursion",Gd)),hl("recursion",ou))}const iu={name:"recursion",install(){ru()}};const au={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 lu=!1;function cu(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 du(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 uu(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 fu(e){return e.startsWith("$")}function hu(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 pu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||oe(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||oe(`${t} entries must be non-empty strings.`),e.startsWith("$")&&oe(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&oe(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function gu(e){const t=pu(e,W)??[],n=pu(e,D)??[],o=gc(e),s=function(e){const t=e[V];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}oe(`${W} entry "${e}" is not declared on the state.${ce(e,hu(o,"value"))}`)}"function"==typeof t.value&&oe(`${W} entry "${e}" is a method. Declare it in ${D} instead.`)}for(const e of n){const t=o[e];void 0===t&&oe(`${D} entry "${e}" is not declared on the state.${ce(e,hu(o,"method"))}`),"function"!=typeof t.value&&oe(`${D} entry "${e}" is not a method. Declare it in ${W} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function mu(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||oe(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Ue(e);null!==r&&"function"==typeof r.define||oe(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&oe(`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}=gu(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,g=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(Q))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=Ue(this._shadow);return null!==e&&Ge(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(lu||(lu=!0,cl("dcc",au)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${W} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=gc(n);for(const[e,t]of Object.entries(m)){if(fu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=uu(e,o)}else n.get=cu(e),n.set=du(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:cu(e),set:du(e)});r.define(s,g)}async function yu(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&oe(`"bind-component" cannot be used inside a [${Q}] 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 el(t);oe(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await Za(n,t.tagName.toLowerCase());oe(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){oe(`DCC: Failed to load state: ${e}`)}}(o,t);mu(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const wu={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Q)?yu(e,t.host,t):null}};let bu=!1;const vu=new WeakMap;function $u(e,t,n){let o=vu.get(e);void 0===o&&(o=new Map,vu.set(e,o));const s=o.get(t);null!=s&&oe(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function xu(e,t){if(null===e)return!1;const n=vu.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+c)||e.startsWith(t+c))return!0;return!1}const Su=new WeakMap;function Pu(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+c+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...s)=>t[n](e+c+o,...s)}return t[o]}return t[e+c+o]}},set:(n,o,s)=>("string"!=typeof o||(t[e+c+o]=s),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Iu=new WeakMap,Au=[];const Nu=new WeakMap,ku=new WeakSet;function _u(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 Tu=null;const Cu=new WeakMap,Eu=new Set;function Mu(e,t,n,o){let s=Cu.get(e);if(void 0===s){if(!o)return null;s=new Map,Cu.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 Ou(e,t){if(!e.component.isConnected)return!1;const n=yt(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 Ru(e,t,n,o){const s=Mu(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&&Ou(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?Ou(r,o)&&(null!==a&&oe(`[wcs/mount-export-ambiguous] "${t}${c}${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 ju(e){const t=e.parentStateElement,n=yt(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 Lu=new WeakMap;class Wu{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 yn(ie(this.markerParentPath+c+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(Dc(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?Wc(e,t):Dc(e,t),a=zc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Wc(e,t):Dc(e,t),l=zc(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 vl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[Dc(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)||oe(`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[Wc(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 Dc(this.record,t),!0}catch{return!1}}}function Du(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Lu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Lu.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 Wu(e,s,t.listIndex,r,n,o))}function Bu(e){const t=e.parentStateElement,n=(t,n)=>{const o=yt(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(Dc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Wc(e,n):Dc(e,n),l=yt(e.component)?.listIndex.indexes??[],c=zc(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:Dc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Wc(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 Dc(e,n),!0}catch{return!1}}})}function zu(e,t){const n=function(e){return Fc.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&oe(`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&&us(t).dispose(),function(e,t){Jc(),Fc.set(e,t),Uc.set(t,e);let n=Vc.get(t.parentStateElement);void 0===n&&(n=new Map,Vc.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=qc.get(t.component);void 0===o&&(o=new Map,qc.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Hc.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=ga.get(e);if(void 0!==n){if(n===t)return;oe("A state tree is already registered on this root.")}ga.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Bc(e,t,n);te(t);const o=yt(e.component);qa(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),aa(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=Dc(e,n)}catch{continue}const o=t.indexOf(c+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)+c+r,a=ie(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Mu(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),mc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=yt(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(Eu.has(s))continue;const r=ie(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Et](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Eu.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),ju(e),o=t,s=Promise.resolve(),ma.set(o,s),s.then(()=>xa(o),()=>{})}function Fu(e,t){const n=us(t),o=yt(e.component);n.forEachActiveBindingNode(e=>wt(e,o));ia(n.rebindAddresses()),ju(e)}function qu(e,t){if(function(e){const t=Vc.get(e);return void 0!==t&&t.size>0}(t))for(const n of Xc(t)){if(!Vu(n.component,e))continue;const t=Gc(n);null!==t&&Fu(n,t)}}function Vu(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 Hu={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Yc(e,t.pathInfo.path);if(null!==s)return Du(s,t,n,o)}return il},readMissing(e,t,n,o,s){if(null===n){if(xu(e.rootNode??null,t.pathInfo.path))return;return il}if(!0===e.hasMounts){const n=Ru(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Du(e,yn(ie(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return il},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=Su.get(e);if(void 0===n||0===n.size)return null;const o=t+c;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&oe(`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 il},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Ru(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Du(e,yn(ie(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return il},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Yc(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(c,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=Fc.get(n);if(void 0!==e)return e;n=n.parentNode}return Fc.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 Iu.get(e)??Au}(e);for(const s of o){const o=s.mountPath+c,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=tn(n.listIndex,l);(i[a]??=[]).push(e)}}if(r.size>0)try{s.callback.call(Pu(s.mountPath,n),Array.from(r),i)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>xu(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){qu(t,e)}};let Uu=!1;const Gu=new WeakMap;function Ku(e){let t=Gu.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Gu.set(e,t)),t}function Ju(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=vu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function Xu(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{$u(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 ba(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Yu(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");try{!function(e){0===e.length&&oe('"mount" requires a non-empty tree path.');const t=ie(e);for(const n of t.segments)0===n.length&&oe(`"mount" path "${e}" has an empty segment.`),n===d&&oe(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&oe(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),n.hasAttribute("bind-component")&&oe('"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).`),$u(s,r,e),ba(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===ba(s)&&function(e,t){const n=()=>{if(null!==ba(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&&Ju(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&&Xu(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 sp(t,i);ip(),function(e,t){if(ku.has(e))return void _u(t);let n=Nu.get(e);void 0===n&&(n=[],Nu.set(e,n)),n.push(t)}(e,i)}(l,ba(l),r,a,i,()=>Xu(e,t,l)):i(null)}const Qu={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=Ku(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{$u(n,t.mountPath,e),ba(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,cc}return Yu(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Ku(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&ba(n)===t.graftInfo.rootStateElement&&tp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Gu.get(e)?.initializing)return;const t=e.getAttribute("mount");oe(`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){ku.add(e);const t=Nu.get(e);if(void 0!==t){Nu.delete(e);for(const e of t)_u(e)}}(t)},initializeFailureCleared(e,t){!function(e){ku.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Ku(e);return null!==t.graftInfo&&tp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,Ju(e,t)),e.clearConnectedRootNode(),!0}};let Zu=!1;const ef=new WeakMap;function tf(e,t){let n=ef.get(e);n||(n=new Set,ef.set(e,n)),n.add(t)}const nf=new WeakMap;const of=new WeakMap,sf=new WeakMap;const rf=new WeakMap;const af={isComplete:function(e,t){return!0===ef.get(e)?.has(t)},isDeclared:function(e,t){return!0===nf.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=of.get(e);o||(o=new Map,of.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=sf.get(e);o||(o=new Map,sf.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=rf.get(e);s||(s=new Map,rf.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function lf(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 cf=new WeakMap;class df{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=cf.get(e);return n?n.get(t)??null:null}(e,t)??oe("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 uf=e=>()=>e;function ff(e,t,n,o){!function(e,t,n){let o=cf.get(e);o||(o=new Map,cf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(lf(o));const s=function(e,t){const n=new df(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:uf(s),enumerable:!0,configurable:!0}),tf(t,n),hf(t,n)}function hf(e,t){if(L in e){const n=e[L];"function"==typeof n?n.call(e,t).catch(e=>{oe(`Error in ${L}: ${e instanceof Error?e.message:String(e)}`)}):oe(`${L} is not a function.`)}}const pf=new Set;function gf(e,t){pf.has(e)||(pf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function mf(e){const t=e.rootEntry,n=yt(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 yf=new WeakMap;function wf(e,t){e.landInitialization(),oe(t)}async function bf(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?Ve(a):null;null!==a&&null!==l||oe(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||wf(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&&oe(`"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=nf.get(e);n||(n=new Set,nf.set(e,n)),n.add(t)}(a,d);const u=Ue(a);null===u&&oe(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await ze(a),d in a||oe(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||oe(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=of.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=rt(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||(rt(a)??[]).some(e=>e.propSegments[0]===d)||wf(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=(rt(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=ba(a.getRootNode())??wf(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,qc.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(function(e,t,n){const o=rf.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;rf.get(e).delete(t)}}(a,d,f),u=kc(a,d,o,c,f,function(e,t){return sf.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=mf(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;gf(`${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{zu(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Bu(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),tf(a,d)}return hf(a,d),function(e){const t=Ic.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(K)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;Ac.has(n)||(Ac.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 Nc(u,"$connectedCallback")}}ff(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const vf={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=yf.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},yf.set(e,t)),t}(e);return bf(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=yf.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&Fu(n,o)}),Nc(n,"$connectedCallback"),!0},disconnecting(e){const t=yf.get(e);return void 0!==t&&null!==t.mountRecord&&(Nc(t.mountRecord,"$disconnectedCallback"),ju(t.mountRecord),e.clearConnectedRootNode(),!0)}};let $f=!1;function xf(){$f||($f=!0,fc("bindComponent",vf),hs=af)}const Sf=new WeakMap,Pf=new Set,If=new Set;function Af(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Nf(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function kf(e){return Sf.get(e)}function _f(e){Tf(e),Sf.delete(e)}function Tf(e){Pf.delete(e),If.delete(e)}const Cf=new WeakMap,Ef=new WeakMap,Mf=new Set,Of=new Map;function Rf(e){return Cf.get(e)??Of}function jf(e){Mf.add(e),function(e){const t=Sf.get(e);void 0!==t&&(Af(t)&&Pf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&If.add(e))}(e)}const Lf=new Map;function Wf(e){return Ef.get(e)??Lf}function Df(e){0===e.length&&oe(`[wcs/watch-declaration-invalid] ${H} entry name must be a non-empty state path.`),e.startsWith("$")&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" must not start with "$" (reserved namespace).${de}`),e.includes("@")&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${de}`),e in Object.prototype&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ie(e);for(const n of t.segments)0===n.length&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" has an empty path segment.${de}`);return t.wildcardCount>u&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Bf(e,t){const n=t[H];if(void 0===n)return null;"object"==typeof n&&null!==n||oe(`[wcs/watch-declaration-invalid] ${H} must be an object mapping state paths to handler functions.${de}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${t}" must be a function.${de}`);const n=Df(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Cf.set(e,t)}(e,o),s.size>0?s:null}let zf=0,Ff=0;function qf(e){zf=e+1}function Vf(){zf=0}function Hf(){zf>Ff&&(Ff=zf)}const Uf=new WeakMap;function Gf(e,t,n){let o=Uf.get(e);void 0===o&&(o=new Map,Uf.set(e,o)),o.set(t,n)}const Kf=new Map;function Jf(e,t){Kf.has(e)||Kf.set(e,t)}function Xf(e){return Kf.get(e)}const Yf={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||Jf(n,o)},swapped(e,t,n){var o;o=n,Kf.has(o)&&Jf(t,Xf(n))}};function Qf(e){for(let t=e;null!==t;t=t.parentListIndex)if(js(t))return!0;return!1}function Zf(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](yn(t.wildcardParentPathInfos[i],r)),l=Ws(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=en(o,i,t.wildcardCount);if(l!==c&&!Ms(l,c)){if(js(c))return"gone";s="replaced"}r=l}return s}function eh(e,t,n){const o=new Map;for(const s of n){const n=Zf(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 th=new Set;function nh(e){th.delete(e)}function oh(){return th}const sh=Symbol("wcs-stream-last-notified-uncertain"),rh=new WeakMap;function ih(e,t){const n=rh.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function ah(e,t){const n=rh.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:sh,error:Object.is(o.error,null)?null:sh})}const lh=new WeakMap;function ch(e){return lh.get(e)??new Map}function dh(e){nh(e);const t=lh.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,ah(e,n.name)}const uh=new WeakSet;let fh=0;function hh(e){return kf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function ph(e){if(0===If.size)return;if(t=e.absolutePathInfo.stateElement,!If.has(t))return;var t;const n=hh(e);if(void 0!==n)for(const e of n)gh(e)}function gh(e){uh.has(e)||(uh.add(e),fh++)}function mh(e){return!!uh.delete(e)&&(fh--,!0)}const yh=/^(?:0|[1-9]\d*)$/;function wh(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function bh(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&&yh.test(t)&&wh(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&wh(e,t))?"object":null}function vh(e,t){const n=bh(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]=vh(o[e],t);return r}function $h(e){return vh(e,new Map)}function xh(e,t,n){if(Object.is(e,t))return!0;const o=bh(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(bh(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(!xh(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&xh(s[e],r[e],n))}function Sh(e,t){return xh(e,t,new Map)}const Ph=new WeakMap;function Ih(e,t){if("function"!=typeof t)return;const n=Ph.get(t);void 0===n?Ph.set(t,new Set([e])):n.add(e)}const Ah={"read-source":e=>`${U} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${U} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${U} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${U} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${U} could not write the output "${e}".`},Nh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function kh(e,t,n){null!==bt&&bt({type:"state:watch-error",phase:t,path:`${U}.${e}`,error:n})}function _h(e,t,n){console.error(`[@wcstack/state] ${Ah[n](e)}`,t),kh(e,Nh[n],t)}function Th(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Ch(e,t){t.then(void 0,()=>{}),_h(e,new TypeError(`${U} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Eh=new WeakSet;const Mh=Object.freeze([]);function Oh(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 Rh(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 jh(e,t){return t.has(e.stateElement)&&!0===kf(e.stateElement)?.entries.has(e.entry)}function Lh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Wh(n,e))||mh(t)}function Wh(e,t){return er().hasQueuedPath(e,t)}function Dh(e,t){!function(e,t,n){if(0!==fh)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=hh(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||mh(t)}}(e,t,Wh)}function Bh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function zh(e,t,n){if(!jh(e,n))return Lh(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(Eh.has(e))return;Eh.add(e);const o=`[wcs/scan-source-computed] ${U} 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}`),kh(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=ch(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:eh(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Rh)){let n;try{n=Bh(t,r,e)}catch(e){_h(s.name,e,"read-source");continue}const o=a(l,n,Xf(e.absAddress),...e.indexes);if(Th(o))return void Ch(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){_h(s.name,e,i.failure)}return i.plan}function Fh(e,t){const{group:n}=e;if(!jh(n,t))return void Lh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||mh(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!Sh(o,s.initial):!Object.is(o,e.next)){const o=n.reset?$h(s.initial):e.next;t[s.name]=o,Ih(s.name,o)}})}catch(e){_h(s.name,e,"write")}}function qh(e,t,n){if(Dh(e,t),0===Pf.size)return Mh;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=kf(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=tn(n.listIndex,r.wildcardCount)}for(const s of i)Oh(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)Oh(o,e,t).reset=!0}if(0===o.size)return Mh;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=zh(n,e,t);null!==o&&r.push(o)}}finally{Vf()}return r}function Vh(e){Zh(),(0!==Rf(e).size||0!==Wf(e).size||function(e){const t=Sf.get(e);return void 0!==t&&Af(t)}(e))&&(jf(e),function(e){const t=[];for(const n of Rf(e).values())Hh(e,n)&&t.push(n);for(const n of Wf(e).values())for(const o of n)Hh(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{Gf(e,Kt(e,o.pathInfo,null),n[o.path])}catch(t){Gh(e,o.path,"prime",t)}})}(e))}function Hh(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Uh={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Gh(e,t,n,o){console.error(`[@wcstack/state] $watch ${Uh[n]} "${t}" threw.`,o),null!==bt&&bt({type:"state:watch-error",phase:n,path:t,error:o})}function Kh(e){const t=Mf;try{if(0===t.size)return void Dh(e,t);const n=function(){const e=Ff;return Ff=0,e}();if(n>32){Dh(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!==bt&&bt({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)Fh(n,t)}finally{Vf()}}}(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=Rf(e).get(s),i=Wf(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=tn(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Xh);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];(Qf(o.absAddress.listIndex)||s?.entry===o.entry&&Jh(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(eh(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){Gh(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=Rf(e.stateElement).get(e.entry.path)===e.entry,o=!0===Wf(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&Yh(e)}}finally{Vf()}}(e,t,n)}finally{Kf.clear()}}function Jh(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Xh(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 Yh(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Hh(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 Gh(0,n.path,"evaluate",e)}const a=r?function(e,t){return Uf.get(e)?.get(t)}(t,o):Xf(o);r&&Gf(t,o,i),null!==bt&&bt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Gh(0,n.path,"handler",e)}}let Qh=!1;function Zh(){Qh||(Qh=!0,cl("watch",Yf),hl("watch",ep),Xs(Kh,10),Js(Hf))}const ep={order:10,register(e,t){var n;n=e,Mf.delete(n),Tf(n),Cf.delete(n),function(e){Uf.delete(e)}(e);const o=Bf(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?H:U)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Vh(e)},deactivate(e){var t;t=e,Mf.delete(t),Tf(t)}};function tp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Pu(e.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function np(e,t,n){const o=n[H];if(void 0!==o){const n=[],s=new Set;let r=0;for(const[i,a]of Object.entries(o)){const o=t+c+i,l=function(e,n,...o){a.call(Pu(t,this),e,n,...o)};n.push({path:o,pathInfo:ie(o),handler:l,order:1e6+r++}),s.add(o),e.setPathInfo(o,"prop","watch")}n.length>0&&(!function(e,t){let n=Ef.get(e);void 0===n&&(n=new Map,Ef.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),Vh(e))}const s=n[J];if(void 0!==s){const n=new Map;for(const[e,o]of Object.entries(s))n.set(t+c+e,o);e.mergeVolumeListKeys?.(n)}const r=n[R];"function"==typeof r&&(!function(e,t){let n=Iu.get(e);void 0===n&&(n=[],Iu.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 op(e,t,n){!function(e,t,n){const o=n[H];if(void 0!==o){"object"==typeof o&&null!==o||oe(`${H} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(o))"function"!=typeof t&&oe(`${H} entry "${e}" must be a function.`),Df(e)}const s=n[J];if(void 0!==s){"object"==typeof s&&null!==s||oe(`${J} 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)&&oe(`${J} entry "${n}" must map a list path to a field name or a key function.`),e.listKeys?.has(t+c+n)&&oe(`${J} entry "${t+c+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&oe(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&oe(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[G]&&oe(`Volume "${t}" declares ${G}, 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(gc(n)))-1!==e.indexOf(K)&&oe(`Volume "${t}" declares "${e}", which uses "${K}". 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=ie(t),i=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===r.segments.length&&t in e){if(i)return;oe(`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+c+o];n=""===n?o:n+c+o,s||(e[n]={})}if(r.segments.length>1&&void 0!==e[t]){if(i)return;oe(`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=Su.get(e);void 0===n&&(n=new Set,Su.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,o]of s){const s=t+c+n,r=o.get,i=o.set,a={enumerable:!1,configurable:!0};"function"==typeof r&&(a.get=function(){return r.call(Pu(t,this))}),"function"==typeof i&&(a.set=function(e){i.call(Pu(t,this),e)}),e.defineTreeAccessor(s,a)}np(e,t,n);const a=n.$connectedCallback;return"function"==typeof a&&e.createState("writable",e=>{let n;try{n=a.call(Pu(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 sp(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=op(e,t.mountPath,t.volumeState)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let rp=!1;function ip(){var e;rp||(rp=!0,Uu||(Uu=!0,cl("scopes",Hu)),Zu||(Zu=!0,fc("scopes",Qu)),xf(),Tu=sp,e=ap,wa.includes(e)||wa.push(e))}function ap(e,t){(function(e){const t=vu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){ku.delete(e);const n=Nu.get(e);if(void 0===n||0===n.length||null===Tu)return;Nu.delete(e);const o=Tu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const lp={name:"scopes",install(){ip(),bu||(bu=!0,fc("dcc",wu))}},cp=/^@@wcs-(?:for|if|elseif|else):[^-]/,dp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,up=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,fp=/^@@wcs-text-start:(.+)$/;function hp(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class pp extends pc{_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=Qc.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=hp(JSON.stringify(t)),e.appendChild(n);const s=Array.from(Pa.keys());for(const t of s){const n=Aa(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(Ai);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=Ii(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=hp(JSON.stringify(t)),e.appendChild(n)}}Ai.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(dp.test(e.data)||up.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;cp.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=fp.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;dp.test(e.data)&&i.push(e)}for(const e of i){const t=dp.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()}pp.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(cp.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 gp={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",Qc),pp.buildContent(o,pp.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const mp=new Set(["for","if","elseif","else"]);function yp(e){const t=new ds;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]=ft(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 wp(e,t,n){for(const o of t)"event"===o.bindingType||mp.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in E||ie(o.statePathName).wildcardCount>n||e.push(o)}function bp(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 vp(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,_a()],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;Wa(a),"string"==typeof l&&Ra(a,l),qa(n,a,l);Ia(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:La(a)})}}const $p={hydrate:async function(e){await ca(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="${Qc}". Falling back to full render.`),pp.cleanupDom(e),!1}for(const n of t)vp(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=dp.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=oi(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=yp(s.nodes);Rr(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");bs(t,r),Wr(t,i);const l=[];for(const e of r)e.statePathName in E&&l.push(e);if(xs(t,l),"for"===s.type&&null!==s.index){const i=bp(e,"for",s.uuid);if(i){const e=_s(null,s.index);pi(i,e,t),gi(i,s.nodes[s.nodes.length-1]),Jr(i,t);const l=ie(s.path+"."+d);Dr(t,yn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),wp(o,r,l.wildcardCount);let c=n.get(s.uuid);c||(c=[],n.set(s.uuid,c)),c.push(e)}}else{const n=bp(e,s.type,s.uuid);n&&(Jr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),wp(o,r,0))}}for(const[t,o]of n){const n=bp(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=Aa(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ba(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&Bs(t,o)})}return o}(document.body,n);pp.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());pp.restoreTextBindings(document.body);const[i,a]=ft(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(wt(e,null),t.setAttribute("data-wcs-completed",""))}else wt(e,null);const l=[],c=[],u=us(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(mp.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(d))continue;l.push(e)}for(const e of c)if("for"===e.bindingType){const t=an(e),n=ba(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(xt(t,o),kt(t,o))})}ia([...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=pp.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await va(e.rootNode);const t=pp.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",Qc),pp.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let xp=!1;function Sp(){var t;xp||(xp=!0,ha=$p,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,pp)},vc.includes(t)||vc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=gp)}())}const Pp={name:"ssr",install(){Sp()}},Ip="[wcs/scan-declaration-invalid]",Ap=Object.freeze([]);function Np(e){return`${U} entry "${e}"`}function kp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function _p(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${d}${d}`)?`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.${de}`}function Tp(e,t,n){0===n.length&&oe(`${Ip} ${e} "${t}" must be a non-empty state path.${de}`),n.startsWith("$")&&oe(`${Ip} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${de}`),n.includes("@")&&oe(`${Ip} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${de}`),n in Object.prototype&&oe(`${Ip} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${de}`);const o=ie(n);for(const s of o.segments)0===s.length&&oe(`${Ip} ${e} ${t} "${n}" has an empty path segment.${de}`);return o.wildcardCount>u&&oe(`${Ip} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Cp(e,t,n,o){const s=Np(e);0===e.length&&oe(`${Ip} ${U} entry name must be a non-empty string.${de}`),(e.includes(c)||e.includes(d))&&oe(`${Ip} ${s} must be a flat property name ("${c}" and "${d}" are not allowed). The output is a property the runtime owns.${de}`),e.startsWith("$")&&oe(`${Ip} ${s} must not start with "$" (reserved namespace).${de}`),e in Object.prototype&&oe(`${Ip} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${de}`),t.has(e)&&oe(`${Ip} ${s} conflicts with a getter declared on the state.${de}`),n.has(e)&&oe(`${Ip} ${s} conflicts with a setter declared on the state.${de}`),o.has(e)&&oe(`${Ip} ${s} conflicts with the ${V} entry of the same name — each output has exactly one owner.${de}`)}function Ep(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Ph.get(t)?.has(e)}(e,o)&&oe(`${Ip} ${Np(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${de}`)}function Mp(e,t,n,o,s,r){const i=Np(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&oe(`${Ip} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${de}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||oe(`${Ip} ${i} "on" must be a non-empty event-token name.${de}`),n.has(e)||oe(`${Ip} ${i} on "${e}" is not declared in ${F}.${ce(e,n)}${de}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&oe(`${Ip} ${i} "from" must be a state path string.${de}`);const u=Tp(i,"from",d),f=kp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&oe(_p(i,"from",d,f));const h=kp(u,s);return null!==h&&oe(function(e,t,n){return`${Ip} ${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.${de}`}(i,d,h)),(d===e||d.startsWith(e+c))&&oe(`${Ip} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${de}`),{kind:"path",path:d,pathInfo:u}}function Op(e,t,n,o){if(void 0===t)return Ap;const s=Np(e);Array.isArray(t)||oe(`${Ip} ${s} "resetOn" must be an array of state paths.${de}`);const r=[];for(const e of t){"string"!=typeof e&&oe(`${Ip} ${s} "resetOn" must contain only state path strings.${de}`);const t=Tp(s,"resetOn",e);t.wildcardCount>0&&oe(`${Ip} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${de}`);const i=kp(t,o);null!==i&&oe(_p(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&oe(`${Ip} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${de}`),"path"===n.kind&&e.startsWith(n.path+c)&&oe(`${Ip} ${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.${de}`),r.push(e)}return r}function Rp(e,t,n=null){const o=e[U];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&oe(`${Ip} ${U} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${de}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(gc(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[V];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)){Cp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&oe(`${Ip} ${Np(e)} must be an object ({ from | on, initial, fold, resetOn? }).${de}`);const o=u;Ep(e,a,o);const f=Mp(e,o,t,s,i,n);"initial"in o||oe(`${Ip} ${Np(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${de}`),"function"!=typeof o.fold&&oe(`${Ip} ${Np(e)} fold must be a function.${de}`);const h=Op(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=ie(e).segments[0];t.has(n)&&oe(`${Ip} ${Np(o.name)} resetOn "${e}" reads the ${U} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${de}`)}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&&oe(`${Ip} ${U} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${de}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function jp(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 uh.has(e)}(e),l=a&&!Sh(n,e.initial)?$h(e.initial):n,c=t(l,o,...s);if(Th(c))return void Ch(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Ih(e.name,c)),a&&mh(e)}catch(t){_h(e.name,t,i)}}}function Lp(e,t,n){const o=function(e,t){_f(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Nf(n,e.source.path,e);for(const t of e.resetOn)Nf(o,t,e),"event"===e.source.kind&&Nf(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Sf.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)&&er().hasQueuedPath(e,n))&&gh(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 Wp="scanEntries",Dp={order:8,validate(e,t,n){const o=Rp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Wp,o)},applyEarly(e,t,n){const o=n.get(Wp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=$h(n.initial);e[n.name]=t,Ih(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&En(e,n.source.tokenName).subscribe(jp(n))}(e,o))},register(e,t,n){const o=n.get(Wp)??null,s=function(e){const t=new Map,n=kf(e);if(void 0!==n)for(const e of n.entries)mh(e)&&t.set(e.name,e.resetOn);return _f(e),t}(e);e.setScanPaths?.(null===o?null:Lp(e,o,s))}};let Bp=!1;const zp=Object.freeze([]),Fp=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)??zp,i=e.dynamicDependency.get(n)??zp,a=t.byFromPath.get(n)??Fp;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Vp=(e,t)=>t,Hp=new Set;function Up(e,t){const n=t[V];if(void 0===n)return void ih(e,Hp);"object"==typeof n&&null!==n||oe(`${V} 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&&oe(`${V} entry name must be a non-empty string.`),s.includes(c)&&oe(`${V} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.includes(d)&&oe(`${V} entry "${s}" must be a flat property name ("${d}" is not allowed).`),s.startsWith("$")&&oe(`${V} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&oe(`${V} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&oe(`${V} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&oe(`${V} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||oe(`${V} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&oe(`${V} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&oe(`${V} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&oe(`${V} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&oe(`${V} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??Vp,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){lh.set(e,t)}(e,o),ih(e,new Set(o.keys()))}const Gp=new WeakMap,Kp=new WeakMap;function Jp(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=ch(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&ch(e).has(n),ownKeys:()=>Array.from(ch(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=ch(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){oe(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){oe(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Xp(e){const t=Gp.get(e);if(void 0!==t)return t;const n=Jp(e,X,e=>e.status);return Gp.set(e,n),n}function Yp(e){const t=Kp.get(e);if(void 0!==t)return t;const n=Jp(e,Y,e=>e.error);return Kp.set(e,n),n}function Qp(e){Gp.delete(e),Kp.delete(e)}let Zp=null;function eg(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 tg={read(e,t){!function(e,t){null!==Zp&&Zp.add(Gt(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===X?eg(Xp(e),t.pathInfo.segments):n===Y?eg(Yp(e),t.pathInfo.segments):il},get:(e,t)=>t===X?Xp(e.stateElement):t===Y?Yp(e.stateElement):il};async function ng(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 og(e){dg();const t=ch(e);if(0!==t.size){!function(e){th.add(e)}(e);for(const n of t.values())sg(e,n)}}function sg(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=Zp,s=new Set;let r;Zp=s;try{e.createState("readonly",e=>{r=n(e)})}finally{Zp=o}r instanceof Promise&&oe(`${V} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${X}${c}${t.name}`,a=`${Y}${c}${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||oe(`${V} 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&&oe(`${V} 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=kf(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)&&oe(`[wcs/scan-feedback-loop] ${V} entry "${t.name}" args read "${n}", which is derived from the ${U} 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}),rg(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(){rg(e,t,"done",null)},fail(o){rg(e,t,"error",o),n.abort()}};ng(s.source,o,n.signal,r)}function rg(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return rh.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=rh.get(e);void 0===s&&(s=new Map,rh.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${X}${c}${t.name}`),i&&e.$postUpdate(`${Y}${c}${t.name}`)}))}function ig(e){const t=oh();if(0===t.size)return;const n=[];for(const o of t)for(const t of ch(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)&&ch(e).get(o.name)===o)try{sg(e,o)}catch(n){o.controller?.abort(),t.has(e)&&ch(e).get(o.name)===o&&rg(e,o,"error",n)}}let ag=!1;const lg=new WeakMap,cg={order:20,apply(e,t){var n;Qp(e),dh(n=e),nh(n),lh.delete(n),Up(e,t),void 0!==t[V]&&e.attachAddressHooks?.("streams",V)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return og(e),void lg.set(e,e.connectGeneration??0)}n===e.connectGeneration&&lg.get(e)!==n&&og(e)}},deactivate(e){dh(e),Qp(e)}};function dg(){ag||(ag=!0,cl("streams",tg),hl("streams",cg),Xs(ig,20))}const ug=[Ed,{name:"temporal",install(){Zh(),Bp||(Bp=!0,hl("scan",Dp),Js(ph)),dg()}},iu,lp,Pp,dd,$d];function fg(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(ug),Sc(e,t)}function hg(e){return e}const pg={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"ブール値を反転",hasArgs:!1,resultType:"boolean",acceptTypes:["boolean"],minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},inc:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},dec:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},fix:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},uc:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lc:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},cap:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},pad:{description:"パディング (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},rep:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},rev:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator])",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},time:{description:"ロケール形式の時刻",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},datetime:{description:"ロケール形式の日時",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},ymd:{description:"YYYY-MM-DD 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},null:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},gg=1;function mg(){return{version:1,syntax:{bindAttribute:o.bindAttributeName,tagName:o.tagNames.state,pathDelimiter:c,wildcard:d,delimiters:{binding:";",propValue:":",modifier:h,filter:p},structuralDirectives:Array.from(ue),modifiers:{flags:w,keyValue:$,eventNamePrefix:P},indexParam:{prefix:T,maxDepth:u},bindingTypes:{elseKeyword:x,spread:S,eventPropertyPrefix:P,propNamespaces:{eventToken:I,command:A,class:N,attr:k,style:_}}},filters:Object.keys(_d),filterMeta:pg,reservedLifecycle:[M,O,R,j,L],reservedStateApi:[W,D,B,z,F,q,V,H,U,J,G,X,Y]}}const yg=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),wg=Object.freeze([]);function bg(e){if(!o.enableContractAnalyzer)return wg;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))yg.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?vg(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,$g,e=>{t.push(e),null!==bt&&bt(e)}),t}function vg(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function $g(e){const t=Ue(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{pp as Ssr,Ni as TRUSTED_TYPES_POLICY_SLOT,Qc as VERSION,gg as WCS_MANIFEST_VERSION,bg as analyzeContract,fg as bootstrapState,da as buildBindings,pg as builtinFilterMeta,hg as defineState,va as getBindingsReady,s as getConfig,ki as getTrustedTypesPolicy,mg as getWcsManifest,_i as setTrustedTypesPolicy};
1
+ const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={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;function s(){return o}const r=Symbol.for("wcstack.binder");const i=Symbol.for("wcstack.binder.pending"),a=Symbol.for("wcstack.binder.taken");function l(){const e=function(){const e=globalThis[r];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[i];return void 0===t&&(t=[],e[i]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[a];return void 0===t&&(t=new WeakSet,e[a]=t),t}();for(const t of n)o.add(t),e.bind(t)}const c=".",d="*",u=128,f=128,h="#",p="|",g="prevent",m="stop",y="ro",w=Object.freeze([g,m,y]),b="init",v="sync",$=Object.freeze([b,v]),x="else",S="...",P="on",I="eventToken",A="state",N="command",k="class",_="attr",T="style",C="$",E={};for(let e=0;e<u;e++)E[`${C}${e+1}`]=e;const M=Object.freeze(E),O="$connectedCallback",R="$disconnectedCallback",j="$renderedCallback",L="$errorCallback",W="$stateReadyCallback",D="$bindables",B="$commands",z="$commandTokens",F="$command",q="$eventTokens",V="$on",H="$stream",U="$watch",G="$scan",K="$recursion",J="**",X="$listKeys",Y="$streamStatus",Q="$streamError",Z="data-wc-definition",ee=/\{\{\s*(.+?)\s*\}\}/g,te=new Set(["SCRIPT","STYLE"]);function ne(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&&te.has(e.parentElement.tagName)||oe(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),ne(t.content)}else ne(e.content)}function oe(e){const t=e.data;if(ee.lastIndex=0,!ee.test(t))return;ee.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=ee.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 se(e){throw new Error(`[@wcstack/state] ${e}`)}const re=new Map;let ie=0;function ae(e){let t=re.get(e);return void 0!==t||(-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] "${e}" uses "${J}", 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 le(e)),re.set(e,t)),t}class le{id=++ie;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:ae(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===d&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),c.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=u,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function ce(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 de(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ce(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ue=" Validate statically: npx @wcstack/lint <file>.",fe=new Set(["if","elseif","else","for"]),he={not:()=>e=>!e},pe={input:new Map,output:new Map},ge={input:new Map,output:new Map},me={input:new Map,output:new Map},ye=new Map;function we(e,t,n,o){const s=pe[e],r=ge[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??{}))me[e].set(t,o[t]);ye.clear()}function be(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=ye.get(s);if(void 0!==r)return r;const i=me[n].get(e)??e,a=pe[n].get(i)??he[i];void 0===a&&se(`[wcs/filter-unknown] filter not found: ${e}.${de(e,function(e){return[...new Set([...Object.keys(he),...pe[e].keys()])]}(n))}${ue}`);const l=ge[n].get(i);void 0!==l&&(t.length<l[0]||t.length>l[1])&&se(t.length<l[0]?`[wcs/filter-arity] filter "${e}" requires at least ${l[0]} argument(s) (${t.length} given).${ue}`:`[wcs/filter-arity] filter "${e}" accepts at most ${l[1]} argument(s) (${t.length} given).${ue}`);const c=a(t,o);return ye.set(s,c),c}function ve(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const $e=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function xe(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:$e.test(e)?Number(e):e)}function Se(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=ve(o,i,a);t.push(e),n.push(xe(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&&se(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ue}`);const c=ve(o,i,a);return(c||r)&&(t.push(c),n.push(xe(c,r))),{args:t,literals:n}}function Pe(e,t){return e.map(t=>{const n=t.indexOf("("),o=t.lastIndexOf(")");-1!==n&&-1===o&&se(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==o&&-1===n&&se(`Invalid filter format: missing opening parenthesis in "${t}"`);const s=(-1===n?t:t.substring(0,n)).trim();if(0===s.length&&se(`[wcs/binding-syntax] an empty filter in "${e.join("|")}" — remove the extra "|" or name the filter.${ue}`),-1===n)return{filterName:s,args:[],literals:[]};return{filterName:s,...Se(t.substring(n+1,o))}})}const Ie=e=>e.trim(),Ae=e=>"'"===e||'"'===e;function Ne(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(Ae(s))n=s;else if(s===t)return o}return-1}function ke(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):Ae(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const _e=new Map;function Te(e){const t=Ne(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),_e.has(s)?r=_e.get(s):(o=ke(s,p).map(Ie),r=Pe(o),_e.set(s,r))):n=e.trim();const i=n.split(h).map(Ie);i.length>2&&se(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${h}" — write "${i[0]}${h}${i.slice(1).join(",")}".${ue}`);const[a,l]=i,d=a.split(c).map(Ie);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(Ie):[],inFilters:r}}const Ce=new Map;function Ee(e){const t=Ne(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ce.has(s)?r=Ce.get(s):(o=ke(s,p).map(Ie),r=Pe(o),Ce.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&se(`"${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:ae(n),outFilters:r}}const Me=new Set([x,"if","elseif","for",S]),Oe=new Set([k,_,T,N,I]);function Re(e){const[...t]=function(e){return ke(e,";")}(e).map(Ie).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&se(`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(h)[0].split(p)[0].trim();if(s!==n&&Me.has(s)&&se(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ue}`),n===x){o.length>0&&se(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ue}`);const t=ae("#else");return{propName:x,propSegments:[x],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===S){const t=Ee(o);return t.outFilters.length>0&&se(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&se(`Invalid spread binding "${e}": spread target path is required.`),{propName:S,propSegments:[S],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ee(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Ee(o);return{...Te(n),...e,bindingType:s}}{const e=Ee(o),t=Te(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Oe.has(o[0]))&&se(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Oe].join(", ")}).${ue}`),{...t,propName:o.join(c),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===I||t.propSegments[0].startsWith(P)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>fe.has(e.bindingType))&&se(`[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">).${ue}`)}return n}const je=new WeakMap,Le=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),We=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function De(e){const t=je.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=We.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Le.has(r)?(je.set(e,s[2]),s[2]):null}function Be(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ee(e),bindingType:"text"}}const ze=new WeakMap,Fe=new WeakSet;let qe=0;async function Ve(e){const t=function(e){let t,n=ze.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++qe,promise:o,resolve:t},ze.set(e,n),Fe.has(e)&&n.resolve(),n}(e);await t.promise}function He(e){const t=ze.get(e);void 0===t?Fe.add(e):t.resolve()}const Ue=new WeakMap;function Ge(e){const t=Ue.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{Ue.set(e,n)}}function Ke(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Je(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Ke(t);if(void 0!==n)return Ke(n)}return Ke(globalThis.customElements)}function Xe(e,t){e.upgrade?.(t)}function Ye(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=tt(s.properties,Qe);if(null===r)return null;const i=void 0===s.inputs?new Map:tt(s.inputs,Ze);if(null===i)return null;const a=void 0===s.commands?new Map:tt(s.commands,et);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Qe(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 Ze(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 et(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 tt(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 nt(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ae(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ot(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function st(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&&se("Spread binding requires an element node.");const t=e,o=Ge(t);null===o&&se(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Je(t);null===a&&se(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||se(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Xe(a,t);const l=Ye(t);null===l&&se(`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=nt(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=nt(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=ot(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=ot(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 rt(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 it(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:be(s.filterName,s.args,t,s.literals??s.args)})}return n}const at=new WeakMap;function lt(e){return at.get(e)||null}function ct(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function dt(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!ct(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function ut(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 ft(e){const t=[],n=dt(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!==De(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&ut(e,n)||t.push(e)}return t}const ht=new WeakSet;function pt(e,t,n,o){const s=st(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ge(e):null;return null===n&&se("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}ht.add(e);const r=function(e,t){const n=[];for(const o of t){const t=it(o.inFilters,"input"),s=it(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){at.set(e,t)}(e,r),He(e),{bindings:r,deferred:null}}function gt(e,t){const n=ft(e),o=[],s=[];for(const e of n){if(ht.has(e))continue;const n=pt(e,Ta(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function mt(e){ht.add(e)}function yt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){ht.delete(e)}(t);return pt(t,n,{allowDeferred:!1},o).bindings}const wt=new WeakMap;let bt=null;function vt(e){let t=e;for(;t;){const e=wt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==bt&&t instanceof ShadowRoot&&(n=bt(t)),t=n}return null}function $t(e,t){null!==t?wt.set(e,t):wt.delete(e)}let xt=null;const St=new WeakMap;function Pt(e){return St.get(e)??[]}function It(e,t){St.set(e,t)}function At(e){return St.has(e)}const Nt=new WeakMap;let kt=null,_t=0;function Tt(e){return Nt.get(e)??[]}function Ct(e,t){null===kt?Nt.set(e,t):kt.set(e,t)}function Et(){_t++,null===kt&&(kt=new Map)}function Mt(){if(0!==_t&&(_t--,!(_t>0||null===kt))){for(const[e,t]of kt)Nt.set(e,t);kt=null}}function Ot(e){return(kt?.has(e)??!1)||Nt.has(e)}const Rt=Symbol("$$setLoopContext"),jt=Symbol("$$getByAddress"),Lt=Symbol("$$hasByAddress"),Wt=Symbol("$$setByAddress"),Dt=Symbol("$$connectedCallback"),Bt=Symbol("$$disconnectedCallback"),zt=Symbol("$$updatedCallback"),Ft=Symbol("$$errorCallback"),qt=new WeakMap,Vt=new WeakMap;class Ht{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Ut(e,t){if(null===t){let t=Vt.get(e);return void 0!==t||(t=new Ht(e,null),Vt.set(e,t)),t}{let n=qt.get(t);void 0===n&&(n=new WeakMap,qt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Ht(e,t),n.set(e,o)),o}}const Gt=new WeakMap;function Kt(e,t){let n=Gt.get(e);void 0===n&&(n=new Map,Gt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Jt(e,t)),n.set(t,o)),o}class Jt{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Xt(e,t){return Ut(Kt(e,t.pathInfo),t.listIndex)}function Yt(e,t,n){return Ut(Kt(e,t),n)}const Qt=new WeakMap;function Zt(e,t){null===t?Qt.delete(e):Qt.set(e,t)}function en(e){return Qt.get(e)||null}const tn=new Map;function nn(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=tn.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,tn.set(s,r),r}function on(e,t,n){return t<0||t>=n?null:e.at(t-n)}function sn(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const rn=new WeakMap;function an(e){const t=vt(e.node);if(null===t)return null;let n=rn.get(t);if(void 0===n)n=new WeakMap,rn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=nn(t.pathInfo,e.statePathInfo);return n>0&&(o=on(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const ln=new WeakMap;function cn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=en(n);null===t?se(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function dn(e,t){let n=null;if(n=ln.get(e)||null,null!==n)return n;const o=cn(e,t),s=an(e),r=xa(o);return null===r&&se("No state tree found on this root for binding."),n=Yt(r,e.statePathInfo,s),ln.set(e,n),n}function un(e){ln.delete(e)}const fn=new WeakMap;function hn(e,t){const n=fn.get(e);void 0===n?fn.set(e,t):n instanceof Set?n.add(t):n!==t&&fn.set(e,new Set([n,t])),null!==xt&&xt({type:"state:binding-added",absoluteAddress:e,binding:t})}function pn(e,t){const n=fn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&fn.delete(e),null!==xt&&xt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const gn=new WeakMap;function mn(e){const t=fn.get(e);return void 0!==t?t:null!==e.listIndex?gn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const yn=new WeakMap,wn=new WeakMap;class bn{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===d?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=vn(e,t)}}function vn(e,t){if(null===t){let t=wn.get(e);return void 0!==t||(t=new bn(e,null),wn.set(e,t)),t}{let n=yn.get(t);void 0===n&&(n=new WeakMap,yn.set(t,n));let o=n.get(e);return void 0!==o||(o=new bn(e,t),n.set(e,o)),o}}const $n=new WeakMap;function xn(e){let t=null;if(t=$n.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=an(e);null===n&&se(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=vn(e.statePathInfo,n)}else t=vn(e.statePathInfo,null);return $n.set(e,t),t}function Sn(e){$n.delete(e)}function Pn(){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 In=new Map,An=Pn();function Nn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function kn(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function _n(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=kn(e),s=Nn(e,o);let r=In.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=xa(o.getRootNode());null===i&&se("No state tree found on this root for two-way binding.");const a=vt(o);i.createState("writable",e=>{e[Rt](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]:[]})})},In.set(s,r)),e.node.addEventListener(o,r),An.add(s,e),!0}var t,n;return!1}function Tn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Cn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Tn(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class En{_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 Mn extends En{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==xt&&xt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const On=new WeakMap;function Rn(e,t){let n=On.get(e);void 0===n&&(n=new Map,On.set(e,n));let o=n.get(t);return void 0===o&&(o=new Mn(t,e),n.set(t,o)),o}const jn=new WeakMap;function Ln(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Ge(t),o=Je(t);if(null!==n&&void 0===o?.get(n))return null===o&&se(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(jn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||se('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Ge(e)?null:Ye(e)}(t);null===r&&se(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&se(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${de(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(g)&&e.preventDefault(),c.includes(m)&&e.stopPropagation();const n=xa(t.getRootNode());null===n&&se("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||se(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${de(l,n.eventTokenNames)}${ue}`);const o=vt(t);n.createStateAsync("writable",async t=>{Cn(t[Rt](o,()=>{const s=null!==o?sn(o.listIndex,o.pathInfo.wildcardCount):[];return Rn(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),jn.set(e,{eventName:a,handler:d}),!0}class Wn extends En{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==xt&&xt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Dn(e){return e instanceof Wn}const Bn=new Map,zn=Pn();function Fn(e){const t=e.propModifiers.filter(e=>e===g||e===m).sort().join(",");return`${e.statePathName}::${t}`}const qn=(e,t,n)=>o=>{t.includes(g)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=xa(r);null===i&&se("No state tree found on this root for event handler.");const a=vt(s),l=e.startsWith(F+".");i.createStateAsync("writable",async t=>{const c=t[Rt](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?sn(a.listIndex,c):[];if(l){const s=t[jt](vn(n,null));return Dn(s)||se(`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&&se(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Cn(c,`"${e}"`)})};function Vn(e){if(!e.propName.startsWith(P))return!1;const t=Fn(e);let n=Bn.get(t);void 0===n&&(n=qn(e.statePathName,e.propModifiers,e.statePathInfo),Bn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),zn.add(t,e),!0}function Hn(e){if(!e.propName.startsWith(P))return!1;const t=Fn(e),n=Bn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==zn.countOf(t)&&(zn.remove(t,e)&&Bn.delete(t),!0)}const Un=new Map,Gn=Pn();function Kn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Jn(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function Xn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=Jn(e),s=Kn(e,o);let r=Un.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=xa(o.getRootNode());null===r&&se("No state tree found on this root for two-way binding.");const i=vt(o);r.createState("writable",e=>{e[Rt](i,()=>{e[t]=s})})},Un.set(s,r)),e.node.addEventListener(o,r),Gn.add(s,e),!0}var t,n;return!1}const Yn=new Set(["radio","checkbox"]),Qn=new Set(["value","valueAsNumber","valueAsDate"]);function Zn(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(Yn.has(e)&&"checked"===t)return!0;if(Qn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ge(n);if(null!==s){const e=Je(n)?.get(s);void 0===e&&se(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ye(n);if(o?.knownProperties.has(t))return!0}return!1}let eo=1,to=1,no=1;const oo=new WeakMap;function so(e,t,n){let o=oo.get(e);void 0===o&&(o=new Map,oo.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=eo++,o.set(s,r)),r}function ro(e,t){return"to-element"===t?2*e:2*e+1}const io=new Set;function ao(e){return{transactionId:to++,originBindingId:e,visitedEdges:io,hop:0}}function lo(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let co=null;function uo(){return co}function fo(e,t){const n=co;co=e;try{return t()}finally{co=n}}const ho=[];let po=!1;const go=new Map,mo=Pn(),yo=new WeakMap,wo=e=>e.detail,bo=new WeakMap;function vo(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function $o(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ge(e.node);if(null!==n){const o=Je(e.node)?.get(n);void 0===o&&se(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ye(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function xo(e){if(null!==Ge(e.node)){const t=Ye(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??wo}return null}function So(e){if(null===Ge(e.node))return!1;const t=Ye(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const Po=(e,t,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==wo||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=bo.get(e);void 0===r&&(r=new Set,bo.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=yo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=so(a,e,t),s=function(e,t){for(let n=ho.length-1;n>=0;n--){const o=ho[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==xt&&xt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:ro(n,"to-state"),node:a,member:e}));const r=ro(n,"to-state"),i=uo();if(null!==i&&i.visitedEdges.has(r))return void(null!==xt&&xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=lo(i??ao(n),r)}const f=xa(a.getRootNode());null===f&&se("No state tree found on this root for two-way binding.");const h=vt(a),p=()=>{r&&(po=!0);try{f.createState("writable",e=>{e[Rt](h,()=>{e[t]=c})})}finally{r&&(po=!1)}};null!==u?fo(u,p):p()};const Io=new WeakSet;function Ao(e){Io.add(e)}function No(e){return!!Io.has(e)&&(Io.delete(e),!0)}const ko=new WeakMap;function _o(e,t){const n=ko.get(e);return!(void 0===n||n<t)&&(n===t?ko.delete(e):ko.set(e,n-t),!0)}const To=new WeakSet;function Co(e){To.add(e)}function Eo(e){return!!To.has(e)&&(To.delete(e),!0)}let Mo=0;function Oo(){Mo--}function Ro(){return Mo>0}class jo{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 Lo=new WeakMap;function Wo(e){let t=Lo.get(e);return void 0===t&&(t=new jo(e),Lo.set(e,t)),t}function Do(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!==b&&s!==v&&se(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&se(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Bo(e){return e.propModifiers.some(e=>e.includes("="))}const zo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Fo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function qo(e,t){return"state"===e&&"call"===t?zo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Vo(e){if(!o.enableDirectionalInitialSync)return Bo(e)&&se("init=/sync= modifiers require enableDirectionalInitialSync."),zo;const t=null===(n=Do(e,b))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:se(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":se(`Invalid sync modifier value "${e}".`)}(Do(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&se("Event bindings only allow init=none."),"call"===s?Fo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===N)return qo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&se(`Binding type "${e.bindingType}" does not support init=${t}.`),qo(t??"state",s);const r=Ye(e.node);if(null===r)return qo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||se(`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)||se(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||se(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Ho(e,t){return"auto"!==t?t:function(e){const t=xa(e.replaceNode.getRootNode());null===t&&se("No state tree found on this root for binding.");const n=xn(e);let o=!1;return t.createState("readonly",e=>{o=e[Lt](n)}),o}(e)?"state":"element"}let Uo=0,Go=0;const Ko=["active","disposed","failed"],Jo=new WeakMap,Xo=new WeakMap,Yo=new WeakMap,Qo=new WeakMap,Zo=new WeakMap;function es(e,t){const n=Zo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Zo.set(e,new Set([n,t]))):Zo.set(e,t)}function ts(e){return Zo.has(e)}function ns(e,t){const n=Zo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function os(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))os(n,t)}function ss(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class rs{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||!_o(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)No(e)||os(e,e=>{ns(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Eo(e)&&!Ro()||os(e,e=>{ns(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&ca(o)}}const is=new WeakMap;function as(e){let t=is.get(e);return void 0===t&&(t=new rs(e),is.set(e,t)),t}function ls(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function cs(e,t,n){const o=xa(cn(e,n));null===o&&se("No state tree found on this root for binding.");const s=Kt(o,e.statePathInfo);return function(e,t,n){let o=gn.get(e);void 0===o&&(o=new WeakMap,gn.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!==xt&&xt({type:"state:binding-added",absoluteAddress:Ut(e,t),binding:n})}(s,t,e),s}function ds(e,t){const n=dn(e,t);return hn(n,e),n}function us(e,t,n,o){null!==t?pn(t,e):function(e,t,n){const o=gn.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!==xt&&xt({type:"state:binding-removed",absoluteAddress:Ut(e,t),binding:n}))}(n,o,e),Sn(e),un(e)}function fs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class hs{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=Xo.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(ss(t)&&as(t),null===this.rowPlan)for(const n of e){const e=Xo.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 Bo(e)&&Vo(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=Xo.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:Ko[t.phases[n]],teardowns:null};const o=Xo.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=Xo.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(fs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Je(e);null===s&&se(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),es(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=Wo(s).wait(t,()=>{if(a())try{Xe(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=Xo.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&&(pn(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&&(pn(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?dn(n):null;if(us(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=dn(n);e!==o&&At(o)&&It(e,Pt(o)),e!==o&&Ot(o)&&Ct(e,Tt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return ss(t)?t:null}(e);null!==t&&as(t)}handleMutations(e,t,n){for(const n of t)os(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)os(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&ca(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=Xo.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=Qo.get(t);void 0===e&&(e=ls(t),Qo.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;es(n,this);const o=this.knownMapFor(n);let s=Qo.get(e);void 0===s&&(s=ls(e),Qo.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:++Uo,session:this,generation:++Go,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(es(r,this),this.addKnownRowBinding(r,o,e),Jo.set(o,s),n[e].isEvent){try{Vn(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=++Go,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{Vn(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=Jo.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=an(o);null!==s?(e.patternPathInfos[t]=cs(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=ds(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(us(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{Hn(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:++Uo,info:e,generation:++Go,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};Xo.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;Vn(t)?e.eventAttached=!0:t.propSegments[0]!==I?(Xn(t)&&fs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=Jn(e),n=Kn(e,t),o=Un.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Gn.countOf(n)&&(Gn.remove(n,e)&&Un.delete(n),!0))}return!1}(t)),_n(t)&&fs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=kn(e),n=Nn(e,t),o=In.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==An.countOf(n)&&(An.remove(n,e)&&In.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Zn(t.node,t.propName)&&-1===t.propModifiers.indexOf(y)){const n=function(e,t,n){let o=yo.get(e);void 0===o&&(o=new Map,yo.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&yo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});fs(e,n)}!function(e){const t=Ge(e.node);if(null!==t){const n=Je(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&se(`CustomElementRegistry is unavailable for <${t}>.`))}if(Zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=$o(e),n=xo(e),o=So(e),s=vo(e,t,null!==n,o);let r=go.get(s);void 0===r&&(r=Po(e.propName,e.statePathName,e.inFilters,n,o),go.set(s,r)),e.node.addEventListener(t,r),mo.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Ln(t)&&fs(e,()=>function(e){if(e.propSegments[0]!==I)return!1;const t=jn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),jn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Ge(e.info.node);if(null===n)return void t();const o=Je(e.info.node);if(null===o&&se(`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=Wo(o).wait(n,()=>{if(this.isAlive(e,s))try{Xe(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))});fs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Vo(e.info),n=Ho(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void Mo++;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,Oo()),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=xa(e.node.getRootNode());null===o&&se("No state tree found on this root for initial binding sync.");const s=vt(e.node);o.createState("writable",t=>{t[Rt](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=an(n);if(null!==o?(e.patternPathInfo=cs(n,o,t),e.patternListIndex=o):e.address=ds(n,t),!e.options.registerPathInfo)return;const s=xa(n.replaceNode.getRootNode());null===s&&se("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&&Xo.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,Oo());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{us(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=Ge(e.node);if(null!==t){const n=Je(e.node),o=n?.get(t);if(void 0===o)return}if(Zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=$o(e),n=vo(e,t,null!==xo(e),So(e)),o=go.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),mo.remove(n,e)&&go.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{Hn(t)}catch{}}}}function ps(e){let t=Yo.get(e);return void 0===t&&(t=new hs(e),Yo.set(e,t)),t}function gs(e){return Xo.get(e)?.session??Jo.get(e)?.session??null}let ms=null;function ys(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ws=Object.freeze([]);const bs=new WeakMap;const vs=new WeakMap;function $s(e){return vs.get(e)??[]}function xs(e,t){vs.set(e,t)}const Ss=new WeakMap;function Ps(e){return Ss.get(e)??[]}function Is(e,t){Ss.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});let As=0;function Ns(){return`u${(As++).toString(36)}`}let ks=0,_s=0;const Ts=Symbol("wcs.listIndex.noValue");class Cs{uuid=Ns();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=Ts,this._index=t,this._version=ks,this._chainGeneration=_s}get index(){return this._index}set index(e){this._index=e,this._version=++ks,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(e){this._value=e}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=ks),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===_s||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=_s),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++ks,_s++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Es(e,t,n=e){return new Cs(e,t,n)}function Ms(e,t){e.reparent(t)}function Os(e){return e.homeParentListIndex}function Rs(e,t){e.value=t}function js(e,t){const n=e.value;return n!==Ts&&n===t.value}const Ls=new WeakMap,Ws=new WeakSet;function Ds(e){return Ws.has(e)}function Bs(e,t){const n=Os(e),o=e.parentListIndex;return null===n||n===o||Ws.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Ws.has(e)&&!Ws.has(n)&&n.position===e.position&&js(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Ws.has(e)&&!Ws.has(t)}(o,t)?t:null:n}function zs(e){const t=Ls.get(e);return void 0===t?null:t}function Fs(e,t){const n=Ls.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Bs(o,t);if(null!==e)for(const t of n)Ms(t,e)}return n}function qs(e,t){null!==t?Ls.set(e,t):Ls.delete(e)}const Vs=new WeakMap;function Hs(e,t){null===t?Vs.delete(e):Vs.set(e,t)}function Us(e){const t=Vs.get(e);t&&(t.dirty=!0)}const Gs=Symbol.for("wcstack.transition-runner");function Ks(e){const t=globalThis[Gs];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 Js(e,t,n){const o=Ks(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Xs=[],Ys=[];function Qs(e){Ys.includes(e)||Ys.push(e)}function Zs(e,t=0){const n=Xs.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Xs.push(o):Xs.splice(n,0,o)}function er(e){queueMicrotask(()=>{throw e})}class tr{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Ys.length;t++)Ys[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(){Et(),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!==xt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&xt({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!==xt&&xt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=mn(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?ca(r,i):ca(r)};if(t()||0===r.length)e();else{const t=Js("state",e);void 0!==t&&t.catch(er)}}finally{Mt(),function(e){for(const t of Xs.slice())t.listener(e)}(s)}}}const nr=new tr;function or(){return nr}const sr=new WeakMap,rr=new WeakMap,ir=new WeakMap,ar=new WeakMap;let lr=!1;const cr=new WeakMap,dr=new WeakMap,ur=new WeakMap,fr=[];function hr(e,t){const n=pr(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ae(t).cumulativePaths;if(o.length<2)return;let s=ur.get(e);void 0===s&&ur.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 pr(e){let t=sr.get(e);return void 0===t&&sr.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function gr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function mr(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function yr(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=rr.get(o);if(void 0===r&&rr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(mr(s,e,o),r.set(t,n),gr(s,n,o)),!1}return r.set(t,n),gr(s,n,o),!0}function wr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function br(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&wr(ir,o.listIndex,r),null!==r.levelListIndex&&wr(ar,r.levelListIndex,r))}function vr(e,t,n,o,s){lr=!0;const r=pr(e);hr(e,t);br(r,t,s,o,yr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function $r(e,t){pr(e).tracked.add(t)}function xr(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(Xt(e.stateElement,vn(t,o)))}function Sr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Pr(e,t,n,o,s){const r=sr.get(e),i=r?.byPath.get(t),a=cr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return fr;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&&Sr(i.get(o),d),f&&Sr(i.get(c),d),u&&Sr(i.get(s),d)),void 0!==a)for(const e of a)n&&xr(e,o,d),f&&xr(e,c,d),u&&xr(e,s,d);return d}function Ir(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Ar(e,t,n){const o=sr.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())Sr(e,n);const s=cr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)xr(e,t,n)}function Nr(e){const t=ar.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function kr(e){if(!lr)return;const t=ir.get(e);if(void 0!==t){ir.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=rr.get(o),r=s.get(n);s.delete(n),mr(sr.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Nr(e)}}}function _r(e,t,n){if(!lr)return;const o=ar.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=sr.get(e),i=o.byPath.get(s);mr(i,t,r),gr(i,n,r),rr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Us(r),or().enqueueAbsoluteAddress(r,null))}}const Tr=new WeakMap,Cr=Object.freeze([]),Er=new Set;function Mr(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Cr,s=Array.isArray(n)&&n.length>0?n:Cr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Cr,o=Array.isArray(t)&&t.length>0?t:Cr;let s=Tr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Fs(o,e)||[],a=i.length>0?Os(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Er,deleteIndexSet:new Set(i),addIndexSet:Er};let t=Fs(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Es(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:Er,deleteIndexSet:Er,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:Er,deleteIndexSet:Er,addIndexSet:Er};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=Es(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=Tr.get(e);o||(o=new WeakMap,Tr.set(e,o)),o.set(t,n)}(o,s,l),qs(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,_r(e[n],t,n)}Rs(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Cr),function(e){for(const t of e)Ws.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)kr(e);return function(e){for(const t of e)Ws.delete(t)}(o.newIndexes),function(e,t){if(!lr||e===t)return;const n=dr.get(e);if(void 0===n)return;dr.delete(e);const o=dr.get(t);dr.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=pr(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&&!Ds(e))for(const t of o.getters){const n=Xt(o.stateElement,vn(t,e));Us(n),or().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function Or(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 Rr=new WeakSet;const jr=new WeakMap;function Lr(e){return jr.get(e)??null}function Wr(e,t){jr.set(e,t)}const Dr=new WeakMap;function Br(e){return Dr.get(e)??[]}function zr(e,t){Dr.set(e,t)}function Fr(e,t){const n=Br(e);for(const e of n)$t(e,t)}const qr=new WeakMap;const Vr=new WeakMap;function Hr(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function Ur(e,t,n,o,s){const r=function(e,t,n){let o=Vr.get(e);void 0===o&&Vr.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||Hr(d.prefixes,i)){aa(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[jt](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]]}ia(c,s,f)}}function Gr(e,t,n){Fr(e,t);const o=$s(e),s=Lr(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return qr.get(e)??null}(e);if(null!==r)return void Ur(r,o,s,t,n)}for(const e of o){if(null===s){hn(dn(e),e)}(null===s||s.shouldApplyState(e))&&aa(e,n)}}function Kr(e){if(!e.mounted)return;const t=$s(e),n=Lr(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{pn(dn(o),o)}}!function(e){const t=Br(e);for(let e=0;e<t.length;e++)$t(t[e],null)}(e)}function Jr(){return Object.freeze(new Set)}const Xr=new WeakMap,Yr=Jr();function Qr(e,t){const n=Xr.get(e);n?n.add(t):Xr.set(e,new Set([t]))}function Zr(e){const t=Xr.get(e);return void 0!==t?t:Yr}function ei(e,t){const n=Xr.get(e);n&&(n.delete(t),0===n.size&&Xr.delete(e))}function ti(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:be(s.filterName,s.args,t,s.literals??s.args)})}return n}function ni(e){return{...e,inFilters:ti(e.inFilters,"input"),outFilters:ti(e.outFilters,"output")}}const oi=new Set(["if","elseif","else","for"]);class si{_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];Co(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){Co(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=Lr(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow($s(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Ao(n),n.parentNode.removeChild(n))}const n=$s(this);for(let e=0;e<n.length;e++){const t=n[e];oi.has(t.bindingType)&&Zr(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Lr(this);null!==e&&(e.isRowSession?e.disposeBindings($s(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=$s(this);for(let t=0;t<e.length;t++){const n=e[t];oi.has(n.bindingType)&&Zr(n.node).forEach(e=>{e.unmount()}),Sn(n),un(n)}}unmount(){{const e=Lr(this);null!==e&&(e.isRowSession?e.disposeBindings($s(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Ao(e),e.parentNode.removeChild(e));const e=$s(this);for(let t=0;t<e.length;t++){const n=e[t];oi.has(n.bindingType)&&Zr(n.node).forEach(e=>{e.unmount()}),Sn(n),un(n)}this._mounted=!1}}function ri(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 ii(e){const t=document.createDocumentFragment(),n=new si(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 ai(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=rt(o,s[e].nodePath);null===t&&se(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),mt(t),He(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=ua.get(n);void 0!==o&&o.currentRowPlan===e||(o=new hs,ua.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new si(o);return Wr(d,c),xs(d,a),function(e,t){qr.set(e,t)}(d,n),Is(d,l),zr(d,r),Qr(e.node,d),d}function li(e){void 0!==e.uuid&&null!==e.uuid||se("BindingInfo.uuid is null.");const n=_a(e.uuid);n||se(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&ri(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=rt(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===N||s===I)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ge(r))return null;if("prop"===o&&Zn(r,e.propName))return null;const i=ni(e);let a;try{a=Vo({...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 M,policy:a,authority:a.authority})}}return{directional:t,slots:n}}(n)),null!==r)return ai(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=rt(e,s.nodePath);if(null===t&&se(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),ht.has(t))continue;const r=pt(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new hs,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 si(i,s);Wr(l,a.bindingSession),xs(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in M&&c.push(e);return Is(l,c),zr(l,a.nodes),Qr(e.node,l),l}const ci=new WeakSet,di=Symbol.for("wcstack.state.view-transition-naming");function ui(){const e=Ks("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function fi(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||ci.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[di]??={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.`)):(ci.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 hi=new WeakMap,pi=new WeakMap,gi=new WeakMap,mi=new WeakMap;function yi(e,t,n){!function(e,t,n){let o=pi.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,pi.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function wi(e,t){hi.set(e,t)}function bi(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 vi(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 $i(e,t,n){if(o=t,!Rr.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 xi=new Set(["if","elseif","else","for"]);function Si(e,t){for(const n of $s(e))if(t.appliedBindingSet.delete(n),xi.has(n.bindingType))for(const e of Zr(n.node))Si(e,t)}function Pi(e){for(const t of $s(e)){if(!xi.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Zr(t.node))Pi(n),e&&n.mounted&&(Kr(n),n.unmount(),ei(t.node,n))}}function Ii(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ai(e,n,s){const r=Boolean(s);let i;const a=Zr(e.node);i=0===a.size?li(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Ii(e)}`),Kr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Ii(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);Gr(i,vt(e.node),n);const t=ui();null!==t&&fi(i,"branch",t)}}const Ni=new WeakMap;function ki(e){return Ni.get(e)??[]}const _i=new Set;const Ti=Symbol.for("wcstack.trustedTypes.policy");function Ci(){const e=globalThis[Ti];return null===e||"object"!=typeof e?null:e}function Ei(e){globalThis[Ti]=e}let Mi;let Oi=!1;function Ri(e,t){if(Oi)return;if(!function(){if(void 0!==Mi)return Mi;if(!("trustedTypes"in globalThis))return Mi=!1,Mi;try{document.createElement("div").innerHTML="<i></i>",Mi=!1}catch{Mi=!0}return Mi}())return;Oi=!0;const n="function"==typeof Ci()?.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 ji={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")}},Li=new Set(["textContent","innerText","innerHTML"]);function Wi(e,n,s){if(void 0===s&&1===e.propSegments.length&&Li.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!==ms&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Ge(r)&&ms.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=Ci(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Ri(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=Ge(e);if(null===n)return null;const o=Je(e)?.get(n);if(void 0===o)return null;const s=Ye(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Zn(r,c)){const t=so(r,c,e.statePathName),o=ro(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??uo()??ao(t);if(a.visitedEdges.has(o))null!==xt&&xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=lo(a,o);fo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:no++,writtenValue:n};ho.push({receipt:i,node:e});try{return r()}finally{ho.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=ji[c];e?e(r,s):(!function(e,t,n){let o=Ni.get(e);o||(o=[],Ni.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,_i.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!==ms&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ge(r)&&(u in d?ms.rememberOverwrittenValue(r,c,u,d[u]):ms.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 Di=new WeakSet;function Bi(e,t,n){}function zi(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 Fi(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+c:"";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(c)&&o.push(t)}return o}const qi={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Vi={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Hi(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}.${ue}`}function Ui(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 Gi(e,t){return`$setAll("${e}") ${t}`}function Ki(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.${ue}`}function Ji(e,t){const n=xn(t);if(n.pathInfo.path in M){const e=vt(t.node);return null===e&&se(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&se("ListIndex not found for loopContext:");const n=M[t];void 0===n&&se(`Invalid index name: ${t}`);const o=on(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&se(Ki(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[jt](n)}const Xi=new WeakSet;function Yi(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Qi=Object.freeze({[k]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&se("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,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)},[T]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[N]:function(e,t,n){Dn(n)||se("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=bs.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||se('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Ge(e);if(null===t)return null;const n=Je(e)?.get(t);return void 0===n&&se(`Custom element <${t}> is not defined for command binding.`),Ye(e)}(r);null===a&&se(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||se(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${de(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),bs.delete(e));const l=new WeakRef(r);let c=null;c=o.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void bs.delete(e);const o=n[i];return"function"!=typeof o&&se(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),bs.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Zi={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Di.has(e.replaceNode)){Di.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=an(e),i=dn(e),a=Pt(i),l=a.length>0&&!pi.has(e.node)?[]:a,c=Mr(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=pi.get(e.node);const f=void 0!==u?$i(u,l,c):null,h=Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=mi.get(e.node);if(void 0===t){const n=hi.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(bi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(bi(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),mi.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){ko.set(e,(ko.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return gi.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;c.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(Kr(o),Pi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?ei(e.node,o):(Kr(o),o.unmount(),function(e,t){let n=gi.get(e.node);void 0===n&&(n=[],gi.set(e.node,n)),n.length<1e3?n.push(t):ei(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(pi.delete(e.node),u=void 0)}let g=e.node;const m=ae(s.path+"."+d),y=n.stateElement.loopContextStack,w=Or(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&g.isConnected&&null===f&&(b=document.createDocumentFragment(),Zt(b,n.rootNode));const v=t(),$=ui(),x=e.uuid??"",S=gi.get(e.node);for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const r=vn(m,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=li(e):Si(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(g.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);g.parentNode.insertBefore(e,g.nextSibling),g=e}o.mountAfter(g)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??g;n.parentNode.insertBefore(e,n.nextSibling)}}Gr(o,r,n),null!==$&&fi(o,"row",$)}),void 0===o&&se(`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,c.changeIndexSet.has(t)){const e=Ps(o);for(const t of e)aa(t,n)}null===o&&se(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&vi(g,o.firstNode)||g.nextSibling===o.firstNode||o.mountAfter(g),e){const e=o,s=vn(m,t);y.createLoopContext(s,t=>{Gr(e,t,n)})}}g=o.lastNode||g,void 0===u&&(u=new WeakMap,pi.set(e.node,u)),u.set(t,o)}hi.set(e.node,g),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Zt(b,null))},if:Ai,else:Ai,elseif:Ai,radio:function(e,t,n){const o=e.node,s=ys(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=ys(o.value,e.inFilters),r=Array.isArray(n)?n:ws;o.checked=r.includes(s)}},ea=new WeakMap,ta=new WeakMap,na=new WeakMap;function oa(){}function sa(e){const t=ms;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Bi;if(t.isDeclared(n,o))return oa}return Wi}function ra(e,t){ia(e,t,Ji(t.state,e))}function ia(e,t,n){const o=ys(n,e.outFilters);if(!0===ta.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=ea.get(e);if(void 0===s){if(ea.has(e))return s=sa(e),s===Bi&&ea.set(e,s),void s(e,t,o);if(s=Zi[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Qi[t],ea.set(e,s),void 0===s){Ge(e.replaceNode)?(s=sa(e),s===Bi&&ea.set(e,s)):(s=Wi,ea.set(e,s))}}if(s===Wi){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 ta.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function aa(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=dn(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=gs(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==na.get(e)){const t=Ge(e.replaceNode);if(t&&void 0===Je(e.replaceNode)?.get(t))return void function(e,t){if(Xi.has(e))return;Xi.add(e);const n=()=>{Xi.delete(e);const t=gs(e);(null===t||t.shouldApplyState(e))&&ca([e])},o=n=>{Xi.delete(e),Yi(t,n)},s=gs(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Xi.delete(e),r()})||(Xi.delete(e),r()))}const r=Je(e.replaceNode);if(null===r)return Xi.delete(e),void Yi(t,new Error("CustomElementRegistry is unavailable."));Wo(r).wait(t,()=>{e.replaceNode.isConnected?n():Xi.delete(e)},o)}(e,t);na.set(e,!0)}if(!0===t.sameRootVerified)return void ra(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=en(o),null===o&&se("Root node for fragment not found for binding.")),o!==t.rootNode){const n=xa(o);null===n&&se("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};ra(e,r)})}else ra(e,t)}function la(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!==xt&&xt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function ca(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=en(d),null===d&&se("Root node for fragment not found for binding."));const u=xa(d);null===u&&se("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{aa(n,f)}catch(e){la(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{Wi(e,{propagationContextByBinding:t},n)}catch(t){la(e,t,o??null,c)}for(const[e,t]of i.entries())It(e,t),Ct(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[zt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Ft](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 da(e,t,n){const[o,s,r]=gt(e,n),i=ps(e);for(const e of o)$t(e,t);ca(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=yt(o);0!==e.length&&($t(o.node,t),ca(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const ua=new WeakMap;async function fa(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Je(e);null===s&&se(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(ct(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function ha(e){if(e===document)await fa(document),ne(document),Ua(document,document),da(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await Ve(t.host),await fa(t),ne(t),Ua(t,t),da(t,null)}}const pa={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function ga(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${pa[e]??e}" before the state is defined.`}let ma=null;function ya(e){return null===ma&&se(ga("ssr",e)),ma}const wa=new WeakMap,ba=new WeakMap,va=new Set,$a=[];function xa(e){return wa.get(e)??null}function Sa(e){return ba.get(e)??Promise.resolve()}const Pa=new WeakSet;function Ia(e){Pa.add(e)}function Aa(e,n){const s=wa.get(e);if(null===n){if(void 0===s)return;wa.delete(e),va.delete(s),null!==xt&&xt({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 ya('the "enable-ssr" attribute').hydrate(e)||await ha(e)}else await ha(e);Ia(e),Qa(),t()}catch(e){n(e)}})});ba.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await ha(e),Ia(e),Qa(),t()}catch(e){n(e)}})});ba.set(e,t)}}void 0!==s&&se('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="...">.'),wa.set(e,n),va.add(n);for(let t=0;t<$a.length;t++)$a[t](e,n);null!==xt&&xt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Na=new Map;function ka(e,t,n){if(null===n)Na.delete(e);else{Na.set(e,n);const o=xa(t);null===o&&se("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 Na.get(e)||null}function Ta(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Re(t.getAttribute(o.bindAttributeName)||"");return t.localName===o.tagNames.state&&t.hasAttribute("mount")?n.filter(e=>e.propSegments[0]!==A):n}if(e.nodeType===Node.COMMENT_NODE){const t=De(e);null===t&&se("Comment node binding text not found.");const n=_a(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Be(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Ca;function Ea(){return Ca??={filterName:"not",args:[]}}const Ma=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Oa(e,t){const n=t+c+d,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+c+s.slice(1)}return r.length>0?s+r:s}function Ra(e,t){const n=Ma.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Oa(s,t)+r}function ja(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=Oa(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function La(e,t){return ja(e,t)}function Wa(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=Ra(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=ja(r,t);e!==r&&o.setAttribute(n,e)}}}function Da(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 Ba(e){const t=[],n=ft(e);for(const e of n){const n=Ta(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:Da(o),parseBindTextResults:n})}return t}function za(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 Fa=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),qa=Ea();function Va(e,t){const n=t.outFilters;return{...t,outFilters:[...n,qa],bindingType:e}}function Ha(e,t,n,o,s,r=!0){za(t),"string"==typeof o&&Wa(t,o),Ua(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ba(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 Ua(e,t,n,s){const r=o.commentElsePrefix,i=dt(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=La(i,n));let a=Re(i)[0];const d=Fa.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Ns();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&se("'else' binding found without preceding 'if' or 'elseif' binding."),a=Va("else",l.parseBindTextResult),p=Ha(e,f,a,g,s,!1),ka(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:Da(o),parseBindTextResults:Ta(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&se("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ha(e,f,a,g,s),ka(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=Ns(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Va("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Da(n),parseBindTextResults:Ta(n)}),ka(o,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:Da(m),parseBindTextResults:Ta(m)})):t.replaceWith(m)}else{p=Ha(e,f,a,g,s),ka(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 Ga=()=>`[${o.bindAttributeName}]`;function Ka(e){if(ts(e))return!0;if(!Ja(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(Ga());return null!==t&&ts(t)}function Ja(e){return 1===e.nodeType}function Xa(e){if(Ka(e))return;ne(e),Ua(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);da(t&&s?n:e,null)}const Ya=[];function Qa(){const e=Ya.splice(0,Ya.length);for(const t of e)Xa(t);l()}const Za={protocol:"wcs-binder",version:1,bind:function(e){var t;Ja(e)&&!Ka(e)&&(t=e.getRootNode(),Pa.has(t)?Xa(e):Ya.push(e))}};const el="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let tl=0;async function nl(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++tl}\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 ${el}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${el}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function ol(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){se(`Failed to load script file: ${e}`)}}class sl{_loopContextStack=Array(f).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&se("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=f&&se("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&&se("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&&se("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&&se(`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 rl={$updatedCallback:j,$streams:H},il=new WeakSet;function al(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function ll(e){if(!il.has(e)){for(const t of Object.keys(rl)){if(!(t in e))continue;const n=rl[t];n in e&&se(`[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=al(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}il.add(e)}}const cl=new WeakMap;function dl(e,t){let n=cl.get(e);void 0===n&&(n=new Map,cl.set(e,n));let o=n.get(t);return void 0===o&&(o=new Wn(t,e),n.set(t,o)),o}const ul=new WeakMap;function fl(e){const t=ul.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return dl(e,n)},has:(t,n)=>"string"==typeof n&&e.commandTokenNames.has(n),ownKeys:()=>Array.from(e.commandTokenNames),getOwnPropertyDescriptor(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:dl(e,n)}},set(){se("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){se("$command namespace is read-only; deleting from it is not allowed.")}});return ul.set(e,n),n}const hl=Symbol("wcs.notHandled"),pl=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],gl=new Map;function ml(e,t){gl.set(e,t)}const yl=new Map;let wl=[],bl=[];function vl(e,t){yl.set(e,t),wl=Array.from(yl.values()).sort((e,t)=>e.order-t.order),bl=wl.slice().reverse()}function $l(e,t){for(let n=0;n<wl.length;n++)wl[n].activate?.(e,t)}function xl(e){"readonly"===e.mutability&&se("This state is readonly.")}const Sl=new Map;class Pl{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=ae(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 Il(e){let t;return Sl.get(e)??(Sl.set(e,t=new Pl(e)),t)}function Al(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:on(n.listIndex,o,n.pathInfo.wildcardCount)}function Nl(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=nn(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?on(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?on(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function kl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function _l(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!==hl)return a}}return hl}function Tl(e,t,n,o,s){if(t.pathInfo.segments[0]===F)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}(fl(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=_l(s,t,null,n,o);if(r!==hl)return r;se(function(e,t,n){return`[${qi.binding}] Path "${e}" does not exist on the state tree.${de(e,Fi(t,"",n))}${ue}`}(t.pathInfo.path,e,s.getterPaths))}const r=El(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!==d&&!(i in Object(r))){const e=_l(s,t,Object(r),n,o);if(e!==hl)return e}if(i===d){const e=t.listIndex?.index??se(Ki(`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 Cl(e,t,n,o,s){const r=Xt(s,t),i=function(e){return Vs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Tl(e,t,n,o,s);return Hs(r,{value:l,dirty:!1,generation:a}),l}function El(e,t,n,o){Nl(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!==hl)return i}}return kl(s,t)?Cl(e,t,n,o,s):Tl(e,t,n,o,s)}function Ml(e,t,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=vn(f,r),p=Xt(n.stateElement,h),g=Tt(p),m=El(e,h,t,n),y=Mr(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??se(`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())Ct(e,Array.isArray(t)?t:[]);return l}function Ol(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Fs(El(e,vn(a,r),t,n),r);null==l&&se(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??se(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Rl(e,t,n,o){"object"==typeof e&&null!==e||se(`${X} 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&&se(`${X} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function jl(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&se(`${X} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function Ll(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];Rl(a,n,o,i);const l=jl(a,t,n,o,i);r.has(l)&&se(`${X} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Wl(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 Dl(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=El(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===d){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const Bl=new WeakMap;function zl(e,t){null===t?Bl.delete(e):Bl.set(e,t)}function Fl(e,t,n){const s=vn(ae(e.wildcardParentPaths[t]),n),r=Xt(e.stateElement,s),i=Tt(r),a=e.stateProxy[jt](s),l=Mr(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)Fl(e,t+1,n)}const ql=[];function Vl(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:ql,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:ql,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Hl=[];function Ul(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Hl;let s=null;const r=t+c;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ae(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Hl}function Gl(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=ae(r);if(e.listPathSet.has(o)&&s.lastSegment===d){const i=e.stateProxy[jt](t),a=Xt(e.stateElement,t),l=Tt(a),c=Mr(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Vl(e,o,0,0,c);for(const t of d.fullRows){const o=vn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=Ul(e,r,s);if(null===t)for(const t of d.movedRows){const o=vn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=vn(s,o);e.result.add(t),n.push(t)}}}else{const o=vn(s,t.listIndex);e.result.add(o),n.push(o)}}const r=e.dynamicMap.get(o);if(r)for(const o of r){const s=ae(o),r=[];if(s.wildcardCount>0){const n=nn(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&se(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=on(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};Fl(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&se(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=on(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=vn(s,t);e.result.add(o),n.push(o)}}}function Kl(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&&se(`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,Gl(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)Ct(e,t);return Array.from(u.result)}function Jl(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 Xl(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 Yl(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 Ql(e,t,n,s,r,i){const a=function(e,t){return!0===sr.get(e)?.byPath.has(t)||!0===cr.get(e)?.has(t)}(e,t),l=function(e,t){return!0===ur.get(e)?.has(t)}(e,t);if(!a&&!l)return;const c=or(),u=o.enablePropagationContext?uo()??null:null,f=e=>{Us(e),c.enqueueAbsoluteAddress(e,u)};a&&Pr(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=ae(t).segments.length,r=[];for(const i of ur.get(e).get(t)){const t=ae(i).segments.slice(s);if(t.includes(d))Ar(e,i,r);else for(const s of Pr(e,i,!0,Ir(n,t),Ir(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?uo()??ao(-1):null,c=or();c.enqueueAbsoluteAddress(t,l),i&&Us(t),Kl(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Xt(s.stateElement,t);Us(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function ec(e,t,n,o,s){s&&(e.getterPaths.has(t)?Us(n):Hs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function tc(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=El(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??se(Ki(`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 nc(e,t,n,o,s,r,i,a){const l=t.parentAddress??se(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=El(e,l,s,r)??[];let f=(h=u,Bl.get(h)??null);var h;if(null===f){const e=zs(u)??[];f={value:[...u],listIndexes:[...e]},zl(u,f)}try{return tc(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=El(e,l,s,r)??[],a=Array.isArray(i)?zs(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:Es(l.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;zl(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=or(),l=Xt(i,e);Pt(l)===n&&(qs(t.value,t.listIndexes),It(l,t.value),function(e){Rr.add(e)}(t.value));a.enqueueRenderOnlyAddress(l);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=ae(e.pathInfo.path+c+d);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=vn(f,n),d=Xt(i,c);if(void 0===l){const n=Yt(i,f,t.listIndexes[e]??null);Yl(i,d,n),Zl(c,d,s,r,null,kl(i,c),"full");continue}Kl(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Xt(i,e);Us(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(l,f,i,a,s,r)}}}function oc(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=El(e,t,o,s),a=function(e,t,n,o){const s=Ll(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Ll(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===zs(o)&&Mr(a,null,o);const l=Mr(a,o,n.list),u=sc(e,t,n.list,s,r,i),f=ae(i+c+d);for(const t of n.matched){const n=Wl(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?oc(e,vn(ae(f.path+c+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return sc(e,t,n,o,s,null)}function sc(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==hl)return i}}const u=!!po&&(po=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=El(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===d?t.listIndex?.index:e;let p,g=!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,g=!0}Ql(a,l,g,p,n,()=>f[h]);const m=kl(a,t),y=Xt(a,t);null!==xt&&xt({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:g}),Jl(a,l,y,p,g);let w=!1;try{if(void 0===h&&se(Ki(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==d&&!(h in f)){const e=c.writeMissing;for(let o=0;o<e.length;o++){w=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==hl)return i;w=!1}}return Reflect.set(f,h,n)}finally{Zl(t,y,s,r,i,m),w?Us(y):ec(a,l,y,n,m),Xl(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=El(e,t,s,r);if(Dl(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Ql(a,l,h,f,n,()=>El(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),g=kl(a,t),m=Xt(a,t);null!==xt&&xt({type:"state:write",absoluteAddress:m,value:n,oldValue:f,hasOldValue:h}),Jl(a,l,m,f,h);try{return p?nc(e,t,m,n,s,r,i,g):tc(e,t,m,n,s,r,i,g)}finally{p||ec(a,l,m,n,g),Xl(a,t.pathInfo,{value:n})}}function rc(e,t,n,o){return(t,s,...r)=>{const i=ae(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&&se(Hi("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=vn(i,Ol(e,n,o,i,s));if(0===r.length)return El(e,a,n,o);xl(o),oc(e,a,r[0],n,o)}}function ic(e,t,n,o){const s=rc(e,0,n,o);return(t,r)=>{const i=ae(t);if(void 0===r||Array.isArray(r)||se(`$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&&se(Hi("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=Al(o,i.wildcardPaths[e]);if(t){r=sn(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&&se(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=Ml(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 ac(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Al(o,s.wildcardPaths.at(-1)??se(`lastWildcardPath is null: ${t.pathInfo.path}`))??se(`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]??se(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Fs(El(e,vn(i,s),n,o),s)??se(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??se(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??se(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":se(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function lc(e,t,n,o){return(t,s,r,i)=>{xl(o);const a=ae(t);Array.isArray(s)||se(Gi(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&se(Hi("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&se(Gi(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&se(Gi(t,"requires an array as the value when { spread: true } is set."));const d=Ml(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&se(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=Ol(e,n,o,a,d[t]);u.push(vn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(El(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(oc(e,s,i,n,o),f++)}return f}}function cc(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of ae(t).cumulativePaths)if(n.has(e))return!0;return!1}const dc=/^\$\d+$/,uc=`${Y}${c}`,fc=`${Q}${c}`,hc=new WeakMap;function pc(e,t,n,o){const s=M[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&dc.test(t)&&se(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${C}1 to ${C}128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&se(`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&&se(`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=on(r,i,a.wildcardCount);return c?.index??se(`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!==hl)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>ic(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>lc(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=Il(t),i=ac(e,r,n,o),a=vn(r.pathInfo,i),l=Xt(s,a),c=or();c.enqueueAbsoluteAddress(l),Kl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Xt(s,e);Us(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)=>rc(e,0,n,o)(t,s,...r);case"$dependOn":case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(J)&&se(`[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&&se(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??se("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(cc(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&$r(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)&&vr(o.stateElement,e,t,Xt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=cc(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?$r(o.stateElement,e):vr(o.stateElement,e,i,Xt(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||se(`$eqIndex("${e}") needs a list row scope.`);const r=on(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&se(`$eqIndex("${e}", ${t}): no list index at that level.`),cc(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&$r(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?zs(l):null;null!==t?function(e,t,n,o,s){lr=!0,pr(e).lastValue.set(t,s),hr(e,t);let r=cr.get(e);void 0===r&&cr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=dr.get(o);void 0===l?dr.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){lr=!0;const r=pr(e);hr(e,t),br(r,t,s,o,yr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Xt(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 F:return fl(o.stateElement)}if(!t.startsWith(uc)&&!t.startsWith(fc))return}const r=Il(t),i=ac(e,r,n,o),a=vn(r.pathInfo,i);return El(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=hc.get(e);return void 0===t&&(t=new Map,hc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Rt:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&se("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case jt:i=t=>El(e,t,n,o);break;case Lt:i=t=>Dl(e,t,n,o);break;case Wt:i=(t,s)=>oc(e,t,s,n,o);break;case Dt:i=()=>async function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Bt:i=()=>function(e,t,n){const o=Reflect.get(e,R);"function"==typeof o&&o.call(n)}(e,0,n);break;case zt:i=t=>function(e,t,n,o){const s=Reflect.get(e,j);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=sn(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 Ft:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,L);"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 gc{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=xa(e);null===n&&se("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&&se("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=f&&(this._hasRepeatedAddress()&&se(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),se(`[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&&se(`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 pc(e,t,n,this)}set(e,t,n,o){return xl(this),function(e,t,n,o,s){if("string"==typeof t){const r=Il(t),i=ac(e,r,o,s);return oc(e,vn(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}}const mc=Promise.resolve(),yc=new Map;let wc=[];function bc(e,t){yc.set(e,t),wc=Array.from(yc.values()).sort((e,t)=>e.order-t.order)}function vc(e,t){return se(ga(e,t))}const $c="undefined"==typeof HTMLElement?class{}:HTMLElement;function xc(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 Sc=null;const Pc=new Set(["for","if","elseif","else"]);function Ic(e,n,o){const s=new Map;for(const e of o){const t=ae(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=Xt(e,t);if(i.has(n))return;i.add(n);const o=mn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(vn(n,t.listIndex))}};Et();try{if(e.createState("readonly",t=>{for(const o of n){const n=vn(ae(o),null);a(n);try{Kl(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)Pc.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=()=>{ca(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Js("state",s);void 0!==i&&i.catch(er)}finally{Mt()}}class Ac extends $c{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Sa(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 sl}();_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&&se(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){ll(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<wl.length;o++)wl[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[z];if(void 0===n)return t;Array.isArray(n)||se(`${z} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||se(`${z} entries must be non-empty strings.`),e===F&&se(`${z} entry "${e}" conflicts with the reserved namespace name "${F}".`),t.has(e)&&se(`${z} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[q];if(void 0===n)return t;Array.isArray(n)||se(`${q} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||se(`${q} entries must be non-empty strings.`),t.has(e)&&se(`${q} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[X];if(void 0===t)return null;"object"==typeof t&&null!==t||se(`${X} 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&&se(`${X} entry path must be a non-empty string.`);const t=e.split(c);t.some(e=>0===e.length)&&se(`${X} entry "${e}" must not contain empty path segments.`),t[t.length-1]===d&&se(`${X} entry "${e}" must be the list path itself, not the element path (drop the trailing "${c}${d}").`),-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] ${X} entry "${e}" uses "${J}", which ${X} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${c}${d}${c}children").`),"function"!=typeof o?("string"!=typeof o&&se(`${X} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&se(`${X} entry "${e}" key field name must be a non-empty string.`),(o.includes(c)||o.includes(d))&&se(`${X} entry "${e}" key field name "${o}" must be a flat property name ("${c}" / "${d}" are not allowed).`),o in Object.prototype&&se(`${X} 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<wl.length;o++)wl[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&Sc?.reset(this),this._hasUpdatedCallback=j in e,this._hasErrorCallback=L in e,i=this,On.delete(i),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[V];if(void 0!==o){"object"==typeof o&&null!==o||se(`${V} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||se(`${V} entry "${t}" is not declared in $eventTokens.${de(t,n)}`),"function"!=typeof s&&se(`${V} entry "${t}" must be a function.`),Rn(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const a=function(e){const t=new Set,n=new Set,o=xc(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<wl.length;o++)wl[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].register?.(e,t,n)}(this,e,n),$l(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")?ya('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){se("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 nl(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||se(`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 ol(e);se(`Unsupported src file type: ${e}`)}}catch(e){se(`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&&(Aa(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),se(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===xa(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),ba.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<wc.length;o++)wc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{O in e&&await e[Dt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{R in e&&e[Bt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<wc.length;t++)if(!0===wc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||xa(this._rootNode)===this||Aa(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<wc.length;t++){const n=wc[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(Z))try{vc("dcc",`a <${o.tagNames.state}> inside a [${Z}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{vc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<wc.length;t++){const n=wc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&vc("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 ya('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}$l(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<wc.length;t++)if(!0===wc[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<wc.length;n++)wc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Aa(this.rootNode,null),e=this,ul.delete(e),function(e){for(let t=0;t<bl.length;t++)bl[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=>(ll(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",U)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&se(`$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 zi(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&&se("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=gl.get(e);return void 0===n&&se(ga(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<pl.length;n++){const o=pl[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",D)}_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+"."+d)),!this._pathSet.has(e)){const t=ae(e);if(this._pathSet.add(e),Sc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ae(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 gc(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&&se(`<${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<wc.length;t++)wc[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&se("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(xc(n)))e.startsWith("$")||e.includes(d)||"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){Ic(this,e,this._pathRegistrations.keys())}}const Nc=[];function kc(e=customElements){for(let t=0;t<Nc.length;t++)Nc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,Ac)}function _c(e){if("string"==typeof e?.locale)return e;const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}function Tc(e,t){const o=_c(e);var s;o&&((s=o).tagNames&&Object.assign(n.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(n.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(n.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(n.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(n.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(n.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(n.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(n.locale=s.locale),"boolean"==typeof s.debug&&(n.debug=s.debug),"boolean"==typeof s.enableMustache&&(n.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(n.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(n.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(n.sameValueGuard=s.sameValueGuard)),kc(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=Za)}()}function Cc(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 Ec(e,t){for(const n of e)if(Cc(t,n.innerSegments))return n;return null}function Mc(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+c+n.join(c)}let Oc=0;const Rc=["$watch",H,"$scan","$listKeys",j,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],jc=new Set;function Lc(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 Wc(e,t,n,o,s,r=new Set){0===n.length&&se(`Cannot build a mount record without host bindings for "${t}".`),ll(s);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(c);a.has(n)&&se("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(y)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++Oc,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 g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?u:l.outerPathInfo.path+c+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function Dc(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function Bc(e,t){const n=Ec(e.entries,t);return null===n?null:Mc(n,t)}function zc(e,t){return e.markerBasePath+c+t}function Fc(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+c+n;s.set(n,{accessorName:o,indexShift:ae(r).wildcardCount-ae(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function qc(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 Vc(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(c)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${Dc(t)}: path") or declare the key on the component state.`}const Hc=/^\$(\d+)$/;function Uc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=Dc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||qc(e,o))return null;const s=function(e,t){return Ec(e.entries,t)}(e,t.split(c));return null!==s&&s.readonly?s:null}function Gc(e,t){const n=Uc(e,t);if(null!==n){const o=0===n.innerSegments.length?"":c+n.innerSegments.join(c);se(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${y}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${y} from the mount.`)}return Kc(e,t)}function Kc(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(c);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===d){o=e;break}if(-1===o)return Fc(e,e.markerBasePath,t,t),zc(e,t);if(qc(e,n[0]))return Fc(e,e.markerBasePath,t,t),zc(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Bc(e,s);null===i&&se(Vc(e,t)),0===r.length&&se(`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+c+e.marker;return Fc(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=Dc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return zc(e,t);if(qc(e,o))return zc(e,t);const s=Bc(e,t.split(c));if(null!==s)return s;se(Vc(e,t))}function Jc(e,t,n){let o;const s=Hc.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ae(Kc(e,t)).wildcardCount-ae(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Kc(e,t.statePathName),"for"===t.bindingType){const n=ae(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+c+d,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(y)&&null!==Uc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ae(o),...i?{propModifiers:[...r,y]}:{}}:t}function Xc(e,t,n,o,s){if(void 0===o)return;const r=ae(n).wildcardCount-ae(t).wildcardCount;return 0===r?o:(s.length<r&&se(`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 Yc=new WeakMap,Qc=new WeakMap;const Zc=new WeakMap;const ed=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)}),td=new WeakMap;function nd(e){return td.get(e)??null}let od=!1;function sd(){od||(od=!0,bt=e=>Yc.has(e)?e.host:null)}function rd(e){const t=Zc.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 id(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Zc.get(e);if(void 0===o)return null;const s=t.indexOf(c,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 ad="3.2.0",ld=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function cd(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 dd(e){const t=function(e){const t=sr.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:cr.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 ud="__WCSTACK_DEVTOOLS_HOOK__";function fd(){const e=globalThis,t=e[ud];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[ud]=n,n}const hd=e=>{null!==xt&&xt({type:"state:update-batch",addresses:e})};function pd(e){const t=null!==xt;!function(e){xt=e}(e);const n=null!==e;n&&!t?Zs(hd,0):!n&&t&&function(e){const t=Xs.findIndex(t=>t.listener===e);-1!==t&&Xs.splice(t,1)}(hd)}function gd(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 md(e){return xa(e)??se("devtools: no state tree on this root")}let yd=null;function wd(){if(t())return;if(null!==yd)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:ad,getStateElements(){const e=[];for(const t of va)e.push(gd(t));return e},overlays:e=>rd(md(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=>dd(md(e)),keys(e){const t=md(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 md(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){md(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(cd(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=st(t,Re(n));for(const o of e)r(cd(t,o,"attribute",n))}catch{}continue}const t=ld.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(cd(e,Be(s),"comment",s))}catch{}}else r(cd(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:pd};yd=e,fd().register(e)}const bd={name:"devtools",install(){wd()}},vd=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),$d=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const xd=new WeakMap;const Sd=new WeakMap,Pd=new WeakSet,Id=new WeakMap;function Ad(e,t,n,o){console.warn(`[@wcstack/state] [${qi[n]}] ${Vi[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${de(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ue}`),null!==xt&&xt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Nd={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=ae(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=xd.get(e);return void 0===n&&(n=new Set,xd.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!==zi(e,t))return $d;const o=ae(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+c+i,t>0&&t<o.length-1&&void 0!==zi(e,r))return vd;if(Object(s)!==s)return vd;if(i===d){if(!Array.isArray(s)||0===s.length)return vd;s=s[0];continue}const l=zi(s,i);if(void 0===l)return{existence:"missing",missingSegment:i,candidates:Fi(s,a,n)};if("function"==typeof l.get)return t===o.length-1?$d:vd;s=l.value}return $d}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===Id.get(e)?.has(t)}(e,n)||("binding"!==o?Ad(e,n,o,i):function(e,t,n){let o=Sd.get(e);void 0===o&&(o=new Map,Sd.set(e,o));if(o.set(t,n),Pd.has(e))return;Pd.add(e),setTimeout(()=>function(e){Pd.delete(e);const t=Sd.get(e);if(void 0===t)return;Sd.delete(e);for(const[n,o]of t)Ad(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){xd.delete(e),Sd.delete(e)},markExported:function(e,t){let n=Id.get(e);void 0===n&&(n=new Set,Id.set(e,n)),n.add(t),Sd.get(e)?.delete(t)}};let kd=!1;function _d(){kd||(kd=!0,function(e){Sc=e}(Nd))}const Td={name:"diagnostics",install(){_d()}};function Cd(e){se(`filter ${e} requires at least one option`)}function Ed(e){se(`filter ${e} requires a number as option`)}function Md(e){se(`filter ${e} requires a number value`)}function Od(e){se(`filter ${e} requires a date value`)}const Rd={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function jd(e){return!(!e||isNaN(Number(e)))}const Ld={eq:(e,t)=>{const n=e?.[0]??Cd("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(jd(n)||Ed("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Cd("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(jd(n)||Ed("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>("boolean"!=typeof e&&se(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??Cd("lt");return jd(t)||Ed("lt"),e=>("number"!=typeof e&&Md("lt"),e<Number(t))},le:e=>{const t=e?.[0]??Cd("le");return jd(t)||Ed("le"),e=>("number"!=typeof e&&Md("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??Cd("gt");return jd(t)||Ed("gt"),e=>("number"!=typeof e&&Md("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??Cd("ge");return jd(t)||Ed("ge"),e=>("number"!=typeof e&&Md("ge"),e>=Number(t))},add:e=>{const t=e?.[0]??Cd("add");return jd(t)||Ed("add"),e=>("number"!=typeof e&&Md("add"),e+Number(t))},sub:e=>{const t=e?.[0]??Cd("sub");return jd(t)||Ed("sub"),e=>("number"!=typeof e&&Md("sub"),e-Number(t))},mul:e=>{const t=e?.[0]??Cd("mul");return jd(t)||Ed("mul"),e=>("number"!=typeof e&&Md("mul"),e*Number(t))},div:e=>{const t=e?.[0]??Cd("div");return jd(t)||Ed("div"),e=>("number"!=typeof e&&Md("div"),e/Number(t))},mod:e=>{const t=e?.[0]??Cd("mod");return jd(t)||Ed("mod"),e=>("number"!=typeof e&&Md("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&Md("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??Cd("clamp");jd(t)||Ed("clamp");const n=e?.[1]??Cd("clamp");jd(n)||Ed("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&Md("clamp"),Math.min(Math.max(e,o),s))},toFixed:e=>{const t=e?.[0]??"0";return jd(t)||Ed("toFixed"),e=>("number"!=typeof e&&Md("toFixed"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Md("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]??Cd("slice");jd(n)||Ed("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(jd(o)||Ed("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??Cd("substr");jd(t)||Ed("substr");const n=e?.[1]??Cd("substr");return jd(n)||Ed("substr"),e=>String(e).substr(Number(t),Number(n))},padStart:e=>{const t=e?.[0]??Cd("padStart");jd(t)||Ed("padStart");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},padEnd:e=>{const t=e?.[0]??Cd("padEnd");jd(t)||Ed("padEnd");const n=e?.[1]??" ";return e=>String(e).padEnd(Number(t),n)},repeat:e=>{const t=e?.[0]??Cd("repeat");return jd(t)||Ed("repeat"),e=>String(e).repeat(Number(t))},reverse:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??Cd("truncate");jd(t)||Ed("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)||se(`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 jd(t)||Ed("round"),e=>{"number"!=typeof e&&Md("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return jd(t)||Ed("floor"),e=>{"number"!=typeof e&&Md("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return jd(t)||Ed("ceil"),e=>{"number"!=typeof e&&Md("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return jd(t)||Ed("percent"),e=>("number"!=typeof e&&Md("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??Cd("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Od("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||Od("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]??Cd("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Cd("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},Wd={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]},Dd=Ld,Bd=Ld;let zd=!1;const Fd={name:"formats",install(){zd||(zd=!0,we("input",Bd,Wd,Rd),we("output",Dd,Wd,Rd))}};function qd(e){return-1!==e.indexOf(J)}function Vd(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+c;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(qd(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function Hd(e){return 0===e.length?e:c+Kd(e.slice(1))}function Ud(e,t,n){const o=c+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 Gd(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(Ud(e,t,n.slice(0,o)))return!0;return!1}function Kd(e){const t=e.split(c);for(let e=0;e<t.length;e++)t[e]===d||Number.isNaN(Number(t[e]))||(t[e]=d);return t.join(c)}function Jd(e,t){const n=e.repeat.split(c),o=c+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===c+e.repeatList+c+"length")return!0;for(let e=1;e<n.length;e++)if(s===c+n.slice(0,e).join(c))return!0;return!1}function Xd(e,t,n){n<0&&se(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=c+e.repeat;const s=o+t;let r=0;for(const e of s.split(c))e===d&&r++;return r>u&&se(`[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 Yd(e,t){return Xd(e,"",t)}function Qd(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=c+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 Zd(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=c+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 eu(e,t,n){const o=e.recursionRegistry,s=Vd(o.spec,n);null===s&&se(Ui(n,o.spec.recursiveAnchor));const r=Zd(t,o);return null===r&&se(`[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 tu(e,t,n,o,s){const r=o.spec,i=[],a=new Map,l=[],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(vn(e,n));const s=g(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function g(o,s,i){const l=vn(o,s),c=Xt(n.stateElement,l),u=El(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)&&se(`[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)&&se(`[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=Mr(s,Tt(c),u);return a.set(c,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=l[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:ae(n),childListPathInfo:ae(r+c+d)};return l[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(vn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,ae(u),null);for(const[e,t]of a)Ct(e,t);return i}function nu(e,t,n,o,s,r,i){xl(n);const a=n.stateElement.recursionRegistry,l=Vd(a.spec,o);null===l&&se(Ui(o,a.spec.recursiveAnchor));const c=Hd(l);Array.isArray(s)||se(Gi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&se(`[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&&se(Gi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&se(Gi(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){Jd(e,n)&&se(`[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&&se(`[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=tu(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(oc(e,u[o],r,t,n),f++);return f}const ou={write(e,t){if(!0!==e.hasRecursion)return hl;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&se(`[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.`),hl},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return hl;if("$getAll"===t)return(t,s)=>{if(qd(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Vd(r.spec,o);null===i&&se(Ui(o,r.spec.recursiveAnchor)),Array.isArray(s)||se(`[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&&se(`[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=tu(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(El(e,a[o],t,n));return l}(o,n,e,t,s);t=eu(e.stateElement,e,t)}return ic(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>qd(t)?nu(o,n,e,t,s,r,i):lc(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&qd(t)){const s=Il(eu(e.stateElement,e,t)),r=ac(o,s,n,e);return El(o,vn(s.pathInfo,r),n,e)}return hl}};let su=!1;function ru(e,t){"string"==typeof t&&0!==t.length||se(`[wcs/recursion-declaration-invalid] ${K} ${e} must be a non-empty string.`);const n=t.split(c);n.some(e=>0===e.length)&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain empty path segments.`),n.length<2&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must name a list element: a property path ending with "${c}${d}" (for example "nodes${c}${d}").`),n[n.length-1]!==d&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must end with "${c}${d}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===d&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must have exactly one "${d}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===J&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain "${J}" — the declaration is what gives "${J}" its meaning.`),isNaN(Number(n[o]))||se(`[wcs/recursion-declaration-invalid] ${K} ${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 iu=new WeakSet;function au(e){return"function"==typeof e.get&&iu.has(e.get)}function lu(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&au(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=ae(o),s=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void Hs(Yt(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=zs(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 cu="[wcs/recursion-declaration-invalid]";class du{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=xc(t);for(const[t,o]of Object.entries(n)){if(!qd(t))continue;"function"==typeof o.set&&se(`${cu} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&se(`${cu} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Vd(e,t);null===n&&se(Ui(t,e.recursiveAnchor)),0===n.length&&se(`${cu} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),Jd(e,Hd(n))&&se(`${cu} "${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}${c}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(qd(t)||au(n))continue;const e=this._matchExpansion(t);null!==e&&se(`${cu} "${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++)Ud(this.spec,e[t].suffix,e[n].suffix)&&se(`${cu} "${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(Gd(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=Kd(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(c);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(c,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!==Qd(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=Qd(this.spec,e.suffix,t);null!==n&&(null!==o&&se(`"${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||au(s)||se(`"${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,iu.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(Yd(e,o)+c+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 lu(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=Xd(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 uu="recursionSpec",fu="recursionRegistry",hu={order:5,validateEarly(e,t,n){const o=function(e){const t=e[K];if(void 0===t)return null;"object"==typeof t&&null!==t||se(`[wcs/recursion-declaration-invalid] ${K} 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&&se(`[wcs/recursion-declaration-invalid] ${K} must declare exactly one anchor; it is empty.`),n.length>1&&se(`[wcs/recursion-declaration-invalid] ${K} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];ru("anchor",o),"string"!=typeof s&&se(`[wcs/recursion-declaration-invalid] ${K} entry "${o}" must map to the repeating sub-path as a string (for example "children${c}${d}").`),ru("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(c)),i=s.slice(0,s.lastIndexOf(c)),a=r+c+J;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(uu,o),n.set(fu,null===o?null:new du(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(fu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",K)},apply(e,t,n){const o=n.get(uu)??null;null!==o&&e.addListPath(o.anchorList)}};let pu=!1;function gu(){pu||(pu=!0,su||(su=!0,ml("recursion",ou)),vl("recursion",hu))}const mu={name:"recursion",install(){gu()}};const yu={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 wu=!1;function bu(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 vu(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 $u(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 xu(e){return e.startsWith("$")}function Su(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 Pu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||se(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||se(`${t} entries must be non-empty strings.`),e.startsWith("$")&&se(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&se(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Iu(e){ll(e);const t=Pu(e,D)??[],n=Pu(e,B)??[],o=xc(e),s=function(e){const t=e[H];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}se(`${D} entry "${e}" is not declared on the state.${de(e,Su(o,"value"))}`)}"function"==typeof t.value&&se(`${D} entry "${e}" is a method. Declare it in ${B} instead.`)}for(const e of n){const t=o[e];void 0===t&&se(`${B} entry "${e}" is not declared on the state.${de(e,Su(o,"method"))}`),"function"!=typeof t.value&&se(`${B} entry "${e}" is not a method. Declare it in ${D} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function Au(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||se(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Je(e);null!==r&&"function"==typeof r.define||se(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&se(`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}=Iu(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,g=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(Z))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=Je(this._shadow);return null!==e&&Xe(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(wu||(wu=!0,ml("dcc",yu)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${D} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=xc(n);for(const[e,t]of Object.entries(m)){if(xu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=$u(e,o)}else n.get=bu(e),n.set=vu(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:bu(e),set:vu(e)});r.define(s,g)}async function Nu(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&se(`"bind-component" cannot be used inside a [${Z}] 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 ol(t);se(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await nl(n,t.tagName.toLowerCase());se(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){se(`DCC: Failed to load state: ${e}`)}}(o,t);Au(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const ku={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Z)?Nu(e,t.host,t):null}};let _u=!1;const Tu=new WeakMap;function Cu(e,t,n){let o=Tu.get(e);void 0===o&&(o=new Map,Tu.set(e,o));const s=o.get(t);null!=s&&se(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function Eu(e,t){if(null===e)return!1;const n=Tu.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+c)||e.startsWith(t+c))return!0;return!1}const Mu=new WeakMap;const Ou=[];function Ru(e,t,n,o){if(t.length>0){const s=n.split(c),r=Ec(t,s);if(null!==r)return o&&r.readonly&&se(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${A}.${r.innerSegments.join(c)}#${y}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${y} from the injection.`),Mc(r,s)}return e+c+n}function ju(e,t,n){for(const e of t){const t=e.outerPathInfo.path;if(n===t)return e.innerSegments.join(c);if(n.startsWith(t+c))return e.innerSegments.join(c)+n.slice(t.length)}return n===e?"":n.startsWith(e+c)?n.slice(e.length+1):null}function Lu(e,t,n=Ou){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](Ru(e,n,s,!1),...r)}return"$setAll"===s?(o,...s)=>t.$setAll(Ru(e,n,o,!0),...s):"$resolve"===s?(o,...s)=>t.$resolve(Ru(e,n,o,s.length>1),...s):t[s]}return t[Ru(e,n,s,!1)]}},set:(o,s,r)=>("string"!=typeof s||(t[Ru(e,n,s,!0)]=r),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Wu=new WeakMap,Du=[];const Bu=new WeakMap,zu=new WeakSet;function Fu(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 qu=null;const Vu=new WeakMap,Hu=new Set;function Uu(e,t,n,o){let s=Vu.get(e);if(void 0===s){if(!o)return null;s=new Map,Vu.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 Gu(e,t){if(!e.component.isConnected)return!1;const n=vt(e.component)?.listIndex??null;if(null===t)return null===n;let o=n;for(;null!==o;){if(o===t)return!0;o=o.parentListIndex}return!1}function Ku(e,t,n,o){const s=Uu(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&&Gu(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?Gu(r,o)&&(null!==a&&se(`[wcs/mount-export-ambiguous] "${t}${c}${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 Ju(e){const t=e.parentStateElement,n=vt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Rt](n,()=>{e.$postUpdate(o.exportedPath)})})}const Xu=new WeakMap;class Yu{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return vn(ae(this.markerParentPath+c+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(Kc(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?Gc(e,t):Kc(e,t),a=Xc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Gc(e,t):Kc(e,t),l=Xc(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 Nl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[Kc(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)||se(`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[Gc(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 Kc(this.record,t),!0}catch{return!1}}}function Qu(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Xu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Xu.set(e,n)),null===t)return n.noIndex??={...e.privateSnapshot};let o=n.byListIndex.get(t);return void 0===o&&(o={...e.privateSnapshot},n.byListIndex.set(t,o)),o}(e,t.listIndex):{};return new Proxy(i,new Yu(e,s,t.listIndex,r,n,o))}function Zu(e){const t=e.parentStateElement,n=(t,n)=>{const o=vt(e.component);let s;return t[Rt](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(Kc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Gc(e,n):Kc(e,n),l=vt(e.component)?.listIndex.indexes??[],c=Xc(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:Kc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Gc(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 Kc(e,n),!0}catch{return!1}}})}function ef(e,t){const n=function(e){return Yc.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&se(`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&&ps(t).dispose(),function(e,t){sd(),Yc.set(e,t),td.set(t,e);let n=Zc.get(t.parentStateElement);void 0===n&&(n=new Map,Zc.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Qc.get(t.component);void 0===o&&(o=new Map,Qc.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&ed.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=wa.get(e);if(void 0!==n){if(n===t)return;se("A state tree is already registered on this root.")}wa.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Jc(e,t,n);ne(t);const o=vt(e.component);Ua(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),da(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=Kc(e,n)}catch{continue}const o=t.indexOf(c+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)+c+r,a=ae(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Uu(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),Sc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=vt(e.component);if(e.delta>0&&null===t)return;const n=e.component.tagName.toLowerCase();for(const o of e.exports.values()){const s=`${n}|${o.exportedPath}`;if(Hu.has(s))continue;const r=ae(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Rt](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Hu.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),Ju(e),o=t,s=Promise.resolve(),ba.set(o,s),s.then(()=>Ia(o),()=>{})}function tf(e,t){const n=ps(t),o=vt(e.component);n.forEachActiveBindingNode(e=>$t(e,o));ca(n.rebindAddresses()),Ju(e)}function nf(e,t){if(function(e){const t=Zc.get(e);return void 0!==t&&t.size>0}(t))for(const n of rd(t)){if(!of(n.component,e))continue;const t=nd(n);null!==t&&tf(n,t)}}function of(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 sf={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=id(e,t.pathInfo.path);if(null!==s)return Qu(s,t,n,o)}return hl},readMissing(e,t,n,o,s){if(null===n){if(Eu(e.rootNode??null,t.pathInfo.path))return;return hl}if(!0===e.hasMounts){const n=Ku(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Qu(e,vn(ae(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return hl},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=Mu.get(e);if(void 0===n||0===n.size)return null;const o=t+c;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&se(`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 hl},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Ku(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Qu(e,vn(ae(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return hl},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=id(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(c,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=Yc.get(n);if(void 0!==e)return e;n=n.parentNode}return Yc.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 Wu.get(e)??Du}(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=ju(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=sn(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(Lu(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>Eu(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){nf(t,e)}};let rf=!1;const af=new WeakMap;function lf(e){let t=af.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},af.set(e,t)),t}function cf(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Tu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function df(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{Cu(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 xa(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function uf(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&se('"mount" requires a non-empty tree path.');const t=ae(e);for(const n of t.segments)0===n.length&&se(`"mount" path "${e}" has an empty segment.`),n===d&&se(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&se(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],s=new Set;for(const r of Re(e)){if(r.propSegments[0]!==A)continue;const e=r.propSegments.slice(1),i=r.statePathInfo,a=e=>se(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> "${r.propName}: ${r.statePathName}": ${e}`);1===e.length&&e[0]&&e[0]!==d&&"$"!==e[0][0]&&"#"!==e[0][0]||a(`inject one key at a time ("${A}.<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!==y)&&a(`an injection accepts only #${y}.`),s.has(e[0])&&a(`"${e[0]}" is injected twice.`),s.add(e[0]),n.push({innerSegments:e,outerPathInfo:i,readonly:r.propModifiers.includes(y)})}return n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&se('"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).`),Cu(s,r,e),xa(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===xa(s)&&function(e,t){const n=()=>{if(null!==xa(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&&cf(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 c=e.connectedRootNode??null;null!==c&&df(e,t,c)?function(e,t,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};if(null!==t)return void yp(t,a);bp(),function(e,t){if(zu.has(e))return void Fu(t);let n=Bu.get(e);void 0===n&&(n=[],Bu.set(e,n)),n.push(t)}(e,a)}(c,xa(c),r,l,a,()=>df(e,t,c),i):a(null)}const ff={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=lf(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{Cu(n,t.mountPath,e),xa(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,mc}return uf(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=lf(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&xa(n)===t.graftInfo.rootStateElement&&pp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==af.get(e)?.initializing)return;const t=e.getAttribute("mount");se(`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){zu.add(e);const t=Bu.get(e);if(void 0!==t){Bu.delete(e);for(const e of t)Fu(e)}}(t)},initializeFailureCleared(e,t){!function(e){zu.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=lf(e);return null!==t.graftInfo&&pp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,cf(e,t)),e.clearConnectedRootNode(),!0}};let hf=!1;const pf=new WeakMap;function gf(e,t){let n=pf.get(e);n||(n=new Set,pf.set(e,n)),n.add(t)}const mf=new WeakMap;const yf=new WeakMap,wf=new WeakMap;const bf=new WeakMap;const vf={isComplete:function(e,t){return!0===pf.get(e)?.has(t)},isDeclared:function(e,t){return!0===mf.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=yf.get(e);o||(o=new Map,yf.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=wf.get(e);o||(o=new Map,wf.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=bf.get(e);s||(s=new Map,bf.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function $f(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 xf=new WeakMap;class Sf{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=xf.get(e);return n?n.get(t)??null:null}(e,t)??se("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 Pf=e=>()=>e;function If(e,t,n,o){!function(e,t,n){let o=xf.get(e);o||(o=new Map,xf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState($f(o));const s=function(e,t){const n=new Sf(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Pf(s),enumerable:!0,configurable:!0}),gf(t,n),Af(t,n)}function Af(e,t){if(W in e){const n=e[W];"function"==typeof n?n.call(e,t).catch(e=>{se(`Error in ${W}: ${e instanceof Error?e.message:String(e)}`)}):se(`${W} is not a function.`)}}const Nf=new Set;function kf(e,t){Nf.has(e)||(Nf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function _f(e){const t=e.rootEntry,n=vt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Rt](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Tf=new WeakMap;function Cf(e,t){e.landInitialization(),se(t)}async function Ef(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?Ge(a):null;null!==a&&null!==l||se(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||Cf(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&&se(`"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=mf.get(e);n||(n=new Set,mf.set(e,n)),n.add(t)}(a,d);const u=Je(a);null===u&&se(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await Ve(a),d in a||se(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||se(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=yf.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=lt(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||(lt(a)??[]).some(e=>e.propSegments[0]===d)||Cf(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=(lt(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=xa(a.getRootNode())??Cf(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,Qc.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(function(e,t,n){const o=bf.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;bf.get(e).delete(t)}}(a,d,f),u=Wc(a,d,o,c,f,function(e,t){return wf.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=_f(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;kf(`${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{ef(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Zu(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),gf(a,d)}return Af(a,d),function(e){const t=Rc.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(J)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;jc.has(n)||(jc.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 Lc(u,"$connectedCallback")}}If(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=Tf.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Tf.set(e,t)),t}(e);return Ef(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Tf.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&tf(n,o)}),Lc(n,"$connectedCallback"),!0},disconnecting(e){const t=Tf.get(e);return void 0!==t&&null!==t.mountRecord&&(Lc(t.mountRecord,"$disconnectedCallback"),Ju(t.mountRecord),e.clearConnectedRootNode(),!0)}};let Of=!1;function Rf(){Of||(Of=!0,bc("bindComponent",Mf),ms=vf)}const jf=new WeakMap,Lf=new Set,Wf=new Set;function Df(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Bf(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function zf(e){return jf.get(e)}function Ff(e){qf(e),jf.delete(e)}function qf(e){Lf.delete(e),Wf.delete(e)}const Vf=new WeakMap,Hf=new WeakMap,Uf=new Set,Gf=new Map;function Kf(e){return Vf.get(e)??Gf}function Jf(e){Uf.add(e),function(e){const t=jf.get(e);void 0!==t&&(Df(t)&&Lf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Wf.add(e))}(e)}const Xf=new Map;function Yf(e){return Hf.get(e)??Xf}function Qf(e){0===e.length&&se(`[wcs/watch-declaration-invalid] ${U} entry name must be a non-empty state path.`),e.startsWith("$")&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not start with "$" (reserved namespace).${ue}`),e.includes("@")&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ue}`),e in Object.prototype&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ae(e);for(const n of t.segments)0===n.length&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" has an empty path segment.${ue}`);return t.wildcardCount>u&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Zf(e,t){const n=t[U];if(void 0===n)return null;"object"==typeof n&&null!==n||se(`[wcs/watch-declaration-invalid] ${U} must be an object mapping state paths to handler functions.${ue}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&se(`[wcs/watch-declaration-invalid] ${U} entry "${t}" must be a function.${ue}`);const n=Qf(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Vf.set(e,t)}(e,o),s.size>0?s:null}let eh=0,th=0;function nh(e){eh=e+1}function oh(){eh=0}function sh(){eh>th&&(th=eh)}const rh=new WeakMap;function ih(e,t,n){let o=rh.get(e);void 0===o&&(o=new Map,rh.set(e,o)),o.set(t,n)}const ah=new Map;function lh(e,t){ah.has(e)||ah.set(e,t)}function ch(e){return ah.get(e)}const dh={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||lh(n,o)},swapped(e,t,n){var o;o=n,ah.has(o)&&lh(t,ch(n))}};function uh(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ds(t))return!0;return!1}function fh(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[jt](vn(t.wildcardParentPathInfos[i],r)),l=zs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=on(o,i,t.wildcardCount);if(l!==c&&!js(l,c)){if(Ds(c))return"gone";s="replaced"}r=l}return s}function hh(e,t,n){const o=new Map;for(const s of n){const n=fh(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 ph=new Set;function gh(e){ph.delete(e)}function mh(){return ph}const yh=Symbol("wcs-stream-last-notified-uncertain"),wh=new WeakMap;function bh(e,t){const n=wh.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function vh(e,t){const n=wh.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:yh,error:Object.is(o.error,null)?null:yh})}const $h=new WeakMap;function xh(e){return $h.get(e)??new Map}function Sh(e){gh(e);const t=$h.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,vh(e,n.name)}const Ph=new WeakSet;let Ih=0;function Ah(e){return zf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Nh(e){if(0===Wf.size)return;if(t=e.absolutePathInfo.stateElement,!Wf.has(t))return;var t;const n=Ah(e);if(void 0!==n)for(const e of n)kh(e)}function kh(e){Ph.has(e)||(Ph.add(e),Ih++)}function _h(e){return!!Ph.delete(e)&&(Ih--,!0)}const Th=/^(?:0|[1-9]\d*)$/;function Ch(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Eh(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&&Th.test(t)&&Ch(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Ch(e,t))?"object":null}function Mh(e,t){const n=Eh(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 Oh(e){return Mh(e,new Map)}function Rh(e,t,n){if(Object.is(e,t))return!0;const o=Eh(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(Eh(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(!Rh(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&Rh(s[e],r[e],n))}function jh(e,t){return Rh(e,t,new Map)}const Lh=new WeakMap;function Wh(e,t){if("function"!=typeof t)return;const n=Lh.get(t);void 0===n?Lh.set(t,new Set([e])):n.add(e)}const Dh={"read-source":e=>`${G} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${G} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${G} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${G} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${G} could not write the output "${e}".`},Bh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function zh(e,t,n){null!==xt&&xt({type:"state:watch-error",phase:t,path:`${G}.${e}`,error:n})}function Fh(e,t,n){console.error(`[@wcstack/state] ${Dh[n](e)}`,t),zh(e,Bh[n],t)}function qh(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Vh(e,t){t.then(void 0,()=>{}),Fh(e,new TypeError(`${G} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Hh=new WeakSet;const Uh=Object.freeze([]);function Gh(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 Kh(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 Jh(e,t){return t.has(e.stateElement)&&!0===zf(e.stateElement)?.entries.has(e.entry)}function Xh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Yh(n,e))||_h(t)}function Yh(e,t){return or().hasQueuedPath(e,t)}function Qh(e,t){!function(e,t,n){if(0!==Ih)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=Ah(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||_h(t)}}(e,t,Yh)}function Zh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function ep(e,t,n){if(!Jh(e,n))return Xh(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(Hh.has(e))return;Hh.add(e);const o=`[wcs/scan-source-computed] ${G} 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}`),zh(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=xh(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:hh(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Kh)){let n;try{n=Zh(t,r,e)}catch(e){Fh(s.name,e,"read-source");continue}const o=a(l,n,ch(e.absAddress),...e.indexes);if(qh(o))return void Vh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){Fh(s.name,e,i.failure)}return i.plan}function tp(e,t){const{group:n}=e;if(!Jh(n,t))return void Xh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||_h(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!jh(o,s.initial):!Object.is(o,e.next)){const o=n.reset?Oh(s.initial):e.next;t[s.name]=o,Wh(s.name,o)}})}catch(e){Fh(s.name,e,"write")}}function np(e,t,n){if(Qh(e,t),0===Lf.size)return Uh;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=zf(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=sn(n.listIndex,r.wildcardCount)}for(const s of i)Gh(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)Gh(o,e,t).reset=!0}if(0===o.size)return Uh;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];nh(n);try{for(const n of s){const o=ep(n,e,t);null!==o&&r.push(o)}}finally{oh()}return r}function op(e){fp(),(0!==Kf(e).size||0!==Yf(e).size||function(e){const t=jf.get(e);return void 0!==t&&Df(t)}(e))&&(Jf(e),function(e){const t=[];for(const n of Kf(e).values())sp(e,n)&&t.push(n);for(const n of Yf(e).values())for(const o of n)sp(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{ih(e,Yt(e,o.pathInfo,null),n[o.path])}catch(t){ip(e,o.path,"prime",t)}})}(e))}function sp(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const rp={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function ip(e,t,n,o){console.error(`[@wcstack/state] $watch ${rp[n]} "${t}" threw.`,o),null!==xt&&xt({type:"state:watch-error",phase:n,path:t,error:o})}function ap(e){const t=Uf;try{if(0===t.size)return void Qh(e,t);const n=function(){const e=th;return th=0,e}();if(n>32){Qh(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!==xt&&xt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){nh(n);try{for(const n of e)tp(n,t)}finally{oh()}}}(np(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=Kf(e).get(s),i=Yf(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=sn(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(cp);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];(uh(o.absAddress.listIndex)||s?.entry===o.entry&&lp(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(hh(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){ip(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);nh(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Kf(e.stateElement).get(e.entry.path)===e.entry,o=!0===Yf(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&dp(e)}}finally{oh()}}(e,t,n)}finally{ah.clear()}}function lp(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function cp(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 dp(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=sp(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 ip(0,n.path,"evaluate",e)}const a=r?function(e,t){return rh.get(e)?.get(t)}(t,o):ch(o);r&&ih(t,o,i),null!==xt&&xt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){ip(0,n.path,"handler",e)}}let up=!1;function fp(){up||(up=!0,ml("watch",dh),vl("watch",hp),Zs(ap,10),Qs(sh))}const hp={order:10,register(e,t){var n;n=e,Uf.delete(n),qf(n),Vf.delete(n),function(e){rh.delete(e)}(e);const o=Zf(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?U:G)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&op(e)},deactivate(e){var t;t=e,Uf.delete(t),qf(t)}};function pp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Lu(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function gp(e,t,n,o){const s=n[U];if(void 0!==s){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(s)){const s=Ru(t,o,a,!1),c=function(e,n,...s){l.call(Lu(t,this,o),e,n,...s)};n.push({path:s,pathInfo:ae(s),handler:c,order:1e6+i++}),r.add(s),e.setPathInfo(s,"prop","watch")}n.length>0&&(!function(e,t){let n=Hf.get(e);void 0===n&&(n=new Map,Hf.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),op(e))}const r=n[X];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(Ru(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[j];"function"==typeof i&&(!function(e,t){let n=Wu.get(e);void 0===n&&(n=[],Wu.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 mp(e,t,n,o=[]){ll(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||se(`Volume "${t}" declares "${o}" as an accessor or a method and also injects it ("${A}.${o}: ${e.outerPathInfo.path}"). Rename one of them.`)}const s=n[U];if(void 0!==s){"object"==typeof s&&null!==s||se(`${U} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(s))"function"!=typeof t&&se(`${U} entry "${e}" must be a function.`),Qf(e)}const r=n[X];if(void 0!==r){"object"==typeof r&&null!==r||se(`${X} 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)&&se(`${X} entry "${n}" must map a list path to a field name or a key function.`);const r=Ru(t,o,n,!1);e.listKeys?.has(r)&&se(`${X} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[H]&&se(`Volume "${t}" declares ${H}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&se(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[K]&&se(`Volume "${t}" declares ${K}, 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(xc(n)))-1!==e.indexOf(J)&&se(`Volume "${t}" declares "${e}", which uses "${J}". 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=ae(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;se(`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+c+o];n=""===n?o:n+c+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;se(`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=Mu.get(e);void 0===n&&(n=new Set,Mu.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+c+n,i=s.get,a=s.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(Lu(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(Lu(t,this,o),e)}),e.defineTreeAccessor(r,l)}gp(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(Lu(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 yp(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=mp(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 wp=!1;function bp(){var e;wp||(wp=!0,rf||(rf=!0,ml("scopes",sf)),hf||(hf=!0,bc("scopes",ff)),Rf(),qu=yp,e=vp,$a.includes(e)||$a.push(e))}function vp(e,t){(function(e){const t=Tu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){zu.delete(e);const n=Bu.get(e);if(void 0===n||0===n.length||null===qu)return;Bu.delete(e);const o=qu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const $p={name:"scopes",install(){bp(),_u||(_u=!0,bc("dcc",ku))}},xp=/^@@wcs-(?:for|if|elseif|else):[^-]/,Sp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,Pp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Ip=/^@@wcs-text-start:(.+)$/;function Ap(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Np extends $c{_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=ad.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=Ap(JSON.stringify(t)),e.appendChild(n);const s=Array.from(Na.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(_i);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=ki(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=Ap(JSON.stringify(t)),e.appendChild(n)}}_i.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Sp.test(e.data)||Pp.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;xp.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=Ip.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;Sp.test(e.data)&&i.push(e)}for(const e of i){const t=Sp.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()}Np.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(xp.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 kp={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",ad),Np.buildContent(o,Np.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const _p=new Set(["for","if","elseif","else"]);function Tp(e){const t=new hs;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]=gt(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 Cp(e,t,n){for(const o of t)"event"===o.bindingType||_p.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in M||ae(o.statePathName).wildcardCount>n||e.push(o)}function Ep(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=Re(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,Ea()],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;za(a),"string"==typeof l&&Wa(a,l),Ua(n,a,l);ka(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Ba(a)})}}const Op={hydrate:async function(e){await fa(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="${ad}". Falling back to full render.`),Np.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=Sp.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=ii(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=Tp(s.nodes);Wr(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");xs(t,r),zr(t,i);const l=[];for(const e of r)e.statePathName in M&&l.push(e);if(Is(t,l),"for"===s.type&&null!==s.index){const i=Ep(e,"for",s.uuid);if(i){const e=Es(null,s.index);yi(i,e,t),wi(i,s.nodes[s.nodes.length-1]),Qr(i,t);const l=ae(s.path+"."+d);Fr(t,vn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Cp(o,r,l.wildcardCount);let c=n.get(s.uuid);c||(c=[],n.set(s.uuid,c)),c.push(e)}}else{const n=Ep(e,s.type,s.uuid);n&&(Qr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Cp(o,r,0))}}for(const[t,o]of n){const n=Ep(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=_a(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=xa(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&qs(t,o)})}return o}(document.body,n);Np.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());Np.restoreTextBindings(document.body);const[i,a]=gt(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||($t(e,null),t.setAttribute("data-wcs-completed",""))}else $t(e,null);const l=[],c=[],u=ps(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(_p.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(d))continue;l.push(e)}for(const e of c)if("for"===e.bindingType){const t=dn(e),n=xa(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(It(t,o),Ct(t,o))})}ca([...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=Np.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Sa(e.rootNode);const t=Np.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",ad),Np.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let Rp=!1;function jp(){var t;Rp||(Rp=!0,ma=Op,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Np)},Nc.includes(t)||Nc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=kp)}())}const Lp={name:"ssr",install(){jp()}},Wp="[wcs/scan-declaration-invalid]",Dp=Object.freeze([]);function Bp(e){return`${G} entry "${e}"`}function zp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Fp(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${d}${d}`)?`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.${ue}`}function qp(e,t,n){0===n.length&&se(`${Wp} ${e} "${t}" must be a non-empty state path.${ue}`),n.startsWith("$")&&se(`${Wp} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ue}`),n.includes("@")&&se(`${Wp} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ue}`),n in Object.prototype&&se(`${Wp} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ue}`);const o=ae(n);for(const s of o.segments)0===s.length&&se(`${Wp} ${e} ${t} "${n}" has an empty path segment.${ue}`);return o.wildcardCount>u&&se(`${Wp} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Vp(e,t,n,o){const s=Bp(e);0===e.length&&se(`${Wp} ${G} entry name must be a non-empty string.${ue}`),(e.includes(c)||e.includes(d))&&se(`${Wp} ${s} must be a flat property name ("${c}" and "${d}" are not allowed). The output is a property the runtime owns.${ue}`),e.startsWith("$")&&se(`${Wp} ${s} must not start with "$" (reserved namespace).${ue}`),e in Object.prototype&&se(`${Wp} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ue}`),t.has(e)&&se(`${Wp} ${s} conflicts with a getter declared on the state.${ue}`),n.has(e)&&se(`${Wp} ${s} conflicts with a setter declared on the state.${ue}`),o.has(e)&&se(`${Wp} ${s} conflicts with the ${H} entry of the same name — each output has exactly one owner.${ue}`)}function Hp(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Lh.get(t)?.has(e)}(e,o)&&se(`${Wp} ${Bp(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ue}`)}function Up(e,t,n,o,s,r){const i=Bp(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&se(`${Wp} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ue}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||se(`${Wp} ${i} "on" must be a non-empty event-token name.${ue}`),n.has(e)||se(`${Wp} ${i} on "${e}" is not declared in ${q}.${de(e,n)}${ue}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&se(`${Wp} ${i} "from" must be a state path string.${ue}`);const u=qp(i,"from",d),f=zp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&se(Fp(i,"from",d,f));const h=zp(u,s);return null!==h&&se(function(e,t,n){return`${Wp} ${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.${ue}`}(i,d,h)),(d===e||d.startsWith(e+c))&&se(`${Wp} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ue}`),{kind:"path",path:d,pathInfo:u}}function Gp(e,t,n,o){if(void 0===t)return Dp;const s=Bp(e);Array.isArray(t)||se(`${Wp} ${s} "resetOn" must be an array of state paths.${ue}`);const r=[];for(const e of t){"string"!=typeof e&&se(`${Wp} ${s} "resetOn" must contain only state path strings.${ue}`);const t=qp(s,"resetOn",e);t.wildcardCount>0&&se(`${Wp} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${ue}`);const i=zp(t,o);null!==i&&se(Fp(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&se(`${Wp} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ue}`),"path"===n.kind&&e.startsWith(n.path+c)&&se(`${Wp} ${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.${ue}`),r.push(e)}return r}function Kp(e,t,n=null){const o=e[G];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&se(`${Wp} ${G} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ue}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(xc(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){ll(e);const t=e[H];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)){Vp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&se(`${Wp} ${Bp(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ue}`);const o=u;Hp(e,a,o);const f=Up(e,o,t,s,i,n);"initial"in o||se(`${Wp} ${Bp(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ue}`),"function"!=typeof o.fold&&se(`${Wp} ${Bp(e)} fold must be a function.${ue}`);const h=Gp(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=ae(e).segments[0];t.has(n)&&se(`${Wp} ${Bp(o.name)} resetOn "${e}" reads the ${G} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ue}`)}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&&se(`${Wp} ${G} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ue}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Jp(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 Ph.has(e)}(e),l=a&&!jh(n,e.initial)?Oh(e.initial):n,c=t(l,o,...s);if(qh(c))return void Vh(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Wh(e.name,c)),a&&_h(e)}catch(t){Fh(e.name,t,i)}}}function Xp(e,t,n){const o=function(e,t){Ff(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Bf(n,e.source.path,e);for(const t of e.resetOn)Bf(o,t,e),"event"===e.source.kind&&Bf(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return jf.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)&&or().hasQueuedPath(e,n))&&kh(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 Yp="scanEntries",Qp={order:8,validate(e,t,n){const o=Kp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Yp,o)},applyEarly(e,t,n){const o=n.get(Yp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=Oh(n.initial);e[n.name]=t,Wh(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Rn(e,n.source.tokenName).subscribe(Jp(n))}(e,o))},register(e,t,n){const o=n.get(Yp)??null,s=function(e){const t=new Map,n=zf(e);if(void 0!==n)for(const e of n.entries)_h(e)&&t.set(e.name,e.resetOn);return Ff(e),t}(e);e.setScanPaths?.(null===o?null:Xp(e,o,s))}};let Zp=!1;const eg=Object.freeze([]),tg=Object.freeze([]);function ng(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??eg,i=e.dynamicDependency.get(n)??eg,a=t.byFromPath.get(n)??tg;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const og=(e,t)=>t,sg=new Set;function rg(e,t){ll(t);const n=t[H];if(void 0===n)return void bh(e,sg);"object"==typeof n&&null!==n||se(`${H} 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&&se(`${H} entry name must be a non-empty string.`),s.includes(c)&&se(`${H} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.includes(d)&&se(`${H} entry "${s}" must be a flat property name ("${d}" is not allowed).`),s.startsWith("$")&&se(`${H} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&se(`${H} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&se(`${H} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&se(`${H} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||se(`${H} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&se(`${H} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&se(`${H} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&se(`${H} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&se(`${H} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??og,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){$h.set(e,t)}(e,o),bh(e,new Set(o.keys()))}const ig=new WeakMap,ag=new WeakMap;function lg(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=xh(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&xh(e).has(n),ownKeys:()=>Array.from(xh(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=xh(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){se(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){se(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function cg(e){const t=ig.get(e);if(void 0!==t)return t;const n=lg(e,Y,e=>e.status);return ig.set(e,n),n}function dg(e){const t=ag.get(e);if(void 0!==t)return t;const n=lg(e,Q,e=>e.error);return ag.set(e,n),n}function ug(e){ig.delete(e),ag.delete(e)}let fg=null;function hg(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 pg={read(e,t){!function(e,t){null!==fg&&fg.add(Xt(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===Y?hg(cg(e),t.pathInfo.segments):n===Q?hg(dg(e),t.pathInfo.segments):hl},get:(e,t)=>t===Y?cg(e.stateElement):t===Q?dg(e.stateElement):hl};async function gg(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 mg(e){Sg();const t=xh(e);if(0!==t.size){!function(e){ph.add(e)}(e);for(const n of t.values())yg(e,n)}}function yg(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=fg,s=new Set;let r;fg=s;try{e.createState("readonly",e=>{r=n(e)})}finally{fg=o}r instanceof Promise&&se(`${H} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${Y}${c}${t.name}`,a=`${Q}${c}${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||se(`${H} 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&&se(`${H} 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=zf(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=ng(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&se(`[wcs/scan-feedback-loop] ${H} entry "${t.name}" args read "${n}", which is derived from the ${G} 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}),wg(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(){wg(e,t,"done",null)},fail(o){wg(e,t,"error",o),n.abort()}};gg(s.source,o,n.signal,r)}function wg(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return wh.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=wh.get(e);void 0===s&&(s=new Map,wh.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${Y}${c}${t.name}`),i&&e.$postUpdate(`${Q}${c}${t.name}`)}))}function bg(e){const t=mh();if(0===t.size)return;const n=[];for(const o of t)for(const t of xh(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)&&xh(e).get(o.name)===o)try{yg(e,o)}catch(n){o.controller?.abort(),t.has(e)&&xh(e).get(o.name)===o&&wg(e,o,"error",n)}}let vg=!1;const $g=new WeakMap,xg={order:20,apply(e,t){var n;ug(e),Sh(n=e),gh(n),$h.delete(n),rg(e,t),void 0!==t[H]&&e.attachAddressHooks?.("streams",H)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return mg(e),void $g.set(e,e.connectGeneration??0)}n===e.connectGeneration&&$g.get(e)!==n&&mg(e)}},deactivate(e){Sh(e),ug(e)}};function Sg(){vg||(vg=!0,ml("streams",pg),vl("streams",xg),Zs(bg,20))}const Pg=[Fd,{name:"temporal",install(){fp(),Zp||(Zp=!0,vl("scan",Qp),Qs(Nh)),Sg()}},mu,$p,Lp,bd,Td];function Ig(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(Pg),Tc(e,t)}function Ag(e){return e}const Ng={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"ブール値を反転",hasArgs:!1,resultType:"boolean",acceptTypes:["boolean"],minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},add:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},sub:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},toFixed:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},upper:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lower:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},capitalize:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},padStart:{description:"先頭を埋める (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},padEnd:{description:"末尾を埋める (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},repeat:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},reverse:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator])",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},time:{description:"ロケール形式の時刻",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},datetime:{description:"ロケール形式の日時",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},ymd:{description:"YYYY-MM-DD 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},coalesce:{description:"null / undefined の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},nullIfEmpty:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},kg=1;function _g(){return{version:1,syntax:{bindAttribute:o.bindAttributeName,tagName:o.tagNames.state,pathDelimiter:c,wildcard:d,delimiters:{binding:";",propValue:":",modifier:h,filter:p},structuralDirectives:Array.from(fe),modifiers:{flags:w,keyValue:$,eventNamePrefix:P},indexParam:{prefix:C,maxDepth:u},bindingTypes:{elseKeyword:x,spread:S,eventPropertyPrefix:P,explicitPropertyPrefix:c,propNamespaces:{eventToken:I,command:N,class:k,attr:_,style:T}}},filters:Object.keys(Dd),filterMeta:Ng,filterAliases:Rd,reservedLifecycle:[O,R,j,L,W],reservedStateApi:[D,B,z,F,q,V,H,U,G,X,K,Y,Q]}}const Tg=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),Cg=Object.freeze([]);function Eg(e){if(!o.enableContractAnalyzer)return Cg;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))Tg.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?Mg(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,Og,e=>{t.push(e),null!==xt&&xt(e)}),t}function Mg(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function Og(e){const t=Je(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{Np as Ssr,Ti as TRUSTED_TYPES_POLICY_SLOT,ad as VERSION,kg as WCS_MANIFEST_VERSION,Eg as analyzeContract,Ig as bootstrapState,ha as buildBindings,Ng as builtinFilterMeta,Ag as defineState,Sa as getBindingsReady,s as getConfig,Ci as getTrustedTypesPolicy,_g as getWcsManifest,Ei as setTrustedTypesPolicy};
2
2
  //# sourceMappingURL=index.esm.js.map