@wcstack/state 3.3.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +94 -27
- package/README.md +94 -27
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.d.ts +52 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/split/chunks/binder.js +1 -1
- package/dist/split/chunks/binder.js.map +1 -1
- package/dist/split/chunks/checkDependency.js +1 -1
- package/dist/split/chunks/checkDependency.js.map +1 -1
- package/dist/split/chunks/declarationAliases.js.map +1 -1
- package/dist/split/chunks/diagnosticsHooks.js.map +1 -1
- package/dist/split/chunks/featureBridge.js +1 -1
- package/dist/split/chunks/filterRegistry.js +1 -1
- package/dist/split/chunks/filterRegistry.js.map +1 -1
- package/dist/split/chunks/getAllPropertyDescriptors.js +1 -1
- package/dist/split/chunks/lifecycleHooks.js +1 -1
- package/dist/split/chunks/lifecycleHooks.js.map +1 -1
- package/dist/split/chunks/pathDiagnostics.js +1 -1
- package/dist/split/chunks/pathDiagnostics.js.map +1 -1
- package/dist/split/chunks/registerComponents.js +1 -1
- package/dist/split/chunks/registerComponents.js.map +1 -1
- package/dist/split/chunks/setAll.js +1 -1
- package/dist/split/chunks/setAll.js.map +1 -1
- package/dist/split/chunks/version.js +1 -1
- package/dist/split/core.d.ts +77 -1
- package/dist/split/core.js +1 -1
- package/dist/split/features/devtools.js +1 -1
- package/dist/split/features/devtools.js.map +1 -1
- package/dist/split/features/diagnostics.js +1 -1
- package/dist/split/features/diagnostics.js.map +1 -1
- package/dist/split/features/formats.js +1 -1
- package/dist/split/features/formats.js.map +1 -1
- package/dist/split/features/recursion.js +1 -1
- package/dist/split/features/recursion.js.map +1 -1
- package/dist/split/features/scopes.js +1 -1
- package/dist/split/features/scopes.js.map +1 -1
- package/dist/split/features/ssr.js +1 -1
- package/dist/split/features/ssr.js.map +1 -1
- package/dist/split/features/temporal.js +1 -1
- package/dist/split/features/temporal.js.map +1 -1
- package/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",k="state",A="command",N="class",_="attr",T="style",E="$",C={};for(let e=0;e<u;e++)C[`${E}${e+1}`]=e;const M=Object.freeze(C),O="$connectedCallback",R="$disconnectedCallback",j="$renderedCallback",L="$errorCallback",D="$stateReadyCallback",W="$bindables",B="$commands",z="$commandTokens",F="$command",q="$eventTokens",V="$on",H="$stream",K="$watch",U="$scan",G="$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);if(void 0!==t)return 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.`);const n=function(e){let t=1;for(let n=0;n<e.length;n++)e[n]===c&&t++;return t}(e);return n>512&&se(`[wcs/binding-syntax] "${e}" has ${n} path segments — the limit is 512. Every prefix of a path is interned, so the cost grows with the square of the depth.`),t=Object.freeze(new 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"]);function he(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}function pe(e){if(0===e.length)return"";let t="";for(let n=0;n<e.length;n++){const o=e[n];n>0&&(t+="|"),t+=`${o.filterName}(${he(o.args,o.literals??o.args)})`}return t}const ge=new Map([["not",()=>e=>!e]]),me=new Map([["not",[0,0]]]),ye={input:new Map,output:new Map},we={input:new Map,output:new Map},be={input:new Map,output:new Map},ve=new Map;function $e(e,t,n,o){const s=ye[e],r=we[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}const i=o??{},a=be[e];for(const[e,n]of[...a])Object.prototype.hasOwnProperty.call(t,n)&&i[e]!==n&&a.delete(e);for(const e of Object.keys(i))a.set(e,i[e]);ve.clear()}function xe(e,t,n,o=t){const s=be[n].get(e)??e,r=`${s}${he(t,o)}:${n}`,i=ve.get(r);if(void 0!==i)return i;const a=ye[n].get(s)??ge.get(s);if(void 0===a){const t=0===ye[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";se(`[wcs/filter-unknown] filter not found: ${e}.${de(e,function(e){return[...new Set([...ge.keys(),...ye[e].keys()])]}(n))}${t}${ue}`)}const l=we[n].get(s)??me.get(s);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 ve.set(r,c),c}function Se(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const Pe=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function Ie(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:Pe.test(e)?Number(e):e)}function ke(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=Se(o,i,a);t.push(e),n.push(Ie(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=Se(o,i,a);return(c||r)&&(t.push(c),n.push(Ie(c,r))),{args:t,literals:n}}const Ae=e=>e.trim(),Ne=e=>"'"===e||'"'===e;function _e(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if(Ne(s))n=s;else if(s===t)return o}return-1}function Te(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):Ne(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}function Ee(e,t,n){const o=n??e.join("|");return e.map(e=>{const n=_e(e,"(");let s=function(e,t){let n=null,o=-1;for(let s=0;s<e.length;s++){const r=e[s];null!==n?r===n&&(n=null):Ne(r)?n=r:r===t&&(o=s)}return o}(e,")");if(-1===s&&(s=e.lastIndexOf(")")),-1!==n&&-1===s&&se(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${e}".${ue}`),-1!==s&&-1===n&&se(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${e}".${ue}`),-1!==s&&s<n&&se(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${e}".${ue}`),-1!==s&&e.slice(s+1).trim().length>0){const t=e.slice(s+1).trim();se(`[wcs/binding-syntax] "${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,s+1)}|${t}").${ue}`)}const r=(-1===n?e:e.substring(0,n)).trim();if(0===r.length&&se(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${ue}`),r.includes(h)){const[e,n]=r.split(h);se("input"===t?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${h}${n}" comes before the input filters, not inside one — write "<property>${h}${n}|${e}".${ue}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${h}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${e}" here.${ue}`)}if(-1===n)return{filterName:r,args:[],literals:[]};return{filterName:r,...ke(e.substring(n+1,s))}})}const Ce=new Map;function Me(e){const t=_e(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=Te(s,p).map(Ae),r=Ee(o,"input",e),Ce.set(s,r))):n=e.trim();const i=n.split(h).map(Ae);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(Ae);d.length>1&&""===d[0]||0!==a.length&&!d.some(e=>0===e.length)||se(`[wcs/binding-syntax] "${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${ue}`);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(Ae):[],inFilters:r}}const Oe=new Map;function Re(e){const t=_e(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Oe.has(s)?r=Oe.get(s):(o=Te(s,p).map(Ae),r=Ee(o,"output",e),Oe.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.`);const i=n,a=i.startsWith(c),l=a?i.slice(1):i;(l.length>0&&l.split(c).some(e=>0===e.length)||!a&&0===l.length)&&se(`[wcs/binding-syntax] "${e}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).${ue}`);return{statePathName:i,statePathInfo:ae(i),outFilters:r}}const je=new Set([x,"if","elseif","for",S]),Le=new Set([N,_,T,A,I,k]);function De(e){const[...t]=function(e){return Te(e,";")}(e).map(Ae).filter(e=>e.length>0),n=t.map(e=>{const t=_e(e,":");-1===t&&se(`[wcs/binding-syntax] Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.${ue}`);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&&je.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){0===o.length&&se(`[wcs/binding-syntax] Invalid spread binding "${e}": spread target path is required.${ue}`);const t=Re(o);return t.outFilters.length>0&&se(`[wcs/binding-syntax] Invalid spread binding "${e}": filters are not allowed on spread targets.${ue}`),{propName:S,propSegments:[S],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Re(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Re(o);return{...Me(n),...e,bindingType:s}}{const e=Re(o),t=Me(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Le.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 (${[...Le].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 We=new WeakMap,Be=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),ze=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Fe(e){const t=We.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=ze.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Be.has(r)?(We.set(e,s[2]),s[2]):null}function qe(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Re(e),bindingType:"text"}}const Ve=new WeakMap,He=new WeakSet;let Ke=0;async function Ue(e){const t=function(e){let t,n=Ve.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++Ke,promise:o,resolve:t},Ve.set(e,n),He.has(e)&&n.resolve(),n}(e);await t.promise}function Ge(e){const t=Ve.get(e);void 0===t?He.add(e):t.resolve()}const Je=new WeakMap;function Xe(e){const t=Je.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{Je.set(e,n)}}function Ye(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Qe(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Ye(t);if(void 0!==n)return Ye(n)}return Ye(globalThis.customElements)}function Ze(e,t){e.upgrade?.(t)}function et(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=st(s.properties,tt);if(null===r)return null;const i=void 0===s.inputs?new Map:st(s.inputs,nt);if(null===i)return null;const a=void 0===s.commands?new Map:st(s.commands,ot);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function tt(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 nt(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 ot(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 st(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 rt(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ae(n),inFilters:[],outFilters:[],bindingType:"prop"}}function it(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function at(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=Xe(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=Qe(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}Ze(a,t);const l=et(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=rt(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=rt(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=it(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=it(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 lt(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 ct(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:xe(s.filterName,s.args,t,r)})}return n}function dt(e){return{...e,inFilters:ct(e.inFilters,"input"),outFilters:ct(e.outFilters,"output")}}const ut=new WeakMap;function ft(e){return ut.get(e)||null}function ht(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function pt(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!ht(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function gt(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 mt(e){const t=[],n=pt(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!==Fe(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&>(e,n)||t.push(e)}return t}const yt=new WeakSet;function wt(e,t,n,o){const s=at(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Xe(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}}}yt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=ct(o.inFilters,"input"),s=ct(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){ut.set(e,t)}(e,r),Ge(e),{bindings:r,deferred:null}}function bt(e,t){const n=mt(e),o=[],s=[];for(const e of n){if(yt.has(e))continue;const n=wt(e,Ua(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function vt(e){yt.add(e)}function $t(e){const{node:t,parseResults:n,transform:o}=e;!function(e){yt.delete(e)}(t);return wt(t,n,{allowDeferred:!1},o).bindings}const xt=new WeakMap;let St=null;function Pt(e){let t=e;for(;t;){const e=xt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==St&&t instanceof ShadowRoot&&(n=St(t)),t=n}return null}function It(e,t){null!==t?xt.set(e,t):xt.delete(e)}let kt=null;const At=new WeakMap;function Nt(e){return At.get(e)??[]}function _t(e,t){At.set(e,t)}function Tt(e){return At.has(e)}const Et=new WeakMap;let Ct=null,Mt=0;function Ot(e){return Et.get(e)??[]}function Rt(e,t){null===Ct?Et.set(e,t):Ct.set(e,t)}function jt(){Mt++,null===Ct&&(Ct=new Map)}function Lt(){if(0!==Mt&&(Mt--,!(Mt>0||null===Ct))){for(const[e,t]of Ct)Et.set(e,t);Ct=null}}function Dt(e){return(Ct?.has(e)??!1)||Et.has(e)}const Wt=Symbol("$$setLoopContext"),Bt=Symbol("$$getByAddress"),zt=Symbol("$$hasByAddress"),Ft=Symbol("$$connectedCallback"),qt=Symbol("$$disconnectedCallback"),Vt=Symbol("$$updatedCallback"),Ht=Symbol("$$errorCallback"),Kt=new WeakMap,Ut=new WeakMap;class Gt{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Jt(e,t){if(null===t){let t=Ut.get(e);return void 0!==t||(t=new Gt(e,null),Ut.set(e,t)),t}{let n=Kt.get(t);void 0===n&&(n=new WeakMap,Kt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Gt(e,t),n.set(e,o)),o}}const Xt=new WeakMap;function Yt(e,t){let n=Xt.get(e);void 0===n&&(n=new Map,Xt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Qt(e,t)),n.set(t,o)),o}class Qt{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Zt(e,t){return Jt(Yt(e,t.pathInfo),t.listIndex)}function en(e,t,n){return Jt(Yt(e,t),n)}const tn=new WeakMap;function nn(e,t){null===t?tn.delete(e):tn.set(e,t)}function on(e){return tn.get(e)||null}const sn=new Map;function rn(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=sn.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,sn.set(s,r),r}function an(e,t,n){return t<0||t>=n?null:e.at(t-n)}function ln(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const cn=new WeakMap;function dn(e){const t=Pt(e.node);if(null===t)return null;let n=cn.get(t);if(void 0===n)n=new WeakMap,cn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=rn(t.pathInfo,e.statePathInfo);return n>0&&(o=an(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const un=new WeakMap;function fn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=on(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 hn(e,t){let n=null;if(n=un.get(e)||null,null!==n)return n;const o=fn(e,t),s=dn(e),r=Wa(o);return null===r&&se("No state tree found on this root for binding."),n=en(r,e.statePathInfo,s),un.set(e,n),n}function pn(e){un.delete(e)}const gn=new WeakMap;function mn(e,t){const n=gn.get(e);void 0===n?gn.set(e,t):n instanceof Set?n.add(t):n!==t&&gn.set(e,new Set([n,t])),null!==kt&&kt({type:"state:binding-added",absoluteAddress:e,binding:t})}function yn(e,t){const n=gn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&gn.delete(e),null!==kt&&kt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const wn=new WeakMap;function bn(e){const t=gn.get(e);return void 0!==t?t:null!==e.listIndex?wn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const vn=new WeakMap,$n=new WeakMap;class xn{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=Sn(e,t)}}function Sn(e,t){if(null===t){let t=$n.get(e);return void 0!==t||(t=new xn(e,null),$n.set(e,t)),t}{let n=vn.get(t);void 0===n&&(n=new WeakMap,vn.set(t,n));let o=n.get(e);return void 0!==o||(o=new xn(e,t),n.set(e,o)),o}}const Pn=new WeakMap;function In(e){let t=null;if(t=Pn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=dn(e);null===n&&se(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=Sn(e.statePathInfo,n)}else t=Sn(e.statePathInfo,null);return Pn.set(e,t),t}function kn(e){Pn.delete(e)}function An(){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 Nn=new Map,_n=An();function Tn(e,t){const n=pe(e.inFilters);return`${e.statePathName}::${t}::${n}`}function En(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function Cn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=En(e),s=Tn(e,o);let r=Nn.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=Wa(o.getRootNode());null===i&&se("No state tree found on this root for two-way binding.");const a=Pt(o);i.createState("writable",e=>{e[Wt](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]:[]})})},Nn.set(s,r)),e.node.addEventListener(o,r),_n.add(s,e),!0}var t,n;return!1}function Mn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function On(e,t){console.error(`[wcstack/state] ${t} rejected.`,e)}function Rn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Mn(e)&&Promise.resolve(e).catch(e=>On(e,t))}class jn{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,e)}return t}}class Ln extends jn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==kt&&kt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Dn=new WeakMap;function Wn(e,t){let n=Dn.get(e);void 0===n&&(n=new Map,Dn.set(e,n));let o=n.get(t);return void 0===o&&(o=new Ln(t,e),n.set(t,o)),o}const Bn=new WeakMap;function zn(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Xe(t),o=Qe(t);if(null!==n&&void 0===o?.get(n))return null===o&&se(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Bn.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===Xe(e)?null:et(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=Wa(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=Pt(t);n.createStateAsync("writable",async t=>{Rn(t[Wt](o,()=>{const s=null!==o?ln(o.listIndex,o.pathInfo.wildcardCount):[];return Wn(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Bn.set(e,{eventName:a,handler:d}),!0}class Fn extends jn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==kt&&kt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function qn(e){return e instanceof Fn}const Vn=new Map,Hn=An();function Kn(e){const t=e.propModifiers.filter(e=>e===g||e===m).sort().join(",");return`${e.statePathName}::${t}`}const Un=(e,t,n)=>o=>{t.includes(g)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Wa(r);null===i&&se("No state tree found on this root for event handler.");const a=Pt(s),l=e.startsWith(F+".");i.createStateAsync("writable",async t=>{const c=t[Wt](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?ln(a.listIndex,c):[];if(l){const s=t[Bt](Sn(n,null));return qn(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])});Rn(c,`"${e}"`)}).catch(t=>On(t,`"${e}"`))};function Gn(e){return"event"===e.bindingType&&e.propName.startsWith(P)}function Jn(e){if(!Gn(e))return!1;const t=Kn(e);let n=Vn.get(t);void 0===n&&(n=Un(e.statePathName,e.propModifiers,e.statePathInfo),Vn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Hn.add(t,e),!0}function Xn(e){if(!Gn(e))return!1;const t=Kn(e),n=Vn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Hn.countOf(t)&&(Hn.remove(t,e)&&Vn.delete(t),!0)}const Yn=new Map,Qn=An();function Zn(e,t){const n=pe(e.inFilters);return`${e.statePathName}::${t}::${n}`}function eo(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function to(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=eo(e),s=Zn(e,o);let r=Yn.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=Wa(o.getRootNode());null===r&&se("No state tree found on this root for two-way binding.");const i=Pt(o);r.createState("writable",e=>{e[Wt](i,()=>{e[t]=s})})},Yn.set(s,r)),e.node.addEventListener(o,r),Qn.add(s,e),!0}var t,n;return!1}const no=new Set(["radio","checkbox"]),oo=new Set(["value","valueAsNumber","valueAsDate"]);function so(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(no.has(e)&&"checked"===t)return!0;if(oo.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Xe(n);if(null!==s){const e=Qe(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=et(n);if(o?.knownProperties.has(t))return!0}return!1}let ro=1,io=1,ao=1;const lo=new WeakMap;function co(e,t,n){let o=lo.get(e);void 0===o&&(o=new Map,lo.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=ro++,o.set(s,r)),r}function uo(e,t){return"to-element"===t?2*e:2*e+1}const fo=new Set;function ho(e){return{transactionId:io++,originBindingId:e,visitedEdges:fo,hop:0}}function po(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let go=null;function mo(){return go}function yo(e,t){const n=go;go=e;try{return t()}finally{go=n}}const wo=[];let bo=!1;const vo=new Map,$o=An(),xo=new WeakMap,So=e=>e.detail,Po=new WeakMap;const Io=new WeakMap;let ko=0;const Ao=new WeakMap;function No(e,t,n,o){const s=pe(e.inFilters);return`${e.propName}::${e.statePathName}::${t}::${s}::${function(e){if(null===e)return"n";let t=Io.get(e);return void 0===t&&Io.set(e,t=++ko),`g${t}`}(n)}::${o?"o":"s"}`}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!==So||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=Po.get(e);void 0===r&&(r=new Set,Po.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=xo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=co(a,e,t),s=function(e,t){for(let n=wo.length-1;n>=0;n--){const o=wo[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==kt&&kt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:uo(n,"to-state"),node:a,member:e}));const r=uo(n,"to-state"),i=mo();if(null!==i&&i.visitedEdges.has(r))return void(null!==kt&&kt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=po(i??ho(n),r)}const f=Wa(a.getRootNode());null===f&&se("No state tree found on this root for two-way binding.");const h=Pt(a),p=()=>{r&&(bo=!0);try{f.createState("writable",e=>{e[Wt](h,()=>{e[t]=c})})}finally{r&&(bo=!1)}};null!==u?yo(u,p):p()};function To(e){const t=Xe(e.node);if(null!==t){const n=Qe(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&se(`CustomElementRegistry is unavailable for <${t}>.`))}if(so(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Xe(e.node);if(null!==n){const o=Qe(e.node)?.get(n);void 0===o&&se(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=et(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}(e),n=function(e){if(null!==Xe(e.node)){const t=et(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??So}return null}(e),o=function(e){if(null===Xe(e.node))return!1;const t=et(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}(e),s=No(e,t,n,o);Ao.set(e,{key:s,eventName:t});let r=vo.get(s);void 0===r&&(r=_o(e.propName,e.statePathName,e.inFilters,n,o),vo.set(s,r)),e.node.addEventListener(t,r),$o.add(s,e)}}const Eo=new WeakSet;function Co(e){Eo.add(e)}function Mo(e){return!!Eo.has(e)&&(Eo.delete(e),!0)}const Oo=new WeakMap;function Ro(e,t){const n=Oo.get(e);return!(void 0===n||n<t)&&(n===t?Oo.delete(e):Oo.set(e,n-t),!0)}const jo=new WeakSet;function Lo(e){jo.add(e)}function Do(e){return!!jo.has(e)&&(jo.delete(e),!0)}let Wo=0;function Bo(){Wo--}function zo(){return Wo>0}class Fo{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 qo=new WeakMap;function Vo(e){let t=qo.get(e);return void 0===t&&(t=new Fo(e),qo.set(e,t)),t}const Ho=new Set([N,_,T,A]);function Ko(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 Uo(e){return e.propModifiers.some(e=>e.includes("="))}const Go=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Jo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Xo(e,t){return"state"===e&&"call"===t?Go:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Yo(e){if(!o.enableDirectionalInitialSync)return Uo(e)&&se("init=/sync= modifiers require enableDirectionalInitialSync."),Go;const t=null===(n=Ko(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}".`)}(Ko(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&se("Event bindings only allow init=none."),"call"===s?Jo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(Ho.has(e.propSegments[0]))return Xo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&se(`Binding type "${e.bindingType}" does not support init=${t}.`),Xo(t??"state",s);const r=et(e.node);if(null===r)return Xo(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 Qo(e,t){return"auto"!==t?t:function(e){const t=Wa(e.replaceNode.getRootNode());null===t&&se("No state tree found on this root for binding.");const n=In(e);let o=!1;return t.createState("readonly",e=>{o=e[zt](n)}),o}(e)?"state":"element"}let Zo=0,es=0;const ts=["active","disposed","failed"],ns=new WeakMap,os=new WeakMap,ss=new WeakMap,rs=new WeakMap,is=new WeakMap,as=new WeakMap;function ls(e,t){const n=as.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):as.set(e,new Set([n,t]))):as.set(e,t)}function cs(e){return as.has(e)}function ds(e,t){const n=as.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function us(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))us(n,t)}function fs(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class hs{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||!Ro(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)Mo(e)||us(e,e=>{ds(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Do(e)&&!zo()||us(e,e=>{ds(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&Ia(o)}}const ps=new WeakMap;function gs(e){let t=ps.get(e);return void 0===t&&(t=new hs(e),ps.set(e,t)),t}function ms(e){const t=pe(e.inFilters),n=pe(e.outFilters);return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function ys(e,t,n){const o=Wa(fn(e,n));null===o&&se("No state tree found on this root for binding.");const s=Yt(o,e.statePathInfo);return function(e,t,n){let o=wn.get(e);void 0===o&&(o=new WeakMap,wn.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!==kt&&kt({type:"state:binding-added",absoluteAddress:Jt(e,t),binding:n})}(s,t,e),s}function ws(e,t){const n=hn(e,t);return mn(n,e),n}function bs(e,t,n,o){null!==t?yn(t,e):function(e,t,n){const o=wn.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!==kt&&kt({type:"state:binding-removed",absoluteAddress:Jt(e,t),binding:n}))}(n,o,e),kn(e),pn(e)}function vs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class $s{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=ss.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(fs(t)&&gs(t),null===this.rowPlan)for(const n of e){const e=ss.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 Uo(e)&&Yo(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=ss.get(e);return void 0===n||n.session!==this||(!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority)))}getRecord(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0){let o=os.get(t);void 0===o&&os.set(t,o=[]);return{id:o[n]??(o[n]=++Zo),info:e,generation:t.generation,phase:ts[t.phases[n]],teardowns:null}}const o=ss.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=ss.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(vs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Qe(e);null===s&&se(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),ls(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=Vo(s).wait(t,()=>{if(a())try{Ze(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=ss.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&&(yn(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&&(yn(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?hn(n):null;if(bs(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=hn(n);e!==o&&Tt(o)&&_t(e,Nt(o)),e!==o&&Dt(o)&&Rt(e,Ot(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return fs(t)?t:null}(e);null!==t&&gs(t)}handleMutations(e,t,n){for(const n of t)us(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)us(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=ss.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=is.get(t);void 0===e&&(e=ms(t),is.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;ls(n,this);const o=this.knownMapFor(n);let s=is.get(e);void 0===s&&(s=ms(e),is.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:++Zo,session:this,generation:++es,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(ls(r,this),this.addKnownRowBinding(r,o,e),ns.set(o,s),n[e].isEvent){let t=!1;try{t=Jn(o)}catch(t){throw s.phases[e]=2,t}t&&(s.flags[e]|=2)}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++es,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){let n=!1;try{n=Jn(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}n&&(o.flags[e]|=2)}this.registerRowSlot(o,e,n)}}rowOf(e){const t=ns.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=dn(o);null!==s?(e.patternPathInfos[t]=ys(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=ws(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(bs(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{Xn(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:++Zo,info:e,generation:++es,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};ss.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;Jn(t)?e.eventAttached=!0:t.propSegments[0]!==I?(to(t)&&vs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=eo(e),n=Zn(e,t),o=Yn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Qn.countOf(n)&&(Qn.remove(n,e)&&Yn.delete(n),!0))}return!1}(t)),Cn(t)&&vs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=En(e),n=Tn(e,t),o=Nn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==_n.countOf(n)&&(_n.remove(n,e)&&Nn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&so(t.node,t.propName)&&-1===t.propModifiers.indexOf(y)){const n=function(e,t,n){let o=xo.get(e);void 0===o&&(o=new Map,xo.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&xo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});vs(e,n)}To(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{zn(t)&&vs(e,()=>function(e){if(e.propSegments[0]!==I)return!1;const t=Bn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Bn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Xe(e.info.node);if(null===n)return void t();const o=Qe(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=Vo(o).wait(n,()=>{if(this.isAlive(e,s))try{Ze(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))});vs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Yo(e.info),n=Qo(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void Wo++;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,Bo()),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=Wa(e.node.getRootNode());null===o&&se("No state tree found on this root for initial binding sync.");const s=Pt(e.node);o.createState("writable",t=>{t[Wt](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=dn(n);if(null!==o?(e.patternPathInfo=ys(n,o,t),e.patternListIndex=o):e.address=ws(n,t),!e.options.registerPathInfo)return;const s=Wa(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&&ss.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,Bo());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{bs(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=Ao.get(e);if(void 0===t)return;Ao.delete(e);const n=vo.get(t.key);void 0!==n&&(e.node.removeEventListener(t.eventName,n),$o.remove(t.key,e)&&vo.delete(t.key))}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{Xn(t)}catch{}}}}function xs(e){let t=rs.get(e);return void 0===t&&(t=new $s(e),rs.set(e,t)),t}function Ss(e){return ss.get(e)?.session??ns.get(e)?.session??null}let Ps=null;function Is(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ks=Object.freeze([]);const As=new WeakMap;const Ns=new WeakMap;function _s(e){return Ns.get(e)??[]}function Ts(e,t){Ns.set(e,t)}const Es=new WeakMap;function Cs(e){return Es.get(e)??[]}function Ms(e,t){Es.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 Os=0;function Rs(){return`u${(Os++).toString(36)}`}let js=0,Ls=0;const Ds=Symbol("wcs.listIndex.noValue");class Ws{uuid=Rs();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=Ds,this._index=t,this._version=js,this._chainGeneration=Ls}get index(){return this._index}set index(e){this._index=e,this._version=++js,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=js),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Ls||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Ls),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++js,Ls++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Bs(e,t,n=e){return new Ws(e,t,n)}function zs(e,t){e.reparent(t)}function Fs(e){return e.homeParentListIndex}function qs(e,t){e.value=t}function Vs(e,t){const n=e.value;return n!==Ds&&n===t.value}const Hs=new WeakMap,Ks=new WeakSet;function Us(e){return Ks.has(e)}function Gs(e,t){const n=Fs(e),o=e.parentListIndex;return null===n||n===o||Ks.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Ks.has(e)&&!Ks.has(n)&&n.position===e.position&&Vs(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Ks.has(e)&&!Ks.has(t)}(o,t)?t:null:n}function Js(e){const t=Hs.get(e);return void 0===t?null:t}function Xs(e,t){const n=Hs.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Gs(o,t);if(null!==e)for(const t of n)zs(t,e)}return n}function Ys(e,t){null!==t?Hs.set(e,t):Hs.delete(e)}const Qs=new WeakMap;function Zs(e,t){null===t?Qs.delete(e):Qs.set(e,t)}function er(e){const t=Qs.get(e);t&&(t.dirty=!0)}const tr=Symbol.for("wcstack.transition-runner");function nr(e){const t=globalThis[tr];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 or(e,t,n){const o=nr(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const sr=[],rr=[];function ir(e){rr.includes(e)||rr.push(e)}function ar(e,t=0){const n=sr.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?sr.push(o):sr.splice(n,0,o)}function lr(e){queueMicrotask(()=>{throw e})}class cr{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<rr.length;t++)rr[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(){jt(),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!==kt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&kt({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!==kt&&kt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=bn(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=or("state",e);void 0!==t&&t.catch(lr)}}finally{Lt(),function(e){for(const t of sr.slice())t.listener(e)}(s)}}}const dr=new cr;function ur(){return dr}const fr=new WeakMap,hr=new WeakMap,pr=new WeakMap,gr=new WeakMap;let mr=!1;const yr=new WeakMap;function wr(e){const t=e.absolutePathInfo.stateElement;let n=yr.get(t);void 0===n&&yr.set(t,n=new Set),n.add(e)}function br(e){const t=yr.get(e);return void 0===t?null:(yr.delete(e),t)}const vr=new WeakMap,$r=new WeakMap,xr=new WeakMap,Sr=new WeakMap,Pr=new WeakMap,Ir=[];function kr(e,t){const n=Ar(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ae(t).cumulativePaths;if(o.length<2)return;let s=Pr.get(e);void 0===s&&Pr.set(e,s=new Map);for(let e=0;e<o.length-1;e++){let n=s.get(o[e]);void 0===n&&s.set(o[e],n=new Set),n.add(t)}}function Ar(e){let t=fr.get(e);return void 0===t&&fr.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function Nr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function _r(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function Tr(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=hr.get(o);if(void 0===r&&hr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(_r(s,e,o),r.set(t,n),Nr(s,n,o)),!1}return r.set(t,n),Nr(s,n,o),!0}function Er(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):(o.push(n),!1)}function Cr(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&Er(pr,o.listIndex,r)&&function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){let n=xr.get(t);void 0===n&&xr.set(t,n=new Set),n.add(e)}}(o.listIndex),null!==r.levelListIndex&&Er(gr,r.levelListIndex,r))}function Mr(e,t,n,o,s){mr=!0;const r=Ar(e);kr(e,t);Cr(r,t,s,o,Tr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function Or(e,t){Ar(e).tracked.add(t)}function Rr(e,t){return!0===fr.get(e)?.byPath.has(t)||!0===vr.get(e)?.has(t)}function jr(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(Zt(e.stateElement,Sn(t,o)))}function Lr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Dr(e,t,n,o,s){const r=fr.get(e),i=r?.byPath.get(t),a=vr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return Ir;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&&Lr(i.get(o),d),f&&Lr(i.get(c),d),u&&Lr(i.get(s),d)),void 0!==a)for(const e of a)n&&jr(e,o,d),f&&jr(e,c,d),u&&jr(e,s,d);return d}function Wr(e,t){return!0===Pr.get(e)?.has(t)}function Br(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function zr(e,t,n,o,s=!0){const r=ae(t).segments.length,i=[];for(const a of Pr.get(e).get(t)){const t=ae(a).segments.slice(r);if(t.includes(d)){Fr(e,a,i);continue}const l=s?Br(n,t):void 0;for(const n of Dr(e,a,s,l,Br(o,t)))i.push(n)}return i}function Fr(e,t,n){const o=fr.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())Lr(e,n);const s=vr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)jr(e,t,n)}function qr(e){const t=gr.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Vr(e){const t=pr.get(e);if(void 0!==t){pr.delete(e),function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){const n=xr.get(t);void 0!==n&&(n.delete(e),0===n.size&&xr.delete(t))}}(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=hr.get(o),r=s.get(n);s.delete(n),_r(fr.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&qr(e)}}}function Hr(e){const t=Sr.get(e);if(void 0!==t){Sr.delete(e);for(const e of t){const t=vr.get(e.stateElement),n=t.get(e.path);n.delete(e),0===n.size&&t.delete(e.path);const o=$r.get(e.indexes);o.splice(o.indexOf(e),1),0===o.length&&$r.delete(e.indexes)}}}function Kr(e){if(!mr)return;Vr(e),Hr(e);const t=xr.get(e);if(void 0!==t){xr.delete(e);for(const e of t)Vr(e),Hr(e),xr.delete(e)}}function Ur(e,t,n){if(!mr)return;const o=gr.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=fr.get(e),i=o.byPath.get(s);_r(i,t,r),Nr(i,n,r),hr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(er(r),ur().enqueueAbsoluteAddress(r,null),wr(r))}}const Gr=new WeakMap,Jr=Object.freeze([]),Xr=new Set;function Yr(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Jr,s=Array.isArray(n)&&n.length>0?n:Jr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Jr,o=Array.isArray(t)&&t.length>0?t:Jr;let s=Gr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Xs(o,e)||[],a=i.length>0?Fs(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Xr,deleteIndexSet:new Set(i),addIndexSet:Xr};let t=Xs(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Bs(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:Xr,deleteIndexSet:Xr,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:Xr,deleteIndexSet:Xr,addIndexSet:Xr};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=Bs(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=Gr.get(e);o||(o=new WeakMap,Gr.set(e,o)),o.set(t,n)}(o,s,l),Ys(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,Ur(e[n],t,n)}qs(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Jr),function(e){for(const t of e)Ks.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)Kr(e);return function(e){for(const t of e)Ks.delete(t)}(o.newIndexes),function(e,t){if(!mr||e===t)return;const n=$r.get(e);if(void 0===n)return;$r.delete(e);const o=$r.get(t);$r.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=Ar(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=e[n],r=t[n];if(s!==r)for(const e of[s,r])if(void 0!==e&&!Us(e))for(const t of o.getters){const n=Zt(o.stateElement,Sn(t,e));er(n),ur().enqueueAbsoluteAddress(n,null),wr(n)}}}(o.oldIndexes,o.newIndexes),o}function Qr(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 Zr=new WeakSet;const ei=new WeakMap;function ti(e){return ei.get(e)??null}function ni(e,t){ei.set(e,t)}const oi=new WeakMap;function si(e){return oi.get(e)??[]}function ri(e,t){oi.set(e,t)}function ii(e,t){const n=si(e);for(const e of n)It(e,t)}const ai=new WeakMap;const li=new WeakMap;function ci(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function di(e,t,n,o,s){const r=function(e,t,n){let o=li.get(e);void 0===o&&li.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let e=0;e<t.length;e++){const d=t[e];if(!n.shouldApplyState(d))continue;const u=r[e];if(null===u||ci(u.prefixes,i)){Sa(d,s);continue}if(s.appliedBindingSet.has(d))continue;c||(l=s.state[Bt](o),c=!0);const f=u.tail;let h=l,p=!1;for(let e=0;e<f.length;e++){if(null==h){h=void 0;break}if(a&&!(f[e]in Object(h))){p=!0;break}h=h[f[e]]}p?Sa(d,s):(s.appliedBindingSet.add(d),xa(d,s,h))}}function ui(e,t,n){ii(e,t);const o=_s(e),s=ti(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return ai.get(e)??null}(e);if(null!==r)return void di(r,o,s,t,n)}for(const e of o){if(null===s){mn(hn(e),e)}(null===s||s.shouldApplyState(e))&&Sa(e,n)}}function fi(e){if(!e.mounted)return;const t=_s(e),n=ti(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{yn(hn(o),o)}}!function(e){const t=si(e);for(let e=0;e<t.length;e++)It(t[e],null)}(e)}function hi(){return Object.freeze(new Set)}const pi=new WeakMap,gi=hi();function mi(e,t){const n=pi.get(e);n?n.add(t):pi.set(e,new Set([t]))}function yi(e){const t=pi.get(e);return void 0!==t?t:gi}function wi(e,t){const n=pi.get(e);n&&(n.delete(t),0===n.size&&pi.delete(e))}const bi=new Set(["if","elseif","else","for"]);class vi{_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];Lo(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){Lo(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=ti(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&&(Co(n),n.parentNode.removeChild(n))}const n=_s(this);for(let e=0;e<n.length;e++){const t=n[e];bi.has(t.bindingType)&&yi(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=ti(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];bi.has(n.bindingType)&&yi(n.node).forEach(e=>{e.unmount()}),kn(n),pn(n)}}unmount(){{const e=ti(this);null!==e&&(e.isRowSession?e.disposeBindings(_s(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Co(e),e.parentNode.removeChild(e));const e=_s(this);for(let t=0;t<e.length;t++){const n=e[t];bi.has(n.bindingType)&&yi(n.node).forEach(e=>{e.unmount()}),kn(n),pn(n)}this._mounted=!1}}function $i(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 xi(e){const t=document.createDocumentFragment(),n=new vi(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=lt(o,s[e].nodePath);null===t&&se(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),vt(t),Ge(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=Na.get(n);void 0!==o&&o.currentRowPlan===e||(o=new $s,Na.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new vi(o);return ni(d,c),Ts(d,a),function(e,t){ai.set(e,t)}(d,n),Ms(d,l),ri(d,r),mi(e.node,d),d}function Pi(e){void 0!==e.uuid&&null!==e.uuid||se("BindingInfo.uuid is null.");const n=Ka(e.uuid);n||se(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&$i(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=lt(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!==Xe(r))return null;if("prop"===o&&so(r,e.propName))return null;const i=dt(e);let a;try{a=Yo({...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 0===n.length?null:{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=lt(e,s.nodePath);if(null===t&&se(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),yt.has(t))continue;const r=wt(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new $s,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 vi(i,s);ni(l,a.bindingSession),Ts(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in M&&c.push(e);return Ms(l,c),ri(l,a.nodes),mi(e.node,l),l}const Ii=new WeakSet,ki=Symbol.for("wcstack.state.view-transition-naming");function Ai(){const e=nr("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Ni(e,t,n){const o=function(e){const t=e.firstNode;if(null===t)return null;const n=e.lastNode;for(let e=t;null!==e;e=e.nextSibling){if(e.nodeType===Node.ELEMENT_NODE)return e;if(e===n)break}return null}(e);if(null===o||Ii.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[ki]??={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 _i=new WeakMap,Ti=new WeakMap,Ei=new WeakMap,Ci=new WeakMap;function Mi(e,t,n){!function(e,t,n){let o=Ti.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,Ti.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function Oi(e,t){_i.set(e,t)}function Ri(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 ji(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 Li(e,t,n){if(o=t,!Zr.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 Di=new Set(["if","elseif","else","for"]);function Wi(e,t){for(const n of _s(e))if(t.appliedBindingSet.delete(n),Di.has(n.bindingType))for(const e of yi(n.node))Wi(e,t)}function Bi(e){for(const t of _s(e)){if(!Di.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of yi(t.node))Bi(n),e&&n.mounted&&(fi(n),n.unmount(),wi(t.node,n))}}function zi(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Fi(e,n,s){const r=Boolean(s);let i;const a=yi(e.node);i=0===a.size?Pi(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${zi(e)}`),fi(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${zi(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);ui(i,Pt(e.node),n);const t=Ai();null!==t&&Ni(i,"branch",t)}}const qi=new WeakMap;function Vi(e){return qi.get(e)??[]}const Hi=new Set;function Ki(){Hi.clear()}const Ui=Symbol.for("wcstack.trustedTypes.policy");function Gi(){const e=globalThis[Ui];return null===e||"object"!=typeof e?null:e}function Ji(e){globalThis[Ui]=e}let Xi;let Yi=!1;function Qi(e,t){if(Yi)return;if(!function(){if(void 0!==Xi)return Xi;if(!("trustedTypes"in globalThis))return Xi=!1,Xi;try{document.createElement("div").innerHTML="<i></i>",Xi=!1}catch{Xi=!0}return Xi}())return;Yi=!0;const n="function"==typeof Gi()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${t}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:e,property:t})}const Zi={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function ea(e,n,s){if(1===e.propSegments.length){const t=e.propSegments[0];"textContent"===t||"innerText"===t?s=null==s?"":String(s):void 0===s&&"innerHTML"===t&&(s="")}if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==s){null!==Ps&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Xe(r)&&Ps.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=Gi(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Qi(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=Xe(e);if(null===n)return null;const o=Qe(e)?.get(n);if(void 0===o)return null;const s=et(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&so(r,c)){const t=co(r,c,e.statePathName),o=uo(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??mo()??ho(t);if(a.visitedEdges.has(o))null!==kt&&kt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=po(a,o);yo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:ao++,writtenValue:n};wo.push({receipt:i,node:e});try{return r()}finally{wo.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=Zi[c];e?e(r,s):(!function(e,t,n){let o=qi.get(e);o||(o=[],qi.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,Hi.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!==Ps&&2===i.length&&"object"==typeof d&&null!==d&&null!==Xe(r)&&(u in d?Ps.rememberOverwrittenValue(r,c,u,d[u]):Ps.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 ta=new WeakSet;function na(e,t,n){}function oa(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 sa(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 ra={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},ia={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function aa(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 la(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 ca(e,t){return`$setAll("${e}") ${t}`}function da(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 ua(e,t){const n=In(t);if(n.pathInfo.path in M){const e=Pt(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=an(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&se(da(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Bt](n)}const fa=new WeakSet;function ha(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const pa=Object.freeze({[N]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?("boolean"!=typeof n&&se(`Invalid value for class application: expected boolean, got ${typeof n}. Write "|truthy" if you mean to coerce.`),o.classList.toggle(s,n)):o.classList.toggle(s,!1)},[_]:function(e,t,n){const o=e.node,s=e.propSegments[1];if(null==n)return void(o.hasAttribute(s)&&o.removeAttribute(s));const r=String(n);o.getAttribute(s)!==r&&o.setAttribute(s,r)},[T]: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){qn(n)||se("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=As.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=Xe(e);if(null===t)return null;const n=Qe(e)?.get(t);return void 0===n&&se(`Custom element <${t}> is not defined for command binding.`),et(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(),As.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 As.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)}),As.set(e,{token:o,unsubscribe:c,elementRef:l})}}),ga={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!ta.has(e.replaceNode)){ta.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,n,o){const s=e.statePathInfo,r=dn(e),i=hn(e),a=Nt(i),l=a.length>0&&!Ti.has(e.node)?[]:a,c=Yr(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=Ti.get(e.node);const f=void 0!==u?Li(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=Ci.get(e.node);if(void 0===t){const n=_i.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Ri(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Ri(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),Ci.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){Oo.set(e,(Oo.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return Ei.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)?(fi(o),Bi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?wi(e.node,o):(fi(o),o.unmount(),function(e,t){let n=Ei.get(e.node);void 0===n&&(n=[],Ei.set(e.node,n)),n.length<1e3?n.push(t):wi(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(Ti.delete(e.node),u=void 0)}let g=e.node;const m=ae(s.path+"."+d),y=n.stateElement.loopContextStack,w=Qr(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&g.isConnected&&null===f&&(b=document.createDocumentFragment(),nn(b,n.rootNode));const v=t(),$=Ai(),x=e.uuid??"",S=Ei.get(e.node);for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const r=Sn(m,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=Pi(e):Wi(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)}}ui(o,r,n),null!==$&&Ni(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=Cs(o);for(const t of e)Sa(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)&&ji(g,o.firstNode)||g.nextSibling===o.firstNode||o.mountAfter(g),e){const e=o,s=Sn(m,t);y.createLoopContext(s,t=>{ui(e,t,n)})}}g=o.lastNode||g,void 0===u&&(u=new WeakMap,Ti.set(e.node,u)),u.set(t,o)}_i.set(e.node,g),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),nn(b,null))},if:Fi,else:Fi,elseif:Fi,radio:function(e,t,n){const o=e.node,s=Is(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=Is(o.value,e.inFilters),r=Array.isArray(n)?n:ks;o.checked=r.includes(s)}},ma=new WeakMap,ya=new WeakMap,wa=new WeakMap;function ba(){}function va(e){const t=Ps;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return na;if(t.isDeclared(n,o))return ba}return ea}function $a(e,t){xa(e,t,ua(t.state,e))}function xa(e,t,n){const o=Is(n,e.outFilters);if(!0===ya.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=ma.get(e);if(void 0===s){if(ma.has(e))return s=va(e),s===na&&ma.set(e,s),void s(e,t,o);if(s=ga[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=pa[t],ma.set(e,s),void 0===s){Xe(e.replaceNode)?(s=va(e),s===na&&ma.set(e,s)):(s=ea,ma.set(e,s))}}if(s===ea){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 ya.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=hn(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=Ss(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==wa.get(e)){const t=Xe(e.replaceNode);if(t&&void 0===Qe(e.replaceNode)?.get(t))return void function(e,t){if(fa.has(e))return;fa.add(e);const n=()=>{fa.delete(e);const t=Ss(e);(null===t||t.shouldApplyState(e))&&Ia([e])},o=n=>{fa.delete(e),ha(t,n)},s=Ss(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{fa.delete(e),r()})||(fa.delete(e),r()))}const r=Qe(e.replaceNode);if(null===r)return fa.delete(e),void ha(t,new Error("CustomElementRegistry is unavailable."));Vo(r).wait(t,()=>{e.replaceNode.isConnected?n():fa.delete(e)},o)}(e,t);wa.set(e,!0)}if(!0===t.sameRootVerified)return void $a(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=on(o),null===o&&se("Root node for fragment not found for binding.")),o!==t.rootNode){const n=Wa(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};$a(e,r)})}else $a(e,t)}function Pa(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!==kt&&kt({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=on(d),null===d&&se("Root node for fragment not found for binding."));const u=Wa(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{Sa(n,f)}catch(e){Pa(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{ea(e,{propagationContextByBinding:t},n)}catch(t){Pa(e,t,o??null,c)}for(const[e,t]of i.entries())_t(e,t),Rt(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Vt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Ht](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 ka(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=$t(o);if(0===e.length)return;It(o.node,t);Ia(n.initialize(e))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}function Aa(e,t,n){const[o,s,r]=bt(e,n),i=xs(e);for(const e of o)It(e,t);Ia(i.initialize(s)),ka(r,t,i)}const Na=new WeakMap;async function _a(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Qe(e);null===s&&se(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(ht(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function Ta(e){if(e===document)await _a(document),ne(document),ul(document,document),Aa(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await Ue(t.host),await _a(t),ne(t),ul(t,t),Aa(t,null)}}const Ea={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function Ca(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${Ea[e]??e}" before the state is defined.`}let Ma=null;function Oa(e){return null===Ma&&se(Ca("ssr",e)),Ma}const Ra=new WeakMap,ja=new WeakMap,La=new Set,Da=[];function Wa(e){return Ra.get(e)??null}function Ba(e){return ja.get(e)??Promise.resolve()}const za=new WeakSet;function Fa(e){za.add(e)}function qa(e,n){const s=Ra.get(e);if(null===n){if(void 0===s)return;Ra.delete(e),La.delete(s),null!==kt&&kt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await Oa('the "enable-ssr" attribute').hydrate(e)||await Ta(e)}else await Ta(e);Fa(e),yl(),t()}catch(e){n(e)}})});ja.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await Ta(e),Fa(e),yl(),t()}catch(e){n(e)}})});ja.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="...">.'),Ra.set(e,n),La.add(n);for(let t=0;t<Da.length;t++)Da[t](e,n);null!==kt&&kt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Va=new Map;function Ha(e,t,n){if(null===n)Va.delete(e);else{Va.set(e,n);const o=Wa(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 Ka(e){return Va.get(e)||null}function Ua(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=De(t.getAttribute(o.bindAttributeName)||"");if(t.localName===o.tagNames.state){if(t.hasAttribute("mount"))return n.filter(e=>e.propSegments[0]!==k);const e=n.find(e=>e.propSegments[0]===k);if(void 0!==e){const t=`on a volume element — a <${o.tagNames.state}> with a "mount" attribute`;se(1===e.propSegments.length?`[wcs/mount-path-invalid] "${e.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${k}.<key>: <path>") ${t}.`:`[wcs/mount-path-invalid] "${e.propName}: ${e.statePathName}" is a volume injection declaration, and it can only be written ${t}. Add mount="<path>", or bind an element property instead.`)}}return n}if(e.nodeType===Node.COMMENT_NODE){const t=Fe(e);null===t&&se("Comment node binding text not found.");const n=Ka(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=qe(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Ga;function Ja(){return Ga??={filterName:"not",args:[]}}const Xa=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Ya(e,t){const n=t+c+d,o=_e(e,"|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+c+s.slice(1)}return r.length>0?s+r:s}function Qa(e,t){const n=Xa.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Ya(s,t)+r}function Za(e,t){const n=Te(e,";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=_e(n,":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Ya(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function el(e,t){return Za(e,t)}function tl(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=Qa(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Za(r,t);e!==r&&o.setAttribute(n,e)}}}function nl(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}const ol=new WeakMap;function sl(e){return ol.get(e)??null}function rl(e){const t=[],n=mt(e);for(const e of n){const n=Ua(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");ol.set(t,e.data),e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:nl(o),parseBindTextResults:n})}return t}function il(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 al=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),ll=Ja();function cl(e,t){const n=t.outFilters;return{...t,outFilters:[...n,ll],bindingType:e}}function dl(e,t,n,o,s,r=!0){il(t),"string"==typeof o&&tl(t,o),ul(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:rl(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 ul(e,t,n,s){const r=o.commentElsePrefix,i=pt(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=el(i,n));let a=De(i)[0];const d=al.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Rs();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=cl("else",l.parseBindTextResult),p=dl(e,f,a,g,s,!1),Ha(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:nl(o),parseBindTextResults:Ua(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&se("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=dl(e,f,a,g,s),Ha(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=Rs(),i={fragment:document.createDocumentFragment(),parseBindTextResult:cl("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:nl(n),parseBindTextResults:Ua(n)}),Ha(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:nl(m),parseBindTextResults:Ua(m)})):t.replaceWith(m)}else{p=dl(e,f,a,g,s),Ha(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 fl=()=>`[${o.bindAttributeName}]`;function hl(e){if(cs(e))return!0;if(!pl(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(fl());return null!==t&&cs(t)}function pl(e){return 1===e.nodeType}function gl(e){if(hl(e))return;ne(e),ul(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 ml=[];function yl(){const e=ml.splice(0,ml.length);for(const t of e)gl(t);l()}const wl={protocol:"wcs-binder",version:1,bind:function(e){var t;pl(e)&&!hl(e)&&(t=e.getRootNode(),za.has(t)?gl(e):ml.push(e))}};const bl="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let vl=0;async function $l(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++vl}\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 ${bl}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${bl}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function xl(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 Pl={$updatedCallback:j,$streams:H},Il=new WeakSet;function kl(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function Al(e){if((null===e||"object"!=typeof e&&"function"!=typeof e)&&se(`The state must be an object, got ${null===e?"null":typeof e}. Check the source of the state element (json / src / the inline <script>).`),!Il.has(e)){for(const t of Object.keys(Pl)){if(!(t in e))continue;const n=Pl[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}".${ue}`),Object.isExtensible(e)||se(`[wcs/declaration-alias] The state is not extensible, so the old name "${t}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${ue}`);const o=kl(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}Il.add(e)}}const Nl=new WeakMap;function _l(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 Fn(t,e),n.set(t,o)),o}const Tl=new WeakMap;function El(e){const t=Tl.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 _l(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:_l(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 Tl.set(e,n),n}const Cl=Symbol("wcs.notHandled"),Ml=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Ol=new Map;function Rl(e,t){Ol.set(e,t)}const jl=new Map;let Ll=[],Dl=[];function Wl(e,t){jl.set(e,t),Ll=Array.from(jl.values()).sort((e,t)=>e.order-t.order),Dl=Ll.slice().reverse()}function Bl(e){return jl.has(e)}function zl(e,t){for(let n=0;n<Ll.length;n++)Ll[n].activate?.(e,t)}function Fl(e){"readonly"===e.mutability&&se("This state is readonly.")}const ql=new Map;class Vl{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 Hl(e){let t;return ql.get(e)??(ql.set(e,t=new Vl(e)),t)}function Kl(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:an(n.listIndex,o,n.pathInfo.wildcardCount)}function Ul(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=rn(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?an(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?an(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function Gl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function Jl(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!==Cl)return a}}return Cl}function Xl(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}(El(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=Jl(s,t,null,n,o);if(r!==Cl)return r;se(function(e,t,n){return`[${ra.binding}] Path "${e}" does not exist on the state tree.${de(e,sa(t,"",n))}${ue}`}(t.pathInfo.path,e,s.getterPaths))}const r=Ql(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=Jl(s,t,Object(r),n,o);if(e!==Cl)return e}if(i===d){const e=t.listIndex?.index??se(da(`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 Yl(e,t,n,o,s){const r=Zt(s,t),i=function(e){return Qs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Xl(e,t,n,o,s);return Zs(r,{value:l,dirty:!1,generation:a}),l}function Ql(e,t,n,o){Ul(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!==Cl)return i}}return Gl(s,t)?Yl(e,t,n,o,s):Xl(e,t,n,o,s)}function Zl(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=Sn(f,r),p=Zt(n.stateElement,h),g=Ot(p),m=Ql(e,h,t,n),y=Yr(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())Rt(e,Array.isArray(t)?t:[]);return l}function ec(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Xs(Ql(e,Sn(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 tc(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 nc(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 oc(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];tc(a,n,o,i);const l=nc(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 sc(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 rc(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=Ql(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 ic=new WeakMap;function ac(e,t){null===t?ic.delete(e):ic.set(e,t)}function lc(e,t,n){const s=Sn(ae(e.wildcardParentPaths[t]),n),r=Zt(e.stateElement,s),i=Ot(r),a=e.stateProxy[Bt](s),l=Yr(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)lc(e,t+1,n)}const cc=[];function dc(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:cc,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:cc,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const uc=[];function fc(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return uc;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??uc}function hc(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,pc(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}function pc(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[Bt](t),a=Zt(e.stateElement,t),l=Ot(a),c=Yr(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=dc(e,o,0,0,c);for(const t of d.fullRows){const o=Sn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=fc(e,r,s);if(null===t)for(const t of d.movedRows){const o=Sn(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=Sn(s,o);e.result.add(t),n.push(t)}}}else{const o=Sn(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=rn(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=an(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};lc(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=an(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=Sn(s,t);e.result.add(o),n.push(o)}}}function gc(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&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};hc(u,t,a),function(e,t){for(let n=0;n<1e3;n++){const n=br(e.stateElement);if(null===n)return;n.forEach(n=>{hc(e,Sn(n.absolutePathInfo.pathInfo,n.listIndex),t)})}}(u,a);for(const[e,t]of u.observedListValueByAbsAddress)Rt(e,t);return Array.from(u.result)}function mc(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 yc(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 wc(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 bc(e,t,n,o,s,r){const i=Rr(e,t),a=Wr(e,t);if(!i&&!a)return null;const l=[],c=$c(l);return i&&Dr(e,t,n,o,s).forEach(c),a&&zr(e,t,n?o:r(),s).forEach(c),l}function vc(){return o.enablePropagationContext?mo()??null:null}function $c(e){const t=ur(),n=vc();return o=>{er(o),t.enqueueAbsoluteAddress(o,n),e.push(o)}}function xc(e,t,n){if(null===e||0===e.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=ur(),a=vc();for(let n=0;n<e.length;n++){const l=e[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const d=Sn(l.pathInfo,e[n].listIndex);gc(o,d,s,r,o.listPaths,t,"new",e=>{if(e===d)return;const t=Zt(o,e);er(t),i.enqueueAbsoluteAddress(t,a)},{listExpansion:"diff"})}}function Sc(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?mo()??ho(-1):null,c=ur();c.enqueueAbsoluteAddress(t,l),i&&er(t),gc(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Zt(s.stateElement,t);er(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Pc(e,t,n,o,s){s&&(e.getterPaths.has(t)?er(n):Zs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function Ic(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=Ql(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??se(da(`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{Sc(t,n,s,r,i,a)}}function kc(e,t,n,o,s,r,i,a){const l=t.parentAddress??se(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=Ql(e,l,s,r)??[];let f=(h=u,ic.get(h)??null);var h;if(null===f){const e=Js(u)??[];f={value:[...u],listIndexes:[...e]},ac(u,f)}try{return Ic(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=Ql(e,l,s,r)??[],a=Array.isArray(i)?Js(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:Bs(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;ac(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=ur(),l=Zt(i,e);Nt(l)===n&&(Ys(t.value,t.listIndexes),_t(l,t.value),function(e){Zr.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=Sn(f,n),d=Zt(i,c);if(void 0===l){const n=en(i,f,t.listIndexes[e]??null);wc(i,d,n),Sc(c,d,s,r,null,Gl(i,c),"full");continue}gc(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Zt(i,e);er(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(l,f,i,a,s,r)}}}function Ac(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=Ql(e,t,o,s),a=function(e,t,n,o){const s=oc(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=oc(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===Js(o)&&Yr(a,null,o);const l=Yr(a,o,n.list),u=Nc(e,t,n.list,s,r,i),f=ae(i+c+d);for(const t of n.matched){const n=sc(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?Ac(e,Sn(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 Nc(e,t,n,o,s,null)}function Nc(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!==Cl)return i}}const u=!!bo&&(bo=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=Ql(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}const m=bc(a,l,g,p,n,()=>f[h]),y=Gl(a,t),w=Zt(a,t);null!==kt&&kt({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:g}),mc(a,l,w,p,g);let b=!1;try{if(void 0===h&&se(da(`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++){b=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==Cl)return i;b=!1}}return Reflect.set(f,h,n)}finally{Sc(t,w,s,r,i,y),xc(m,s,r),b?er(w):Pc(a,l,w,n,y),yc(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Ql(e,t,s,r);if(rc(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}const p=bc(a,l,h,f,n,()=>Ql(e,t,s,r)),g=a.elementPaths.has(t.pathInfo.path),m=Gl(a,t),y=Zt(a,t);null!==kt&&kt({type:"state:write",absoluteAddress:y,value:n,oldValue:f,hasOldValue:h}),mc(a,l,y,f,h);try{return g?kc(e,t,y,n,s,r,i,m):Ic(e,t,y,n,s,r,i,m)}finally{xc(p,s,r),g||Pc(a,l,y,n,m),yc(a,t.pathInfo,{value:n})}}function _c(e,t,n,o){return(t,s,...r)=>{Array.isArray(s)||se(`$resolve("${t}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&se(`$resolve("${t}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);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(aa("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=Sn(i,ec(e,n,o,i,s));if(0===r.length)return Ql(e,a,n,o);Fl(o),Ac(e,a,r[0],n,o)}}function Tc(e,t,n,o){const s=_c(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(aa("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=Kl(o,i.wildcardPaths[e]);if(t){r=ln(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=Zl(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 Kl(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=Xs(Ql(e,Sn(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 Cc(e,t,n,o){const s=o.stateElement;return t=>{const r=Hl(t),i=Ec(e,r,n,o),a=Sn(r.pathInfo,i),l=Zt(s,a),c=ur();c.enqueueAbsoluteAddress(l),function(e,t,n,o,s){const r=Rr(e,t),i=Wr(e,t);if(!r&&!i)return;const a=n(),l=[],c=$c(l);r&&Dr(e,t,!1,void 0,a).forEach(c),i&&zr(e,t,void 0,a,!1).forEach(c),xc(l,o,s)}(s,r.pathInfo.path,()=>Ql(e,a,n,o),n,o),gc(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Zt(s,e);er(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}function Mc(e,t,n,o){return(t,s,r,i)=>{Fl(o);const a=ae(t);Array.isArray(s)||se(ca(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&se(aa("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&se(ca(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&se(ca(t,"requires an array as the value when { spread: true } is set."));const d=Zl(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=ec(e,n,o,a,d[t]);u.push(Sn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(Ql(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(Ac(e,s,i,n,o),f++)}return f}}function Oc(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 Rc=/^\$\d+$/,jc=`${Y}${c}`,Lc=`${Q}${c}`,Dc=new WeakMap;function Wc(e,t,n,o){const s=M[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&Rc.test(t)&&se(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${E}1 to ${E}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=an(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!==Cl)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Tc(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>Mc(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>Cc(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>_c(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(Oc(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Or(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)&&Mr(o.stateElement,e,t,Zt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Oc(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?Or(o.stateElement,e):Mr(o.stateElement,e,i,Zt(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=an(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&se(`$eqIndex("${e}", ${t}): no list index at that level.`),Oc(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&Or(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?Js(l):null;null!==t?function(e,t,n,o,s){mr=!0,Ar(e).lastValue.set(t,s),kr(e,t);let r=vr.get(e);void 0===r&&vr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=$r.get(o);if(void 0===l?$r.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);const n=o[0]?.parentListIndex??null;if(null!==n){let e=Sr.get(n);void 0===e&&Sr.set(n,e=new Set),e.add(a)}}a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){mr=!0;const r=Ar(e);kr(e,t),Cr(r,t,s,o,Tr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Zt(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 El(o.stateElement)}if(!t.startsWith(jc)&&!t.startsWith(Lc))return}const r=Hl(t),i=Ec(e,r,n,o),a=Sn(r.pathInfo,i);return Ql(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=Dc.get(e);return void 0===t&&(t=new Map,Dc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Wt: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 Bt:i=t=>Ql(e,t,n,o);break;case zt:i=t=>rc(e,t,n,o);break;case Ft:i=()=>async function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&await o.call(n)}(e,0,n);break;case qt:i=()=>function(e,t,n){const o=Reflect.get(e,R);"function"==typeof o&&o.call(n)}(e,0,n);break;case Vt: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=ln(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 Ht: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 Bc{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=Wa(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 Wc(e,t,n,this)}set(e,t,n,o){return Fl(this),function(e,t,n,o,s){if("string"==typeof t){const r=Hl(t),i=Ec(e,r,o,s);return Ac(e,Sn(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}deleteProperty(e,t){return Fl(this),Reflect.deleteProperty(e,t)}defineProperty(e,t,n){return Fl(this),Reflect.defineProperty(e,t,n)}}const zc=Promise.resolve(),Fc=new Map;let qc=[];function Vc(e,t){Fc.set(e,t),qc=Array.from(Fc.values()).sort((e,t)=>e.order-t.order)}function Hc(e,t){return se(Ca(e,t))}const Kc="undefined"==typeof HTMLElement?class{}:HTMLElement;function Uc(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 Gc=null;const Jc=new Set(["for","if","elseif","else"]);function Xc(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=Zt(e,t);if(i.has(n))return;i.add(n);const o=bn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(Sn(n,t.listIndex))}};jt();try{if(e.createState("readonly",t=>{for(const o of n){const n=Sn(ae(o),null);a(n);try{gc(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)Jc.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=or("state",s);void 0!==i&&i.catch(lr)}finally{Lt()}}const Yc=[[K,"watch"],[U,"scan"],[H,"streams"],[G,"recursion"]];class Qc extends Kc{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Ba(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){Al(e),function(e){for(let t=0;t<Yc.length;t++){const[n,o]=Yc[t];n in e&&!Bl(o)&&se(Ca(o,`"${n}"`))}}(e);const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<Ll.length;o++)Ll[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<Ll.length;o++)Ll[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<Ll.length;o++)Ll[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&Gc?.reset(this),this._hasUpdatedCallback=j in e,this._hasErrorCallback=L in e,i=this,Dn.delete(i),function(e,t,n){for(let o=0;o<Ll.length;o++)Ll[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.`),Wn(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=Uc(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<Ll.length;o++)Ll[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<Ll.length;o++)Ll[o].register?.(e,t,n)}(this,e,n),zl(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")?Oa('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 $l(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 xl(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&&(qa(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===Wa(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),ja.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<qc.length;o++)qc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{O in e&&await e[Ft]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{R in e&&e[qt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<qc.length;t++)if(!0===qc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Wa(this._rootNode)===this||qa(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const e=function(e){for(let t=0;t<qc.length;t++){const n=qc[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{Hc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(Z))try{Hc("dcc",`a <${o.tagNames.state}> inside a [${Z}] host`)}catch(e){this._failInitializeLoudly(e)}let n=!1;try{const e=function(e){for(let t=0;t<qc.length;t++){const n=qc[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 Oa('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}zl(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<qc.length;t++)if(!0===qc[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<qc.length;n++)qc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{qa(this.rootNode,null),e=this,Tl.delete(e),function(e){for(let t=0;t<Dl.length;t++)Dl[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=>(Al(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",K)}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 oa(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=Ol.get(e);return void 0===n&&se(Ca(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<Ml.length;n++){const o=Ml[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=ae(e);if(this._pathSet.add(e),Gc?.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 Bc(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<qc.length;t++)qc[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(Uc(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){Xc(this,e,this._pathRegistrations.keys())}}const Zc=[],ed=[];function td(){const e=[];let t=0;for(let n=0;n<ed.length;n++){const o=ed[n].deref();void 0!==o&&(e.push(o),ed[t++]=ed[n])}return ed.length=t,e}function nd(e=customElements){td().includes(e)||ed.push(new WeakRef(e));for(let t=0;t<Zc.length;t++)Zc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,Qc)}function od(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 sd(e,t){const o=od(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)),nd(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=wl)}()}let rd=null;function id(e){return rd??se(Ca("watch",`"$watch" in <wcs-state mount="${e}">`))}let ad=null;const ld=Object.freeze([]);const cd="3.3.0",dd=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function ud(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 fd(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=`${pe(e.inFilters)}\0${pe(e.outFilters)}`;return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=Ka(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(ud(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=at(t,De(n));for(const o of e)r(ud(t,o,"attribute",n))}catch{}continue}const t=dd.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=Ka(s);if(null===a){if(n===o.commentTextPrefix)try{r(ud(e,qe(s),"comment",s))}catch{}}else r(ud(e,a.parseBindTextResult,"comment",s)),i(s)}return t}function hd(e){const t=function(e){const t=fr.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:vr.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 pd="__WCSTACK_DEVTOOLS_HOOK__";function gd(){const e=globalThis,t=e[pd];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[pd]=n,n}const md=e=>{null!==kt&&kt({type:"state:update-batch",addresses:e})};function yd(e){const t=null!==kt;!function(e){kt=e}(e);const n=null!==e;n&&!t?ar(md,0):!n&&t&&function(e){const t=sr.findIndex(t=>t.listener===e);-1!==t&&sr.splice(t,1)}(md)}function wd(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 bd(e){return Wa(e)??se("devtools: no state tree on this root")}let vd=null;function $d(){if(t())return;if(null!==vd)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:cd,getStateElements(){const e=[];for(const t of La)e.push(wd(t));return e},overlays(e){return t=bd(e),null===ad?ld:ad(t);var t},keyedSubscriptions:e=>hd(bd(e)),keys(e){const t=bd(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 bd(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){bd(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>fd(e),_setSink:yd};vd=e,gd().register(e)}const xd={name:"devtools",install(){$d()}},Sd=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Pd=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const Id=new WeakMap;const kd=new WeakMap,Ad=new WeakSet,Nd=new WeakMap;function _d(e,t,n,o){console.warn(`[@wcstack/state] [${ra[n]}] ${ia[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!==kt&&kt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Td={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=Id.get(e);return void 0===n&&(n=new Set,Id.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!==oa(e,t))return Pd;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!==oa(e,r))return Sd;if(Object(s)!==s)return Sd;if(i===d){if(!Array.isArray(s)||0===s.length)return Sd;s=s[0];continue}const l=oa(s,i);if(void 0===l)return{existence:"missing",missingSegment:i,candidates:sa(s,a,n)};if("function"==typeof l.get)return t===o.length-1?Pd:Sd;s=l.value}return Pd}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===Nd.get(e)?.has(t)}(e,n)||("binding"!==o?_d(e,n,o,i):function(e,t,n){let o=kd.get(e);void 0===o&&(o=new Map,kd.set(e,o));if(o.set(t,n),Ad.has(e))return;Ad.add(e),setTimeout(()=>function(e){Ad.delete(e);const t=kd.get(e);if(void 0===t)return;kd.delete(e);for(const[n,o]of t)_d(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){Id.delete(e),kd.delete(e)},markExported:function(e,t){let n=Nd.get(e);void 0===n&&(n=new Set,Nd.set(e,n)),n.add(t),kd.get(e)?.delete(t)}};let Ed=!1;function Cd(){Ed||(Ed=!0,function(e){Gc=e}(Td))}const Md={name:"diagnostics",install(){Cd()}};function Od(e){se(`filter ${e} requires at least one option`)}function Rd(e){se(`filter ${e} requires a number as option`)}function jd(e){se(`filter ${e} requires a number value`)}function Ld(e){se(`filter ${e} requires a date value`)}const Dd={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function Wd(e){return!(!e||isNaN(Number(e)))}function Bd(e,t){return Wd(e)||Rd(t),Number(e)}function zd(e,t,n){return Bd(e?.[t]??Od(n),n)}const Fd=e=>t=>{const n=e(t);return e=>null==e?e:n(e)},qd={eq:(e,t)=>{const n=e?.[0]??Od("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e===o:(Wd(n)||Rd("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Od("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e!==o:(Wd(n)||Rd("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>!e,lt:e=>{const t=zd(e,0,"lt");return e=>("number"!=typeof e&&jd("lt"),e<t)},le:e=>{const t=zd(e,0,"le");return e=>("number"!=typeof e&&jd("le"),e<=t)},gt:e=>{const t=zd(e,0,"gt");return e=>("number"!=typeof e&&jd("gt"),e>t)},ge:e=>{const t=zd(e,0,"ge");return e=>("number"!=typeof e&&jd("ge"),e>=t)},add:e=>{const t=zd(e,0,"add");return e=>("number"!=typeof e&&jd("add"),e+t)},sub:e=>{const t=zd(e,0,"sub");return e=>("number"!=typeof e&&jd("sub"),e-t)},mul:e=>{const t=zd(e,0,"mul");return e=>("number"!=typeof e&&jd("mul"),e*t)},div:e=>{const t=zd(e,0,"div");return e=>("number"!=typeof e&&jd("div"),e/t)},mod:e=>{const t=zd(e,0,"mod");return e=>("number"!=typeof e&&jd("mod"),e%t)},abs:e=>e=>("number"!=typeof e&&jd("abs"),Math.abs(e)),clamp:e=>{const t=zd(e,0,"clamp"),n=zd(e,1,"clamp");return e=>("number"!=typeof e&&jd("clamp"),Math.min(Math.max(e,t),n))},toFixed:e=>{const t=Bd(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&jd("toFixed"),e.toFixed(t))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&jd("locale"),e.toLocaleString(t??o.locale))},upper:Fd(e=>e=>String(e).toUpperCase()),lower:Fd(e=>e=>String(e).toLowerCase()),capitalize:Fd(e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),trim:Fd(e=>e=>String(e).trim()),slice:Fd(e=>{const t=[zd(e,0,"slice")],n=e?.[1];return void 0!==n&&t.push(Bd(n,"slice")),e=>String(e).slice(...t)}),substr:Fd(e=>{const t=zd(e,0,"substr"),n=zd(e,1,"substr");return e=>String(e).substr(t,n)}),padStart:Fd(e=>{const t=zd(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),padEnd:Fd(e=>{const t=zd(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),repeat:Fd(e=>{const t=zd(e,0,"repeat");return e=>String(e).repeat(t)}),reverse:Fd(e=>e=>String(e).split("").reverse().join("")),truncate:Fd(e=>{const t=zd(e,0,"truncate"),n=e?.[1]??"…";return e=>{const o=String(e);return o.length<=t?o:o.slice(0,t)+n}}),join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||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=Math.pow(10,Bd(e?.[0]??"0","round"));return e=>("number"!=typeof e&&jd("round"),Math.round(e*t)/t)},floor:e=>{const t=Math.pow(10,Bd(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&jd("floor"),Math.floor(e*t)/t)},ceil:e=>{const t=Math.pow(10,Bd(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&jd("ceil"),Math.ceil(e*t)/t)},percent:e=>{const t=Bd(e?.[0]??"0","percent");return e=>("number"!=typeof e&&jd("percent"),`${(100*e).toFixed(t)}%`)},unit:Fd(e=>{const t=e?.[0]??Od("unit");return e=>String(e)+t}),date:e=>{const t=e?.[0];return e=>(e instanceof Date||Ld("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Ld("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Ld("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Ld("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||Ld("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]??Od("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Od("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},Vd={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[2,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,1],time:[0,1],datetime:[0,1],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},Hd=qd,Kd=qd;let Ud=!1;const Gd={name:"formats",install(){Ud||(Ud=!0,$e("input",Kd,Vd,Dd),$e("output",Hd,Vd,Dd))}};function Jd(e){return-1!==e.indexOf(J)}function Xd(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(Jd(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function Yd(e){return 0===e.length?e:c+eu(e.slice(1))}function Qd(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 Zd(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(Qd(e,t,n.slice(0,o)))return!0;return!1}function eu(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 tu(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 nu(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 ou(e,t){return nu(e,"",t)}function su(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 ru(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 iu(e,t,n){const o=e.recursionRegistry,s=Xd(o.spec,n);null===s&&se(la(n,o.spec.recursiveAnchor));const r=ru(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 au(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(Sn(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=Sn(o,s),c=Zt(n.stateElement,l),u=Ql(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=Yr(s,Ot(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(Sn(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)Rt(e,t);return i}function lu(e,t,n,o,s,r,i){Fl(n);const a=n.stateElement.recursionRegistry,l=Xd(a.spec,o);null===l&&se(la(o,a.spec.recursiveAnchor));const c=Yd(l);Array.isArray(s)||se(ca(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(ca(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&se(ca(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){tu(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=au(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Ac(e,u[o],r,t,n),f++);return f}const cu={write(e,t){if(!0!==e.hasRecursion)return Cl;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.`),Cl},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return Cl;if("$getAll"===t)return(t,s)=>{if(Jd(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Xd(r.spec,o);null===i&&se(la(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=au(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Ql(e,a[o],t,n));return l}(o,n,e,t,s);t=iu(e.stateElement,e,t)}return Tc(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>Jd(t)?lu(o,n,e,t,s,r,i):Mc(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&Jd(t)){const s=Hl(iu(e.stateElement,e,t)),r=Ec(o,s,n,e);return Ql(o,Sn(s.pathInfo,r),n,e)}return Cl}};let du=!1;function uu(e,t){"string"==typeof t&&0!==t.length||se(`[wcs/recursion-declaration-invalid] ${G} ${e} must be a non-empty string.`);const n=t.split(c);n.some(e=>0===e.length)&&se(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not contain empty path segments.`),n.length<2&&se(`[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&&se(`[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)&&se(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&se(`[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&&se(`[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]===J&&se(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not contain "${J}" — the declaration is what gives "${J}" its meaning.`),isNaN(Number(n[o]))||se(`[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 fu=new WeakSet;function hu(e){return"function"==typeof e.get&&fu.has(e.get)}const pu="[wcs/recursion-declaration-invalid]";class gu{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=Uc(t);for(const[t,o]of Object.entries(n)){if(!Jd(t))continue;"function"==typeof o.set&&se(`${pu} 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(`${pu} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Xd(e,t);null===n&&se(la(t,e.recursiveAnchor)),0===n.length&&se(`${pu} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),tu(e,Yd(n))&&se(`${pu} "${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(Jd(t)||hu(n))continue;const e=this._matchExpansion(t);null!==e&&se(`${pu} "${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++)Qd(this.spec,e[t].suffix,e[n].suffix)&&se(`${pu} "${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(Zd(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=eu(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!==su(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=su(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||hu(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,fu.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(ou(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 function(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&hu(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}}}(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let o=n[t];return void 0===o&&(o=nu(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 mu="recursionSpec",yu="recursionRegistry",wu={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||se(`[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&&se(`[wcs/recursion-declaration-invalid] ${G} must declare exactly one anchor; it is empty.`),n.length>1&&se(`[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];uu("anchor",o),"string"!=typeof s&&se(`[wcs/recursion-declaration-invalid] ${G} entry "${o}" must map to the repeating sub-path as a string (for example "children${c}${d}").`),uu("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(mu,o),n.set(yu,null===o?null:new gu(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(yu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",G)},apply(e,t,n){const o=n.get(mu)??null;null!==o&&e.addListPath(o.anchorList)}};let bu=!1;function vu(){bu||(bu=!0,du||(du=!0,Rl("recursion",cu)),Wl("recursion",wu))}const $u={name:"recursion",install(){vu()}};const xu={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 Su=!1;function Pu(e){return function(){const t=this.stateElement;if(!t)return;if(!0!==t.initialized)return;let n;try{t.createState("readonly",t=>{n=t[e]})}catch(t){return void console.warn(`[@wcstack/state] DCC getter "${e}" failed:`,t)}return n}}function Iu(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 ku(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[e](...t)}).then(()=>o)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[e](...t)}),o})}}function Au(e){return e.startsWith("$")}function Nu(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 _u(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 Tu(e){Al(e);const t=_u(e,W)??[],n=_u(e,B)??[],o=Uc(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(`${W} entry "${e}" is not declared on the state.${de(e,Nu(o,"value"))}`)}"function"==typeof t.value&&se(`${W} 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,Nu(o,"method"))}`),"function"!=typeof t.value&&se(`${B} entry "${e}" is not a method. Declare it in ${W} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function Eu(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=Qe(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}=Tu(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=Qe(this._shadow);return null!==e&&Ze(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?(Su||(Su=!0,Rl("dcc",xu)),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=Uc(n);for(const[e,t]of Object.entries(m)){if(Au(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=ku(e,o)}else n.get=Pu(e),n.set=Iu(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:Pu(e),set:Iu(e)});r.define(s,g)}async function Cu(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 xl(t);se(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await $l(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);Eu(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const Mu={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Z)?Cu(e,t.host,t):null}};let Ou=!1;function Ru(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 ju(e,t){for(const n of e)if(Ru(t,n.innerSegments))return n;return null}function Lu(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+c+n.join(c)}const Du=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function Wu(e,t,n){const o=Du.get(e);return void 0===o?null:(...e)=>{const s=e.slice();for(let e=0;e<o.length;e++){const n=o[e];"string"==typeof s[n]&&(s[n]=t(s[n]))}return n(s)}}const Bu=new WeakMap;function zu(e,t,n){let o=Bu.get(e);void 0===o&&(o=new Map,Bu.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 Fu(e,t){if(null===e)return!1;const n=Bu.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 qu=new WeakMap;const Vu=[];function Hu(e,t,n,o){if(t.length>0){const s=n.split(c),r=ju(t,s);if(null!==r)return o&&r.readonly&&se(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${k}.${r.innerSegments.join(c)}#${y}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${y} from the injection.`),Lu(r,s)}return e+c+n}function Ku(e,t,n){let o=-1,s=null;for(const e of t){const t=e.outerPathInfo.path;t.length<=o||(n===t?(o=t.length,s=e.innerSegments.join(c)):n.startsWith(t+c)&&(o=t.length,s=e.innerSegments.join(c)+n.slice(t.length)))}if(e.length>o){if(n===e)return"";if(n.startsWith(e+c))return n.slice(e.length+1)}return s}function Uu(e,t,n=Vu){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](Hu(e,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>t.$setAll(Hu(e,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>t.$resolve(Hu(e,n,o,s.length>1),...s);const o=Wu(s,t=>Hu(e,n,t,!1),e=>t[s](...e));return null!==o?o:t[s]}return t[Hu(e,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(t[s]=r,!0):(t[Hu(e,n,s,!0)]=r,!0)),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Gu=new WeakMap,Ju=[];const Xu=new WeakMap,Yu=new WeakSet;function Qu(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 Zu=null;let ef=0;const tf=["$watch",H,"$scan","$listKeys",j,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],nf=new Set;function of(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 sf(e,t,n,o,s,r=new Set){0===n.length&&se(`Cannot build a mount record without host bindings for "${t}".`),Al(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=++ef,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Uc(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)1===e.innerSegments.length&&p.add(e.innerSegments[0]);const g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id: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,hasReadonlyEntries:i.some(e=>e.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function rf(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function af(e,t){const n=ju(e.entries,t);return null===n?null:Lu(n,t)}function lf(e,t){return e.markerBasePath+c+t}function cf(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 df(e,t){return!e.injectedKeys.has(t)&&(!e.getterKeys.has(t)&&"function"==typeof e.stateObject[t]||!e.mappedKeys.has(t)&&(Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t)))}function uf(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}.${rf(t)}: path") or declare the key on the component state.`}const ff=/^\$(\d+)$/;function hf(e,t){if(!e.hasReadonlyEntries)return null;const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=rf(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||df(e,o))return null;const s=function(e,t){return ju(e.entries,t)}(e,t.split(c));return null!==s&&s.readonly?s:null}function pf(e,t){const n=hf(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 gf(e,t)}function gf(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 cf(e,e.markerBasePath,t,t),lf(e,t);if(df(e,n[0]))return cf(e,e.markerBasePath,t,t),lf(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=af(e,s);null===i&&se(uf(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 cf(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=rf(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return lf(e,t);if(df(e,o))return lf(e,t);const s=af(e,t.split(c));if(null!==s)return s;se(uf(e,t))}const mf=new Set(["prop","radio","checkbox"]);function yf(e,t,n){let o;const s=ff.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ae(gf(e,t)).wildcardCount-ae(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=gf(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)&&mf.has(t.bindingType??"")&&!r.includes(y)&&null!==hf(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ae(o),...i?{propModifiers:[...r,y]}:{}}:t}function wf(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 bf=new WeakMap,vf=new WeakMap;const $f=new WeakMap;const xf=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)}),Sf=new WeakMap;function Pf(e){return Sf.get(e)??null}let If=!1;function kf(){If||(If=!0,St=e=>bf.has(e)?e.host:null)}function Af(e){return Nf(e).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join(c),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]}))}function Nf(e){const t=$f.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 _f(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=$f.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 Tf=new WeakMap,Ef=new Set;function Cf(e,t,n,o){let s=Tf.get(e);if(void 0===s){if(!o)return null;s=new Map,Tf.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 Mf(e,t){if(!e.component.isConnected)return!1;const n=Pt(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 Of(e,t,n,o){const s=Cf(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&&Mf(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?Mf(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 Rf(e){const t=e.parentStateElement,n=Pt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Wt](n,()=>{e.$postUpdate(o.exportedPath)})})}const jf=new WeakMap;class Lf{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 Sn(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(gf(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?pf(e,t):gf(e,t),a=wf(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?pf(e,t):gf(e,t),l=wf(0,t,a,r,n);return o[s](a,l,...i)}}const e=this.record,n=this.receiver,o=Wu(t,t=>gf(e,t),e=>n[t](...e));return null!==o?o:this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return Ul(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[gf(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[pf(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 gf(this.record,t),!0}catch{return!1}}}function Df(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=jf.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},jf.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 Lf(e,s,t.listIndex,r,n,o))}function Wf(e){const t=e.parentStateElement,n=(t,n)=>{const o=Pt(e.component);let s;return t[Wt](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(gf(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?pf(e,n):gf(e,n),l=Pt(e.component)?.listIndex.indexes??[],c=wf(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);const r=Wu(s,t=>gf(e,t),e=>{let o;return t.createState("readonly",t=>{o=n(t,()=>t[s](...e))}),o});if(null!==r)return r;let i;return t.createState("readonly",t=>{i=n(t,()=>t["$"===s[0]?s:gf(e,s)])}),i},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:pf(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 gf(e,n),!0}catch{return!1}}})}function Bf(e,t){const n=function(e){return bf.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&&xs(t).dispose(),function(e,t){kf(),bf.set(e,t),Sf.set(t,e);let n=$f.get(t.parentStateElement);void 0===n&&(n=new Map,$f.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=vf.get(t.component);void 0===o&&(o=new Map,vf.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&xf.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=Ra.get(e);if(void 0!==n){if(n===t)return;se("A state tree is already registered on this root.")}Ra.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>yf(e,t,n);ne(t);const o=Pt(e.component);ul(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=gf(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),Cf(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),Gc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=Pt(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(Ef.has(s))continue;const r=ae(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Wt](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Ef.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),Rf(e),o=t,s=Promise.resolve(),ja.set(o,s),s.then(()=>Fa(o),()=>{})}function zf(e,t){const n=xs(t),o=Pt(e.component);n.forEachActiveBindingNode(e=>It(e,o));Ia(n.rebindAddresses()),Rf(e)}function Ff(e,t){if(function(e){const t=$f.get(e);return void 0!==t&&t.size>0}(t))for(const n of Nf(t)){if(!qf(n.component,e))continue;const t=Pf(n);null!==t&&zf(n,t)}}function qf(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 Vf={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=_f(e,t.pathInfo.path);if(null!==s)return Df(s,t,n,o)}return Cl},readMissing(e,t,n,o,s){if(null===n){if(Fu(e.rootNode??null,t.pathInfo.path))return;return Cl}if(!0===e.hasMounts){const n=Of(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Df(e,Sn(ae(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return Cl},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=qu.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 Cl},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Of(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Df(e,Sn(ae(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return Cl},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=_f(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=bf.get(n);if(void 0!==e)return e;n=n.parentNode}return bf.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 Gu.get(e)??Ju}(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=Ku(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=ln(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(Uu(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>Fu(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){Ff(t,e)}};let Hf=!1;function Kf(){Hf||(Hf=!0,Rl("scopes",Vf),ad=Af)}const Uf=new WeakMap;function Gf(e){let t=Uf.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Uf.set(e,t)),t}function Jf(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Bu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function Xf(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{zu(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 Wa(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Yf(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;let r;try{r=De(e)}catch(e){se(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> has an invalid ${o.bindAttributeName}: ${e instanceof Error?e.message:String(e)}`)}for(const e of r){if(e.propSegments[0]!==k)continue;const r=e.propSegments.slice(1),i=e.statePathInfo,a=n=>se(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> "${e.propName}: ${e.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==d&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${k}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(e.inFilters.length>0||e.outFilters.length>0)&&a("an injection takes no filters."),e.propModifiers.some(e=>e!==y)&&a(`an injection accepts only #${y}.`),s.has(r[0])&&a(`"${r[0]}" is injected twice.`),s.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:e.propModifiers.includes(y)})}return n.sort((e,t)=>t.innerSegments.length-e.innerSegments.length),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).`),zu(s,r,e),Wa(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===Wa(s)&&function(e,t){const n=()=>{if(null!==Wa(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&&Jf(e,t),e.settleInitialization()};let l;try{await Promise.resolve(),l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const c=e.connectedRootNode??null;null!==c&&Xf(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 kh(t,a);Nh(),function(e,t){if(Yu.has(e))return void Qu(t);let n=Xu.get(e);void 0===n&&(n=[],Xu.set(e,n)),n.push(t)}(e,a)}(c,Wa(c),r,l,a,()=>Xf(e,t,c),i):a(null)}const Qf={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=Gf(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{zu(n,t.mountPath,e),Wa(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,zc}return Yf(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Gf(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&Wa(n)===t.graftInfo.rootStateElement&&Sh(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Uf.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){Yu.add(e);const t=Xu.get(e);if(void 0!==t){Xu.delete(e);for(const e of t)Qu(e)}}(t)},initializeFailureCleared(e,t){!function(e){Yu.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Gf(e);return null!==t.graftInfo&&Sh(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,Jf(e,t)),e.clearConnectedRootNode(),!0}};let Zf=!1;const eh=new WeakMap;function th(e,t){let n=eh.get(e);n||(n=new Set,eh.set(e,n)),n.add(t)}const nh=new WeakMap;const oh=new WeakMap,sh=new WeakMap;const rh=new WeakMap;const ih={isComplete:function(e,t){return!0===eh.get(e)?.has(t)},isDeclared:function(e,t){return!0===nh.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=oh.get(e);o||(o=new Map,oh.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=sh.get(e);o||(o=new Map,sh.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=rh.get(e);s||(s=new Map,rh.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function ah(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 lh=new WeakMap;class ch{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=lh.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 dh=e=>()=>e;function uh(e,t,n,o){!function(e,t,n){let o=lh.get(e);o||(o=new Map,lh.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(ah(o));const s=function(e,t){const n=new ch(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:dh(s),enumerable:!0,configurable:!0}),th(t,n),fh(t,n)}function fh(e,t){if(D in e){const n=e[D];"function"==typeof n?n.call(e,t).catch(e=>{se(`Error in ${D}: ${e instanceof Error?e.message:String(e)}`)}):se(`${D} is not a function.`)}}const hh=new Set;function ph(e,t){hh.has(e)||(hh.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function gh(e){!function(e){const t=e.component.tagName.toLowerCase(),n=e.stateProp;let o=null;for(const s of e.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=Uc(e.stateObject);const i=o[r];let a;if(e.getterKeys.has(r)||e.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)a="an accessor";else if("function"==typeof i?.value)a="a method";else{if(e.mappedKeys.has(r)||e.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(e.stateObject,r))continue;a="an own data key"}const l=s.innerSegments.join(c);ph(`${t}|${n}|${l}|entry`,`<${t}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${l}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(e);const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=mh(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;ph(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}function mh(e){const t=e.rootEntry,n=Pt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Wt](n,()=>{o=e[t.outerPathInfo.path]})}),o}const yh=new WeakMap;function wh(e,t){e.landInitialization(),se(t)}async function bh(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?Xe(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)||wh(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=nh.get(e);n||(n=new Set,nh.set(e,n)),n.add(t)}(a,d);const u=Qe(a);null===u&&se(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await Ue(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=oh.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=ft(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||(ft(a)??[]).some(e=>e.propSegments[0]===d)||wh(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=(ft(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=Wa(a.getRootNode())??wh(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,vf.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(!function(e,t,n){const o=rh.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;rh.get(e).delete(t)}}(a,d,f),u=sf(a,d,o,c,f,function(e,t){return sh.get(e)?.get(t)}(a,d)),gh(u)),t.mountRecord=u,n.parentNode!==i)return;try{Bf(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Wf(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),th(a,d)}return fh(a,d),function(e){const t=tf.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}`;nf.has(n)||(nf.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 of(u,"$connectedCallback")}}uh(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const vh={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=yh.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},yh.set(e,t)),t}(e);return bh(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=yh.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&zf(n,o)}),of(n,"$connectedCallback"),!0},disconnecting(e){const t=yh.get(e);return void 0!==t&&null!==t.mountRecord&&(of(t.mountRecord,"$disconnectedCallback"),Rf(t.mountRecord),e.clearConnectedRootNode(),!0)}};let $h=!1;function xh(){$h||($h=!0,Vc("bindComponent",vh),Ps=ih)}function Sh(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Uu(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function Ph(e,t,n,o){const s=n[K];if(void 0!==s){const n=id(t),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=Hu(t,o,n,!1),c=function(e,n,...s){l.call(Uu(t,this,o),e,n,...s)};r.push({path:s,pathInfo:ae(s),handler:c,order:1e6+a++}),i.add(s),e.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(e,r),e.addVolumeWatchPaths?.(i),n.start(e))}const r=n[X];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(Hu(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[j];"function"==typeof i&&(!function(e,t){let n=Gu.get(e);void 0===n&&(n=[],Gu.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 Ih(e,t,n,o=[]){Al(n),function(e,t,n,o){const s=0===o.length?null:Uc(n);for(const e of o){const n=e.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||se(`[wcs/mount-path-invalid] Volume "${t}" declares "${n}" as an accessor or a method and also injects it ("${k}.${n}: ${e.outerPathInfo.path}"). Rename one of them.`)}const r=n[K];if(void 0!==r){"object"==typeof r&&null!==r||se(`${K} must be an object mapping state paths to handler functions.`);const e=id(t);for(const[t,n]of Object.entries(r))"function"!=typeof n&&se(`${K} entry "${t}" must be a function.`),e.assertValidPath(t)}const i=n[X];if(void 0!==i){"object"==typeof i&&null!==i||se(`${X} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(i)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&se(`${X} entry "${n}" must map a list path to a field name or a key function.`);const r=Hu(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[G]&&se(`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(Uc(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(Uc(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=qu.get(e);void 0===n&&(n=new Set,qu.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(Uu(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(Uu(t,this,o),e)}),e.defineTreeAccessor(r,l)}Ph(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(Uu(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 kh(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=Ih(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 Ah=!1;function Nh(){var e;Ah||(Ah=!0,Kf(),Zf||(Zf=!0,Vc("scopes",Qf)),xh(),Zu=kh,e=_h,Da.includes(e)||Da.push(e))}function _h(e,t){(function(e){const t=Bu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){Yu.delete(e);const n=Xu.get(e);if(void 0===n||0===n.length||null===Zu)return;Xu.delete(e);const o=Zu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const Th={name:"scopes",install(){Nh(),Ou||(Ou=!0,Vc("dcc",Mu))}},Eh=/^@@wcs-(?:for|if|elseif|else):[^-]/,Ch=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,Mh=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Oh=/^@@wcs-text-start:(.+)$/;function Rh(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function jh(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const e=n.currentNode;t(e.data)&&o.push(e)}return o}const Lh=e=>Eh.test(e),Dh=e=>Ch.test(e);function Wh(e){const t=e.fragment.cloneNode(!0);for(const n of e.nodeInfos){const o=sl(lt(e.fragment,n.nodePath));if(null===o)continue;const s=lt(t,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return t}class Bh extends Kc{_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=cd.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,n){const s=n??e.ownerDocument,r=document.createElement("script");r.setAttribute("type","application/json"),r.textContent=Rh(JSON.stringify(t)),e.appendChild(r);for(const[t,n]of function(e){const t=new Map,n=[e];for(;n.length>0;)for(const e of jh(n.shift(),Lh)){const o=e.data,s=o.slice(o.indexOf(":")+1);if(t.has(s))continue;const r=Ka(s);null!==r&&(t.set(s,r),n.push(r.fragment))}return t}(s)){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),s.content.appendChild(Wh(n)),e.appendChild(s)}const i=e.ownerDocument,a=Array.from(Hi);if(a.length>0){const t={};for(let e=0;e<a.length;e++){const n=a[e];if(!n.isConnected||n.ownerDocument!==i)continue;const o=Vi(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const e of o)r[e.propName]=e.value;t[s]=r}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=Rh(JSON.stringify(t)),e.appendChild(n)}}Ki()}static removeBlockBoundaryComments(e){for(const t of jh(e,e=>Ch.test(e)||Mh.test(e)))t.remove()}static removeStructuralComments(e){for(const t of jh(e,Lh))t.remove()}static restoreTextBindings(e){for(const t of jh(e,e=>Oh.test(e))){const e=Oh.exec(t.data)[1],n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(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)}}for(const e of jh(t,Dh)){const t=Ch.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()}Bh.restoreTextBindings(t);for(const e of jh(t,Lh)){const t=s.get(e.data.split(":")[1]);if(t){const n=document.createElement("template"),s=t.getAttribute(o.bindAttributeName);s&&n.setAttribute(o.bindAttributeName,s);const r=document.importNode(t.content,!0);if(r.childNodes.length>0)n.content.appendChild(r);else for(const e of Array.from(t.childNodes))n.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(n,e)}}const r=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of r)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const zh={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",cd),Bh.buildContent(o,Bh.extractStateData(e),e.getRootNode()),e.parentNode?.insertBefore(o,e)}Ki()},reset:function(){Va.clear(),Ki()}};const Fh=new Set(["for","if","elseif","else"]);function qh(e){const t=new $s;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t,deferredSpreads:[]};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,a]=bt(s),l=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:l,subscriberNodes:r,bindingSession:t,deferredSpreads:a}}const Vh=/^\s*@@\s*(?:wcs-text)?\s*:/;function Hh(e,t,n){for(const o of t)"event"===o.bindingType||Fh.has(o.bindingType)||(o.node.nodeType!==Node.COMMENT_NODE||"text"===o.bindingType&&Vh.test(o.node.data))&&(o.statePathName in M||ae(o.statePathName).wildcardCount>n||e.push(o))}function Kh(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}`;return jh(e,e=>e===r)[0]??null}function Uh(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=De(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,Ja()],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;il(a),"string"==typeof l&&tl(a,l),ul(n,a,l);Ha(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:rl(a)})}}const Gh={hydrate:async function(e){await _a(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="${cd}". Falling back to full render.`),Bh.cleanupDom(e),!1}for(const n of t)Uh(e,n);Bh.restoreTextBindings(document.body);const n=function(e){const t=[];for(const n of jh(e,Dh)){const e=Ch.exec(n.data),o=e[1],s=e[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=n.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=xi(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a,deferredSpreads:l}=qh(s.nodes);ni(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");Ts(t,r),ri(t,i);const c=[];for(const e of r)e.statePathName in M&&c.push(e);if(Ms(t,c),"for"===s.type&&null!==s.index){const i=Kh(e,"for",s.uuid);if(i){const e=Bs(null,s.index);Mi(i,e,t),Oi(i,s.nodes[s.nodes.length-1]),mi(i,t);const c=ae(s.path+"."+d),u=Sn(c,e);ii(t,u),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Hh(o,r,c.wildcardCount),ka(l,u,a);let f=n.get(s.uuid);f||(f=[],n.set(s.uuid,f)),f.push(e)}}else{const n=Kh(e,s.type,s.uuid);n&&(mi(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Hh(o,r,0),ka(l,null,a))}}for(const[t,o]of n){const n=Kh(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=Ka(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Wa(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&Ys(t,o)})}return o}(document.body,n);Bh.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());const[i,a,l]=bt(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(It(e,null),t.setAttribute("data-wcs-completed",""))}else It(e,null);const c=[],u=[],f=xs(document.body),h=f.initialize(a);ka(l,null,f);for(const e of h)if("event"!==e.bindingType)if(Fh.has(e.bindingType))u.push(e);else{if(e.statePathName.includes(d))continue;c.push(e)}for(const e of u)if("for"===e.bindingType){const t=hn(e),n=Wa(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(_t(t,o),Rt(t,o))})}Ia([...c,...s]);for(const{el:e,parent:t,next:n}of r)t.insertBefore(e,n);const p=new Map;for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))p.set(t.getAttribute("data-wcs-ssr-id"),t);for(const t of e.querySelectorAll(o.tagNames.ssr))for(const[e,n]of Object.entries(t.hydrateProps)){const t=p.get(e);if(t)for(const[e,o]of Object.entries(n))t[e]=o}for(const t of e.querySelectorAll("[data-wcs-completed],[data-wcs-ssr-id]"))t.removeAttribute("data-wcs-completed"),t.removeAttribute("data-wcs-ssr-id");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=Bh.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Ba(e.rootNode);const t=Bh.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",cd),Bh.buildContent(n,t,e.rootNode),e.parentNode?.insertBefore(n,e)}};let Jh=!1;function Xh(){Jh||(Jh=!0,Ma=Gh,function(e){if(!Zc.includes(e)){Zc.push(e);for(const t of td())e(t)}}(e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Bh)}),function(){const t=globalThis;void 0===t[e]&&(t[e]=zh)}())}const Yh={name:"ssr",install(){Xh()}},Qh=new WeakMap,Zh=new Set,ep=new Set;function tp(e){return e.byFromPath.size>0||e.byResetPath.size>0}function np(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function op(e){return Qh.get(e)}function sp(e){rp(e),Qh.delete(e)}function rp(e){Zh.delete(e),ep.delete(e)}const ip=new WeakSet;let ap=0;function lp(e){return op(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function cp(e){if(0===ep.size)return;if(t=e.absolutePathInfo.stateElement,!ep.has(t))return;var t;const n=lp(e);if(void 0!==n)for(const e of n)dp(e)}function dp(e){ip.has(e)||(ip.add(e),ap++)}function up(e){return!!ip.delete(e)&&(ap--,!0)}const fp=/^(?:0|[1-9]\d*)$/;function hp(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function pp(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&&fp.test(t)&&hp(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&hp(e,t))?"object":null}function gp(e,t){const n=pp(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]=gp(o[e],t);return r}function mp(e){return gp(e,new Map)}function yp(e,t,n){if(Object.is(e,t))return!0;const o=pp(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(pp(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(!yp(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&yp(s[e],r[e],n))}function wp(e,t){return yp(e,t,new Map)}const bp=new WeakMap;function vp(e,t){if("function"!=typeof t)return;const n=bp.get(t);void 0===n?bp.set(t,new Set([e])):n.add(e)}function $p(e,t){return"function"==typeof t&&!0===bp.get(t)?.has(e)}const xp={"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-rows":e=>`${U} could not read the rows of "from" for "${e}". Nothing was folded or written.`,"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}".`},Sp={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Pp(e,t,n){null!==kt&&kt({type:"state:watch-error",phase:t,path:`${U}.${e}`,error:n})}function Ip(e,t,n){console.error(`[@wcstack/state] ${xp[n](e)}`,t),Pp(e,Sp[n],t)}function kp(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Ap(e,t){t.then(void 0,()=>{}),Ip(e,new TypeError(`${U} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Np=new WeakSet;const _p="[wcs/scan-declaration-invalid]",Tp=Object.freeze([]);function Ep(e){return`${U} entry "${e}"`}function Cp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Mp(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 Op(e,t,n){0===n.length&&se(`${_p} ${e} "${t}" must be a non-empty state path.${ue}`),n.startsWith("$")&&se(`${_p} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ue}`),n.includes("@")&&se(`${_p} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ue}`),n in Object.prototype&&se(`${_p} ${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(`${_p} ${e} ${t} "${n}" has an empty path segment.${ue}`);return o.wildcardCount>u&&se(`${_p} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Rp(e,t,n,o){const s=Ep(e);0===e.length&&se(`${_p} ${U} entry name must be a non-empty string.${ue}`),(e.includes(c)||e.includes(d))&&se(`${_p} ${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(`${_p} ${s} must not start with "$" (reserved namespace).${ue}`),e in Object.prototype&&se(`${_p} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ue}`),t.has(e)&&se(`${_p} ${s} conflicts with a getter declared on the state.${ue}`),n.has(e)&&se(`${_p} ${s} conflicts with a setter declared on the state.${ue}`),o.has(e)&&se(`${_p} ${s} conflicts with the ${H} entry of the same name — each output has exactly one owner.${ue}`)}function jp(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!$p(e,o)&&se(`${_p} ${Ep(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ue}`)}function Lp(e,t,n,o,s,r){const i=Ep(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&se(`${_p} ${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(`${_p} ${i} "on" must be a non-empty event-token name.${ue}`),n.has(e)||se(`${_p} ${i} on "${e}" is not declared in ${q}.${de(e,n)}${ue}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&se(`${_p} ${i} "from" must be a state path string.${ue}`);const u=Op(i,"from",d),f=Cp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&se(Mp(i,"from",d,f));const h=Cp(u,s);return null!==h&&se(function(e,t,n){return`${_p} ${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(`${_p} ${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 Dp(e,t,n,o){if(void 0===t)return Tp;const s=Ep(e);Array.isArray(t)||se(`${_p} ${s} "resetOn" must be an array of state paths.${ue}`);const r=[];for(const e of t){"string"!=typeof e&&se(`${_p} ${s} "resetOn" must contain only state path strings.${ue}`);const t=Op(s,"resetOn",e);t.wildcardCount>0&&se(`${_p} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${ue}`);const i=Cp(t,o);null!==i&&se(Mp(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&se(`${_p} ${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(`${_p} ${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 Wp(e,t,n=null){const o=e[U];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&se(`${_p} ${U} 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(Uc(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){Al(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)){Rp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&se(`${_p} ${Ep(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ue}`);const o=u;jp(e,a,o);const f=Lp(e,o,t,s,i,n);"initial"in o||se(`${_p} ${Ep(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ue}`),"function"!=typeof o.fold&&se(`${_p} ${Ep(e)} fold must be a function.${ue}`);const h=Dp(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(`${_p} ${Ep(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.${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(`${_p} ${U} 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 Bp(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 ip.has(e)}(e),l=a&&!wp(n,e.initial)?mp(e.initial):n,c=t(l,o,...s);if(kp(c))return void Ap(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,vp(e.name,c)),a&&up(e)}catch(t){Ip(e.name,t,i)}}}function zp(e,t,n){const o=function(e,t){sp(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&np(n,e.source.path,e);for(const t of e.resetOn)np(o,t,e),"event"===e.source.kind&&np(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Qh.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)&&ur().hasQueuedPath(e,n))&&dp(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 Fp="scanEntries",qp={order:8,validate(e,t,n){const o=Wp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Fp,o)},applyEarly(e,t,n){const o=n.get(Fp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=mp(n.initial);e[n.name]=t,vp(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Wn(e,n.source.tokenName).subscribe(Bp(n))}(e,o))},register(e,t,n){const o=n.get(Fp)??null,s=function(e){const t=new Map,n=op(e);if(void 0!==n)for(const e of n.entries)up(e)&&t.set(e.name,e.resetOn);return sp(e),t}(e);e.setScanPaths?.(null===o?null:zp(e,o,s))}};let Vp=!1;const Hp=Object.freeze([]),Kp=Object.freeze([]);function Up(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??Hp,i=e.dynamicDependency.get(n)??Hp,a=t.byFromPath.get(n)??Kp;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Gp=Symbol("wcs-stream-last-notified-uncertain"),Jp=new WeakMap;function Xp(e,t){const n=Jp.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Yp(e,t){const n=Jp.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Gp,error:Object.is(o.error,null)?null:Gp})}const Qp=new Set;function Zp(e){Qp.delete(e)}const eg=new WeakMap;function tg(e){return eg.get(e)??new Map}function ng(e){Zp(e);const t=eg.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Yp(e,n.name)}const og=(e,t)=>t,sg=new Set;function rg(e,t){Al(t);const n=t[H];if(void 0===n)return void Xp(e,sg);"object"==typeof n&&null!==n||se(`${H} must be an object mapping stream names to stream definitions.`);const o=new Map,s=Uc(t);for(const[r,i]of Object.entries(n)){0===r.length&&se(`${H} entry name must be a non-empty string.`),r.includes(c)&&se(`${H} entry "${r}" must be a flat property name ("${c}" is not allowed).`),r.includes(d)&&se(`${H} entry "${r}" must be a flat property name ("${d}" is not allowed).`),r.startsWith("$")&&se(`${H} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&se(`${H} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(r)&&se(`${H} entry "${r}" conflicts with a getter declared on the state.`),e.setterPaths.has(r)&&se(`${H} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||se(`${H} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||$p(r,a)||se(`${H} entry "${r}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&se(`${H} entry "${r}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&se(`${H} entry "${r}" fold must be a function.`),l&&!("initial"in n)&&se(`${H} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&se(`${H} entry "${r}" args must be a function.`);const u={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??og,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in t||(t[r]=u.definition.initial,vp(r,u.definition.initial)),o.set(r,u)}!function(e,t){eg.set(e,t)}(e,o),Xp(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=tg(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&tg(e).has(n),ownKeys:()=>Array.from(tg(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=tg(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(Zt(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):Cl},get:(e,t)=>t===Y?cg(e.stateElement):t===Q?dg(e.stateElement):Cl};async function gg(e,t,n,o){let s=null;const r=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",r,{once:!0});try{const i=await e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError(`[@wcstack/state] ${H}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",r)}}function mg(e){Sg();const t=tg(e);if(0!==t.size){!function(e){Qp.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=op(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=Up(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 ${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}),vp(t.name,t.definition.initial),wg(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{const o=s.fold(e[t.name],n);e[t.name]=o,vp(t.name,o)})},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 Jp.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=Jp.get(e);void 0===s&&(s=new Map,Jp.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=Qp;if(0===t.size)return;const n=[];for(const o of t)for(const t of tg(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)&&tg(e).get(o.name)===o)try{yg(e,o)}catch(n){o.controller?.abort(),t.has(e)&&tg(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),ng(n=e),Zp(n),eg.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){ng(e),ug(e)}};function Sg(){vg||(vg=!0,Rl("streams",pg),Wl("streams",xg),ar(bg,20))}let Pg=0,Ig=0;function kg(e){Pg=e+1}function Ag(){Pg=0}function Ng(){Pg>Ig&&(Ig=Pg)}const _g=new WeakMap;function Tg(e,t,n){let o=_g.get(e);void 0===o&&(o=new Map,_g.set(e,o)),o.set(t,n)}const Eg=new Map;function Cg(e,t){Eg.has(e)||Eg.set(e,t)}function Mg(e){return Eg.get(e)}const Og=new WeakMap,Rg=new WeakMap,jg=new Set,Lg=new Map;function Dg(e){return Og.get(e)??Lg}function Wg(e){jg.add(e),function(e){const t=Qh.get(e);void 0!==t&&(tp(t)&&Zh.add(e),function(e){return e.eventResetByPath.size>0}(t)&&ep.add(e))}(e)}function Bg(){return jg}function zg(e,t){let n=Rg.get(e);void 0===n&&(n=new Map,Rg.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}const Fg=new Map;function qg(e){return Rg.get(e)??Fg}function Vg(e){0===e.length&&se(`[wcs/watch-declaration-invalid] ${K} entry name must be a non-empty state path.`),e.startsWith("$")&&se(`[wcs/watch-declaration-invalid] ${K} entry "${e}" must not start with "$" (reserved namespace).${ue}`),e.includes("@")&&se(`[wcs/watch-declaration-invalid] ${K} 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] ${K} 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] ${K} entry "${e}" has an empty path segment.${ue}`);return t.wildcardCount>u&&se(`[wcs/watch-declaration-invalid] ${K} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Hg(e,t){const n=t[K];if(void 0===n)return null;"object"==typeof n&&null!==n||se(`[wcs/watch-declaration-invalid] ${K} 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] ${K} entry "${t}" must be a function.${ue}`);const n=Vg(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Og.set(e,t)}(e,o),s.size>0?s:null}const Kg={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||Cg(n,o)},swapped(e,t,n){var o;o=n,Eg.has(o)&&Cg(t,Mg(n))}};function Ug(e){for(let t=e;null!==t;t=t.parentListIndex)if(Us(t))return!0;return!1}function Gg(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[Bt](Sn(t.wildcardParentPathInfos[i],r)),l=Js(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=an(o,i,t.wildcardCount);if(l!==c&&!Vs(l,c)){if(Us(c))return"gone";s="replaced"}r=l}return s}function Jg(e,t,n){const o=new Map;for(const s of n){const n=Gg(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 Xg=Object.freeze([]);function Yg(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 Qg(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 Zg(e,t){return t.has(e.stateElement)&&!0===op(e.stateElement)?.entries.has(e.entry)}function em(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>tm(n,e))||up(t)}function tm(e,t){return ur().hasQueuedPath(e,t)}function nm(e,t){!function(e,t,n){if(0!==ap)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=lp(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||up(t)}}(e,t,tm)}function om(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function sm(e,t,n){if(!Zg(e,n))return em(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(Np.has(e))return;Np.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}`),Pp(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=tg(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?e.rows:Jg(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Qg)){let n;try{n=om(t,r,e)}catch(e){Ip(s.name,e,"read-source");continue}const o=a(l,n,Mg(e.absAddress),...e.indexes);if(kp(o))return void Ap(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){Ip(s.name,e,i.failure)}return i.plan}function rm(e,t){const{group:n}=e;if(!Zg(n,t))return void em(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||up(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!wp(o,s.initial):!Object.is(o,e.next)){const o=n.reset?mp(s.initial):e.next;t[s.name]=o,vp(s.name,o)}})}catch(e){Ip(s.name,e,"write")}}function im(e,t,n){if(nm(e,t),0===Zh.size)return Xg;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=op(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=ln(n.listIndex,r.wildcardCount)}for(const s of i)Yg(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)Yg(o,e,t).reset=!0}if(0===o.size)return Xg;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];kg(n);try{for(const n of s){const o=sm(n,e,t);null!==o&&r.push(o)}}finally{Ag()}return r}function am(e){mm(),(0!==Dg(e).size||0!==qg(e).size||function(e){const t=Qh.get(e);return void 0!==t&&tp(t)}(e))&&(Wg(e),function(e){const t=[];for(const n of Dg(e).values())lm(e,n)&&t.push(n);for(const n of qg(e).values())for(const o of n)lm(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{Tg(e,en(e,o.pathInfo,null),n[o.path])}catch(t){dm(e,o.path,"prime",t)}})}(e))}function lm(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const cm={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function dm(e,t,n,o){console.error(`[@wcstack/state] $watch ${cm[n]} "${t}" threw.`,o),null!==kt&&kt({type:"state:watch-error",phase:n,path:t,error:o})}function um(e){const t=Bg();try{if(0===t.size)return void nm(e,t);const n=function(){const e=Ig;return Ig=0,e}();if(n>32){nm(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!==kt&&kt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){kg(n);try{for(const n of e)rm(n,t)}finally{Ag()}}}(im(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=Dg(e).get(s),i=qg(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=ln(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(hm);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];(Ug(o.absAddress.listIndex)||s?.entry===o.entry&&fm(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(Jg(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){dm(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);kg(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Dg(e.stateElement).get(e.entry.path)===e.entry,o=!0===qg(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&pm(e)}}finally{Ag()}}(e,t,n)}finally{Eg.clear()}}function fm(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function hm(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 pm(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=lm(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 dm(0,n.path,"evaluate",e)}const a=r?function(e,t){return _g.get(e)?.get(t)}(t,o):Mg(o);r&&Tg(t,o,i),null!==kt&&kt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){dm(0,n.path,"handler",e)}}let gm=!1;function mm(){gm||(gm=!0,Rl("watch",Kg),Wl("watch",ym),ar(um,10),ir(Ng),rd={assertValidPath:Vg,addEntries:zg,start:am})}const ym={order:10,register(e,t){var n;n=e,jg.delete(n),rp(n),Og.delete(n),function(e){_g.delete(e)}(e);const o=Hg(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?K:U)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&am(e)},deactivate(e){var t;t=e,jg.delete(t),rp(t)}},wm=[Gd,{name:"temporal",install(){mm(),Vp||(Vp=!0,Wl("scan",qp),ir(cp)),Sg()}},$u,Th,Yh,xd,Md];function bm(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(wm),sd(e,t)}function vm(e){return e}const $m={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"真偽性を反転(falsy → true)",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},add:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},sub:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},toFixed:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},upper:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lower:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},capitalize:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:2,maxArgs:2,argTypes:["number","number"]},padStart:{description:"先頭を埋める (length[,char]。char の既定は 0 — JS の既定は空白なので注意)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},padEnd:{description:"末尾を埋める (length[,char]。char の既定は空白 — JS と同じ)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},repeat:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},reverse:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix]。suffix の既定は … — U+2026 の 1 文字)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator]。既定はカンマ + 空白)",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},time:{description:"ロケール形式の時刻 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},datetime:{description:"ロケール形式の日時 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},ymd:{description:"YYYY-MM-DD 形式 ([separator]。既定は -)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式 ([separator]。既定は :)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},coalesce:{description:"null / undefined の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},nullIfEmpty:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},xm=2,Sm=Object.freeze({$trackDependency:"$dependOn",$untrackDependency:"$untracked"});function Pm(){return{version:2,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:E,maxDepth:u},bindingTypes:{elseKeyword:x,spread:S,eventPropertyPrefix:P,explicitPropertyPrefix:c,propNamespaces:{eventToken:I,command:A,class:N,attr:_,style:T}}},filters:Object.keys(Hd),filterMeta:$m,filterAliases:Dd,declarationAliases:Pl,apiAliases:Sm,reservedLifecycle:[O,R,j,L,D],reservedStateApi:[W,B,z,F,q,V,H,K,U,X,G,Y,Q]}}const Im=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),km=Object.freeze([]);function Am(e){if(!o.enableContractAnalyzer)return km;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))Im.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?Nm(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,_m,e=>{t.push(e),null!==kt&&kt(e)}),t}function Nm(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 _m(e){const t=Qe(),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{Bh as Ssr,Ui as TRUSTED_TYPES_POLICY_SLOT,cd as VERSION,xm as WCS_MANIFEST_VERSION,Am as analyzeContract,bm as bootstrapState,Ta as buildBindings,Dd as builtinFilterAliases,$m as builtinFilterMeta,vm as defineState,Ba as getBindingsReady,s as getConfig,Gi as getTrustedTypesPolicy,Pm as getWcsManifest,Ji as setTrustedTypesPolicy};
|
|
1
|
+
const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={seen:!1},o={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},s=o;function r(){return s}const i=Symbol.for("wcstack.binder");const a=Symbol.for("wcstack.binder.pending"),l=Symbol.for("wcstack.binder.taken");function c(){const e=function(){const e=globalThis[i];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;const t=function(){const e=globalThis;let t=e[a];return void 0===t&&(t=[],e[a]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[l];return void 0===t&&(t=new WeakSet,e[l]=t),t}();for(const t of n)o.add(t),e.bind(t)}const d=".",u="*",f=128,h=128,p=100,g="#",m="|",y="prevent",w="stop",b="ro",v=Object.freeze([y,w,b]),$="init",x="sync",S=Object.freeze([$,x]),I="else",P="...",k="on",A="eventToken",N="state",_="command",T="class",E="attr",C="style",M="$",O={};for(let e=0;e<f;e++)O[`${M}${e+1}`]=e;const R=Object.freeze(O),j="$connectedCallback",L="$disconnectedCallback",W="$renderedCallback",D="$errorCallback",B="$stateReadyCallback",z="$bindables",F="$commands",q="$commandTokens",V="$command",H="$eventTokens",U="$on",K="$stream",G="$watch",J="$scan",X="$recursion",Y="**",Q="$listKeys",Z="$streamStatus",ee="$streamError",te="data-wc-definition",ne=/\{\{\s*(.+?)\s*\}\}/g,oe=new Set(["SCRIPT","STYLE"]);function se(e){if(!s.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&oe.has(e.parentElement.tagName)||re(e)}(e);const t=Array.from(e.querySelectorAll("template"));for(const e of t)if("http://www.w3.org/2000/svg"===e.namespaceURI){const t=document.createElement("template"),n=Array.from(e.childNodes);for(let e=0;e<n.length;e++){const o=n[e];t.content.appendChild(o)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),se(t.content)}else se(e.content)}function re(e){const t=e.data;if(ne.lastIndex=0,!ne.test(t))return;ne.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=ne.exec(t));){o.index>s&&n.appendChild(document.createTextNode(t.slice(s,o.index)));const e=o[1];n.appendChild(document.createComment(`@@: ${e}`)),s=o.index+o[0].length}s<t.length&&n.appendChild(document.createTextNode(t.slice(s))),e.parentNode.replaceChild(n,e)}function ie(e){throw new Error(`[@wcstack/state] ${e}`)}const ae=new Map;let le=0;function ce(e){let t=ae.get(e);if(void 0!==t)return t;-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] "${e}" uses "${Y}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`);const n=function(e){let t=1;for(let n=0;n<e.length;n++)e[n]===d&&t++;return t}(e);return n>512&&ie(`[wcs/binding-syntax] "${e}" has ${n} path segments — the limit is 512. Every prefix of a path is interned, so the cost grows with the square of the depth.`),t=Object.freeze(new de(e)),ae.set(e,t),t}class de{id=++le;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(e){const t=t=>e===t?this:ce(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],d=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===u&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),c.push(t(h)),d.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=d,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function ue(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;const o=new Array(t.length+1),s=new Array(t.length+1);for(let e=0;e<=t.length;e++)o[e]=e;for(let n=1;n<=e.length;n++){s[0]=n;for(let r=1;r<=t.length;r++){const i=e[n-1]===t[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let e=0;e<=t.length;e++)o[e]=s[e]}return o[t.length]}function fe(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ue(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const he=" Validate statically: npx @wcstack/lint <file>.",pe=new Set(["if","elseif","else","for"]);function ge(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}function me(e){if(0===e.length)return"";let t="";for(let n=0;n<e.length;n++){const o=e[n];n>0&&(t+="|"),t+=`${o.filterName}(${ge(o.args,o.literals??o.args)})`}return t}let ye=null;const we=new Map([["not",()=>e=>!e]]),be=new Map([["not",[0,0]]]),ve={input:new Map,output:new Map},$e={input:new Map,output:new Map},xe={input:new Map,output:new Map},Se=new Map;function Ie(e,t,n,o){const s=ve[e],r=$e[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}const i=o??{},a=xe[e];for(const[e,n]of[...a])Object.prototype.hasOwnProperty.call(t,n)&&i[e]!==n&&a.delete(e);for(const e of Object.keys(i))a.set(e,i[e]);Se.clear()}function Pe(e,t,n,o=t){const s=xe[n].get(e);void 0!==s&&ye?.renamed(e,s);const r=s??e,i=`${r}${ge(t,o)}:${n}`,a=Se.get(i);if(void 0!==a)return a;const l=ve[n].get(r)??we.get(r);if(void 0===l){const t=0===ve[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";ie(`[wcs/filter-unknown] filter not found: ${e}.${fe(e,function(e){return[...new Set([...we.keys(),...ve[e].keys()])]}(n))}${t}${he}`)}const c=$e[n].get(r)??be.get(r);void 0!==c&&(t.length<c[0]||t.length>c[1])&&ie(t.length<c[0]?`[wcs/filter-arity] filter "${e}" requires at least ${c[0]} argument(s) (${t.length} given).${he}`:`[wcs/filter-arity] filter "${e}" accepts at most ${c[1]} argument(s) (${t.length} given).${he}`);const d=l(t,o);return Se.set(i,d),d}function ke(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const Ae=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function Ne(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:Ae.test(e)?Number(e):e)}function _e(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=ke(o,i,a);t.push(e),n.push(Ne(e,r)),o="",r=!1,i=-1,a=-1};for(let t=0;t<e.length;t++){const n=e[t];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&ie(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${he}`);const c=ke(o,i,a);return(c||r)&&(t.push(c),n.push(Ne(c,r))),{args:t,literals:n}}const Te=e=>e.trim(),Ee=e=>"'"===e||'"'===e;function Ce(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if(Ee(s))n=s;else if(s===t)return o}return-1}function Me(e,t){const n=[];let o=null,s=0;for(let r=0;r<e.length;r++){const i=e[r];null!==o?i===o&&(o=null):Ee(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}function Oe(e,t,n){const o=n??e.join("|");return e.map(e=>{const n=Ce(e,"(");let s=function(e,t){let n=null,o=-1;for(let s=0;s<e.length;s++){const r=e[s];null!==n?r===n&&(n=null):Ee(r)?n=r:r===t&&(o=s)}return o}(e,")");if(-1===s&&(s=e.lastIndexOf(")")),-1!==n&&-1===s&&ie(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${e}".${he}`),-1!==s&&-1===n&&ie(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${e}".${he}`),-1!==s&&s<n&&ie(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${e}".${he}`),-1!==s&&e.slice(s+1).trim().length>0){const t=e.slice(s+1).trim();ie(`[wcs/binding-syntax] "${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,s+1)}|${t}").${he}`)}const r=(-1===n?e:e.substring(0,n)).trim();if(0===r.length&&ie(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${he}`),r.includes(g)){const[e,n]=r.split(g);ie("input"===t?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${g}${n}" comes before the input filters, not inside one — write "<property>${g}${n}|${e}".${he}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${g}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${e}" here.${he}`)}if(-1===n)return{filterName:r,args:[],literals:[]};return{filterName:r,..._e(e.substring(n+1,s))}})}const Re=new Map;function je(e){const t=Ce(e,m);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Re.has(s)?r=Re.get(s):(o=Me(s,m).map(Te),r=Oe(o,"input",e),Re.set(s,r))):n=e.trim();const i=n.split(g).map(Te);i.length>2&&ie(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${g}" — write "${i[0]}${g}${i.slice(1).join(",")}".${he}`);const[a,l]=i,c=a.split(d).map(Te);c.length>1&&""===c[0]||0!==a.length&&!c.some(e=>0===e.length)||ie(`[wcs/binding-syntax] "${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${he}`);return{propName:a,propSegments:c,propModifiers:l?l.split(",").map(Te):[],inFilters:r}}const Le=new Map;function We(e){const t=Ce(e,m);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Le.has(s)?r=Le.get(s):(o=Me(s,m).map(Te),r=Oe(o,"output",e),Le.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&ie(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);const i=n,a=i.startsWith(d),l=a?i.slice(1):i;(l.length>0&&l.split(d).some(e=>0===e.length)||!a&&0===l.length)&&ie(`[wcs/binding-syntax] "${e}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).${he}`);return{statePathName:i,statePathInfo:ce(i),outFilters:r}}const De=new Set([I,"if","elseif","for",P]),Be=new Set([T,E,C,_,A,N]);function ze(e){const[...t]=function(e){return Me(e,";")}(e).map(Te).filter(e=>e.length>0),n=t.map(e=>{const t=Ce(e,":");-1===t&&ie(`[wcs/binding-syntax] Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.${he}`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(g)[0].split(m)[0].trim();if(s!==n&&De.has(s)&&ie(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${he}`),n===I){o.length>0&&ie(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${he}`);const t=ce("#else");return{propName:I,propSegments:[I],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===P){0===o.length&&ie(`[wcs/binding-syntax] Invalid spread binding "${e}": spread target path is required.${he}`);const t=We(o);return t.outFilters.length>0&&ie(`[wcs/binding-syntax] Invalid spread binding "${e}": filters are not allowed on spread targets.${he}`),{propName:P,propSegments:[P],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...We(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=We(o);return{...je(n),...e,bindingType:s}}{const e=We(o),t=je(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Be.has(o[0]))&&ie(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Be].join(", ")}).${he}`),{...t,propName:o.join(d),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===A||t.propSegments[0].startsWith(k)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>pe.has(e.bindingType))&&ie(`[wcs/template-syntax] Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${he}`)}return n}const Fe=new WeakMap,qe=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),Ve=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function He(e){const t=Fe.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),o=Ve.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return qe.has(r)?(Fe.set(e,o[2]),o[2]):null}function Ue(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...We(e),bindingType:"text"}}const Ke=new WeakMap,Ge=new WeakSet;let Je=0;async function Xe(e){const t=function(e){let t,n=Ke.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++Je,promise:o,resolve:t},Ke.set(e,n),Ge.has(e)&&n.resolve(),n}(e);await t.promise}function Ye(e){const t=Ke.get(e);void 0===t?Ge.add(e):t.resolve()}const Qe=new WeakMap;function Ze(e){const t=Qe.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{Qe.set(e,n)}}function et(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function tt(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return et(t);if(void 0!==n)return et(n)}return et(globalThis.customElements)}function nt(e,t){e.upgrade?.(t)}function ot(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=at(s.properties,st);if(null===r)return null;const i=void 0===s.inputs?new Map:at(s.inputs,rt);if(null===i)return null;const a=void 0===s.commands?new Map:at(s.commands,it);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function st(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function rt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function it(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function at(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function lt(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ce(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ct(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function dt(e,t,n={}){const o=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&ie("Spread binding requires an element node.");const t=e,s=Ze(t);null===s&&ie(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=tt(t);null===a&&ie(`CustomElementRegistry is unavailable for <${s}>.`);if(void 0===a.get(s)){o||ie(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}nt(a,t);const l=ot(t);null===l&&ie(`Spread binding "${n.statePathName}" requires <${s}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=lt(e,c);i.add(t),r.push(t)}for(const e of l.declaredInputs.keys()){if(d.has(e))continue;d.add(e);const t=lt(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=ct(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=ct(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(s.debug&&i.has(r[t])){const o=r[a.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[t])}return l}function ut(e,t){let n=e;for(let e=0;e<t.length;e++){let o=t[e];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function ft(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:Pe(s.filterName,s.args,t,r)})}return n}function ht(e){return{...e,inFilters:ft(e.inFilters,"input"),outFilters:ft(e.outFilters,"output")}}const pt=new WeakMap;function gt(e){return pt.get(e)||null}function mt(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(s.bindAttributeName)}function yt(e){const t=[],n=e.querySelectorAll(`${s.tagNames.state}[bind-component]`);for(const o of n){if(!mt(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function wt(e,t){for(let n=0;n<t.length;n++){const o=t[n];if(o!==e&&o.contains(e))return!0}return!1}function bt(e){const t=[],n=yt(e),o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==He(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();){const e=o.currentNode;n.length>0&&wt(e,n)||t.push(e)}return t}const vt=new WeakSet;function $t(e,t,n,o){const s=dt(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ze(e):null;return null===n&&ie("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}vt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=ft(o.inFilters,"input"),s=ft(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:e});else{const r=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:r})}}return n}(e,function(e,t){return void 0===t?e:e.map(e=>null!=e.uuid?e:t(e))}(s,o));return function(e,t){pt.set(e,t)}(e,r),Ye(e),{bindings:r,deferred:null}}function xt(e,t){return St(bt(e),t)}function St(e,t){const n=[],o=[];for(const s of e){if(vt.has(s))continue;const e=$t(s,sc(s),{allowDeferred:!0},t);null===e.deferred?n.push(...e.bindings):o.push(e.deferred)}return[e,n,o]}function It(e){vt.add(e)}function Pt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){vt.delete(e)}(t);return $t(t,n,{allowDeferred:!1},o).bindings}const kt=new WeakMap;let At=null;function Nt(e){let t=e;for(;t;){const e=kt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==At&&t instanceof ShadowRoot&&(n=At(t)),t=n}return null}function _t(e,t){null!==t?kt.set(e,t):kt.delete(e)}let Tt=null;let Et=0;function Ct(){return`u${(Et++).toString(36)}`}let Mt=0,Ot=0;const Rt=Symbol("wcs.listIndex.noValue");class jt{uuid=Ct();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;cacheStamp=0;ref;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Rt,this._index=t,this._version=Mt,this._chainGeneration=Ot}get index(){return this._index}set index(e){this._index=e,this._version=++Mt,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}set homeParentListIndex(e){this._homeParentListIndex=e}get value(){return this._value}set value(e){this._value=e}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=Mt),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Ot||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Ot),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Mt,Ot++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Lt(e,t,n=e){return new jt(e,t,n)}function Wt(e,t){e.reparent(t)}function Dt(e){return e.homeParentListIndex}function Bt(e,t){e.homeParentListIndex=t}function zt(e){return e?.cacheStamp}function Ft(e,t){const n=e,o=n.value,s=o!==Rt&&!Object.is(o,t);return o!==t&&(qt.get(o)?.delete(n.ref),function(e,t){if("object"!=typeof e||null===e||null===t.parentListIndex)return;let n=qt.get(e);void 0===n?(n=new Set,qt.set(e,n)):n.size>=(Vt.get(n)??8)&&(Ht(n,t,!0),Vt.set(n,2*n.size+8));n.add(t.ref??=new WeakRef(t))}(t,n)),n.value=t,s}const qt=new WeakMap,Vt=new WeakMap;function Ht(e,t,n=!1){const o=[];return e?.forEach(s=>{const r=s.deref();void 0===r||n&&Kt(r)?e.delete(s):r!==t&&o.push(r)}),o}const Ut=new WeakSet;function Kt(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ut.has(t))return!0;return!1}function Gt(e){return e.value}function Jt(e,t){const n=e.value;return n!==Rt&&n===t.value}let Xt=0;const Yt=new WeakSet;function Qt(e){Yt.add(e)}function Zt(e){return Yt.has(e)}const en=new WeakMap;function tn(e){return Ut.has(e)}const nn=new WeakMap;const on=new WeakMap,sn=new WeakMap;function rn(e,t){return!0===nn.get(t)?.has(e)}function an(e,t){return rn(e,t)||Kt(t)}const ln=new WeakMap;function cn(e){ln.delete(e)}function dn(e,t,n){const o=Object(Gt(t)),s=Gt(n);for(const t in s)if(s[t]===e&&o[t]!==e)return!1;return!0}function un(e,t){return!an(e,t)&&ln.get(t)!==Xt}const fn=new WeakMap,hn=new WeakMap;const pn=new WeakSet;function gn(e,t){const n=(o=e,Ht(qt.get(o.value),o));var o;if(0===n.length)return n;const s=new Set(en.get(t()));return n.filter(t=>t.position===e.position&&!s.has(t)&&!Kt(t))}function mn(e,t,n){const o=Dt(t),s=t.parentListIndex;return null!==o&&o!==s&&!an(e,o)&&dn(e,o,s)?o:function(e,t,n,o){return null!==t&&null!==o&&o!==n&&!!Ut.has(t)&&!(!un(e,o)||o.position!==t.position)&&!rn(e,t)&&Jt(o,t)}(e,o,s,n)||function(e,t,n){return t!==n&&null!==t&&null!==n&&t.position===n.position&&an(e,t)&&un(e,n)}(e,s,n)?n:null}function yn(e){const t=en.get(e);return void 0===t?null:t}function wn(e,t){const n=en.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o&&!Zt(e)){const s=null!==t&&o.parentListIndex!==t&&ln.get(t)!==Xt,r=mn(e,o,t);if(null!==r&&pn.has(e)){pn.delete(e);const t=[...e];Qt(t),en.set(t,n),In(e,t);const o=n.map((t,n)=>{const o=Lt(r,n);return Ft(o,e[n]),o});return en.set(e,o),o}if(null!==r)for(const e of n)Wt(e,r);else if(s){!function(e,t){let n=fn.get(e);void 0===n?(n=new Set,fn.set(e,n)):n.size>=(hn.get(e)??8)&&(n.forEach(t=>{an(e,t)&&n.delete(t)}),hn.set(e,2*n.size+8));for(const e of t)n.add(e)}(e,[o.parentListIndex,t]);const s=o.parentListIndex;if(null!==s&&s.position===t.position&&!dn(e,s,t)&&dn(e,t,s))for(const e of n)Wt(e,t)}}return n}const bn=new WeakSet;function vn(e){bn.delete(e)}function $n(e,t,n=!1){null!==t?(n?bn.add(t):vn(t),en.set(e,t)):en.delete(e)}const xn=new WeakMap;function Sn(e){let t=xn.get(e);return void 0===t&&(t={value:e},xn.set(e,t)),t}function In(e,t){const n=xn.get(e);void 0!==n&&(n.value=t,xn.delete(e))}const Pn=new WeakMap,kn=new WeakMap,An=new Set,Nn=new WeakMap,_n=new WeakMap;function Tn(e){const t=e.absolutePathInfo.stateElement;let n=kn.get(t);return void 0===n&&(n=new WeakMap,kn.set(t,n)),n}function En(e){return Pn.get(e)??[]}function Cn(e,t){const n=Pn.get(e);Pn.set(e,t),_n.delete(e);const o=Tn(e);n!==t&&void 0!==n&&o.get(n).delete(e);const s=o.get(t);void 0===s?o.set(t,new Set([e])):s.has(e)||(s.size>=(Nn.get(s)??8)&&(s.forEach(e=>{Mn(e.listIndex)&&s.delete(e)}),Nn.set(s,Math.max(8,2*s.size))),s.add(e))}function Mn(e){for(let t=e;null!==t;t=t.parentListIndex)if(tn(t))return!0;return!1}function On(e,t){const n=Tn(e).get(t);return void 0===n?An:(n.forEach(e=>{Mn(e.listIndex)&&n.delete(e)}),n)}function Rn(e,t){return!_n.has(e)&&(_n.set(e,t),!0)}function jn(e){return Pn.has(e)}const Ln=new WeakMap;let Wn=null,Dn=0;function Bn(e){return Ln.get(e)??[]}function zn(e,t){null===Wn?Ln.set(e,t):Wn.set(e,t)}function Fn(){Dn++,null===Wn&&(Wn=new Map)}function qn(){if(0!==Dn&&(Dn--,!(Dn>0||null===Wn))){for(const[e,t]of Wn)Ln.set(e,t);Wn=null}}function Vn(e){return(Wn?.has(e)??!1)||Ln.has(e)}const Hn=Symbol("$$setLoopContext"),Un=Symbol("$$getByAddress"),Kn=Symbol("$$hasByAddress"),Gn=Symbol("$$connectedCallback"),Jn=Symbol("$$disconnectedCallback"),Xn=Symbol("$$updatedCallback"),Yn=Symbol("$$errorCallback"),Qn=new WeakMap,Zn=new WeakMap;class eo{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function to(e,t){if(null===t){let t=Zn.get(e);return void 0!==t||(t=new eo(e,null),Zn.set(e,t)),t}{let n=Qn.get(t);void 0===n&&(n=new WeakMap,Qn.set(t,n));let o=n.get(e);return void 0!==o||(o=new eo(e,t),n.set(e,o)),o}}const no=new WeakMap;function oo(e,t){let n=no.get(e);void 0===n&&(n=new Map,no.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new so(e,t)),n.set(t,o)),o}class so{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function ro(e,t){return to(oo(e,t.pathInfo),t.listIndex)}function io(e,t,n){return to(oo(e,t),n)}const ao=new WeakMap;function lo(e,t){null===t?ao.delete(e):ao.set(e,t)}function co(e){return ao.get(e)||null}const uo=new Map;function fo(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=uo.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,uo.set(s,r),r}function ho(e,t,n){return t<0||t>=n?null:e.at(t-n)}function po(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const go=new WeakMap;function mo(e){const t=Nt(e.node);if(null===t)return null;let n=go.get(t);if(void 0===n)n=new WeakMap,go.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=fo(t.pathInfo,e.statePathInfo);return n>0&&(o=ho(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const yo=new WeakMap;function wo(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=co(n);null===t?ie(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function bo(e,t){let n=null;if(n=yo.get(e)||null,null!==n)return n;const o=wo(e,t),s=mo(e),r=Xl(o);return null===r&&ie("No state tree found on this root for binding."),n=io(r,e.statePathInfo,s),yo.set(e,n),n}function vo(e){yo.delete(e)}const $o=new WeakMap;function xo(e,t){const n=$o.get(e);void 0===n?$o.set(e,t):n instanceof Set?n.add(t):n!==t&&$o.set(e,new Set([n,t])),null!==Tt&&Tt({type:"state:binding-added",absoluteAddress:e,binding:t})}function So(e,t){const n=$o.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&$o.delete(e),null!==Tt&&Tt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const Io=new WeakMap;function Po(e){const t=$o.get(e);return void 0!==t?t:null!==e.listIndex?Io.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const ko=new WeakMap,Ao=new WeakMap;class No{pathInfo;listIndex;_parentAddress;_rowAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t,this._rowAddress=null!==t&&e.lastSegment===u}get parentAddress(){const e=this._parentAddress;if(void 0!==e&&(!this._rowAddress||e.listIndex===this.listIndex.parentListIndex))return e;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let n=null;n=this.pathInfo.segments[this.pathInfo.segments.length-1]===u?this.listIndex?.parentListIndex??null:this.listIndex;const o=To(t,n);return void 0!==e&&!_o(o,this.listIndex)&&_o(e,this.listIndex)?e:this._parentAddress=o}}function _o(e,t){const n=e.pathInfo;let o=Gt(e.listIndex);for(const e of n.segments.slice(n.wildcardPositions[n.wildcardCount-1]+1))o=Object(o)[e];return yn(o)?.[t.index]===t}function To(e,t){if(null===t){let t=Ao.get(e);return void 0!==t||(t=new No(e,null),Ao.set(e,t)),t}{let n=ko.get(t);void 0===n&&(n=new WeakMap,ko.set(t,n));let o=n.get(e);return void 0!==o||(o=new No(e,t),n.set(e,o)),o}}const Eo=new WeakMap;function Co(e){let t=null;if(t=Eo.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=mo(e);null===n&&ie(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=To(e.statePathInfo,n)}else t=To(e.statePathInfo,null);return Eo.set(e,t),t}function Mo(e){Eo.delete(e)}function Oo(){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 Ro=new Map,jo=Oo();function Lo(e,t){const n=me(e.inFilters);return`${e.statePathName}::${t}::${n}`}function Wo(e){let t="input";for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}function Do(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const o=Wo(e),s=Lo(e,o);let r=Ro.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=Xl(o.getRootNode());null===i&&ie("No state tree found on this root for two-way binding.");const a=Nt(o);i.createState("writable",e=>{e[Hn](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]:[]})})},Ro.set(s,r)),e.node.addEventListener(o,r),jo.add(s,e),!0}var t,n;return!1}function Bo(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function zo(e,t){console.error(`[wcstack/state] ${t} rejected.`,e)}function Fo(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Bo(e)&&Promise.resolve(e).catch(e=>zo(e,t))}class qo{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,e)}return t}}class Vo extends qo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Tt&&Tt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Ho=new WeakMap;function Uo(e,t){let n=Ho.get(e);void 0===n&&(n=new Map,Ho.set(e,n));let o=n.get(t);return void 0===o&&(o=new Vo(t,e),n.set(t,o)),o}const Ko=new WeakMap;function Go(e){if(e.propSegments[0]!==A)return!1;const t=e.node,n=Ze(t),o=tt(t);if(null!==n&&void 0===o?.get(n))return null===o&&ie(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Ko.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||ie('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Ze(e)?null:ot(e)}(t);null===r&&ie(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&ie(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${fe(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(y)&&e.preventDefault(),c.includes(w)&&e.stopPropagation();const n=Xl(t.getRootNode());null===n&&ie("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||ie(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${fe(l,n.eventTokenNames)}${he}`);const o=Nt(t);n.createStateAsync("writable",async t=>{Fo(t[Hn](o,()=>{const s=null!==o?po(o.listIndex,o.pathInfo.wildcardCount):[];return Uo(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Ko.set(e,{eventName:a,handler:d}),!0}class Jo extends qo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Tt&&Tt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Xo(e){return e instanceof Jo}const Yo=new Map,Qo=Oo();function Zo(e){const t=e.propModifiers.filter(e=>e===y||e===w).sort().join(",");return`${e.statePathName}::${t}`}const es=(e,t,n)=>o=>{t.includes(y)&&o.preventDefault(),t.includes(w)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Xl(r);null===i&&ie("No state tree found on this root for event handler.");const a=Nt(s),l=e.startsWith(V+".");i.createStateAsync("writable",async t=>{const c=t[Hn](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?po(a.listIndex,c):[];if(l){const s=t[Un](To(n,null));return Xo(s)||ie(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...d)}const u=t[e];return"function"!=typeof u&&ie(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Fo(c,`"${e}"`)}).catch(t=>zo(t,`"${e}"`))};function ts(e){return"event"===e.bindingType&&e.propName.startsWith(k)}function ns(e){if(!ts(e))return!1;const t=Zo(e);let n=Yo.get(t);void 0===n&&(n=es(e.statePathName,e.propModifiers,e.statePathInfo),Yo.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Qo.add(t,e),!0}function os(e){if(!ts(e))return!1;const t=Zo(e),n=Yo.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Qo.countOf(t)&&(Qo.remove(t,e)&&Yo.delete(t),!0)}const ss=new Map,rs=Oo();function is(e,t){const n=me(e.inFilters);return`${e.statePathName}::${t}::${n}`}function as(e){let t="input";for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}function ls(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const o=as(e),s=is(e,o);let r=ss.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=Xl(o.getRootNode());null===r&&ie("No state tree found on this root for two-way binding.");const i=Nt(o);r.createState("writable",e=>{e[Hn](i,()=>{e[t]=s})})},ss.set(s,r)),e.node.addEventListener(o,r),rs.add(s,e),!0}var t,n;return!1}const cs=new Set(["radio","checkbox"]),ds=new Set(["value","valueAsNumber","valueAsDate"]);function us(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(cs.has(e)&&"checked"===t)return!0;if(ds.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ze(n);if(null!==s){const e=tt(n)?.get(s);void 0===e&&ie(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=ot(n);if(o?.knownProperties.has(t))return!0}return!1}let fs=1,hs=1,ps=1;const gs=new WeakMap;function ms(e,t,n){let o=gs.get(e);void 0===o&&(o=new Map,gs.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=fs++,o.set(s,r)),r}function ys(e,t){return"to-element"===t?2*e:2*e+1}const ws=new Set;function bs(e){return{transactionId:hs++,originBindingId:e,visitedEdges:ws,hop:0}}function vs(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 $s=null;function xs(){return $s}function Ss(e,t){const n=$s;$s=e;try{return t()}finally{$s=n}}const Is=[];let Ps=0;function ks(e,t,n,o,s=!1){Ps=s?2:1;try{e.createState("writable",e=>{e[Hn](t,()=>{e[n]=o})})}finally{Ps=0}}const As=new Map,Ns=Oo(),_s=new WeakMap,Ts=e=>e.detail,Es=new WeakMap;const Cs=new WeakMap;let Ms=0;const Os=new WeakMap;function Rs(e,t,n,o){const s=me(e.inFilters);return`${e.propName}::${e.statePathName}::${t}::${s}::${function(e){if(null===e)return"n";let t=Cs.get(e);return void 0===t&&Cs.set(e,t=++Ms),`g${t}`}(n)}::${o?"o":"s"}`}const js=(e,t,n,o,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==o)l=o(i),o!==Ts||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=Es.get(e);void 0===r&&(r=new Set,Es.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=_s.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(s.enablePropagationContext){const n=ms(a,e,t),o=function(e,t){for(let n=Is.length-1;n>=0;n--){const o=Is[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==o&&Object.is(o.writtenValue,l))return s.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:o.transactionId,coveredBySameValueGuard:s.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==Tt&&Tt({type:"propagation:suppressed",reason:"confirmation",transactionId:o.transactionId,edgeId:ys(n,"to-state"),node:a,member:e}));const r=ys(n,"to-state"),i=xs();if(null!==i&&i.visitedEdges.has(r))return void(null!==Tt&&Tt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=vs(i??bs(n),r)}const f=Xl(a.getRootNode());null===f&&ie("No state tree found on this root for two-way binding.");const h=Nt(a),p=()=>ks(f,h,t,c,r);null!==u?Ss(u,p):p()};function Ls(e){const t=Ze(e.node);if(null!==t){const n=tt(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&ie(`CustomElementRegistry is unavailable for <${t}>.`))}if(us(e.node,e.propName)&&-1===e.propModifiers.indexOf(b)){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ze(e.node);if(null!==n){const o=tt(e.node)?.get(n);void 0===o&&ie(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=ot(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(k)&&(t=n.slice(2));return t}(e),n=function(e){if(null!==Ze(e.node)){const t=ot(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??Ts}return null}(e),o=function(e){if(null===Ze(e.node))return!1;const t=ot(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}(e),s=Rs(e,t,n,o);Os.set(e,{key:s,eventName:t});let r=As.get(s);void 0===r&&(r=js(e.propName,e.statePathName,e.inFilters,n,o),As.set(s,r)),e.node.addEventListener(t,r),Ns.add(s,e)}}const Ws=new WeakSet;function Ds(e){Ws.add(e)}function Bs(e){return!!Ws.has(e)&&(Ws.delete(e),!0)}const zs=new WeakMap;function Fs(e,t){const n=zs.get(e);return!(void 0===n||n<t)&&(n===t?zs.delete(e):zs.set(e,n-t),!0)}const qs=new WeakSet;function Vs(e){qs.add(e)}function Hs(e){return!!qs.has(e)&&(qs.delete(e),!0)}let Us=0;function Ks(){Us--}function Gs(){return Us>0}class Js{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 Xs=new WeakMap;function Ys(e){let t=Xs.get(e);return void 0===t&&(t=new Js(e),Xs.set(e,t)),t}const Qs=new Set([T,E,C,_]);function Zs(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==$&&s!==x&&ie(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&ie(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function er(e){return e.propModifiers.some(e=>e.includes("="))}const tr=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),nr=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function or(e,t){return"state"===e&&"call"===t?tr:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function sr(e){if(!s.enableDirectionalInitialSync)return er(e)&&ie("init=/sync= modifiers require enableDirectionalInitialSync."),tr;const t=null===(n=Zs(e,$))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:ie(`Invalid init modifier value "${n}".`);var n;const o=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":ie(`Invalid sync modifier value "${e}".`)}(Zs(e,x));if("event"===e.bindingType)return null!==t&&"none"!==t&&ie("Event bindings only allow init=none."),"call"===o?nr:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(Qs.has(e.propSegments[0]))return or("state",o);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&ie(`Binding type "${e.bindingType}" does not support init=${t}.`),or(t??"state",o);const r=ot(e.node);if(null===r)return or(t??"state",o);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||ie(`Property "${e.propName}" is not declared by wcBindable.`);const l=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||ie(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==o||i||ie(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:o,observable:i,outputOnly:i&&!a}}function rr(e){let t=e.getRootNode();return t instanceof DocumentFragment&&!(t instanceof ShadowRoot)&&(t=co(t)),null===t?null:Xl(t)}function ir(e,t){return"auto"!==t?t:function(e){const t=rr(e.replaceNode);null===t&&ie("No state tree found on this root for binding.");const n=Co(e);let o=!1;return t.createState("readonly",e=>{o=e[Kn](n)}),o}(e)?"state":"element"}let ar=0,lr=null,cr=0;const dr=["active","disposed","failed"],ur=new WeakMap,fr=new WeakMap,hr=new WeakMap,pr=new WeakMap,gr=new WeakMap,mr=new WeakMap;function yr(e,t){const n=mr.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):mr.set(e,new Set([n,t]))):mr.set(e,t)}function wr(e){return mr.has(e)}function br(e,t){const n=mr.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function vr(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))vr(n,t)}function $r(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class xr{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||!Fs(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)Bs(e)||vr(e,e=>{br(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Hs(e)&&!Gs()||vr(e,e=>{br(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&jl(o)}}const Sr=new WeakMap;function Ir(e){let t=Sr.get(e);return void 0===t&&(t=new xr(e),Sr.set(e,t)),t}function Pr(e){const t=me(e.inFilters),n=me(e.outFilters);return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function kr(e,t,n){const o=Xl(wo(e,n));null===o&&ie("No state tree found on this root for binding.");const s=oo(o,e.statePathInfo);return function(e,t,n){let o=Io.get(e);void 0===o&&(o=new WeakMap,Io.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!==Tt&&Tt({type:"state:binding-added",absoluteAddress:to(e,t),binding:n})}(s,t,e),s}function Ar(e,t){const n=bo(e,t);return xo(n,e),n}function Nr(e,t,n,o){null!==t?So(t,e):function(e,t,n){const o=Io.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!==Tt&&Tt({type:"state:binding-removed",absoluteAddress:to(e,t),binding:n}))}(n,o,e),Mo(e),vo(e)}function _r(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class Tr{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;disposedAt=0;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=this.rowOf(e),i=null===o?-1:o.bindings.indexOf(e);if(null!==o&&0===o.phases[i]){const t=o;this.observe(e.replaceNode),s.registerAddress&&null===t.addresses[i]&&null===t.patternPathInfos[i]&&(t.registered=!0,this.registerRowSlot(t,i));continue}const a=hr.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($r(t)&&Ir(t),null===this.rowPlan)for(const n of e){const e=hr.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!s.enableDirectionalInitialSync)return er(e)&&sr(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=hr.get(e);return void 0===n||n.session!==this||(!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority)))}getRecord(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0){let o=fr.get(t);void 0===o&&fr.set(t,o=[]);return{id:o[n]??(o[n]=++ar),info:e,generation:t.generation,phase:dr[t.phases[n]],teardowns:null}}const o=hr.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=hr.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(_r(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=this.deferredByNode.get(e)??new Set,r=()=>s.delete(a)&&this.deferred.delete(a),i=()=>{const s=tt(e);null===s&&ie(`CustomElementRegistry is unavailable for <${t}>.`),a.cancel=Ys(s).wait(t,()=>{if(r())try{nt(s,e),n()}catch(e){o(e)}},e=>{r()&&o(e)})},a={node:e,born:++cr,cancel:null,arm:()=>{if(null===a.cancel&&this.deferred.has(a))try{i()}catch(e){r(),o(e)}}},l=e.getRootNode();if(null!==lr||11===l.nodeType&&!$r(l)){if(null===lr){const e=lr=[];queueMicrotask(()=>{lr=null;for(let t=0;t<e.length;t++)e[t].arm()})}lr.push(a)}else i();return $r(l)&&Ir(l),yr(e,this),this.deferredByNode.set(e,s.add(a)),this.deferred.add(a),()=>{r(),a.cancel?.()}}disposeBinding(e){const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0)return void this.disposeRowSlot(t,n)}const n=hr.get(e);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(e){for(let t=0;t<e.length;t++)this.disposeBinding(e[t]);if(!(this.rows.size>0))for(const e of Array.from(this.deferred))e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}destroyRow(e){const t=e.length>0?this.rowOf(e[0]):null;null!==t?(this.destroyRowRecord(t),this.rows.delete(t)):this.destroyRecords()}destroyRowRecord(e){for(let t=0;t<e.bindings.length;t++){const n=e.addresses[t];null!==n&&(So(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){this.disposedAt=cr;for(const e of Array.from(this.rows))for(let t=0;t<e.bindings.length;t++)this.disposeRowSlot(e,t);for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){this.disposedAt=cr;for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(So(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?bo(n):null;if(Nr(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=bo(n);e!==o&&jn(o)&&Cn(e,En(o)),e!==o&&Vn(o)&&zn(e,Bn(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return $r(t)?t:null}(e);null!==t&&Ir(t)}handleMutations(e,t,n){for(const n of t)vr(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)vr(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&jl(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);this.deferredByNode.get(e)?.forEach(e=>{e.cancel?.(),e.cancel=null,this.deferred.delete(e)})}handleAddedNode(e,t){this.deferredByNode.get(e)?.forEach(e=>{e.born<=this.disposedAt||(this.deferred.add(e),e.arm())});const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=hr.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),(o.applyOnReconnect||n.pendingDefinitions>0&&n.generation>this.disposedAt)&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=gr.get(t);void 0===e&&(e=Pr(t),gr.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;yr(n,this);const o=this.knownMapFor(n);let s=gr.get(e);void 0===s&&(s=Pr(e),gr.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:++ar,session:this,generation:++cr,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(yr(r,this),this.addKnownRowBinding(r,o,e),ur.set(o,s),n[e].isEvent){let t=!1;try{t=ns(o)}catch(t){throw s.phases[e]=2,t}t&&(s.flags[e]|=2)}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++cr,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){let n=!1;try{n=ns(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}n&&(o.flags[e]|=2)}this.registerRowSlot(o,e,n)}}rowOf(e){const t=ur.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=mo(o);null!==s?(e.patternPathInfos[t]=kr(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=Ar(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(Nr(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{os(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:++ar,info:e,generation:++cr,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};hr.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;ns(t)?e.eventAttached=!0:t.propSegments[0]!==A?(ls(t)&&_r(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const t=as(e),n=is(e,t),o=ss.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==rs.countOf(n)&&(rs.remove(n,e)&&ss.delete(n),!0))}return!1}(t)),Do(t)&&_r(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(b)){const t=Wo(e),n=Lo(e,t),o=Ro.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==jo.countOf(n)&&(jo.remove(n,e)&&Ro.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(s.enableDirectionalInitialSync&&us(t.node,t.propName)&&-1===t.propModifiers.indexOf(b)){const n=function(e,t,n){let o=_s.get(e);void 0===o&&(o=new Map,_s.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&&_s.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});_r(e,n)}Ls(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Go(t)&&_r(e,()=>function(e){if(e.propSegments[0]!==A)return!1;const t=Ko.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Ko.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Ze(e.info.node);if(null===n)return void t();const o=tt(e.info.node);if(null===o&&ie(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation;_r(e,this.deferUntilDefined(e.info.node,n,()=>{this.isAlive(e,s)&&(t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e)))},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))}))}settleInitialRecord(e){if(s.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=sr(e.info),n=ir(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 Us++;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,Ks()),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=rr(e.node);null===o&&ie("No state tree found on this root for initial binding sync."),ks(o,Nt(e.node),e.statePathName,n)}(e.info,r))}settleConnectedSnapshot(e){if(s.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=mo(n);if(null!==o?(e.patternPathInfo=kr(n,o,t),e.patternListIndex=o):e.address=Ar(n,t),!e.options.registerPathInfo)return;const s=Xl(n.replaceNode.getRootNode());null===s&&ie("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&hr.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,Ks());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{Nr(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=Os.get(e);if(void 0===t)return;Os.delete(e);const n=As.get(t.key);void 0!==n&&(e.node.removeEventListener(t.eventName,n),Ns.remove(t.key,e)&&As.delete(t.key))}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{os(t)}catch{}}}}function Er(e){let t=pr.get(e);return void 0===t&&(t=new Tr(e),pr.set(e,t)),t}function Cr(e){return hr.get(e)?.session??ur.get(e)?.session??null}let Mr=null;function Or(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const Rr=Object.freeze([]);const jr=new WeakMap;const Lr=new WeakMap;function Wr(e){return Lr.get(e)??[]}function Dr(e,t){Lr.set(e,t)}const Br=new WeakMap;function zr(e){return Br.get(e)??[]}function Fr(e,t){Br.set(e,t)}function qr(e,t){const n=zr(e);for(const e of n)_t(e,t)}const Vr=new WeakMap;function Hr(e){return Vr.get(e)??[]}function Ur(e,t){Vr.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});const Kr=new WeakMap,Gr=new WeakSet;function Jr(e,t){if(null===t)Kr.delete(e);else{Kr.set(e,t);const{stateElement:n,pathInfo:o}=e.absolutePathInfo;if(o.wildcardCount>0){for(let e=o.parentPathInfo;null!==e&&e.wildcardCount===o.wildcardCount&&!Gr.has(e);e=e.parentPathInfo)Gr.add(e);n.setPathInfo(o.lastWildcardPath,"prop","internal")}}}function Xr(e){const t=Kr.get(e);t&&(t.dirty=!0),null!==e.listIndex&&Gr.has(e.absolutePathInfo.pathInfo)&&e.listIndex.cacheStamp++}const Yr=Symbol.for("wcstack.transition-runner");function Qr(e){const t=globalThis[Yr];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 Zr(e,t,n){const o=Qr(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const ei=[],ti=[];let ni=-1,oi=0,si=!1;function ri(e){ti.includes(e)||ti.push(e)}function ii(e,t=0){const n=ei.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?ei.push(o):ei.splice(n,0,o)}function ai(e){queueMicrotask(()=>{throw e})}class li{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<ti.length;t++)ti[t](e);ni>oi&&(oi=ni),ni<0&&(si=!0);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Fn(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],Xt++,this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){let o=si?0:oi;oi=0,si=!1;const s=new Map,r=new Set;for(let t=0;t<e.length;t++){const n=e[t],o=s.get(n.absoluteAddress);null!==Tt&&null!=o&&null!==n.context&&o.transactionId!==n.context.transactionId&&Tt({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:o.transactionId,winnerTransactionId:n.context.transactionId}),s.set(n.absoluteAddress,n.context),r.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];s.has(t)||s.set(t,null)}const i=[],a=new Map;s.forEach((e,t)=>{if(null!==e&&e.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),void(null!==Tt&&Tt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=Po(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(i.push(t),null!==e&&a.set(t,e));else!1!==n.replaceNode.isConnected&&(i.push(n),null!==e&&a.set(n,e))});try{const e=()=>{ni=o+1;try{a.size>0?jl(i,a):jl(i)}finally{ni=-1}};if(o>p&&i.length>0){if(101===o++){const e=[...new Set(Array.from(r,e=>e.absolutePathInfo.pathInfo.path))];console.error("[@wcstack/state] render chain depth limit exceeded; bindings for this batch were not applied.",{maxDepth:p,paths:e}),null!==Tt&&Tt({type:"state:render-chain-limit",maxDepth:p,paths:e})}}else if(t()||0===i.length)e();else{const t=Zr("state",e);void 0!==t&&t.catch(ai)}}finally{qn(),ni=o,function(e){for(const t of ei.slice())t.listener(e)}(r),ni=-1}}}const ci=new li;function di(){return ci}const ui=new WeakMap,fi=new WeakMap,hi=new WeakMap,pi=new WeakMap;let gi=!1;const mi=new WeakMap;function yi(e){const t=e.absolutePathInfo.stateElement;let n=mi.get(t);void 0===n&&mi.set(t,n=new Set),n.add(e)}function wi(e){const t=mi.get(e);return void 0===t?null:(mi.delete(e),t)}const bi=new WeakMap,vi=new WeakMap,$i=new WeakMap,xi=new WeakMap,Si=new WeakMap,Ii=[];function Pi(e,t){const n=ki(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ce(t).cumulativePaths;if(o.length<2)return;let s=Si.get(e);void 0===s&&Si.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 ki(e){let t=ui.get(e);return void 0===t&&ui.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function Ai(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function Ni(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function _i(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=fi.get(o);if(void 0===r&&fi.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(Ni(s,e,o),r.set(t,n),Ai(s,n,o)),!1}return r.set(t,n),Ai(s,n,o),!0}function Ti(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):(o.push(n),!1)}function Ei(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&Ti(hi,o.listIndex,r)&&function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){let n=$i.get(t);void 0===n&&$i.set(t,n=new Set),n.add(e)}}(o.listIndex),null!==r.levelListIndex&&Ti(pi,r.levelListIndex,r))}function Ci(e,t,n,o,s){gi=!0;const r=ki(e);Pi(e,t);Ei(r,t,s,o,_i(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function Mi(e,t){ki(e).tracked.add(t)}function Oi(e,t){return!0===ui.get(e)?.byPath.has(t)||!0===bi.get(e)?.has(t)}function Ri(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(ro(e.stateElement,To(t,o)))}function ji(e,t){if(!gi||e===t)return;const n=vi.get(e);if(void 0===n)return;vi.delete(e);const o=vi.get(t);vi.set(t,void 0===o?n:o.concat(n)),vn(t);for(const o of n){o.indexes=t;const n=ki(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&&!tn(e))for(const t of o.getters){const n=ro(o.stateElement,To(t,e));Xr(n),di().enqueueAbsoluteAddress(n,null),yi(n)}}}function Li(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Wi(e,t,n,o,s){const r=ui.get(e),i=r?.byPath.get(t),a=bi.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return Ii;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&&Li(i.get(o),d),f&&Li(i.get(c),d),u&&Li(i.get(s),d)),void 0!==a)for(const e of a)n&&Ri(e,o,d),f&&Ri(e,c,d),u&&Ri(e,s,d);return d}function Di(e,t){return!0===Si.get(e)?.has(t)}function Bi(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function zi(e,t,n,o,s=!0){const r=ce(t).segments.length,i=[];for(const a of Si.get(e).get(t)){const t=ce(a).segments.slice(r);if(t.includes(u)){Fi(e,a,i);continue}const l=s?Bi(n,t):void 0;for(const n of Wi(e,a,s,l,Bi(o,t)))i.push(n)}return i}function Fi(e,t,n){const o=ui.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())Li(e,n);const s=bi.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)Ri(e,t,n)}function qi(e){const t=pi.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Vi(e){const t=hi.get(e);if(void 0!==t){hi.delete(e),function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){const n=$i.get(t);void 0!==n&&(n.delete(e),0===n.size&&$i.delete(t))}}(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=fi.get(o),r=s.get(n);s.delete(n),Ni(ui.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&qi(e)}}}function Hi(e){const t=xi.get(e);if(void 0!==t){xi.delete(e);for(const e of t){const t=bi.get(e.stateElement),n=t.get(e.path);n.delete(e),0===n.size&&t.delete(e.path);const o=vi.get(e.indexes);o.splice(o.indexOf(e),1),0===o.length&&vi.delete(e.indexes)}}}function Ui(e){if(!gi)return;Vi(e),Hi(e);const t=$i.get(e);if(void 0!==t){$i.delete(e);for(const e of t)Vi(e),Hi(e),$i.delete(e)}}function Ki(e,t,n){if(!gi)return;const o=pi.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=ui.get(e),i=o.byPath.get(s);Ni(i,t,r),Ai(i,n,r),fi.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Xr(r),di().enqueueAbsoluteAddress(r,null),yi(r))}}const Gi=new WeakMap,Ji=Object.freeze([]),Xi=new Set,Yi=new WeakMap,Qi=new WeakMap;function Zi(e,t){Qi.set(e,new WeakRef(Object(t)))}function ea(e){return Qi.get(e)?.deref()}function ta(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function na(e){!function(e){for(const t of e)Ut.add(t)}(e);for(const t of e)Ui(t)}function oa(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Ji,s=Array.isArray(n)&&n.length>0?n:Ji,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Ji,o=Array.isArray(t)&&t.length>0?t:Ji;let s=Gi.get(n);return s&&s.get(o)||null}(o,s);if(r&&r.newIndexes===wn(s,e))return r;const i=wn(o,e)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Xi,deleteIndexSet:new Set(i),addIndexSet:Xi};let t=wn(s,e);if(null===t&&null!==e&&function(e,t){const n=fn.get(e);for(const o of n??[])if(an(e,o))n.delete(o);else if(o!==t)return!0;return!1}(o,e)&&Zi(s,o),0===o.length||null===t&&ea(s)===o){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Lt(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:Xi,deleteIndexSet:new Set(i),addIndexSet:new Set(t)}}if(ta(o,s)&&(t??i)===i)return o!==s&&sa(o,i,e),a={oldIndexes:i,newIndexes:i,changeIndexSet:Xi,deleteIndexSet:Xi,addIndexSet:Xi};if(null!==t)return ra(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,l=new Set;let c=!1;for(let o=0;o<s.length;o++){const a=s[o],d=n.get(a),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=Lt(e,o);t.push(n),l.add(n)}else{const e=i[u];c=!0,u!==o&&r.add(e),t.push(e)}}c&&sa(o,t,e);return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:l}}finally{void 0!==a&&(!function(e,t,n){let o=Gi.get(e);o||(o=new WeakMap,Gi.set(e,o)),o.set(t,n)}(o,s,a),vn(i),$n(s,a.newIndexes))}}(e,t,n);return function(e,t){const n=e.newIndexes;let o;for(let e=0;e<n.length;e++){if(n[e].index!==e){const t=n[e].index;n[e].index=e,Ki(n[e],t,e)}Ft(n[e],t[e])&&(o??=[]).push(n[e])}const s=Yi.get(t);s?.[0]===Xt&&(o=o?s[1].concat(o):s[1]),o&&Yi.set(t,[Xt,o]),e.valueChangeIndexes=o}(o,Array.isArray(n)&&n.length>0?n:Ji),function(e){for(const t of e)Ut.delete(t)}(o.newIndexes),ea(n)!==t&&(na(o.deleteIndexSet),ji(o.oldIndexes,o.newIndexes)),o}function sa(e,t,n){var o;if(o=e,pn.add(o),null!==n)for(const e of t)Bt(e,n)}function ra(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}function ia(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 aa=new WeakMap;function la(e){return aa.get(e)??null}function ca(e,t){aa.set(e,t)}const da=new WeakMap;const ua=new WeakMap;function fa(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function ha(e,t,n,o,s){const r=function(e,t,n){let o=ua.get(e);void 0===o&&ua.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let e=0;e<t.length;e++){const d=t[e];if(!n.shouldApplyState(d))continue;const u=r[e];if(null===u||fa(u.prefixes,i)){Ol(d,s);continue}if(s.appliedBindingSet.has(d))continue;c||(l=s.state[Un](o),c=!0);const f=u.tail;let h=l,p=!1;for(let e=0;e<f.length;e++){if(null==h){h=void 0;break}if(a&&!(f[e]in Object(h))){p=!0;break}h=h[f[e]]}p?Ol(d,s):(s.appliedBindingSet.add(d),Ml(d,s,h))}}function pa(e,t,n){qr(e,t);const o=Wr(e),s=la(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return da.get(e)??null}(e);if(null!==r)return void ha(r,o,s,t,n)}for(const e of o){if(null===s){xo(bo(e),e)}(null===s||s.shouldApplyState(e))&&Ol(e,n)}e.spreads&&Ll(e.spreads,t,s,o,Hr(e))}function ga(e){if(!e.mounted)return;const t=Wr(e),n=la(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{So(bo(o),o)}}!function(e){const t=zr(e);for(let e=0;e<t.length;e++)_t(t[e],null)}(e)}function ma(){return Object.freeze(new Set)}const ya=new WeakMap,wa=ma();function ba(e,t){const n=ya.get(e);n?n.add(t):ya.set(e,new Set([t]))}function va(e){const t=ya.get(e);return void 0!==t?t:wa}function $a(e,t){const n=ya.get(e);n&&(n.delete(t),0===n.size&&ya.delete(e))}const xa=new Set(["if","elseif","else","for"]);class Sa{_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];Vs(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){Vs(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=la(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(Wr(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Ds(n),n.parentNode.removeChild(n))}const n=Wr(this);for(let e=0;e<n.length;e++){const t=n[e];xa.has(t.bindingType)&&va(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=la(this);null!==e&&(e.isRowSession?e.disposeBindings(Wr(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=Wr(this);for(let t=0;t<e.length;t++){const n=e[t];xa.has(n.bindingType)&&va(n.node).forEach(e=>{e.unmount()}),Mo(n),vo(n)}}unmount(){{const e=la(this);null!==e&&(e.isRowSession?e.disposeBindings(Wr(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Ds(e),e.parentNode.removeChild(e));const e=Wr(this);for(let t=0;t<e.length;t++){const n=e[t];xa.has(n.bindingType)&&va(n.node).forEach(e=>{e.unmount()}),Mo(n),vo(n)}this._mounted=!1}}function Ia(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${s.commentForPrefix}|${s.commentIfPrefix}|${s.commentElseIfPrefix}|${s.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function Pa(e){return 1<<Math.min(e,31)}function ka(e){let t=e.indexBits;if(void 0===t){t=0;for(const n of e.nodeInfos)for(const e of n.parseBindTextResults)e.statePathName in R&&(t|=Pa(R[e.statePathName])),"string"==typeof e.uuid&&(t|=ka(oc(e.uuid)));e.indexBits=t}return t}function Aa(e){return ka(oc(e.uuid))}function Na(e,t){return e.statePathName in R||xa.has(e.bindingType)&&0!==(Aa(e)&t)}function _a(e,t){const n=document.createDocumentFragment(),o=new Sa(n,t);return o._childNodeArray=e,o._firstNode=e.length>0?e[0]:null,o._lastNode=e.length>0?e[e.length-1]:null,o._mounted=!0,o}function Ta(e,t,n){const o=document.importNode(t.fragment,!0),s=t.nodeInfos,r=new Array(s.length);for(let e=0;e<s.length;e++){const t=ut(o,s[e].nodePath);null===t&&ie(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),It(t),Ye(t),r[e]=t}const i=n.slots,a=new Array(i.length),l=[];for(let e=0;e<i.length;e++){const t=i[e],n=r[t.nodeIndex],o={...t.template,node:n,replaceNode:n};a[e]=o,t.isIndexBinding&&l.push(o)}const c=function(e,t,n){let o=Dl.get(n);void 0!==o&&o.currentRowPlan===e||(o=new Tr,Dl.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new Sa(o);return ca(d,c),Dr(d,a),function(e,t){da.set(e,t)}(d,n),Ur(d,l),Fr(d,r),ba(e.node,d),d}function Ea(e){void 0!==e.uuid&&null!==e.uuid||ie("BindingInfo.uuid is null.");const n=oc(e.uuid);n||ie(`Fragment with UUID "${e.uuid}" not found.`);const o=!t()&&Ia(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==s.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=s.enableDirectionalInitialSync,n=[],o=e.nodeInfos;for(let t=0;t<o.length;t++){const s=o[t],r=ut(e.fragment,s.nodePath);if(null===r)return null;for(const e of s.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===_||s===A)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ze(r))return null;if("prop"===o&&us(r,e.propName))return null;const i=ht(e);let a;try{a=sr({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:t,template:i,isEvent:"event"===o,isIndexBinding:e.statePathName in R,policy:a,authority:a.authority})}}return 0===n.length?null:{directional:t,slots:n}}(n)),null!==r)return Ta(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o,s]=function(e,t){const n=[],o=[],s=[];for(const r of t){const t=ut(e,r.nodePath);if(null===t&&ie(`Node not found by path [${r.nodePath.join(", ")}] in fragment.`),vt.has(t))continue;const i=$t(t,r.parseBindTextResults,{allowDeferred:!0});null!==i.deferred&&(s.push(i.deferred),vt.add(t)),o.push(...i.bindings),n.push(t)}return[n,o,s]}(e,t),r=new Tr,i=r.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:i,bindingSession:r,spreads:s}}(i,n.nodeInfos);o&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new Sa(i,o);a.spreads.length>0&&(l.spreads=a.spreads),ca(l,a.bindingSession),Dr(l,a.bindingInfos);const c="for"===e.bindingType?(d=e.statePathInfo.wildcardCount+1,2**Math.min(d,32)-1):-1;var d;const u=[];for(const e of a.bindingInfos)Na(e,c)&&u.push(e);return Ur(l,u),Fr(l,a.nodes),ba(e.node,l),l}const Ca=new WeakSet,Ma=Symbol.for("wcstack.state.view-transition-naming");function Oa(){const e=Qr("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Ra(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||Ca.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[Ma]??={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.`)):(Ca.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 ja=new WeakMap,La=new WeakMap,Wa=new WeakMap,Da=new WeakMap,Ba=new WeakMap,za=new WeakMap;function Fa(e,t,n,o){let s=za.get(e);void 0===s&&(s=[document.createComment(""),document.createComment("")],za.set(e,s));const[r,i]=s;r.data=`@@wcs-for-start:${o}`,i.data=`@@wcs-for-end:${o}`,e.mounted||(r.remove(),i.remove());const a=null===n?null:n.nextSibling;if(null===r.parentNode)t.insertBefore(r,a),t.insertBefore(i,a),e.mountAfter(r);else if(a!==r){let e=r;for(;e!==i;){const n=e.nextSibling;t.insertBefore(e,a),e=n}t.insertBefore(i,a)}return i}function qa(e,t,n){!function(e,t,n){let o=La.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,La.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function Va(e,t){ja.set(e,t)}function Ha(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 Ua(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const Ka=new Set(["if","elseif","else","for"]);function Ga(e,t){for(const n of Wr(e))if(t.appliedBindingSet.delete(n),Ka.has(n.bindingType))for(const e of va(n.node))Ga(e,t)}function Ja(e,t,n){for(const o of Hr(e))if(Ka.has(o.bindingType)){if(o.statePathName in R&&Ol(o,t),0!==(Aa(o)&n))for(const e of va(o.node))e.mounted&&Ja(e,t,n)}else Ol(o,t)}function Xa(e){for(const t of Wr(e)){if(!Ka.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of va(t.node))Xa(n),e&&n.mounted&&(ga(n),n.unmount(),$a(t.node,n),Ba.delete(t.node),La.delete(t.node))}}function Ya(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Qa(e,o,r){const i=Boolean(r);let a;const l=va(e.node);a=0===l.size?Ea(e):l.values().next().value;const c=t(),d=e.uuid??"",u=e.bindingType;if(i||(s.debug&&console.log(`unmount if content : ${Ya(e)}`),c&&a.mounted&&(n.seen=!0),ga(a),a.unmount()),i){s.debug&&console.log(`mount if content : ${Ya(e)}`);const t=Nt(e.node);if(qr(a,t),c){if(!a.mounted){const t=document.createComment(`@@wcs-${u}-start:${d}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),a.mountAfter(t);const n=document.createComment(`@@wcs-${u}-end:${d}:${e.statePathName}`),o=a.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}}else a.mountAfter(e.node);pa(a,t,o);const n=Oa();null!==n&&Ra(a,"branch",n)}}const Za=new WeakMap;function el(e){return Za.get(e)??[]}const tl=new Set;function nl(){tl.clear()}const ol=Symbol.for("wcstack.trustedTypes.policy");function sl(){const e=globalThis[ol];return null===e||"object"!=typeof e?null:e}function rl(e){globalThis[ol]=e}let il;let al=!1;function ll(e,t){if(al)return;if(!function(){if(void 0!==il)return il;if(!("trustedTypes"in globalThis))return il=!1,il;try{document.createElement("div").innerHTML="<i></i>",il=!1}catch{il=!0}return il}())return;al=!0;const n="function"==typeof sl()?.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 cl={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function dl(e,n,o){if(1===e.propSegments.length){const t=e.propSegments[0];"textContent"===t||"innerText"===t?o=null==o?"":String(o):void 0===o&&"innerHTML"===t&&(o="")}if(void 0===o)return void(s.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==o){null!==Mr&&null!==d&&"object"==typeof d&&null!==o&&"object"==typeof o&&null!==Ze(r)&&Mr.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=sl(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(o):o,e=!0}catch(e){t&&ll(r,c),s.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:o,error:e})}if(e){const e=function(e,t){const n=Ze(e);if(null===n)return null;const o=tt(e)?.get(n);if(void 0===o)return null;const s=ot(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,o)}catch(t){s.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:o,error:t})}}};if(s.enablePropagationContext&&us(r,c)){const t=ms(r,c,e.statePathName),s=ys(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??xs()??bs(t);if(a.visitedEdges.has(s))null!==Tt&&Tt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:s,node:r,member:c});else{const e=vs(a,s);Ss(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:ps++,writtenValue:n};Is.push({receipt:i,node:e});try{return r()}finally{Is.pop()}}(r,c,o,t,e.transactionId,i))}}else i()}if(t()){const e=cl[c];e?e(r,o):(!function(e,t,n){let o=Za.get(e);o||(o=[],Za.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,o),a=r,tl.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==o){if(Object.isFrozen(d))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:o}));null!==Mr&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ze(r)&&(u in d?Mr.rememberOverwrittenValue(r,c,u,d[u]):Mr.recordInjectedKey(r,c,u));try{d[u]=o}catch(e){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:o,error:e})}}}const ul=new WeakSet;function fl(e,t,n){}function hl(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}const pl=new WeakMap;function gl(e,t,n,o){const s=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),r=t.length>0?t+d:"";for(const e of n){if(r.length>0&&!e.startsWith(r))continue;const t=e.slice(r.length);t.length>0&&-1===t.indexOf(d)&&!pl.has(hl(o,e)?.get)&&s.push(t)}return s}const ml={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},yl={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function wl(e,t,n,o){return`[wcs/index-arity] ${e}("${t}") requires ${"$resolve"===e?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${he}`}function bl(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 vl(e,t){return`$setAll("${e}") ${t}`}function $l(e,t,n){return`[wcs/wildcard-rank] ${e} needs ${t} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${he}`}function xl(e,t){const n=Co(t);if(n.pathInfo.path in R){const e=Nt(t.node);return null===e&&ie(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&ie("ListIndex not found for loopContext:");const n=R[t];void 0===n&&ie(`Invalid index name: ${t}`);const o=ho(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&ie($l(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Un](n)}const Sl=new WeakSet;function Il(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Pl=Object.freeze({[T]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?("boolean"!=typeof n&&ie(`Invalid value for class application: expected boolean, got ${typeof n}. Write "|truthy" if you mean to coerce.`),o.classList.toggle(s,n)):o.classList.toggle(s,!1)},[E]:function(e,t,n){const o=e.node,s=e.propSegments[1];if(null==n)return void(o.hasAttribute(s)&&o.removeAttribute(s));const r=String(n);o.getAttribute(s)!==r&&o.setAttribute(s,r)},[C]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[_]:function(e,t,n){Xo(n)||ie("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=jr.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||ie('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Ze(e);if(null===t)return null;const n=tt(e)?.get(t);return void 0===n&&ie(`Custom element <${t}> is not defined for command binding.`),ot(e)}(r);null===a&&ie(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||ie(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${fe(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),jr.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 jr.delete(e);const o=n[i];return"function"!=typeof o&&ie(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),jr.set(e,{token:o,unsubscribe:c,elementRef:l})}}),kl={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!ul.has(e.replaceNode)){ul.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,o,s){const r=e.statePathInfo,i=mo(e),a=bo(e),l=En(a),c=Ba.get(e.node);let d,f;const h=void 0!==c&&function(e,t){const n=_n.get(e);return void 0!==n&&(n===t||yn(t)===yn(n))}(a,s),p=h||void 0===c||c.value===l?null:oa(i,l,s);h?(d=c.value,f=ra(yn(d),yn(s))):null!==p&&p.newIndexes.every(e=>e.parentListIndex===i||tn(e.parentListIndex)||!rn(s,e.parentListIndex))?(d=c.value,f=ra(yn(d)??[],p.newIndexes)):(d=l.length>0&&!La.has(e.node)?[]:l,f=oa(i,d,s));const g=Array.isArray(s)?s:[];o.newListValueByAbsAddress.set(a,g),Ba.set(e.node,Sn(g));let m=La.get(e.node);const y=void 0!==m?function(e,t,n){if(!Zt(t))return null;let o=null;for(let t=0;t<n.newIndexes.length;t++){const s=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(s)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(o??={byAddedIndex:new Map,reused:new Set},o.byAddedIndex.set(s,i),o.reused.add(i))}return o}(m,d,f):null,w=Array.isArray(d)&&d.length===f.deleteIndexSet.size&&f.deleteIndexSet.size>0;if(w&&null===y&&null!==e.node.parentNode){let t=Da.get(e.node);if(void 0===t){const n=ja.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Ha(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Ha(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n.parentNode===e.node.parentNode?n:e.node),Da.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){zs.set(e,(zs.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let b=w?1e3-function(e){return Wa.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;const v=t();if(void 0!==m){const t=m;f.deleteIndexSet.forEach(o=>{const s=t.get(o);void 0!==s&&(v&&(za.get(s)?.forEach(e=>e.remove()),n.seen=!0),null!==y&&y.reused.has(s)?(ga(s),Xa(s),s.unmountInPlace()):b<=0&&s.tryDestroy()?$a(e.node,s):(ga(s),s.unmount(),function(e,t){let n=Wa.get(e.node);void 0===n&&(n=[],Wa.set(e.node,n)),n.length<1e3?n.push(t):$a(e.node,t)}(e,s),b-=1),w||t.delete(o))}),w&&(La.delete(e.node),m=void 0)}let $=e.node;const x=ce(r.path+"."+u),S=o.stateElement.loopContextStack,I=ia(f);let P=null;f.newIndexes.length==f.addIndexSet.size&&f.newIndexes.length>0&&$.isConnected&&null===y&&(P=document.createDocumentFragment(),lo(P,o.rootNode));const k=v?`${e.uuid}:${r.path}:`:"",A=Oa(),N=Wa.get(e.node);for(const t of f.newIndexes){let n;if(f.addIndexSet.has(t)){const s=To(x,t);if(S.createLoopContext(s,s=>{n=y?.byAddedIndex.get(t)??(void 0!==N?N.pop():void 0),void 0===n?n=Ea(e):(Ga(n,o),qr(n,s)),v?$=null!==P?Fa(n,P,null,k+t.index):Fa(n,$.parentNode,$,k+t.index):null!==P?n.appendTo(P):$.nextSibling!==n.firstNode&&n.mountAfter($),pa(n,s,o),null!==A&&Ra(n,"row",A)}),void 0===n&&ie(`Content not found for ListIndex: ${t.index} at path "${r.path}"`),null!==y&&y.reused.has(n)){const e=o.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](o.stateElement,n)}}}else{n=void 0!==m?m.get(t)??null:null,f.changeIndexSet.has(t)&&Ja(n,o,Pa(r.wildcardCount)),null===n&&ie(`Content not found for ListIndex: ${t.index} at path "${r.path}"`);const e=!n.mounted;if(v?$=Fa(n,$.parentNode,$,k+t.index):null!==I&&I.has(t)&&Ua($,n.firstNode)||$.nextSibling===n.firstNode||n.mountAfter($),e){const e=n,s=To(x,t);S.createLoopContext(s,t=>{pa(e,t,o)})}}v||($=n.lastNode||$),void 0===m&&(m=new WeakMap,La.set(e.node,m)),m.set(t,n)}ja.set(e.node,$),null!==P&&(e.node.parentNode.insertBefore(P,e.node.nextSibling),lo(P,null))},if:Qa,else:Qa,elseif:Qa,radio:function(e,t,n){const o=e.node,s=Or(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=Or(o.value,e.inFilters),r=Array.isArray(n)?n:Rr;o.checked=r.includes(s)}},Al=new WeakMap,Nl=new WeakMap,_l=new WeakMap;function Tl(){}function El(e){const t=Mr;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return fl;if(t.isDeclared(n,o))return Tl}return dl}function Cl(e,t){Ml(e,t,xl(t.state,e))}function Ml(e,t,n){const o=Or(n,e.outFilters);if(!0===Nl.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=Al.get(e);if(void 0===s){if(Al.has(e))return s=El(e),s===fl&&Al.set(e,s),void s(e,t,o);if(s=kl[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Pl[t],Al.set(e,s),void 0===s){Ze(e.replaceNode)?(s=El(e),s===fl&&Al.set(e,s)):(s=dl,Al.set(e,s))}}if(s===dl){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 Nl.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function Ol(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=bo(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=Cr(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==_l.get(e)){const t=Ze(e.replaceNode);if(t&&(void 0===tt(e.replaceNode)?.get(t)||function(e){return"waiting-definition"===hr.get(e)?.phase}(e)))return void function(e,t){if(Sl.has(e))return;Sl.add(e);const n=()=>{Sl.delete(e);const t=Cr(e);(null===t||t.shouldApplyState(e))&&jl([e])},o=n=>{Sl.delete(e),Il(t,n)},s=Cr(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Sl.delete(e),r()})||(Sl.delete(e),r()))}const r=tt(e.replaceNode);if(null===r)return Sl.delete(e),void Il(t,new Error("CustomElementRegistry is unavailable."));Ys(r).wait(t,()=>{e.replaceNode.isConnected?n():Sl.delete(e)},o)}(e,t);_l.set(e,!0)}if(!0===t.sameRootVerified)return void Cl(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=co(o),null===o&&ie("Root node for fragment not found for binding.")),o!==t.rootNode){const n=Xl(o);null===n&&ie("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};Cl(e,r)})}else Cl(e,t)}function Rl(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!==Tt&&Tt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function jl(e,t,n){let o=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;o<e.length;){let n=e[o];if(!1===n.replaceNode.isConnected){s.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),o++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=co(d),null===d&&ie("Root node for fragment not found for binding."));const u=Xl(d);null===u&&ie("No state tree found on this root for binding."),u.createState("readonly",s=>{const f={rootNode:d,stateElement:u,state:s,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{Ol(n,f)}catch(e){Rl(n,e,u,c)}o++;const t=e[o];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{dl(e,{propagationContextByBinding:t},n)}catch(t){Rl(e,t,o??null,c)}for(const[e,t]of i.entries())Cn(e,t),zn(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Xn](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Yn](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 Ll(e,t,n,o,s){for(const r of e)r.cancel?.(),r.cancel=n.deferUntilDefined(r.node,r.tagName,()=>{const i=Pt(r);if(o&&(e.splice(e.indexOf(r),1),o.push(...i),s.push(...i.filter(e=>e.statePathName in R))),0===i.length)return;_t(r.node,t);jl(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1}))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,e)})}function Wl(e,t,n){const[o,s,r]=xt(e,n),i=Er(e);for(const e of o)_t(e,t);jl(i.initialize(s)),Ll(r,t,i)}const Dl=new WeakMap;async function Bl(e){const t=e.querySelectorAll(s.tagNames.state),n=[],o=tt(e);null===o&&ie(`CustomElementRegistry is unavailable for <${s.tagNames.state}>.`),await o.whenDefined(s.tagNames.state);for(const e of t){if(mt(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function zl(e){if(e===document)await Bl(document),se(document),xc(document,document),Wl(document.body,null);else{const t=e;t.host.hasAttribute(s.bindAttributeName)&&await Xe(t.host),await Bl(t),se(t),xc(t,t),Wl(t,null)}}const Fl={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function ql(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${Fl[e]??e}" before the state is defined.`}let Vl=null;function Hl(e){return null===Vl&&ie(ql("ssr",e)),Vl}const Ul=new WeakMap,Kl=new WeakMap,Gl=new Set,Jl=[];function Xl(e){return Ul.get(e)??null}function Yl(e){return Kl.get(e)??Promise.resolve()}const Ql=new WeakSet;function Zl(e){Ql.add(e)}function ec(e,n){const o=Ul.get(e);if(null===n){if(void 0===o)return;Ul.delete(e),Gl.delete(o),null!==Tt&&Tt({type:"state:element-unregistered",rootNode:e,element:o}),s.debug&&console.debug("State element unregistered")}else{if(o===n)return;if(void 0===o){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await Hl('the "enable-ssr" attribute').hydrate(e)||await zl(e)}else await zl(e);Zl(e),Nc(),t()}catch(e){n(e)}})});Kl.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await zl(e),Zl(e),Nc(),t()}catch(e){n(e)}})});Kl.set(e,t)}}void 0!==o&&ie('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Ul.set(e,n),Gl.add(n);for(let t=0;t<Jl.length;t++)Jl[t](e,n);null!==Tt&&Tt({type:"state:element-registered",rootNode:e,element:n}),s.debug&&console.debug("State element registered",n)}}const tc=new Map;function nc(e,t,n){if(null===n)tc.delete(e);else{tc.set(e,n);const o=Xl(t);null===o&&ie("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const t of e.parseBindTextResults)o.setPathInfo(t.statePathName,t.bindingType)}}function oc(e){return tc.get(e)||null}function sc(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=ze(t.getAttribute(s.bindAttributeName)||"");if(t.localName===s.tagNames.state){if(t.hasAttribute("mount"))return n.filter(e=>e.propSegments[0]!==N);const e=n.find(e=>e.propSegments[0]===N);if(void 0!==e){const t=`on a volume element — a <${s.tagNames.state}> with a "mount" attribute`;ie(1===e.propSegments.length?`[wcs/mount-path-invalid] "${e.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${N}.<key>: <path>") ${t}.`:`[wcs/mount-path-invalid] "${e.propName}: ${e.statePathName}" is a volume injection declaration, and it can only be written ${t}. Add mount="<path>", or bind an element property instead.`)}}return n}if(e.nodeType===Node.COMMENT_NODE){const t=He(e);null===t&&ie("Comment node binding text not found.");const n=oc(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Ue(t),s=null):s=t,[{...o,uuid:s}]}return[]}let rc;function ic(){return rc??={filterName:"not",args:[]}}const ac=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function lc(e,t){const n=t+d+u,o=Ce(e,"|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+d+s.slice(1)}return r.length>0?s+r:s}function cc(e,t){const n=ac.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+lc(s,t)+r}function dc(e,t){const n=Me(e,";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=Ce(n,":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=lc(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function uc(e,t){return dc(e,t)}function fc(e,t){const n=s.bindAttributeName,o=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const e=o.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=cc(n.data,t);continue}const s=e;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const e=dc(r,t);e!==r&&s.setAttribute(n,e)}}}function hc(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}const pc=new WeakMap;function gc(e){return pc.get(e)??null}function mc(e){const t=[],n=bt(e);for(const e of n){const n=sc(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");pc.set(t,e.data),e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:hc(o),parseBindTextResults:n})}return t}function yc(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 wc=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),bc=ic();function vc(e,t){const n=t.outFilters;return{...t,outFilters:[...n,bc],bindingType:e}}function $c(e,t,n,o,s,r=!0){yc(t),"string"==typeof o&&fc(t,o),xc(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:mc(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 xc(e,t,n,o){const r=s.commentElsePrefix,i=yt(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(s.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(s.bindAttributeName)||"";"string"==typeof n&&(i=uc(i,n));let a=ze(i)[0];const d=wc.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Ct();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&ie("'else' binding found without preceding 'if' or 'elseif' binding."),a=vc("else",l.parseBindTextResult),p=$c(e,f,a,g,o,!1),nc(h,e,p);const n=c.at(-1),s=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:hc(s),parseBindTextResults:sc(s)})):t.replaceWith(s)}else if("elseif"===u){null===l&&ie("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=$c(e,f,a,g,o),nc(h,e,p);const n=document.createComment(`@@${d}:${h}`),s=Ct(),i={fragment:document.createDocumentFragment(),parseBindTextResult:vc("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:hc(n),parseBindTextResults:sc(n)}),nc(s,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${s}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:hc(m),parseBindTextResults:sc(m)})):t.replaceWith(m)}else{p=$c(e,f,a,g,o),nc(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 Sc=()=>`[${s.bindAttributeName}]`;function Ic(e){if(wr(e))return!0;if(!Pc(e))return!1;if(e.hasAttribute(s.bindAttributeName))return!1;const t=e.querySelector(Sc());return null!==t&&wr(t)}function Pc(e){return 1===e.nodeType}function kc(e){if(Ic(e))return;se(e),xc(e.getRootNode(),e);const t=e.hasAttribute(s.bindAttributeName),n=e.parentNode,o=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Wl(t&&o?n:e,null)}const Ac=[];function Nc(){const e=Ac.splice(0,Ac.length);for(const t of e)kc(t);c()}const _c={protocol:"wcs-binder",version:1,bind:function(e){var t;Pc(e)&&!Ic(e)&&(t=e.getRootNode(),Ql.has(t)?kc(e):Ac.push(e))}};const Tc="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ec=0;async function Cc(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Ec}\n`;let s=!1;const r=e=>{e.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+o],{type:"application/javascript"}),s=URL.createObjectURL(t);try{n=await import(s)}finally{URL.revokeObjectURL(s)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+o)));n=await import(`data:application/javascript;base64,${t}`)}}catch(e){throw await new Promise(e=>setTimeout(e)),new Error(`[@wcstack/state] ${function(e,t,n){const o=t?.message??String(t);return n?`The inline <script> of state "${e}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src="./state.js") needs neither. See ${Tc}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Tc}`}(t,e,s)}`,{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Mc(e){const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}class Oc{_loopContextStack=Array(h).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&ie("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=h&&ie("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&ie("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const e=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==e&&ie("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&ie(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=t(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const Rc={$updatedCallback:W,$streams:K},jc=new WeakSet;function Lc(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function Wc(e){if((null===e||"object"!=typeof e&&"function"!=typeof e)&&ie(`The state must be an object, got ${null===e?"null":typeof e}. Check the source of the state element (json / src / the inline <script>).`),!jc.has(e)){ye?.state(e);for(const t of Object.keys(Rc)){if(!(t in e))continue;const n=Rc[t];n in e&&ie(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${he}`),Object.isExtensible(e)||ie(`[wcs/declaration-alias] The state is not extensible, so the old name "${t}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${he}`);const o=Lc(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}jc.add(e)}}const Dc=new WeakMap;function Bc(e,t){let n=Dc.get(e);void 0===n&&(n=new Map,Dc.set(e,n));let o=n.get(t);return void 0===o&&(o=new Jo(t,e),n.set(t,o)),o}const zc=new WeakMap;function Fc(e){const t=zc.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 Bc(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:Bc(e,n)}},set(){ie("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){ie("$command namespace is read-only; deleting from it is not allowed.")}});return zc.set(e,n),n}const qc=Symbol("wcs.notHandled"),Vc=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Hc=new Map;function Uc(e,t){Hc.set(e,t)}const Kc=new Map;let Gc=[],Jc=[];function Xc(e,t){Kc.set(e,t),Gc=Array.from(Kc.values()).sort((e,t)=>e.order-t.order),Jc=Gc.slice().reverse()}function Yc(e){return Kc.has(e)}function Qc(e,t){for(let n=0;n<Gc.length;n++)Gc[n].activate?.(e,t)}const Zc=new Map;class ed{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice();let o=0,s=0,r=0,i="none";const a=[];for(let e=0;e<t.length;e++){const i=t[e];if("*"===i)n[e]="*",a.push(null),o++,r++;else{const t=Number(i);Number.isNaN(t)||(n[e]="*",a.push(t),s++,r++)}}const l=ce(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=e,this.segments=t,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function td(e){let t;return Zc.get(e)??(Zc.set(e,t=new ed(e)),t)}function nd(e){"readonly"===e.mutability&&ie("This state is readonly.")}function od(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:ho(n.listIndex,o,n.pathInfo.wildcardCount)}function sd(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=fo(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?ho(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?ho(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function rd(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function id(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!==qc)return a}}return qc}function ad(e,t,n,o,s){if(t.pathInfo.segments[0]===V)return function(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}(Fc(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=id(s,t,null,n,o);if(r!==qc)return r;ie(function(e,t,n){return`[${ml.binding}] Path "${e}" does not exist on the state tree.${fe(e,gl(t,"",n,t))}${he}`}(t.pathInfo.path,e,s.getterPaths))}const r=ud(e,t.parentAddress,n,o);if(null==r)return;const i=t.pathInfo.segments[t.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==u&&!(i in Object(r))){const e=id(s,t,Object(r),n,o);if(e!==qc)return e}if(i===u){const e=t.listIndex?.index??ie($l(`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 ld(e,t,n,o,s){const r=ro(s,t),i=function(e){return Kr.get(e)??null}(r),a=s.stateGeneration,l=t.pathInfo.lastSegment===u?void 0:zt(t.listIndex);if(null!==i&&!1===i.dirty&&i.generation===a&&i.rowStamp===l)return i.value;const c=ad(e,t,n,o,s);"function"!=typeof c&&Jr(r,{value:c,dirty:!1,generation:a,rowStamp:l});const d=i?.value;return Array.isArray(c)&&c!==d&&s.getterPaths.has(t.pathInfo.path)&&function(e,t,n,o,s,r){const{path:i,wildcardCount:a}=t.pathInfo;r.beginUntrack();try{for(const[l,c]of r.stateElement.dynamicDependency){const d=ce(l);if(!c.includes(i)||d.wildcardCount>a)continue;const u=ud(e,To(d,ho(t.listIndex,d.wildcardCount-1,a)),s,r);u===n?cd.add(t.pathInfo):u===o&&Zi(n,o)}}finally{r.endUntrack()}}(e,t,c,d,n,o),c}const cd=new WeakSet;function dd(e){return cd.has(e)}function ud(e,t,n,o){sd(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!==qc)return i}}return rd(s,t)?ld(e,t,n,o,s):ad(e,t,n,o,s)}function fd(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=To(f,r),p=ro(n.stateElement,h),g=Bn(p),m=ud(e,h,t,n),y=oa(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??ie(`ListIndex not found at index ${w} of ${f.path}`);s+1<o.length?a(o,s+1,e,l,c+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[e,t]of i.entries())zn(e,Array.isArray(t)?t:[]);return l}function hd(e,t,n){const o=wn(n,t.listIndex);if(null!==o)return o;const s=ro(e.stateElement,t),r=oa(t.listIndex,Bn(s),n);return zn(s,Array.isArray(n)?n:[]),r.newIndexes}function pd(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=To(a,r),c=hd(n,l,ud(e,l,t,n)),d=s[i];r=c[d]??ie(`ListIndex not found at index ${d} of ${a.path}`)}return r}function gd(e,t,n,o){"object"==typeof e&&null!==e||ie(`${Q} list "${t}": ${n} row at index ${o} must be a plain object (got ${null===e?"null":typeof e}).`);const s=Object.getPrototypeOf(e);s!==Object.prototype&&null!==s&&ie(`${Q} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function md(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&ie(`${Q} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function yd(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];gd(a,n,o,i);const l=md(a,t,n,o,i);r.has(l)&&ie(`${Q} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function wd(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 bd(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=ud(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===u){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const vd=new WeakMap;function $d(e){return vd.get(e)??null}function xd(e,t){null===t?vd.delete(e):(vn(t.listIndexes),vd.set(e,t))}function Sd(e,t,n){const o=To(ce(e.wildcardParentPaths[t]),n),r=ro(e.stateElement,o),i=Bn(r),a=e.stateProxy[Un](o),l=oa(o.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return s.debug&&console.log(`Invalid search type: ${t}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)Sd(e,t+1,n)}function Id(e,t,n,o){n?e.result.has(t)||e.quiet.add(t):e.quiet.delete(t),e.result.add(t),o.push(t)}const Pd=[];function kd(e,t,n){return"full"!==e.listExpansion&&e.listPathSet.has(t)?e.stateElement.crossRowListPaths?.has(t)?{fullRows:n.newIndexes,movedRows:null}:0===n.addIndexSet.size&&0===n.changeIndexSet.size?0===n.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:Pd,movedRows:null}:{fullRows:n.newIndexes,movedRows:null}:{fullRows:Pd,movedRows:null}:{fullRows:n.addIndexSet,movedRows:n.changeIndexSet}:{fullRows:n.newIndexes,movedRows:null}}const Ad=[];function Nd(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Ad;let s=null;const r=t+d;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ce(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Ad}function _d(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),e.quiet.has(a)?Xr(ro(e.stateElement,a)):n(a),i.length=0,Td(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}function Td(e,t,n){const o=t.pathInfo.path,s=e.quiet.has(t),r=e.staticMap.get(o);if(r)for(const i of r){const r=ce(i);if(r.lastSegment===u){const a=e.stateProxy[Un](t),l=Array.isArray(a)?a:[],c=ro(e.stateElement,t),d=Bn(c),u=e.listPathSet.has(o);if(!u&&"diff"===e.listExpansion&&(e.keyedMergePath===o||yn(l)?.length!==l.length&&!ta(d,l)))continue;const f=oa(t.listIndex,d,l);e.observedListValueByAbsAddress.set(c,l);const h=kd(e,o,f);for(const t of h.fullRows)Id(e,To(r,t),s||!u,n);for(const t of f.valueChangeIndexes??Pd)Id(e,To(r,t),s||!u,n);if(null!==h.movedRows){const t=Nd(e,i,r);if(null===t)for(const t of h.movedRows)Id(e,To(r,t),s,n);else if(t.length>0)for(const o of h.movedRows)for(const r of t)Id(e,To(r,o),s,n)}}else Id(e,To(r,t.listIndex),s,n)}const i=e.dynamicMap.get(o);if(i)for(const o of i){const r=ce(o),i=[];if(r.wildcardCount>0){const n=fo(t.pathInfo,r);if(r.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&ie(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=ho(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const s={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:r.wildcardPaths,wildcardParentPaths:r.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Sd(s,n,o),i.push(...s.targetListIndexes)}else{null===t.listIndex&&ie(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=ho(t.listIndex,n-1,t.pathInfo.wildcardCount);i.push(e)}}else i.push(null);for(const t of i)Id(e,To(r,t),s,n)}}function Ed(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&ie(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null,quiet:new Set};_d(u,t,a),function(e,t){for(let n=0;n<1e3;n++){const n=wi(e.stateElement);if(null===n)return;n.forEach(n=>{_d(e,To(n.absolutePathInfo.pathInfo,n.listIndex),t)})}}(u,a);for(const[e,t]of u.observedListValueByAbsAddress)zn(e,t);return Array.from(u.result)}function Cd(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 Md(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 Od(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 Rd(e,t,n,o,s,r){const i=Oi(e,t),a=Di(e,t);if(!i&&!a)return null;const l=[],c=Ld(l);return i&&Wi(e,t,n,o,s).forEach(c),a&&zi(e,t,n?o:r(),s).forEach(c),l}function jd(){return s.enablePropagationContext?xs()??null:null}function Ld(e){const t=di(),n=jd();return o=>{Xr(o),t.enqueueAbsoluteAddress(o,n),e.push(o)}}function Wd(e,t,n){if(null===e||0===e.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=di(),a=jd();for(let n=0;n<e.length;n++){const l=e[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const d=To(l.pathInfo,e[n].listIndex);Ed(o,d,s,r,o.listPaths,t,"new",e=>{if(e===d)return;const t=ro(o,e);Xr(t),i.enqueueAbsoluteAddress(t,a)},{listExpansion:"diff"})}}function Dd(e,t,n,o,r,i,a="diff"){const l=s.enablePropagationContext?xs()??bs(-1):null,c=di(),f=o.stateElement;c.enqueueAbsoluteAddress(t,l),i&&Xr(t);const h=t=>Ed(f,t,f.staticDependency,f.dynamicDependency,f.listPaths,n,"new",t=>{if(t===e)return;const n=ro(f,t);Xr(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r});if(h(e),e.pathInfo.lastSegment!==u&&null!==e.listIndex&&null!==e.listIndex.parentListIndex){const t=e.listIndex,o=e.pathInfo.wildcardParentPathInfos[t.position],s=To(o,t.parentListIndex),r=()=>n[Un](s),i=e=>{Xr(e),c.enqueueRenderOnlyAddress(e)};for(const n of gn(t,r))i(ro(f,To(e.pathInfo,n)));const a=e.pathInfo.path.slice(e.pathInfo.wildcardPaths[t.position].length);for(const e of On(ro(f,s),r())){const n=e.absolutePathInfo.pathInfo;n!==o&&n.wildcardCount===o.wildcardCount&&i(io(f,ce(n.path+d+u+a),t))}}const{path:p,lastSegment:g,wildcardCount:m,wildcardParentPaths:y,wildcardParentPathInfos:w}=e.pathInfo,b=e.listIndex;for(let e=0;b&&e<m;e++){const t=ho(b,e-1,m);for(const o of f.dynamicDependency.get(y[e])??[]){const s=ce(o);if(f.listPaths.has(o)&&s.wildcardCount===e&&dd(s)&&n[Un](To(s,t))===n[Un](To(w[e],t))){const t=To(ce(o+p.slice(y[e].length)),b);h(t),g===u&&c.enqueueRenderOnlyAddress(ro(f,t.parentAddress))}}}}function Bd(e,t,n,o,s){s&&(e.getterPaths.has(t)?Xr(n):Jr(n,{value:o,dirty:!1,generation:e.stateGeneration,rowStamp:n.absolutePathInfo.pathInfo.lastSegment===u?void 0:zt(n.listIndex)}))}function zd(e,t,n,o,s){const r=t.listIndex,i=yn(n);if(i?.[o]!==r||n[o]===s)return t;const a=Lt(r.parentListIndex,o,Dt(r));if(function(e){return xn.has(e)}(n)){const e=$d(n)??{value:n.slice(),listIndexes:i};$n(e.value,e.listIndexes),In(n,e.value)}const l=function(e){return bn.has(e)}(i)?i:i.slice();l[o]=a,$n(n,l,!0),ji(i,l),na([r]);const c=To(t.pathInfo,a);return Od(e,ro(e,c),ro(e,t)),c}function Fd(e,t,n,o,s,r,i,a,l=!0){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=ud(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===u){const e=t.listIndex?.index??ie($l(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(i,e,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t),r.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{l&&Dd(t,n,s,r,i,a)}}function qd(e,t,n,o,s,r,i,a,l){const c=t.parentAddress??ie(`address.parentAddress is undefined path: ${t.pathInfo.path}`),f=ud(e,c,s,r)??[],h=$d(f);if(l)return h&&(h.value[t.listIndex.index]=o),Ft(t.listIndex,o),Fd(e,t,n,o,s,r,i,a);const p=t.listIndex,g=h??{value:[...f],listIndexes:yn(f)??[],written:new Map};try{return Fd(e,t,n,o,s,r,i,a,!1)}finally{const e=function(e,t,n){const{value:o,listIndexes:s}=e,r=new Map;s.forEach((e,n)=>{if(t[n]!==o[n]){const t=r.get(o[n]);t?t.push(e):r.set(o[n],[e])}});let i,a=0;const l=[];for(let e=0;e<s.length;e++){const n=t[e]===o[e]?s[e]:r.get(t[e])?.shift();if(!n&&(a++?(i??=new Set(o)).has(t[e]):o.includes(t[e])))return null;l.push(n)}return l.map((e,t)=>e??Lt(n,t))}(g,f,c.listIndex);if(null===e)xd(f,g),Ft(p,o),g.written.set(p,Xt),function(e){ln.set(e,Xt)}(p),Dd(t,n,s,r,i,a);else{xd(f,null);const t=[p.index];cn(p),g.written.forEach((e,n)=>{cn(n),Ft(n,g.value[n.index]),e===Xt&&t.push(n.index)}),g.written.delete(p),e.forEach((e,t)=>{e.index=t}),$n(f,e),ji(g.listIndexes,e),function(e,t,n,o,s,r,i){const a=r.stateElement,l=di(),c=ro(a,e);$n(t.value,t.listIndexes),Qt(t.value),In(n,t.value),En(c)===n&&Cn(c,t.value);l.enqueueRenderOnlyAddress(c);for(const e of On(c,n))Rn(e,n)&&l.enqueueRenderOnlyAddress(e);const f=new Map;t.listIndexes.forEach((e,t)=>f.set(e,t));const h=ce(e.pathInfo.path+d+u);for(let e=0;e<o.length;e++){const n=o[e],i=f.get(n);if(i===e)continue;const c=To(h,n),d=ro(a,c);if(void 0===i){const n=io(a,h,t.listIndexes[e]);Od(a,d,n),Dd(c,d,s,r,null,rd(a,c),"full");continue}Ed(a,c,a.staticDependency,a.dynamicDependency,a.listPaths,s,"new",e=>{const t=ro(a,e);Xr(t),l.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}for(const e of i){const n=o[e];if(f.has(n)&&t.written.get(n)!==Xt){const o=To(h,n),i=ro(a,o);Od(a,i,io(a,h,t.listIndexes[e])),Dd(o,i,s,r,null,rd(a,o))}}}(c,g,f,e,s,r,t)}}}function Vd(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=ud(e,t,o,s),a=function(e,t,n,o){const s=yd(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=yd(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===yn(o)&&oa(a,null,o);const l=oa(a,o,n.list),c=Hd(e,t,n.list,s,r,i),f=ce(i+d+u);for(const t of n.matched){const n=wd(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?Vd(e,To(ce(f.path+d+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return c}(e,t,a,r,o,s)}}return Hd(e,t,n,o,s,null)}function Hd(e,t,n,o,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let s=0;s<e.length;s++){const i=e[s](a,t,n,o,r);if(i!==qc)return i}}const d=function(){const e=Ps;return Ps=0,e}(),f=d>1;if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const d=ud(e,t.parentAddress,o,r);if("object"==typeof d&&null!==d){const e=t.pathInfo.lastSegment,h=e===u?t.listIndex?.index:e;let p,g=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in d,t=void 0!==h?d[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}e===u&&(t=zd(a,t,d,h,n));const m=Rd(a,l,g,p,n,()=>d[h]),y=rd(a,t),w=ro(a,t);null!==Tt&&Tt({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:g}),Cd(a,l,w,p,g);let b=!1;try{if(void 0===h&&ie($l(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==u&&!(h in d)){const e=c.writeMissing;for(let s=0;s<e.length;s++){b=!0;const i=e[s](a,t,d,h,n,o,r);if(i!==qc)return i;b=!1}}if(e!==u&&null!==t.listIndex){const o=d[h];o!==n&&(function(e,t,n,o){if(!en.has(e))return!1;let s=!1;for(const t in n)s||=t!==o&&n[t]===e;if(!s){let n=nn.get(t);void 0===n&&(n=new WeakSet,nn.set(t,n)),n.add(e)}const r=en.get(e),i=sn.get(e);if(r[0]?.parentListIndex===t&&(!s||i?.[0]!==t||i[1]!==Xt))for(const n of fn.get(e)??[])if(n!==t&&n.position===t.position&&un(e,n)&&Object(Gt(n))[o]===e){r.forEach(e=>Wt(e,n)),on.set(e,[t,Xt]);break}return s}(o,t.listIndex,d,e)&&Array.isArray(n)&&Zi(n,o),function(e,t){nn.get(t)?.delete(e);const n=en.get(e);if(void 0!==n){sn.set(e,[t,Xt]);const o=on.get(e);o?.[0]===t&&o[1]===Xt&&n.forEach(e=>Wt(e,t))}}(n,t.listIndex))}return Reflect.set(d,h,n)}finally{Dd(t,w,o,r,i,y),Wd(m,o,r),b?Xr(w):Bd(a,l,w,n,y),Md(a,t.pathInfo,{value:n})}}}let h,p=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=ud(e,t,o,r);if(bd(e,t,o,r)&&Object.is(s,n))return!0;h=s,p=!0}const g=Rd(a,l,p,h,n,()=>ud(e,t,o,r)),m=a.elementPaths.has(t.pathInfo.path),y=rd(a,t),w=ro(a,t);null!==Tt&&Tt({type:"state:write",absoluteAddress:w,value:n,oldValue:h,hasOldValue:p}),Cd(a,l,w,h,p);try{return m?qd(e,t,w,n,o,r,i,y,d):Fd(e,t,w,n,o,r,i,y)}finally{Wd(g,o,r),m||Bd(a,l,w,n,y),Md(a,t.pathInfo,{value:n})}}function Ud(e,t,n,o){return(t,s,...r)=>{Array.isArray(s)||ie(`$resolve("${t}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&ie(`$resolve("${t}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=ce(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}s.length!==i.wildcardParentPathInfos.length&&ie(wl("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=To(i,pd(e,n,o,i,s));if(0===r.length)return ud(e,a,n,o);nd(o),Vd(e,a,r[0],n,o)}}function Kd(e,t,n,o){const s=Ud(e,0,n,o);return(t,r)=>{const i=ce(t);if(void 0===r||Array.isArray(r)||ie(`$getAll("${t}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&ie(wl("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=od(o,i.wildcardPaths[e]);if(t){r=po(t,t.length);break}}if(void 0===r){const e=o.addressStackLength>0?o.lastAddressStack:null,n=e?.listIndex??null;i.wildcardCount>0&&null!==e&&null!==n&&n.length>0&&ie(function(e,t){return`$getAll("${e}") was called without indexes inside the loop context of "${t}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(t,e.pathInfo.path)),r=[]}}const a=fd(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 Gd(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return od(o,s.wildcardPaths.at(-1)??ie(`lastWildcardPath is null: ${t.pathInfo.path}`))??ie(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??ie(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=To(i,s),l=hd(o,a,ud(e,a,n,o)),c=t.wildcardIndexes[r]??ie(`wildcardIndex is null: ${t.pathInfo.path}`);s=l[c]??ie(`ListIndex not found at index ${c} of ${i.path}`)}return s}case"partial":ie(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Jd(e,t,n,o){const s=o.stateElement;return t=>{const r=td(t),i=Gd(e,r,n,o),a=To(r.pathInfo,i),l=ro(s,a),c=di();c.enqueueAbsoluteAddress(l),function(e,t,n,o,s){const r=Oi(e,t),i=Di(e,t);if(!r&&!i)return;const a=n(),l=[],c=Ld(l);r&&Wi(e,t,!1,void 0,a).forEach(c),i&&zi(e,t,void 0,a,!1).forEach(c),Wd(l,o,s)}(s,r.pathInfo.path,()=>ud(e,a,n,o),n,o),Ed(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=ro(s,e);Xr(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}function Xd(e,t,n,o){return(t,s,r,i)=>{nd(o);const a=ce(t);Array.isArray(s)||ie(vl(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&ie(wl("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&ie(vl(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&ie(vl(t,"requires an array as the value when { spread: true } is set."));const d=fd(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&ie(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,d.length,r.length));const f=[];for(let t=0;t<d.length;t++){const s=pd(e,n,o,a,d[t]);f.push(To(a,s))}const h=a.lastSegment===u;let p=0;for(let t=0;t<f.length;t++){const s=h?To(a,pd(e,n,o,a,d[t])):f[t];let i;if(c){i=r(ud(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(Vd(e,s,i,n,o),p++)}return p}}function Yd(e,t){if("all"===td(t).wildcardType)return!0;const n=e.getterPaths;if(0===n.size)return!1;for(const e of ce(t).cumulativePaths)if(n.has(e))return!0;return!1}const Qd=/^\$\d+$/,Zd=`${Z}${d}`,eu=`${ee}${d}`,tu=new WeakMap;function nu(e,t,n,o){const s=R[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&Qd.test(t)&&ie(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${M}1 to ${M}128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&ie(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack,n=e?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=e?.listIndex;null==r&&ie(`ListIndex not found: ${t.toString()}`);let i=s;const a=e.pathInfo,l=o.stateElement?.addressHooks;if(l){const t=l.indexShift;for(let n=0;n<t.length;n++)i+=t[n](o,e)}const c=ho(r,i,a.wildcardCount);return c?.index??ie(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,t,n,e);if(i!==qc)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Kd(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>Xd(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>Jd(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Ud(e,0,n,o)(t,s,...r);case"$trackDependency":ye?.renamed(t,"$dependOn");case"$dependOn":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] ${String(t)}("${e}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&ie(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??ie("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==e&&s.addDynamicDependency(e,n.path)}}(0,t,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Yd(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Mi(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)&&Ci(o.stateElement,e,t,ro(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Yd(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?Mi(o.stateElement,e):Ci(o.stateElement,e,i,ro(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||ie(`$eqIndex("${e}") needs a list row scope.`);const r=ho(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&ie(`$eqIndex("${e}", ${t}): no list index at that level.`),Yd(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&(Mi(o.stateElement,e),o.stateElement.addIndexDependentGetterPath?.(s.pathInfo.path)),Object.is(n[e],r.index);const i=t===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[e],i&&(l=n[s.pathInfo.wildcardParentPaths[t-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const t=i?yn(l):null;null!==t?function(e,t,n,o,s){gi=!0,ki(e).lastValue.set(t,s),Pi(e,t);let r=bi.get(e);void 0===r&&bi.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=vi.get(o);if(void 0===l?(vi.set(o,l=[]),vn(o)):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a){a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a);const n=o[0]?.parentListIndex??null;if(null!==n){let e=xi.get(n);void 0===e&&xi.set(n,e=new Set),e.add(a)}}a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){gi=!0;const r=ki(e);Pi(e,t),Ei(r,t,s,o,_i(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,ro(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":ye?.renamed(t,"$untracked");case"$untracked":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case V:return Fc(o.stateElement)}if(!t.startsWith(Zd)&&!t.startsWith(eu))return}const r=td(t),i=Gd(e,r,n,o),a=To(r.pathInfo,i);return ud(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=tu.get(e);return void 0===t&&(t=new Map,tu.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Hn:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&ie("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case Un:i=t=>ud(e,t,n,o);break;case Kn:i=t=>bd(e,t,n,o);break;case Gn:i=()=>async function(e,t,n){const o=Reflect.get(e,j);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Jn:i=()=>function(e,t,n){const o=Reflect.get(e,L);"function"==typeof o&&o.call(n)}(e,0,n);break;case Xn:i=t=>function(e,t,n,o){const s=Reflect.get(e,W);let r;if("function"==typeof s){const e=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,s=t.path;if(-1===s.indexOf("#")&&(e.add(s),t.wildcardCount>0)){const e=po(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}(e.size>0||0===t.length)&&(r=s.call(n,Array.from(e),i))}const i=o.stateElement?.addressHooks;if(i){const e=i.updated;for(let s=0;s<e.length;s++)e[s](o.stateElement,t,n)}return r}(e,t,n,o);break;case Yn:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,D);"function"==typeof s&&s.call(o,t,n)}(e,t,o,n);break;default:return Reflect.get(e,t,n)}return s.set(t,i),i}}class ou{_stateElement;_addressStack=Array(h).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=Xl(e);null===n&&ie("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&ie("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=h&&(this._hasRepeatedAddress()&&ie(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),ie(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=e}_hasRepeatedAddress(){const e=new Set;for(let t=0;t<=this._addressStackIndex;t++){const n=this._addressStack[t];if(n){if(e.has(n))return!0;e.add(n)}}return!1}_tailAddressPaths(){const e=[];for(let t=this._addressStackIndex;t>=0&&e.length<8;t--){const n=this._addressStack[t];n&&e.push(n.pathInfo.path)}return e}_describeAddressCycle(){const e=this._tailAddressPaths();return`${Array.from(new Set(e)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&ie(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return nu(e,t,n,this)}set(e,t,n,o){return nd(this),function(e,t,n,o,s){if("string"==typeof t){const r=td(t),i=Gd(e,r,o,s);return Vd(e,To(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}deleteProperty(e,t){return nd(this),Reflect.deleteProperty(e,t)}defineProperty(e,t,n){return nd(this),Reflect.defineProperty(e,t,n)}}const su=Promise.resolve(),ru=new Map;let iu=[];function au(e,t){ru.set(e,t),iu=Array.from(ru.values()).sort((e,t)=>e.order-t.order)}function lu(e,t){return ie(ql(e,t))}const cu="undefined"==typeof HTMLElement?class{}:HTMLElement;function du(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 uu=null;const fu=new Set(["for","if","elseif","else"]);function hu(e,n,o){const s=new Map;for(const e of o){const t=ce(e);if(null===t.lastWildcardPath)continue;const n=s.get(t.lastWildcardPath);void 0===n?s.set(t.lastWildcardPath,[t]):n.push(t)}const r=[],i=new Set,a=t=>{const n=ro(e,t);if(i.has(n))return;i.add(n);const o=Po(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(To(n,t.listIndex))}};Fn();try{if(e.createState("readonly",t=>{for(const o of n){const n=To(ce(o),null);a(n);try{Ed(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)fu.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=()=>{jl(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Zr("state",s);void 0!==i&&i.catch(ai)}finally{qn()}}const pu=[[G,"watch"],[J,"scan"],[K,"streams"],[X,"recursion"]];class gu extends cu{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Yl(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 Oc}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&ie(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){Wc(e),function(e){for(let t=0;t<pu.length;t++){const[n,o]=pu[t];n in e&&!Yc(o)&&ie(ql(o,`"${n}"`))}}(e);const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<Gc.length;o++)Gc[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[q];if(void 0===n)return t;Array.isArray(n)||ie(`${q} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ie(`${q} entries must be non-empty strings.`),e===V&&ie(`${q} entry "${e}" conflicts with the reserved namespace name "${V}".`),t.has(e)&&ie(`${q} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[H];if(void 0===n)return t;Array.isArray(n)||ie(`${H} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ie(`${H} entries must be non-empty strings.`),t.has(e)&&ie(`${H} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[Q];if(void 0===t)return null;"object"==typeof t&&null!==t||ie(`${Q} must be an object mapping list paths to key specs.`);const n=new Map;for(const[e,o]of Object.entries(t)){0===e.length&&ie(`${Q} entry path must be a non-empty string.`);const t=e.split(d);t.some(e=>0===e.length)&&ie(`${Q} entry "${e}" must not contain empty path segments.`),t[t.length-1]===u&&ie(`${Q} entry "${e}" must be the list path itself, not the element path (drop the trailing "${d}${u}").`),-1!==e.indexOf(Y)&&ie(`[wcs/recursion-unsupported] ${Q} entry "${e}" uses "${Y}", which ${Q} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${d}${u}${d}children").`),"function"!=typeof o?("string"!=typeof o&&ie(`${Q} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&ie(`${Q} entry "${e}" key field name must be a non-empty string.`),(o.includes(d)||o.includes(u))&&ie(`${Q} entry "${e}" key field name "${o}" must be a flat property name ("${d}" / "${u}" are not allowed).`),o in Object.prototype&&ie(`${Q} entry "${e}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(e,o)):n.set(e,o)}return n.size>0?n:null}(e);var i;n.set("eventTokenNames",s),function(e,t,n){for(let o=0;o<Gc.length;o++)Gc[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<Gc.length;o++)Gc[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&uu?.reset(this),this._hasUpdatedCallback=W in e,this._hasErrorCallback=D in e,i=this,Ho.delete(i),function(e,t,n){for(let o=0;o<Gc.length;o++)Gc[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[U];if(void 0!==o){"object"==typeof o&&null!==o||ie(`${U} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||ie(`${U} entry "${t}" is not declared in $eventTokens.${fe(t,n)}`),"function"!=typeof s&&ie(`${U} entry "${t}" must be a function.`),Uo(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=du(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<Gc.length;o++)Gc[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<Gc.length;o++)Gc[o].register?.(e,t,n)}(this,e,n),Qc(this,null),this._resolveLoading?.()}attributeChangedCallback(e,t,n){this._initialized&&t!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===t?"absent":`"${t}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${s.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?Hl('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);return t&&"application/json"===t.type?JSON.parse(t.textContent||"{}"):(console.warn(`[@wcstack/state] state="${e}": no <script type="application/json" id="${e}"> in the document (3.x does not look inside shadow roots), so the state starts empty.`),{})}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const e=this.getAttribute("json");return JSON.parse(e)}{const e=this.querySelector('script[type="module"]');if(e)return await Cc(e,s.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){let t;try{const n=await fetch(e);if(n.ok)return await n.json();t=`HTTP ${n.status} ${n.statusText}`}catch(e){t=e}return console.error(`[@wcstack/state] Failed to load JSON file "${e}", so the state starts empty (4.0 rejects instead):`,t),{}}(e);if(e&&e.endsWith(".js"))return await Mc(e);ie(`Unsupported src file type: ${e}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,n]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=n}return await this._loadingPromise,null!==this._rootNode&&(ec(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),ie(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;this._initializeFailed=!0;const n=["state","src"].find(e=>this.hasAttribute(e));throw console.error(`[@wcstack/state] <${s.tagNames.state}${n?` ${n}="${this.getAttribute(n)}"`:""}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===Xl(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),Kl.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<iu.length;o++)iu[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{j in e&&await e[Gn]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{L in e&&e[Jn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<iu.length;t++)if(!0===iu[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Xl(this._rootNode)===this||ec(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<iu.length;t++){const n=iu[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{lu("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(te))try{lu("dcc",`a <${s.tagNames.state}> inside a [${te}] host`)}catch(e){this._failInitializeLoudly(e)}let n=!1;try{const e=function(e){for(let t=0;t<iu.length;t++){const n=iu[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&lu("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let o=!1;try{o=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!o)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const e=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(e)}if(this.hasAttribute("enable-ssr")&&!t()||e!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await Hl('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}Qc(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<iu.length;t++)if(!0===iu[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<iu.length;n++)iu[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{ec(this.rootNode,null),e=this,zc.delete(e),function(e){for(let t=0;t<Jc.length;t++)Jc[t].deactivate?.(e)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(e=>(ye?.volumeLoaded(e),Wc(e),e))}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t,this.attachAddressHooks("watch",G)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&ie(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),t.set(n,o);this._listKeys=t}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(e){this._listPaths.add(e)}findStateDescriptor(e){return hl(this._state,e)}defineTreeAccessor(e,t){Object.defineProperty(this._state,e,t),"function"==typeof t.get&&this._getterPaths.add(e),"function"==typeof t.set&&this._setterPaths.add(e),this.setPathInfo(e,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&ie("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(e,t){const n=function(e,t){const n=Hc.get(e);return void 0===n&&ie(ql(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<Vc.length;n++){const o=Vc[n],s=t[o];if(void 0===s)continue;const r=e[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(e){this.attachAddressHooks("scopes",e)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e,this.attachAddressHooks("dcc",z)}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){if(!this._addDependency(this._dynamicDependency,e,t))return!1;const n=ce(e);for(let e=n.parentPathInfo;null!==e&&e.wildcardCount>0&&e.wildcardCount===n.wildcardCount;e=e.parentPathInfo)this._addDependency(this._dynamicDependency,e.path,t);return!0}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+u)),!this._pathSet.has(e)){const t=ce(e);this._pathSet.add(e);const o=function(e,t){const n=td(t);return"all"===n.wildcardType&&1===n.wildcardIndexes.length&&isNaN(+n.segments[0])&&!t.includes("#")&&Object.isExtensible(e)&&!(t in e)}(this.__state,e);if(uu?.check(this,this.__state,e,n,o),o&&function(e,t){const{segments:n,cumulativePaths:o}=ce(t),s=n.length-1,r=(e,r,i)=>{let a,l=!1;for(let c=0;c<=s;c++){const d=n[c];if(l||=!(isNaN(+d)||Array.isArray(a)&&+d in a),r&&c===s)return l?a[d]=i:e[t]=i;a=l?a?.[d]:e[o[c]]}return a},i=function(){return r(this)};pl.set(i,td(t).pathInfo.path),e.defineTreeAccessor(t,{get:i,set(e){r(this,!0,e)},configurable:!0})}(this,e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ce(e.parentPath)}}}_rebuildPathInfo(){for(const[e,t]of Array.from(this._pathRegistrations))t.bound&&!this._generatedPaths.has(e)&&this.setPathInfo(e,t.bindingType)}_createState(e,t,n){try{const o=function(e,t,n){const o=new ou(e,n);return new Proxy(t,o)}(e,this._state,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(e){this._indexDependentGetterPaths.add(e)}setInitialState(e){if(!this._initialized)return this._initializeFailed&&ie(`<${s.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);!function(e){for(let t=0;t<iu.length;t++)iu[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&ie("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const t=this.__state;this._state=e;const n=function(e){const t=new Set;for(const n of e)if(void 0!==n)for(const[e,o]of Object.entries(du(n)))e.startsWith("$")||e.includes(u)||"function"==typeof o.value||t.add(e);return t}([t,e]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(e){hu(this,e,this._pathRegistrations.keys())}}const mu=[],yu=[];function wu(){const e=[];let t=0;for(let n=0;n<yu.length;n++){const o=yu[n].deref();void 0!==o&&(e.push(o),yu[t++]=yu[n])}return yu.length=t,e}function bu(e=customElements){wu().includes(e)||yu.push(new WeakRef(e));for(let t=0;t<mu.length;t++)mu[t](e);e.get(s.tagNames.state)||e.define(s.tagNames.state,gu)}function vu(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 $u(e,t){const n=vu(e);var s;n&&((s=n).tagNames&&Object.assign(o.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(o.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(o.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(o.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(o.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(o.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(o.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(o.locale=s.locale),"boolean"==typeof s.debug&&(o.debug=s.debug),"boolean"==typeof s.enableMustache&&(o.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(o.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(o.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(o.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(o.sameValueGuard=s.sameValueGuard)),bu(t),function(){const e=globalThis;void 0===e[i]&&(e[i]=_c)}()}let xu=null;function Su(e){return xu??ie(ql("watch",`"$watch" in <wcs-state mount="${e}">`))}let Iu=null;const Pu=Object.freeze([]);const ku="3.5.0",Au=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Nu(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 _u(e){const t=[],n=new Set,o=new Set,r=e=>{const o=function(e){const t=`${me(e.inFilters)}\0${me(e.outFilters)}`;return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(o.has(e))return;o.add(e);const t=oc(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(Nu(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(s.bindAttributeName);if(null===n||0===n.length)continue;try{const e=dt(t,ze(n));for(const o of e)r(Nu(t,o,"attribute",n))}catch{}continue}const t=Au.exec(e.data.trim());if(null===t)continue;const n=t[1]||s.commentTextPrefix,o=t[2],a=oc(o);if(null===a){if(n===s.commentTextPrefix)try{r(Nu(e,Ue(o),"comment",o))}catch{}}else r(Nu(e,a.parseBindTextResult,"comment",o)),i(o)}return t}function Tu(e){const t=function(e){const t=ui.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:bi.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 Eu="__WCSTACK_DEVTOOLS_HOOK__";function Cu(){const e=globalThis,t=e[Eu];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[Eu]=n,n}const Mu=e=>{null!==Tt&&Tt({type:"state:update-batch",addresses:e})};function Ou(e){const t=null!==Tt;!function(e){Tt=e}(e);const n=null!==e;n&&!t?ii(Mu,0):!n&&t&&function(e){const t=ei.findIndex(t=>t.listener===e);-1!==t&&ei.splice(t,1)}(Mu)}function Ru(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 ju(e){return Xl(e)??ie("devtools: no state tree on this root")}let Lu=null;function Wu(){if(t())return;if(null!==Lu)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:ku,getStateElements(){const e=[];for(const t of Gl)e.push(Ru(t));return e},overlays(e){return t=ju(e),null===Iu?Pu:Iu(t);var t},keyedSubscriptions:e=>Tu(ju(e)),keys(e){const t=ju(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 ju(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){ju(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>_u(e),_setSink:Ou};Lu=e,Cu().register(e)}const Du={name:"devtools",install(){Wu()}},Bu=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),zu=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const Fu=new WeakMap;const qu=new WeakMap,Vu=new WeakSet,Hu=new WeakMap;function Uu(e,t,n,o){console.warn(`[@wcstack/state] [${ml[n]}] ${yl[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${fe(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${he}`),null!==Tt&&Tt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Ku={check:function(e,t,n,o,s){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const r=e.addressHooks;if(r){const t=r.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const i=ce(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=Fu.get(e);return void 0===n&&(n=new Set,Fu.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const a=function(e,t,n,o){if(void 0!==hl(e,t))return zu;const s=ce(t).segments;let r=e,i="";for(let t=0;t<s.length;t++){const a=o&&Array.isArray(r)&&+s[t]>=0?u:s[t],l=i;i=0===t?a:i+d+a;const c=t>0&&hl(e,i),f=c&&pl.get(c.get);if(c&&(!f||hl(e,f)))return t<s.length-1?Bu:zu;if(Object(r)!==r)return Bu;if(a===u){if(!Array.isArray(r)||0===r.length)return Bu;r=r[0];continue}const h=hl(r,a);if(void 0===h)return{existence:"missing",missingSegment:a,candidates:gl(r,l,n,e)};if("function"==typeof h.get)return t===s.length-1?zu:Bu;r=h.value}return zu}(t,n,e.getterPaths,s);"missing"===a.existence&&(function(e,t){return!0===Hu.get(e)?.has(t)}(e,n)||("binding"!==o?Uu(e,n,o,a):function(e,t,n){let o=qu.get(e);void 0===o&&(o=new Map,qu.set(e,o));if(o.set(t,n),Vu.has(e))return;Vu.add(e),setTimeout(()=>function(e){Vu.delete(e);const t=qu.get(e);if(void 0===t)return;qu.delete(e);for(const[n,o]of t)Uu(e,n,"binding",o)}(e),0)}(e,n,a)))},reset:function(e){Fu.delete(e),qu.delete(e)},markExported:function(e,t){let n=Hu.get(e);void 0===n&&(n=new Set,Hu.set(e,n)),n.add(t),qu.get(e)?.delete(t)}};let Gu=!1;function Ju(){Gu||(Gu=!0,function(e){uu=e}(Ku))}const Xu={name:"diagnostics",install(){Ju()}};function Yu(e){ie(`filter ${e} requires at least one option`)}function Qu(e){ie(`filter ${e} requires a number as option`)}function Zu(e){ie(`filter ${e} requires a number value`)}function ef(e){ie(`filter ${e} requires a date value`)}const tf={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function nf(e){return!(!e||isNaN(Number(e)))}function of(e,t){return nf(e)||Qu(t),Number(e)}function sf(e,t,n){return of(e?.[t]??Yu(n),n)}const rf=e=>t=>{const n=e(t);return e=>null==e?e:n(e)},af={eq:(e,t)=>{const n=e?.[0]??Yu("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e===o:(nf(n)||Qu("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Yu("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e!==o:(nf(n)||Qu("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>!e,lt:e=>{const t=sf(e,0,"lt");return e=>("number"!=typeof e&&Zu("lt"),e<t)},le:e=>{const t=sf(e,0,"le");return e=>("number"!=typeof e&&Zu("le"),e<=t)},gt:e=>{const t=sf(e,0,"gt");return e=>("number"!=typeof e&&Zu("gt"),e>t)},ge:e=>{const t=sf(e,0,"ge");return e=>("number"!=typeof e&&Zu("ge"),e>=t)},add:e=>{const t=sf(e,0,"add");return e=>("number"!=typeof e&&Zu("add"),e+t)},sub:e=>{const t=sf(e,0,"sub");return e=>("number"!=typeof e&&Zu("sub"),e-t)},mul:e=>{const t=sf(e,0,"mul");return e=>("number"!=typeof e&&Zu("mul"),e*t)},div:e=>{const t=sf(e,0,"div");return e=>("number"!=typeof e&&Zu("div"),e/t)},mod:e=>{const t=sf(e,0,"mod");return e=>("number"!=typeof e&&Zu("mod"),e%t)},abs:e=>e=>("number"!=typeof e&&Zu("abs"),Math.abs(e)),clamp:e=>{const t=sf(e,0,"clamp"),n=sf(e,1,"clamp");return e=>("number"!=typeof e&&Zu("clamp"),Math.min(Math.max(e,t),n))},toFixed:e=>{const t=of(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&Zu("toFixed"),e.toFixed(t))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Zu("locale"),e.toLocaleString(t??s.locale))},upper:rf(e=>e=>String(e).toUpperCase()),lower:rf(e=>e=>String(e).toLowerCase()),capitalize:rf(e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),trim:rf(e=>e=>String(e).trim()),slice:rf(e=>{const t=[sf(e,0,"slice")],n=e?.[1];return void 0!==n&&t.push(of(n,"slice")),e=>String(e).slice(...t)}),substr:rf(e=>{ye?.removed("substr");const t=sf(e,0,"substr"),n=sf(e,1,"substr");return e=>String(e).substr(t,n)}),padStart:rf(e=>{const t=sf(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),padEnd:rf(e=>{const t=sf(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),repeat:rf(e=>{const t=sf(e,0,"repeat");return e=>String(e).repeat(t)}),reverse:rf(e=>e=>String(e).split("").reverse().join("")),truncate:rf(e=>{const t=sf(e,0,"truncate"),n=e?.[1]??"…";return e=>{const o=String(e);return o.length<=t?o:o.slice(0,t)+n}}),join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||ie(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=Math.pow(10,of(e?.[0]??"0","round"));return e=>("number"!=typeof e&&Zu("round"),Math.round(e*t)/t)},floor:e=>{const t=Math.pow(10,of(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&Zu("floor"),Math.floor(e*t)/t)},ceil:e=>{const t=Math.pow(10,of(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&Zu("ceil"),Math.ceil(e*t)/t)},percent:e=>{const t=of(e?.[0]??"0","percent");return e=>("number"!=typeof e&&Zu("percent"),`${(100*e).toFixed(t)}%`)},unit:rf(e=>{const t=e?.[0]??Yu("unit");return e=>String(e)+t}),date:e=>{const t=e?.[0];return e=>(e instanceof Date||ef("date"),e.toLocaleDateString(t??s.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||ef("time"),e.toLocaleTimeString(t??s.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||ef("datetime"),e.toLocaleString(t??s.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||ef("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||ef("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]??Yu("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Yu("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},lf={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[2,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,1],time:[0,1],datetime:[0,1],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},cf=af,df=af;let uf=!1;const ff={name:"formats",install(){uf||(uf=!0,Ie("input",df,lf,tf),Ie("output",cf,lf,tf))}};function hf(e){return-1!==e.indexOf(Y)}function pf(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+d;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(hf(o))return null;const s=o.slice(1).split(d);return s[0]===u||s.some(e=>0===e.length)?null:o}function gf(e){return 0===e.length?e:d+wf(e.slice(1))}function mf(e,t,n){const o=d+e.repeat,s=t.length<=n.length?t:n,r=t.length<=n.length?n:t;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let e=0;e<i.length;e+=o.length)if(!i.startsWith(o,e))return!1;return!0}function yf(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(d,o-1))if(mf(e,t,n.slice(0,o)))return!0;return!1}function wf(e){const t=e.split(d);for(let e=0;e<t.length;e++)t[e]===u||Number.isNaN(Number(t[e]))||(t[e]=u);return t.join(d)}function bf(e,t){const n=e.repeat.split(d),o=d+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===d+e.repeatList+d+"length")return!0;for(let e=1;e<n.length;e++)if(s===d+n.slice(0,e).join(d))return!0;return!1}function vf(e,t,n){n<0&&ie(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=d+e.repeat;const s=o+t;let r=0;for(const e of s.split(d))e===u&&r++;return r>f&&ie(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function $f(e,t){return vf(e,"",t)}function xf(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const o=n.slice(e.anchor.length,n.length-t.length);if(0===o.length)return 0;const s=d+e.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function Sf(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=t.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const o=d+n.repeat;let s=0,r=n.anchor.length;for(;t.startsWith(o,r);)r+=o.length,s++;return r!==t.length&&46!==t.charCodeAt(r)?null:s}(t,n.pathInfo.path)}function If(e,t,n){const o=e.recursionRegistry,s=pf(o.spec,n);null===s&&ie(bl(n,o.spec.recursiveAnchor));const r=Sf(t,o);return null===r&&ie(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function Pf(e,t,n,o,s){const r=o.spec,i=[],a=new Map,l=[],c=r.repeatList,u=r.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void i.push(To(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=To(o,s),d=ro(n.stateElement,l),u=ud(e,l,t,n),h=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&ie(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&ie(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${c}" array.`),o})(o.path,u,i),p=oa(s,Bn(d),u);return a.set(d,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=l[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:ce(n),childListPathInfo:ce(r+d+c)};return l[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(To(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,ce(u),null);for(const[e,t]of a)zn(e,t);return i}function kf(e,t,n,o,s,r,i){nd(n);const a=n.stateElement.recursionRegistry,l=pf(a.spec,o);null===l&&ie(bl(o,a.spec.recursiveAnchor));const c=gf(l);Array.isArray(s)||ie(vl(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&ie(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&ie(vl(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&ie(vl(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){bf(e,n)&&ie(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const d=a.conflictingRecursiveGetter(c);null!==d&&ie(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${d}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const u=Pf(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Vd(e,u[o],r,t,n),f++);return f}const Af={write(e,t){if(!0!==e.hasRecursion)return qc;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&ie(`[wcs/recursion-readonly] "${t.pathInfo.path}" writes into the recursive getter "${n}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),qc},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return qc;if("$getAll"===t)return(t,s)=>{if(hf(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=pf(r.spec,o);null===i&&ie(bl(o,r.spec.recursiveAnchor)),Array.isArray(s)||ie(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&ie(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=Pf(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(ud(e,a[o],t,n));return l}(o,n,e,t,s);t=If(e.stateElement,e,t)}return Kd(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>hf(t)?kf(o,n,e,t,s,r,i):Xd(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&hf(t)){const s=td(If(e.stateElement,e,t)),r=Gd(o,s,n,e);return ud(o,To(s.pathInfo,r),n,e)}return qc}};let Nf=!1;function _f(e,t){"string"==typeof t&&0!==t.length||ie(`[wcs/recursion-declaration-invalid] ${X} ${e} must be a non-empty string.`);const n=t.split(d);n.some(e=>0===e.length)&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain empty path segments.`),n.length<2&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must name a list element: a property path ending with "${d}${u}" (for example "nodes${d}${u}").`),n[n.length-1]!==u&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must end with "${d}${u}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===u&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must have exactly one "${u}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===Y&&ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain "${Y}" — the declaration is what gives "${Y}" its meaning.`),isNaN(Number(n[o]))||ie(`[wcs/recursion-declaration-invalid] ${X} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const Tf=new WeakSet;function Ef(e){return"function"==typeof e.get&&Tf.has(e.get)}const Cf="[wcs/recursion-declaration-invalid]";class Mf{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=du(t);for(const[t,o]of Object.entries(n)){if(!hf(t))continue;"function"==typeof o.set&&ie(`${Cf} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&ie(`${Cf} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=pf(e,t);null===n&&ie(bl(t,e.recursiveAnchor)),0===n.length&&ie(`${Cf} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${d}total"), not the node.`),bf(e,gf(n))&&ie(`${Cf} "${t}" names the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${e.recursiveAnchor}${d}total").`),this._definitions.set(t,{recursivePath:t,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(hf(t)||Ef(n))continue;const e=this._matchExpansion(t);null!==e&&ie(`${Cf} "${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++)mf(this.spec,e[t].suffix,e[n].suffix)&&ie(`${Cf} "${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(yf(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=wf(e),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let e=n.lastIndexOf(d);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(d,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==xf(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=xf(this.spec,e.suffix,t);null!==n&&(null!==o&&ie(`"${t}" matches both "${o.recursivePath}" and "${e.recursivePath}".`),o=e,s=n)}return null===o?null:this._define(e,o,s,t)}_define(e,t,n,o){const s=e.findStateDescriptor(o);void 0===s||Ef(s)||ie(`"${o}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:t.recursivePath,depth:n}),i=t.get,a=function(){return i.call(this)};var l;return l=a,Tf.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($f(e,o)+d+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return function(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Ef(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}}}(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let o=n[t];return void 0===o&&(o=vf(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 Of="recursionSpec",Rf="recursionRegistry",jf={order:5,validateEarly(e,t,n){const o=function(e){const t=e[X];if(void 0===t)return null;"object"==typeof t&&null!==t||ie(`[wcs/recursion-declaration-invalid] ${X} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&ie(`[wcs/recursion-declaration-invalid] ${X} must declare exactly one anchor; it is empty.`),n.length>1&&ie(`[wcs/recursion-declaration-invalid] ${X} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];_f("anchor",o),"string"!=typeof s&&ie(`[wcs/recursion-declaration-invalid] ${X} entry "${o}" must map to the repeating sub-path as a string (for example "children${d}${u}").`),_f("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(d)),i=s.slice(0,s.lastIndexOf(d)),a=r+d+Y;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(Of,o),n.set(Rf,null===o?null:new Mf(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(Rf)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",X)},apply(e,t,n){const o=n.get(Of)??null;null!==o&&e.addListPath(o.anchorList)}};let Lf=!1;function Wf(){Lf||(Lf=!0,Nf||(Nf=!0,Uc("recursion",Af)),Xc("recursion",jf))}const Df={name:"recursion",install(){Wf()}};const Bf={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1&&-1===t.path.indexOf("#")?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let zf=!1;function Ff(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 qf(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 Vf(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 Hf(e){return e.startsWith("$")}function Uf(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 Kf(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||ie(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||ie(`${t} entries must be non-empty strings.`),e.startsWith("$")&&ie(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&ie(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Gf(e){Wc(e);const t=Kf(e,z)??[],n=Kf(e,F)??[],o=du(e),s=function(e){const t=e[K];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),r=[];for(const e of t){const t=o[e];if(void 0===t){if(s.has(e)){r.push(e);continue}ie(`${z} entry "${e}" is not declared on the state.${fe(e,Uf(o,"value"))}`)}"function"==typeof t.value&&ie(`${z} entry "${e}" is a method. Declare it in ${F} instead.`)}for(const e of n){const t=o[e];void 0===t&&ie(`${F} entry "${e}" is not declared on the state.${fe(e,Uf(o,"method"))}`),"function"!=typeof t.value&&ie(`${F} entry "${e}" is not a method. Declare it in ${z} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function Jf(e,t,n){const o=e.tagName.toLowerCase();o.includes("-")||ie(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const r=tt(e);null!==r&&"function"==typeof r.define||ie(`DCC: CustomElementRegistry is unavailable for "${o}".`),r.get(o)&&ie(`DCC: "${o}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=Gf(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(o,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(o,c):{},p=s.tagNames.state,g=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(te))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=tt(this._shadow);return null!==e&&nt(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(zf||(zf=!0,Uc("dcc",Bf)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${z} but its template has no <${s.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=du(n);for(const[e,t]of Object.entries(m)){if(Hf(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Vf(e,o)}else n.get=Ff(e),n.set=qf(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:Ff(e),set:qf(e)});r.define(o,g)}async function Xf(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&ie(`"bind-component" cannot be used inside a [${te}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await Mc(t);ie(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await Cc(n,t.tagName.toLowerCase());ie(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}(o,t);Jf(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const Yf={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(te)?Xf(e,t.host,t):null}};let Qf=!1;function Zf(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 eh(e,t){for(const n of e)if(Zf(t,n.innerSegments))return n;return null}function th(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+d+n.join(d)}const nh=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function oh(e,t,n){const o=nh.get(e);return void 0===o?null:(...e)=>{const s=e.slice();for(let e=0;e<o.length;e++){const n=o[e];"string"==typeof s[n]&&(s[n]=t(s[n]))}return n(s)}}const sh=new WeakMap;function rh(e,t,n){let o=sh.get(e);void 0===o&&(o=new Map,sh.set(e,o));const s=o.get(t);null!=s&&ie(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function ih(e,t){if(null===e)return!1;const n=sh.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+d)||e.startsWith(t+d))return!0;return!1}const ah=new WeakMap;const lh=[];function ch(e,t,n,o){if(t.length>0){const s=n.split(d),r=eh(t,s);if(null!==r)return o&&r.readonly&&ie(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${N}.${r.innerSegments.join(d)}#${b}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${b} from the injection.`),th(r,s)}return e+d+n}function dh(e,t,n){let o=-1,s=null;for(const e of t){const t=e.outerPathInfo.path;t.length<=o||(n===t?(o=t.length,s=e.innerSegments.join(d)):n.startsWith(t+d)&&(o=t.length,s=e.innerSegments.join(d)+n.slice(t.length)))}if(e.length>o){if(n===e)return"";if(n.startsWith(e+d))return n.slice(e.length+1)}return s}function uh(e,t,n=lh){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](ch(e,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>t.$setAll(ch(e,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>t.$resolve(ch(e,n,o,s.length>1),...s);const o=oh(s,t=>ch(e,n,t,!1),e=>t[s](...e));return null!==o?o:t[s]}return t[ch(e,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(t[s]=r,!0):(t[ch(e,n,s,!0)]=r,!0)),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const fh=new WeakMap,hh=[];const ph=new WeakMap,gh=new WeakSet;function mh(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 yh=null;let wh=0;const bh=["$watch",K,"$scan","$listKeys",W,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],vh=new Set;function $h(e,t,n){const o=e.stateObject[t];if("function"==typeof o)try{const s=o.call(n());s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function xh(e,t,n,o,s,r=new Set){0===n.length&&ie(`Cannot build a mount record without host bindings for "${t}".`),Wc(s);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(d);a.has(n)&&ie("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(b)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const c=++wh,u=`#m${c}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=du(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)1===e.innerSegments.length&&p.add(e.innerSegments[0]);const g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:c,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?u:l.outerPathInfo.path+d+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(e=>e.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function Sh(e){const t=e.indexOf(d);return-1===t?e:e.slice(0,t)}function Ih(e,t){const n=eh(e.entries,t);return null===n?null:th(n,t)}function Ph(e,t){return e.markerBasePath+d+t}function kh(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+d+n;s.set(n,{accessorName:o,indexShift:ce(r).wildcardCount-ce(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function Ah(e,t){return!e.injectedKeys.has(t)&&(!e.getterKeys.has(t)&&"function"==typeof e.stateObject[t]||!e.mappedKeys.has(t)&&(Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t)))}function Nh(e,t){return`Path "${t}" in <${e.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${e.entries.filter(e=>e.innerSegments.length>0).map(e=>e.innerSegments.join(d)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${Sh(t)}: path") or declare the key on the component state.`}const _h=/^\$(\d+)$/;function Th(e,t){if(!e.hasReadonlyEntries)return null;const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=Sh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||Ah(e,o))return null;const s=function(e,t){return eh(e.entries,t)}(e,t.split(d));return null!==s&&s.readonly?s:null}function Eh(e,t){const n=Th(e,t);if(null!==n){const o=0===n.innerSegments.length?"":d+n.innerSegments.join(d);ie(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${b}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${b} from the mount.`)}return Ch(e,t)}function Ch(e,t){const n=t[0];if("$"===n||"#"===n)return t;if(e.getterKeys.has(t)||e.setterKeys.has(t))return function(e,t){const n=t.split(d);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===u){o=e;break}if(-1===o)return kh(e,e.markerBasePath,t,t),Ph(e,t);if(Ah(e,n[0]))return kh(e,e.markerBasePath,t,t),Ph(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Ih(e,s);null===i&&ie(Nh(e,t)),0===r.length&&ie(`Wildcard-terminal accessor "${t}" on mounted <${e.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const a=i+d+e.marker;return kh(e,a,r.join(d),t),a+d+r.join(d)}(e,t);const o=Sh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return Ph(e,t);if(Ah(e,o))return Ph(e,t);const s=Ih(e,t.split(d));if(null!==s)return s;ie(Nh(e,t))}const Mh=new Set(["prop","radio","checkbox"]);function Oh(e,t,n){let o;const s=_h.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ce(Ch(e,t)).wildcardCount-ce(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Ch(e,t.statePathName),"for"===t.bindingType){const n=ce(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+d+u,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&Mh.has(t.bindingType??"")&&!r.includes(b)&&null!==Th(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ce(o),...i?{propModifiers:[...r,b]}:{}}:t}function Rh(e,t,n,o,s){if(void 0===o)return;const r=ce(n).wildcardCount-ce(t).wildcardCount;return 0===r?o:(s.length<r&&ie(`Cannot resolve "${t}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}function jh(e,t,n){if(-1!==e.indexOf(u))return t;const o=t.split(d);let s=0;for(let e=0;e<o.length&&s<n.length;e++)o[e]===u&&(o[e]=String(n[s++]));return o.join(d)}const Lh=new WeakMap,Wh=new WeakMap;const Dh=new WeakMap;const Bh=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)}),zh=new WeakMap;function Fh(e){return zh.get(e)??null}let qh=!1;function Vh(){qh||(qh=!0,At=e=>Lh.has(e)?e.host:null)}function Hh(e){return Lh.get(e)??null}function Uh(e){return Kh(e).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join(d),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]}))}function Kh(e){const t=Dh.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 Gh(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Dh.get(e);if(void 0===o)return null;const s=t.indexOf(d,n),r=-1===s?t.slice(n):t.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const Jh=new WeakMap,Xh=new Set;function Yh(e,t,n,o){let s=Jh.get(e);if(void 0===s){if(!o)return null;s=new Map,Jh.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 Qh(e,t){if(!e.component.isConnected)return!1;const n=Nt(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 Zh(e,t,n,o){const s=Yh(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&&Qh(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?Qh(r,o)&&(null!==a&&ie(`[wcs/mount-export-ambiguous] "${t}${d}${n}" is exported by two mounted components on the same instance: <${a.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=e,a=r):s.holders.delete(e)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function ep(e){const t=e.parentStateElement,n=Nt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Hn](n,()=>{e.$postUpdate(o.exportedPath)})})}const tp=new WeakMap,np=new WeakMap,op=new WeakMap,sp=new WeakMap;function rp(e,t){np.set(e,t);const n=[];for(let e=t?.listIndex.parentListIndex??null;null!==e;e=e.parentListIndex)n.push(e);sp.set(e,n)}function ip(e){return Nt(e.component)??np.get(e)??null}function ap(e){return ip(e)?.listIndex??null}function lp(e){ie(`The host row of <${e.component.tagName.toLowerCase()}> was removed.`)}function cp(e){for(;null!==e;e=e.parentListIndex)if(tn(e))return!0;return!1}function dp(e,t){return!e.component.isConnected&&(cp(t)||!0===sp.get(e)?.some(e=>tn(e)))}class up{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(e,t,n,o,s,r,i,a=!1){this.record=e,this.markerParentPath=t,this.listIndex=n,this.hostRow=o,this.isBase=s,this.receiver=r,this.handler=i,this.authorFacing=a}authorThis(e,t){return this.authorFacing?t:new Proxy(e,new up(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return To(ce(this.markerParentPath+d+e),this.listIndex)}hostIndexes(){const e=this.listIndex??ap(this.record),t=this.hostRow??e;return(null===this.listIndex?t!==e||dp(this.record,t):cp(t))&&lp(this.record),t?.indexes??[]}resolveTreePath(e,t){return-1===t.indexOf(u)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==td(t).wildcardType&&!dp(this.record,this.listIndex)?t:jh(e,t,this.hostIndexes())}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(this.resolveTreePath(e,Ch(this.record,e)))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.hostIndexes(),o=this.receiver,s=this.handler,r=this.listIndex;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Eh(e,t):Ch(e,t),a=Rh(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const i=t;return(t,a,...l)=>{const c="$setAll"===i?Eh(e,t):Ch(e,t),d=Rh(0,t,c,void 0===a&&"$getAll"===i&&null===r&&null===od(s,ce(c).wildcardPaths[0])?[]:a,n);return o[i](c,d,...l)}}const e=this.record,n=this.receiver,o=oh(t,t=>this.resolveTreePath(t,Ch(e,t)),e=>n[t](...e));return null!==o?o:this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return sd(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(this.authorThis(e,n))}return this.receiver[this.resolveTreePath(t,Ch(this.record,t))]}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n);const s=this.accessorNameFor(t);if(void 0!==s){this.record.setterKeys.has(s)||ie(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(t)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,this.authorThis(e,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(e,t)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress(To(ce(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+d+t]=n}finally{this.handler.popAddress()}return!0}return e[t]=n,!0}return this.receiver[this.resolveTreePath(t,Eh(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 Ch(this.record,t),!0}catch{return!1}}}function fp(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=tp.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},tp.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 up(e,s,t.listIndex,t.listIndex??ap(e),r,n,o))}function hp(e){if(null===ap(e))return e.component[e.stateProp];let t=op.get(e);if(void 0===t){const n={row:null};op.set(e,t=[pp(e,n),n])}return t[0]}function pp(e,t){const n=()=>{const n=ip(e);return void 0!==t&&op.get(e)?.[0]!==i&&n.listIndex!==t.row&&lp(e),n},o=()=>{const t=n();return dp(e,t?.listIndex??null)&&lp(e),t?.listIndex.indexes??[]},s=(t,n)=>-1===n.indexOf(u)?n:"partial"===td(n).wildcardType?jh(t,n,o()):-1===n.indexOf("#")&&dp(e,ap(e))?lp(e):n,r=(t,o)=>{let s;const r=n();return e.parentStateElement.createState(t,e=>{s=e[Hn](r,()=>o(e))}),s},i=new Proxy({},{get(t,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(e,t,n,o,s){return"$postUpdate"===t?t=>n("readonly",n=>n.$postUpdate(s(t,Ch(e,t)))):(s,r,...i)=>{const a="$setAll"===t||"$resolve"===t&&i.length>0,l=a?Eh(e,s):Ch(e,s),c=Rh(0,s,l,"$resolve"===t?r??[]:r,o());return n(a?"writable":"readonly",e=>e[t](l,c,...i))}}(e,n,r,o,s);const i=oh(n,t=>s(t,Ch(e,t)),e=>r("readonly",t=>t[n](...e)));if(null!==i)return i;const a=t=>t["$"===n[0]?n:s(n,Ch(e,n))],l=r("readonly",a);return"$"===n[0]||e.getterKeys.has(n)||"function"!=typeof e.stateObject[n]?l:function(...e){return r("writable",t=>a(t).apply(this,e))}},set:(t,n,o)=>("string"==typeof n&&r("writable",t=>{t["$"===n[0]?n:s(n,Eh(e,n))]=o}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return Ch(e,n),!0}catch{return!1}}});return i}function gp(e,t){const n=Hh(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&ie(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&Er(t).dispose(),function(e,t){Vh(),Lh.set(e,t),zh.set(t,e);let n=Dh.get(t.parentStateElement);void 0===n&&(n=new Map,Dh.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Wh.get(t.component);void 0===o&&(o=new Map,Wh.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Bh.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=Ul.get(e);if(void 0!==n){if(n===t)return;ie("A state tree is already registered on this root.")}Ul.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Oh(e,t,n);se(t);const o=Nt(e.component);rp(e,o);xc(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),Wl(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=Ch(e,n)}catch{continue}const o=t.indexOf(d+e.marker);if(-1===o)continue;const s=t.slice(0,o+1+e.marker.length),r=t.slice(s.length+1),i=t.slice(0,o)+d+r,a=ce(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Yh(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),uu?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=Nt(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(Xh.has(s))continue;const r=ce(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Hn](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Xh.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),ep(e),o=t,s=Promise.resolve(),Kl.set(o,s),s.then(()=>Zl(o),()=>{})}function mp(e,t){jl(yp(e,t).rebindAddresses()),ep(e)}function yp(e,t){const n=Er(t),o=Nt(e.component);return rp(e,o),n.forEachActiveBindingNode(e=>_t(e,o)),n}function wp(e){for(let t=e.parentNode;null!==t;t=t.parentNode){const e=Hh(t);if(null!==e)return wp(e.component),void yp(e,t)}}function bp(e,t){if(function(e){const t=Dh.get(e);return void 0!==t&&t.size>0}(t))for(const n of Kh(t)){if(!vp(n.component,e))continue;const t=Fh(n);null!==t&&mp(n,t)}}function vp(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 $p={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Gh(e,t.pathInfo.path);if(null!==s)return fp(s,t,n,o)}return qc},readMissing(e,t,n,o,s){if(null===n){if(ih(e.rootNode??null,t.pathInfo.path))return;return qc}if(!0===e.hasMounts){const n=Zh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=fp(e,To(ce(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return qc},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=ah.get(e);if(void 0===n||0===n.size)return null;const o=t+d;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&ie(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return qc},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Zh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=fp(e,To(ce(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return qc},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Gh(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(d,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const s=-1===o?t:t.slice(0,o),r=-1===o?"":t.slice(o+1),i=e.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:e.delta}(e,o)}return 0},handlerScope(e,t,n,o,s){if(!0!==e.hasMounts)return s;const r=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=Lh.get(n);if(void 0!==e)return e;n=n.parentNode}return Lh.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 fh.get(e)??hh}(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=dh(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=po(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(uh(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>ih(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){bp(t,e)}};let xp=!1;function Sp(){xp||(xp=!0,Uc("scopes",$p),Iu=Uh)}const Ip=new WeakMap;function Pp(e){let t=Ip.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Ip.set(e,t)),t}function kp(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=sh.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function Ap(e,t,n){if(t.slotRootNode===n)return!0;const o=t.mountPath;try{rh(n,o,e)}catch{return console.error(`[@wcstack/state] <${s.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return Xl(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Np(e,t){const n=e,o=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&ie('"mount" requires a non-empty tree path.');const t=ce(e);for(const n of t.segments)0===n.length&&ie(`"mount" path "${e}" has an empty segment.`),n===u&&ie(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&ie(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],o=new Set;let r;try{r=ze(e)}catch(e){ie(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> has an invalid ${s.bindAttributeName}: ${e instanceof Error?e.message:String(e)}`)}for(const e of r){if(e.propSegments[0]!==N)continue;const r=e.propSegments.slice(1),i=e.statePathInfo,a=n=>ie(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> "${e.propName}: ${e.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==u&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${N}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(e.inFilters.length>0||e.outFilters.length>0)&&a("an injection takes no filters."),e.propModifiers.some(e=>e!==b)&&a(`an injection accepts only #${b}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:e.propModifiers.includes(b)})}return n.sort((e,t)=>t.innerSegments.length-e.innerSegments.length),n}(n.getAttribute(s.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&ie('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${s.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),rh(o,r,e),Xl(o)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=o}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===Xl(o)&&function(e,t){const n=()=>{if(null!==Xl(e))return;const n=e.querySelectorAll(s.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${s.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${s.tagNames.state}> to this root node (an empty <${s.tagNames.state}></${s.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=e.ownerDocument??e;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&kp(e,t),e.settleInitialization()};let l;try{await Promise.resolve(),l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const c=e.connectedRootNode??null;null!==c&&Ap(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 og(t,a);rg(),function(e,t){if(gh.has(e))return void mh(t);let n=ph.get(e);void 0===n&&(n=[],ph.set(e,n)),n.push(t)}(e,a)}(c,Xl(c),r,l,a,()=>Ap(e,t,c),i):a(null)}const _p={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=Pp(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{rh(n,t.mountPath,e),Xl(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,su}return Np(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Pp(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&Xl(n)===t.graftInfo.rootStateElement&&eg(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Ip.get(e)?.initializing)return;const t=e.getAttribute("mount");ie(`Cannot replace the state of <${s.tagNames.state} mount="${t}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${t}" on the root state instead.`)},initializeFailed(e,t){!function(e){gh.add(e);const t=ph.get(e);if(void 0!==t){ph.delete(e);for(const e of t)mh(e)}}(t)},initializeFailureCleared(e,t){!function(e){gh.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Pp(e);return null!==t.graftInfo&&eg(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,kp(e,t)),e.clearConnectedRootNode(),!0}};let Tp=!1;const Ep=new WeakMap;function Cp(e,t){let n=Ep.get(e);n||(n=new Set,Ep.set(e,n)),n.add(t)}const Mp=new WeakMap;const Op=new WeakMap,Rp=new WeakMap;const jp=new WeakMap;const Lp={isComplete:function(e,t){return!0===Ep.get(e)?.has(t)},isDeclared:function(e,t){return!0===Mp.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=Op.get(e);o||(o=new Map,Op.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=Rp.get(e);o||(o=new Map,Rp.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=jp.get(e);s||(s=new Map,jp.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function Wp(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 Dp=new WeakMap;class Bp{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=Dp.get(e);return n?n.get(t)??null:null}(e,t)??ie("State element not found for web component.")}get(e,t,n){if("string"==typeof t){let e;return this._innerStateElement.createState("readonly",n=>{e=n[t]}),e}return Reflect.get(e,t,n)}set(e,t,n,o){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,o)}}const zp=e=>()=>e;function Fp(e,t,n,o){!function(e,t,n){let o=Dp.get(e);o||(o=new Map,Dp.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(Wp(o));const s=function(e,t){const n=new Bp(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:zp(s),enumerable:!0,configurable:!0}),Cp(t,n),qp(t,n)}function qp(e,t){if(B in e){const n=e[B];"function"==typeof n?n.call(e,t).catch(e=>{ie(`Error in ${B}: ${e instanceof Error?e.message:String(e)}`)}):ie(`${B} is not a function.`)}}const Vp=new Set;function Hp(e,t){Vp.has(e)||(Vp.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function Up(e){!function(e){const t=e.component.tagName.toLowerCase(),n=e.stateProp;let o=null;for(const s of e.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=du(e.stateObject);const i=o[r];let a;if(e.getterKeys.has(r)||e.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)a="an accessor";else if("function"==typeof i?.value)a="a method";else{if(e.mappedKeys.has(r)||e.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(e.stateObject,r))continue;a="an own data key"}const l=s.innerSegments.join(d);Hp(`${t}|${n}|${l}|entry`,`<${t}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${l}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(e);const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=Kp(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;Hp(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}function Kp(e){const t=e.rootEntry,n=Nt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Hn](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Gp=new WeakMap;function Jp(e,t){e.landInitialization(),ie(t)}async function Xp(e,t){const n=e;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?Ze(a):null;null!==a&&null!==l||ie(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(s.bindAttributeName)||Jp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(e=>n.hasAttribute(e));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&ie(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(e,t){let n=Mp.get(e);n||(n=new Set,Mp.set(e,n)),n.add(t)}(a,d);const u=tt(a);null===u&&ie(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await Xe(a),d in a||ie(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||ie(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=Op.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==h&&function(e,t){if(!e.hasAttribute(s.bindAttributeName))return!1;const n=gt(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(a,d)&&(a[d]=h,f=h),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(gt(a)??[]).some(e=>e.propSegments[0]===d)||Jp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(s.bindAttributeName)){const s=(gt(a)??[]).filter(e=>e.propSegments[0]===d);if(s.length>0){const c=Xl(a.getRootNode())??Jp(e,`No state tree found on this root for mount host <${l}>.`);let u=(o=a,r=d,Wh.get(o)?.get(r)??null);const h=null!==u;if(null===u&&(!function(e,t,n){const o=jp.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;jp.get(e).delete(t)}}(a,d,f),u=xh(a,d,s,c,f,function(e,t){return Rp.get(e)?.get(t)}(a,d)),Up(u)),t.mountRecord=u,n.parentNode!==i)return;try{gp(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=pp(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),Cp(a,d)}return qp(a,d),function(e){const t=bh.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(Y)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;vh.has(n)||(vh.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 $h(u,"$connectedCallback",()=>hp(u))}}Fp(e,t.boundComponent,t.boundComponentStateProp,f)}var o,r}const Yp={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=Gp.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Gp.set(e,t)),t}(e);return Xp(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Gp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&mp(n,o)}),e.isConnected&&(wp(n.component),yp(n,o)),$h(n,"$connectedCallback",()=>hp(n)),!0},disconnecting(e){const t=Gp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord;return $h(n,"$disconnectedCallback",()=>hp(n)),function(e){const t=op.get(e);void 0!==t&&(t[1].row=ap(e),op.delete(e))}(n),ep(t.mountRecord),e.clearConnectedRootNode(),!0}};let Qp=!1;function Zp(){Qp||(Qp=!0,au("bindComponent",Yp),Mr=Lp)}function eg(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(uh(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function tg(e,t,n,o){const s=n[G];if(void 0!==s){const n=Su(t),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=ch(t,o,n,!1),c=function(e,n,...s){l.call(uh(t,this,o),e,n,...s)};r.push({path:s,pathInfo:ce(s),handler:c,order:1e6+a++}),i.add(s),e.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(e,r),e.addVolumeWatchPaths?.(i),n.start(e))}const r=n[Q];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(ch(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[W];"function"==typeof i&&(!function(e,t){let n=fh.get(e);void 0===n&&(n=[],fh.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,injections:o,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[e]&&console.warn(`[@wcstack/state] volume "${t}" declares ${e}, which volumes do not support. Declare it on the root state instead.`);ye?.volume(t,n,o.length)}function ng(e,t,n,o=[]){Wc(n),function(e,t,n,o){const s=0===o.length?null:du(n);for(const e of o){const n=e.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||ie(`[wcs/mount-path-invalid] Volume "${t}" declares "${n}" as an accessor or a method and also injects it ("${N}.${n}: ${e.outerPathInfo.path}"). Rename one of them.`)}const r=n[G];if(void 0!==r){"object"==typeof r&&null!==r||ie(`${G} must be an object mapping state paths to handler functions.`);const e=Su(t);for(const[t,n]of Object.entries(r))"function"!=typeof n&&ie(`${G} entry "${t}" must be a function.`),e.assertValidPath(t)}const i=n[Q];if(void 0!==i){"object"==typeof i&&null!==i||ie(`${Q} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(i)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&ie(`${Q} entry "${n}" must map a list path to a field name or a key function.`);const r=ch(t,o,n,!1);e.listKeys?.has(r)&&ie(`${Q} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[K]&&ie(`Volume "${t}" declares ${K}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&ie(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[X]&&ie(`Volume "${t}" declares ${X}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const e of Object.keys(du(n)))-1!==e.indexOf(Y)&&ie(`Volume "${t}" declares "${e}", which uses "${Y}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n,o);const{data:s,accessors:r}=function(e,t){const n={},o=new Map;for(const[s,r]of Object.entries(du(e)))s.startsWith("$")||t.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(e=>e.innerSegments[0]))),i=ce(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;ie(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let t=0;t<i.segments.length-1;t++){const o=i.segments[t],s=""===n?o in e:void 0!==e[n+d+o];n=""===n?o:n+d+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;ie(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=s}),function(e,t){let n=ah.get(e);void 0===n&&(n=new Set,ah.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+d+n,i=s.get,a=s.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(uh(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(uh(t,this,o),e)}),e.defineTreeAccessor(r,l)}tg(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(uh(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 og(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=ng(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 sg=!1;function rg(){var e;sg||(sg=!0,Sp(),Tp||(Tp=!0,au("scopes",_p)),Zp(),yh=og,e=ig,Jl.includes(e)||Jl.push(e))}function ig(e,t){(function(e){const t=sh.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){gh.delete(e);const n=ph.get(e);if(void 0===n||0===n.length||null===yh)return;ph.delete(e);const o=yh;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const ag={name:"scopes",install(){rg(),Qf||(Qf=!0,au("dcc",Yf))}},lg=/^@@wcs-(?:for|if|elseif|else):[^-]/,cg=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,dg=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,ug=/^@@wcs-text-start:(.+)$/;function fg(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function hg(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const e=n.currentNode;t(e.data)&&o.push(e)}return o}const pg=e=>lg.test(e),gg=e=>cg.test(e),mg=e=>cg.test(e)||dg.test(e);function yg(e){if("else"===e.bindingType)return"else:";let t=`${e.bindingType}: ${e.statePathName}`;for(const n of e.outFilters){const e=n.literals??n.args;t+=`|${n.filterName}`,n.args.length>0&&(t+=`(${n.args.map((t,n)=>"string"==typeof e[n]?`'${t.split("'").join("'\"'\"'")}'`:t).join(",")})`)}return t}function wg(e){const t=e.fragment.cloneNode(!0);for(const n of e.nodeInfos){const o=gc(ut(e.fragment,n.nodePath));if(null===o)continue;const s=ut(t,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return t}class bg extends cu{_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=ku.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static find(e){const t=s.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t,o){const r=o??e.ownerDocument;n.seen&&function(e){const t=new Map;for(const n of hg(e,gg)){if(null===n.parentNode)continue;const[,e,o]=cg.exec(n.data),s=o.split(":")[0],r=n.previousSibling?.data,i=`@@wcs-${e}-end:${o}`;if(r!==`@@wcs-${e}:${s}`&&t.get(r)!==s)for(let e=n;null!==e;){const t=e.nextSibling;e.remove(),e=e.data===i?null:t}else"for"===e&&t.set(i,s)}}(r);const i=document.createElement("script");i.setAttribute("type","application/json"),i.textContent=fg(JSON.stringify(t)),e.appendChild(i);for(const[t,n]of function(e){const t=new Map,n=[e];for(;n.length>0;)for(const e of hg(n.shift(),pg)){const o=e.data,s=o.slice(o.indexOf(":")+1);if(t.has(s))continue;const r=oc(s);null!==r&&(t.set(s,r),n.push(r.fragment))}return t}(r)){const o=document.createElement("template");o.setAttribute("id",t),o.setAttribute(s.bindAttributeName,yg(n.parseBindTextResult)),o.content.appendChild(wg(n)),e.appendChild(o)}const a=e.ownerDocument,l=Array.from(tl);if(l.length>0){const t={};for(let e=0;e<l.length;e++){const n=l[e];if(!n.isConnected||n.ownerDocument!==a)continue;const o=el(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const e of o)r[e.propName]=e.value;t[s]=r}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=fg(JSON.stringify(t)),e.appendChild(n)}}nl()}static removeBlockBoundaryComments(e){for(const t of hg(e,mg))t.remove()}static removeStructuralComments(e){for(const t of hg(e,pg))t.remove()}static restoreTextBindings(e){for(const t of hg(e,e=>ug.test(e))){const e=ug.exec(t.data)[1],n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(s.tagNames.ssr),o=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&o.set(t,e)}}for(const e of hg(t,gg)){const t=cg.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()}bg.restoreTextBindings(t);const r=e=>{for(const t of hg(e,pg)){const e=o.get(t.data.split(":")[1]);if(e){const n=document.createElement("template"),o=e.getAttribute(s.bindAttributeName);o&&n.setAttribute(s.bindAttributeName,o);const i=document.importNode(e.content,!0);if(i.childNodes.length>0)n.content.appendChild(i);else for(const t of Array.from(e.childNodes))n.content.appendChild(document.importNode(t,!0));r(n.content),t.parentNode.replaceChild(n,t)}}};r(t);const i=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of i)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const vg={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=s.tagNames.state,n=s.tagNames.ssr,o=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of o){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",ku),bg.buildContent(o,bg.extractStateData(e),e.getRootNode()),e.parentNode?.insertBefore(o,e)}nl()},reset:function(){tc.clear(),nl(),n.seen=!1}};const $g=new Set(["for","if","elseif","else"]);function xg(e){const[,t,n]=cg.exec(e),[o,...s]=n.split(":");return"for"===t?{type:t,uuid:o,path:s[0],index:parseInt(s[1],10),nodes:[]}:{type:t,uuid:o,path:s.join(":"),index:null,nodes:[]}}function Sg(e){const t=[];for(const n of e)if(n.nodeType===Node.ELEMENT_NODE){const e=n;e.hasAttribute(s.bindAttributeName)&&t.push(e),Array.from(e.children).some(e=>e.localName===s.tagNames.state&&mt(e))||t.push(...bt(e))}else null!==He(n)&&t.push(n);return t}function Ig(e){const[t,n,o]=St(e),s=new Tr;return{bindingInfos:s.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:t,bindingSession:s,deferredSpreads:o}}const Pg=/^\s*@@\s*(?:wcs-text)?\s*:/;function kg(e,t){for(const n of t)"event"===n.bindingType||$g.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&Pg.test(n.node.data))&&e.push(n)}function Ag(e,t){const n=[];for(let o=0;o<e.nodes.length;o++){const s=t.get(e.nodes[o]);s?o+=s.nodes.length+1:n.push(e.nodes[o])}return n}function Ng(e,t,n,o,s,r){t.length>0&&(e.spreads=t);for(const e of t)It(e.node);Ll(t,n,o,s,r)}function _g(e,t){const n=oc(t),o=Xl(e.getRootNode());let s=null;if(n&&o){const{statePathName:e,outFilters:t}=n.parseBindTextResult;o.createState("readonly",n=>{const o=Or(n[e],ft(t,"output"));Array.isArray(o)&&(s=o)})}return s}function Tg(e,t){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[e]}:${t}`}function Eg(e,t,n){const o=Tg(t,n);return hg(e,e=>e===o)[0]??null}function Cg(e,t){const n=e,o=t.templates,r=new Map;for(const[e,t]of o)for(const n of hg(t.content,pg))r.set(n.data.slice(n.data.indexOf(":")+1),e);const i=new Set(yt(e));if(i.size>0)for(const e of hg(n,pg)){const t=e.data.slice(e.data.indexOf(":")+1);let n=e.parentNode;for(;null!==n&&!i.has(n);)n=n.parentNode;null===n||r.has(t)||r.set(t,n)}const a=new Map,l=[];for(const[e,t]of o){let n=ze(t.getAttribute(s.bindAttributeName)||"")[0];const o=n.bindingType,i=r.get(e),c=a.get(i);"else"===o&&c&&(n={...c,outFilters:[...c.outFilters,ic()],bindingType:"else"}),"if"===o||"elseif"===o?a.set(i,n):"else"===o&&a.set(i,null),l.push([e,t,n])}for(const[e,t,o]of l.reverse()){const s=document.importNode(t.content,!0),r="for"===o.bindingType?o.statePathName:void 0;yc(s),"string"==typeof r&&fc(s,r),xc(n,s,r);nc(e,n,{fragment:s,parseBindTextResult:o,nodeInfos:mc(s)})}}const Mg={hydrate:async function(e){await Bl(e);const t=e.querySelectorAll(s.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${ku}". Falling back to full render.`),bg.cleanupDom(e),!1}const n=function(e){const t=[];for(const n of hg(e,mg)){if(!gg(n.data)){t.pop();continue}const e=xg(n.data),o=t.at(-1);if("for"===e.type&&o&&o.uuid!==e.uuid)return[e,o];t.push(e)}return null}(document.body);if(null!==n){const[t,o]=n;return console.warn(`[@wcstack/state] SSR: "for: ${t.path}" in "${o.type}: ${o.path}" (known limitation). Falling back to full render.`),bg.cleanupDom(e),!1}for(const n of t)Cg(e,n);bg.restoreTextBindings(document.body);const o=function(e){const t=[];for(const n of hg(e,gg)){const e=xg(n.data);e.start=n;const o=n.data.replace("-start:","-end:");let s=n.nextSibling;for(;s&&(s.nodeType!==Node.COMMENT_NODE||s.data!==o);)e.nodes.push(s),s=s.nextSibling;t.push(e)}return t}(document.body),r=new Map,i=function(e,t,n=new Map){const o=new Map,s=[],r=new Map(t.map(e=>[e.start,e])),i=new Set;for(let e=t.length-1;e>=0;e--){const n=Sg(t[e].nodes).filter(e=>!i.has(e));for(const e of n)i.add(e);t[e].subscribers=n}for(const i of t){const t=Ag(i,r);if(0===t.length)continue;const a=t.some(e=>pg(e.data));if(a){const e=document.createComment(`wcs-row-end:${i.uuid}`);i.nodes[i.nodes.length-1].after(e),t.push(e)}const{bindingInfos:l,subscriberNodes:c,bindingSession:d,deferredSpreads:f}=Ig(i.subscribers);for(const e of l)if(e.node!==e.replaceNode){const n=t.indexOf(e.node);n>=0&&(t[n]=e.replaceNode)}const h=_a(t,a);ca(h,d),Dr(h,l),Fr(h,c);const p=l.filter(e=>Na(e,-1));if(Ur(h,p),"for"===i.type&&null!==i.index){const t=Eg(e,"for",i.uuid);if(t){let e=n.get(i.uuid);if(!e){const s=_g(t,i.uuid)??i.path;e=o.get(s),e||o.set(s,e=[]),n.set(i.uuid,e)}const r=e[i.index]??=Lt(null,i.index);qa(t,r,h),Va(t,h.lastNode),ba(t,h);const a=To(ce(i.path+"."+u),r);qr(h,a),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),kg(s,l),Ng(h,f,a,d,l,p)}}else{const t=i.start.previousSibling,n=t?.data===Tg(i.type,i.uuid)?t:Eg(e,i.type,i.uuid);if(n){ba(n,h);const e=Nt(n);qr(h,e),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),kg(s,l),Ng(h,f,e,d,l,p)}}}return s}(document.body,o,r);bg.removeBlockBoundaryComments(document.body);const a=[];for(const e of t)e.parentNode&&(a.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());const[,l,c]=xt(document.body),d=[],f=[],h=Er(document.body),p=h.initialize(l);Ll(c,null,h);for(const e of p)if("event"!==e.bindingType)if($g.has(e.bindingType))f.push(e);else{if(e.statePathName.includes(u))continue;d.push(e)}for(const e of f)if("for"===e.bindingType){const t=bo(e),n=Xl(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=Or(n[e.statePathName],e.outFilters);if(Array.isArray(o)){const n=r.get(e.uuid);n&&$n(o,n),Cn(t,o),s=e.node,i=o,Ba.set(s,Sn(i)),zn(t,o)}var s,i})}jl([...d,...i]);for(const{el:e,parent:t,next:n}of a)t.insertBefore(e,n);const g=new Map;for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))g.set(t.getAttribute("data-wcs-ssr-id"),t);for(const t of e.querySelectorAll(s.tagNames.ssr))for(const[e,n]of Object.entries(t.hydrateProps)){const t=g.get(e);if(t)for(const[e,o]of Object.entries(n))Mr?.isDeclared(t,e)||(t[e]=o)}for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))t.removeAttribute("data-wcs-ssr-id");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=bg.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Yl(e.rootNode);const t=bg.extractStateData(e),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",ku),bg.buildContent(n,t,e.rootNode),e.parentNode?.insertBefore(n,e)}};let Og=!1;function Rg(){Og||(Og=!0,Vl=Mg,function(e){if(!mu.includes(e)){mu.push(e);for(const t of wu())e(t)}}(e=>{e.get(s.tagNames.ssr)||e.define(s.tagNames.ssr,bg)}),function(){const t=globalThis;void 0===t[e]&&(t[e]=vg)}())}const jg={name:"ssr",install(){Rg()}},Lg=new WeakMap,Wg=new Set,Dg=new Set;function Bg(e){return e.byFromPath.size>0||e.byResetPath.size>0}function zg(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function Fg(e){return Lg.get(e)}function qg(e){Vg(e),Lg.delete(e)}function Vg(e){Wg.delete(e),Dg.delete(e)}const Hg=new WeakSet;let Ug=0;function Kg(e){return Fg(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Gg(e){if(0===Dg.size)return;if(t=e.absolutePathInfo.stateElement,!Dg.has(t))return;var t;const n=Kg(e);if(void 0!==n)for(const e of n)Jg(e)}function Jg(e){Hg.has(e)||(Hg.add(e),Ug++)}function Xg(e){return!!Hg.delete(e)&&(Ug--,!0)}const Yg=/^(?:0|[1-9]\d*)$/;function Qg(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Zg(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&&Yg.test(t)&&Qg(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Qg(e,t))?"object":null}function em(e,t){const n=Zg(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]=em(o[e],t);return r}function tm(e){return em(e,new Map)}function nm(e,t,n){if(Object.is(e,t))return!0;const o=Zg(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(Zg(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(!nm(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&nm(s[e],r[e],n))}function om(e,t){return nm(e,t,new Map)}const sm=new WeakMap;function rm(e,t){if("function"!=typeof t)return;const n=sm.get(t);void 0===n?sm.set(t,new Set([e])):n.add(e)}function im(e,t){return"function"==typeof t&&!0===sm.get(t)?.has(e)}const am={"read-source":e=>`${J} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-rows":e=>`${J} could not read the rows of "from" for "${e}". Nothing was folded or written.`,"read-output":e=>`${J} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${J} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${J} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${J} could not write the output "${e}".`},lm={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function cm(e,t,n){null!==Tt&&Tt({type:"state:watch-error",phase:t,path:`${J}.${e}`,error:n})}function dm(e,t,n){console.error(`[@wcstack/state] ${am[n](e)}`,t),cm(e,lm[n],t)}function um(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function fm(e,t){t.then(void 0,()=>{}),dm(e,new TypeError(`${J} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const hm=new WeakSet;const pm="[wcs/scan-declaration-invalid]",gm=Object.freeze([]);function mm(e){return`${J} entry "${e}"`}function ym(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function wm(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${u}${u}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${he}`}function bm(e,t,n){0===n.length&&ie(`${pm} ${e} "${t}" must be a non-empty state path.${he}`),n.startsWith("$")&&ie(`${pm} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${he}`),n.includes("@")&&ie(`${pm} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${he}`),n in Object.prototype&&ie(`${pm} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${he}`);const o=ce(n);for(const s of o.segments)0===s.length&&ie(`${pm} ${e} ${t} "${n}" has an empty path segment.${he}`);return o.wildcardCount>f&&ie(`${pm} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function vm(e,t,n,o){const s=mm(e);0===e.length&&ie(`${pm} ${J} entry name must be a non-empty string.${he}`),(e.includes(d)||e.includes(u))&&ie(`${pm} ${s} must be a flat property name ("${d}" and "${u}" are not allowed). The output is a property the runtime owns.${he}`),e.startsWith("$")&&ie(`${pm} ${s} must not start with "$" (reserved namespace).${he}`),e in Object.prototype&&ie(`${pm} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${he}`),t.has(e)&&ie(`${pm} ${s} conflicts with a getter declared on the state.${he}`),n.has(e)&&ie(`${pm} ${s} conflicts with a setter declared on the state.${he}`),o.has(e)&&ie(`${pm} ${s} conflicts with the ${K} entry of the same name — each output has exactly one owner.${he}`)}function $m(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!im(e,o)&&ie(`${pm} ${mm(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${he}`)}function xm(e,t,n,o,s,r){const i=mm(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&ie(`${pm} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${he}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||ie(`${pm} ${i} "on" must be a non-empty event-token name.${he}`),n.has(e)||ie(`${pm} ${i} on "${e}" is not declared in ${H}.${fe(e,n)}${he}`),{kind:"event",tokenName:e}}const c=t.from;"string"!=typeof c&&ie(`${pm} ${i} "from" must be a state path string.${he}`);const u=bm(i,"from",c),f=ym(u,o)??r?.recursiveGetterOwning(c)??null;null!==f&&ie(wm(i,"from",c,f));const h=ym(u,s);return null!==h&&ie(function(e,t,n){return`${pm} ${e} from "${t}" ${n===t?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${he}`}(i,c,h)),(c===e||c.startsWith(e+d))&&ie(`${pm} ${i} from "${c}" reads the entry's own output — the scan would fold its own writes forever.${he}`),{kind:"path",path:c,pathInfo:u}}function Sm(e,t,n,o){if(void 0===t)return gm;const s=mm(e);Array.isArray(t)||ie(`${pm} ${s} "resetOn" must be an array of state paths.${he}`);const r=[];for(const e of t){"string"!=typeof e&&ie(`${pm} ${s} "resetOn" must contain only state path strings.${he}`);const t=bm(s,"resetOn",e);t.wildcardCount>0&&ie(`${pm} ${s} resetOn "${e}" must not contain "${u}" — a reset returns the whole output to "initial".${he}`);const i=ym(t,o);null!==i&&ie(wm(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&ie(`${pm} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${he}`),"path"===n.kind&&e.startsWith(n.path+d)&&ie(`${pm} ${s} resetOn "${e}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${he}`),r.push(e)}return r}function Im(e,t,n=null){const o=e[J];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&ie(`${pm} ${J} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${he}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(du(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){Wc(e);const t=e[K];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),c=[];let d=0;for(const[e,u]of Object.entries(o)){vm(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&ie(`${pm} ${mm(e)} must be an object ({ from | on, initial, fold, resetOn? }).${he}`);const o=u;$m(e,a,o);const f=xm(e,o,t,s,i,n);"initial"in o||ie(`${pm} ${mm(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${he}`),"function"!=typeof o.fold&&ie(`${pm} ${mm(e)} fold must be a function.${he}`);const h=Sm(e,o.resetOn,f,s);c.push({name:e,source:f,fold:o.fold,initial:o.initial,resetOn:h,order:d++})}return function(e){const t=new Set(e.map(e=>e.name)),n=new Map;for(const o of e){for(const e of o.resetOn){const n=ce(e).segments[0];t.has(n)&&ie(`${pm} ${mm(o.name)} resetOn "${e}" reads the ${J} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${he}`)}if("path"===o.source.kind){const e=o.source.pathInfo.segments[0];t.has(e)&&n.set(o.name,e)}}for(const e of n.keys()){const o=[e];let s=n.get(e);for(;void 0!==s&&o.length<=t.size;)s===e&&ie(`${pm} ${J} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${he}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Pm(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 Hg.has(e)}(e),l=a&&!om(n,e.initial)?tm(e.initial):n,c=t(l,o,...s);if(um(c))return void fm(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,rm(e.name,c)),a&&Xg(e)}catch(t){dm(e.name,t,i)}}}function km(e,t,n){const o=function(e,t){qg(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&zg(n,e.source.path,e);for(const t of e.resetOn)zg(o,t,e),"event"===e.source.kind&&zg(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Lg.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)&&di().hasQueuedPath(e,n))&&Jg(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 Am="scanEntries",Nm={order:8,validate(e,t,n){const o=Im(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Am,o)},applyEarly(e,t,n){const o=n.get(Am)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=tm(n.initial);e[n.name]=t,rm(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Uo(e,n.source.tokenName).subscribe(Pm(n))}(e,o))},register(e,t,n){const o=n.get(Am)??null,s=function(e){const t=new Map,n=Fg(e);if(void 0!==n)for(const e of n.entries)Xg(e)&&t.set(e.name,e.resetOn);return qg(e),t}(e);e.setScanPaths?.(null===o?null:km(e,o,s))}};let _m=!1;const Tm=Object.freeze([]),Em=Object.freeze([]);function Cm(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??Tm,i=e.dynamicDependency.get(n)??Tm,a=t.byFromPath.get(n)??Em;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Mm=Symbol("wcs-stream-last-notified-uncertain"),Om=new WeakMap;function Rm(e,t){const n=Om.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function jm(e,t){const n=Om.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Mm,error:Object.is(o.error,null)?null:Mm})}const Lm=new Set;function Wm(e){Lm.delete(e)}const Dm=new WeakMap;function Bm(e){return Dm.get(e)??new Map}function zm(e){Wm(e);const t=Dm.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,jm(e,n.name)}const Fm=(e,t)=>t,qm=new Set;function Vm(e,t){Wc(t);const n=t[K];if(void 0===n)return void Rm(e,qm);"object"==typeof n&&null!==n||ie(`${K} must be an object mapping stream names to stream definitions.`);const o=new Map,s=du(t);for(const[r,i]of Object.entries(n)){0===r.length&&ie(`${K} entry name must be a non-empty string.`),r.includes(d)&&ie(`${K} entry "${r}" must be a flat property name ("${d}" is not allowed).`),r.includes(u)&&ie(`${K} entry "${r}" must be a flat property name ("${u}" is not allowed).`),r.startsWith("$")&&ie(`${K} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&ie(`${K} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(r)&&ie(`${K} entry "${r}" conflicts with a getter declared on the state.`),e.setterPaths.has(r)&&ie(`${K} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||ie(`${K} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||im(r,a)||ie(`${K} entry "${r}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&ie(`${K} entry "${r}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&ie(`${K} entry "${r}" fold must be a function.`),l&&!("initial"in n)&&ie(`${K} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&ie(`${K} entry "${r}" args must be a function.`);const c={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??Fm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in t||(t[r]=c.definition.initial,rm(r,c.definition.initial)),o.set(r,c)}!function(e,t){Dm.set(e,t)}(e,o),Rm(e,new Set(o.keys()))}const Hm=new WeakMap,Um=new WeakMap;function Km(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Bm(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Bm(e).has(n),ownKeys:()=>Array.from(Bm(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Bm(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){ie(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){ie(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Gm(e){const t=Hm.get(e);if(void 0!==t)return t;const n=Km(e,Z,e=>e.status);return Hm.set(e,n),n}function Jm(e){const t=Um.get(e);if(void 0!==t)return t;const n=Km(e,ee,e=>e.error);return Um.set(e,n),n}function Xm(e){Hm.delete(e),Um.delete(e)}let Ym=null;function Qm(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 Zm={read(e,t){!function(e,t){null!==Ym&&Ym.add(ro(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===Z?Qm(Gm(e),t.pathInfo.segments):n===ee?Qm(Jm(e),t.pathInfo.segments):qc},get:(e,t)=>t===Z?Gm(e.stateElement):t===ee?Jm(e.stateElement):qc};let ey=0,ty=null,ny=0;const oy=new WeakMap;function sy(e){ey=e+1}function ry(){ey=0}function iy(e){if(ey>0){const t=ty??=new Map;ey>(t.get(e)??0)&&t.set(e,ey),ny=Math.max(ny,ey)}}function ay(e,t){return oy.get(e)?.get(t)??0}async function ly(e,t,n,o){let s=null;const r=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",r,{once:!0});try{const i=await e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError(`[@wcstack/state] ${K}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",r)}}function cy(e){my();const t=Bm(e);if(0!==t.size){!function(e){Lm.add(e)}(e);for(const n of t.values())dy(e,n)}}function dy(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=Ym,s=new Set;let r;Ym=s;try{e.createState("readonly",e=>{r=n(e)})}finally{Ym=o}r instanceof Promise&&ie(`${K} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${Z}${d}${t.name}`,a=`${ee}${d}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||ie(`${K} entry "${t.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&ie(`${K} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);!function(e,t){const n=Fg(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=Cm(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&ie(`[wcs/scan-feedback-loop] ${K} entry "${t.name}" args read "${n}", which is derived from the ${J} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(e,t),e.createState("writable",e=>{e[t.name]=t.definition.initial}),rm(t.name,t.definition.initial),uy(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{const o=s.fold(e[t.name],n);e[t.name]=o,rm(t.name,o)})},done(){uy(e,t,"done",null)},fail(o){uy(e,t,"error",o),n.abort()}};ly(s.source,o,n.signal,r)}function uy(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return Om.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=Om.get(e);void 0===s&&(s=new Map,Om.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${Z}${d}${t.name}`),i&&e.$postUpdate(`${ee}${d}${t.name}`)}))}function fy(e){const t=Lm;if(0===t.size)return;const n=[];for(const o of t)for(const t of Bm(o).values()){let s=-1;for(const n of t.depAddresses)e.has(n)&&(s=Math.max(s,ay(e,n)));s>=0&&s<=32&&n.push({stateElement:o,entry:t,depth:s})}try{for(const{stateElement:e,entry:o,depth:s}of n)if(t.has(e)&&Bm(e).get(o.name)===o){sy(s);try{dy(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Bm(e).get(o.name)===o&&uy(e,o,"error",n)}}}finally{ry()}}let hy=!1;const py=new WeakMap,gy={order:20,apply(e,t){var n;Xm(e),zm(n=e),Wm(n),Dm.delete(n),Vm(e,t),void 0!==t[K]&&e.attachAddressHooks?.("streams",K)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return cy(e),void py.set(e,e.connectGeneration??0)}n===e.connectGeneration&&py.get(e)!==n&&cy(e)}},deactivate(e){zm(e),Xm(e)}};function my(){hy||(hy=!0,Uc("streams",Zm),Xc("streams",gy),ii(fy,20))}const yy=new WeakMap;function wy(e,t,n){let o=yy.get(e);void 0===o&&(o=new Map,yy.set(e,o)),o.set(t,n)}const by=new Map;function vy(e,t){by.has(e)||by.set(e,t)}function $y(e){return by.get(e)}const xy=new WeakMap,Sy=new WeakMap,Iy=new Set,Py=new Map;function ky(e){return xy.get(e)??Py}function Ay(e){Iy.add(e),function(e){const t=Lg.get(e);void 0!==t&&(Bg(t)&&Wg.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Dg.add(e))}(e)}function Ny(){return Iy}function _y(e,t){let n=Sy.get(e);void 0===n&&(n=new Map,Sy.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}const Ty=new Map;function Ey(e){return Sy.get(e)??Ty}function Cy(e){0===e.length&&ie(`[wcs/watch-declaration-invalid] ${G} entry name must be a non-empty state path.`),e.startsWith("$")&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not start with "$" (reserved namespace).${he}`),e.includes("@")&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${he}`),e in Object.prototype&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ce(e);for(const n of t.segments)0===n.length&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" has an empty path segment.${he}`);return t.wildcardCount>f&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function My(e,t){const n=t[G];if(void 0===n)return null;"object"==typeof n&&null!==n||ie(`[wcs/watch-declaration-invalid] ${G} must be an object mapping state paths to handler functions.${he}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&ie(`[wcs/watch-declaration-invalid] ${G} entry "${t}" must be a function.${he}`);const n=Cy(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){xy.set(e,t)}(e,o),s.size>0?s:null}const Oy={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||vy(n,o)},swapped(e,t,n){var o;o=n,by.has(o)&&vy(t,$y(n))}};function Ry(e){for(let t=e;null!==t;t=t.parentListIndex)if(tn(t))return!0;return!1}function jy(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[Un](To(t.wildcardParentPathInfos[i],r)),l=yn(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=ho(o,i,t.wildcardCount);if(l!==c&&!Jt(l,c)){if(tn(c))return"gone";s="replaced"}r=l}return s}function Ly(e,t,n){const o=new Map;for(const s of n){const n=jy(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 Wy=Object.freeze([]);function Dy(e,t,n,o){let s=e.get(n);return void 0===s&&(s={stateElement:t,entry:n,rows:[],reset:!1,depth:o},e.set(n,s)),s.depth=Math.max(s.depth,o),s}function By(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 zy(e,t){return t.has(e.stateElement)&&!0===Fg(e.stateElement)?.entries.has(e.entry)}function Fy(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>qy(n,e))||Xg(t)}function qy(e,t){return di().hasQueuedPath(e,t)}function Vy(e,t){!function(e,t,n){if(0!==Ug)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=Kg(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||Xg(t)}}(e,t,qy)}function Hy(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function Uy(e,t,n){if(!zy(e,n))return Fy(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(hm.has(e))return;hm.add(e);const o=`[wcs/scan-source-computed] ${J} entry "${t}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),cm(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=Bm(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?e.rows:Ly(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(By)){let n;try{n=Hy(t,r,e)}catch(e){dm(s.name,e,"read-source");continue}const o=a(l,n,$y(e.absAddress),...e.indexes);if(um(o))return void fm(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){dm(s.name,e,i.failure)}return i.plan}function Ky(e,t){const{group:n}=e;if(!zy(n,t))return void Fy(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Xg(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!om(o,s.initial):!Object.is(o,e.next)){const o=n.reset?tm(s.initial):e.next;t[s.name]=o,rm(s.name,o)}})}catch(e){dm(s.name,e,"write")}}function Gy(e,t){if(Vy(e,t),0===Wg.size)return Wy;const n=new Map;for(const o of e){const s=o.absolutePathInfo.stateElement;if(!t.has(s))continue;const r=Fg(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=ay(e,o),l=r.byFromPath.get(i.path);if(void 0!==l){let e=[];if(i.wildcardCount>0){if(null===o.listIndex)continue;e=po(o.listIndex,i.wildcardCount)}for(const t of l)Dy(n,s,t,a).rows.push({absAddress:o,indexes:e})}const c=r.byResetPath.get(i.path);if(void 0!==c)for(const e of c)Dy(n,s,e,a).reset=!0}if(0===n.size)return Wy;const o=Array.from(n.values()).sort((e,t)=>e.entry.order-t.entry.order),s=[];try{for(const n of o){sy(n.depth);const o=Uy(n,e,t);null!==o&&s.push(o)}}finally{ry()}return s}function Jy(e){sw(),(0!==ky(e).size||0!==Ey(e).size||function(e){const t=Lg.get(e);return void 0!==t&&Bg(t)}(e))&&(Ay(e),function(e){const t=[];for(const n of ky(e).values())Xy(e,n)&&t.push(n);for(const n of Ey(e).values())for(const o of n)Xy(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{wy(e,io(e,o.pathInfo,null),n[o.path])}catch(t){Qy(e,o.path,"prime",t)}})}(e))}function Xy(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Yy={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Qy(e,t,n,o){console.error(`[@wcstack/state] $watch ${Yy[n]} "${t}" threw.`,o),null!==Tt&&Tt({type:"state:watch-error",phase:n,path:t,error:o})}function Zy(e){const t=Ny(),n=function(e){const t=ny;return t>0&&(oy.set(e,ty),ty=null,ny=0),t}(e);try{if(n>32){Vy(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!==Tt&&Tt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}if(0===t.size)return void Vy(e,t);!function(e,t){if(0!==e.length)try{for(const n of e)sy(n.group.depth),Ky(n,t)}finally{ry()}}(Gy(e,t),t),function(e,t){const n=[],o=new Set;for(const s of e){const e=s.absolutePathInfo.stateElement;if(!t.has(e))continue;const r=s.absolutePathInfo.pathInfo.path;o.add(r);const i=ky(e).get(r),a=Ey(e).get(r);if(void 0===i&&void 0===a)continue;const l=void 0===i?[]:[i];void 0!==a&&l.push(...a);for(const t of l){let o=[];if(t.pathInfo.wildcardCount>0){if(null===s.listIndex)continue;o=po(s.listIndex,t.pathInfo.wildcardCount)}n.push({stateElement:e,entry:t,absAddress:s,indexes:o})}}if(0===n.length)return;n.sort(tw);const s=function(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(0===s.entry.pathInfo.wildcardCount)continue;const r=e[o-1];(Ry(s.absAddress.listIndex)||r?.entry===s.entry&&ew(r.indexes,s.indexes)||s.entry.pathInfo.wildcardParentPaths.some(e=>t.has(e)))&&(n??=new Set).add(s.entry)}if(null===n)return e;const o=new Set;for(const t of n){const n=e.filter(e=>e.entry===t),s=n[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(Ly(e,t.pathInfo,n));for(const e of n)s.has(e)||o.add(e)})}catch(e){Qy(0,t.path,"evaluate",e);for(const e of n)o.add(e)}}return e.filter(e=>!o.has(e))}(n,o);try{for(const n of s){if(!t.has(n.stateElement))continue;const o=ky(n.stateElement).get(n.entry.path)===n.entry,s=!0===Ey(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(sy(ay(e,n.absAddress)),nw(n))}}finally{ry()}}(e,t)}finally{by.clear()}}function ew(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function tw(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 nw(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Xy(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 Qy(0,n.path,"evaluate",e)}const a=r?function(e,t){return yy.get(e)?.get(t)}(t,o):$y(o);r&&wy(t,o,i),null!==Tt&&Tt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Qy(0,n.path,"handler",e)}}let ow=!1;function sw(){ow||(ow=!0,Uc("watch",Oy),Xc("watch",rw),ii(Zy,10),ri(iy),xu={assertValidPath:Cy,addEntries:_y,start:Jy})}const rw={order:10,register(e,t){var n;n=e,Iy.delete(n),Vg(n),xy.delete(n),function(e){yy.delete(e)}(e);const o=My(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?G:J)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Jy(e)},deactivate(e){var t;t=e,Iy.delete(t),Vg(t)}},iw={name:"temporal",install(){sw(),_m||(_m=!0,Xc("scan",Nm),ri(Gg)),my()}},aw=new Set,lw=new Set;function cw(e){aw.has(e)||(aw.add(e),console.warn(`[@wcstack/state] [wcs/v4-migration] ${e} See "Preparing for 4.0" in the @wcstack/state README.`))}const dw=["debug","commentTextPrefix","enablePropagationContext"],uw=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],fw={bindAttributeName:"string",commentForPrefix:"string",commentIfPrefix:"string",commentElseIfPrefix:"string",commentElsePrefix:"string",tagNames:"object",locale:"string",enableContractAnalyzer:"boolean"},hw=["state","ssr"],pw=["formats","diagnostics","temporal","list-keys","scopes","recursion","ssr","devtools"],gw=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),mw=(e,t,n)=>cw(`${e}: "${t}" is not one of its options, or not ${n}. 4.0 throws on it.`);function yw(e,t){if(lw.has(e))return;lw.add(e);cw(`${"$"===e[0]?"":"filter "}"${e}" is removed in 4.0: write "${t}" (its name since 3.2).`)}const ww={substr:'filter "substr" is removed in 4.0: write slice(start, start + length) — slice takes the end index, not a length.'},bw={$watch:"Move it to the root state, where its paths are absolute.",$listKeys:"Move it to the root state, where its paths are absolute.",$renderedCallback:"Move it to the root state, where it receives absolute paths.",$behavior:"Declare it on the root state.",$features:"Declare it on the root state."},vw=new WeakSet,$w={state(e){const t=e;for(const e of Object.keys(Rc))void 0!==t[e]&&yw(e,Rc[e]);var n;void 0!==t[J]&&cw(`"${J}" is removed in 4.0: rewrite it with $watch (state paths) or $on (event tokens).`),vw.has(e)||(!function(e){if(null==e)return;if("object"!=typeof e)return void mw("state","$behavior","an object");const t=e;for(const e in t){const n=t[e];uw.includes(e)&&"boolean"==typeof n?n!==s[e]&&cw(`$behavior takes effect in 4.0; 3.x does not read it and runs this state with ${e}: ${!n}. Until you upgrade, pass bootstrapState({ ${e}: ${n} }).`):mw("$behavior",e,"a boolean")}}(t.$behavior),void 0!==(n=t.$features)&&(Array.isArray(n)&&!n.some(e=>!pw.includes(e))||cw(`$features is not an array of add-on names (${pw.join(", ")}). 4.0 throws on it.`)))},volumeLoaded(e){vw.add(e)},renamed:yw,removed(e){cw(ww[e])},volume(e,t,n){n>0&&cw(`volume "${e}" injects root paths (data-wcs="state.<key>: …"): 4.0 does not graft a volume with injections. Read the root path in a root getter instead.`);for(const n of Object.keys(bw))void 0!==t[n]&&cw(`volume "${e}" declares ${n}: 4.0 does not graft a volume that declares it. ${bw[n]}`)}};function xw(e){!function(e){ye=e}($w),function(e){if("object"==typeof e&&null!==e)for(const[t,n]of Object.entries(e))if(void 0!==n)if(dw.includes(t))cw(`bootstrapState option "${t}" is removed in 4.0, which throws on it. Remove it.`);else if(uw.includes(t)&&"boolean"==typeof n)cw(`bootstrapState option "${t}" moves to the state's $behavior in 4.0, which throws on it here. When you upgrade, write $behavior: { ${t}: ${n} } in the state.`);else if(uw.includes(t)||!gw(fw,t)||null===n||typeof n!==fw[t]||Array.isArray(n))mw("bootstrapState",t,"of the option's type");else if("tagNames"===t)for(const[e,t]of Object.entries(n))void 0===t||hw.includes(e)&&"string"==typeof t||mw("bootstrapState",`tagNames.${e}`,"of the option's type")}(e)}const Sw=[ff,iw,Df,ag,jg,Du,Xu];function Iw(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(Sw),xw(e),$u(e,t)}function Pw(e){return e}const kw={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"真偽性を反転(falsy → true)",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},add:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},sub:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},toFixed:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},upper:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lower:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},capitalize:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:2,maxArgs:2,argTypes:["number","number"]},padStart:{description:"先頭を埋める (length[,char]。char の既定は 0 — JS の既定は空白なので注意)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},padEnd:{description:"末尾を埋める (length[,char]。char の既定は空白 — JS と同じ)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},repeat:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},reverse:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix]。suffix の既定は … — U+2026 の 1 文字)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator]。既定はカンマ + 空白)",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},time:{description:"ロケール形式の時刻 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},datetime:{description:"ロケール形式の日時 ([locale]。既定は config.locale)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},ymd:{description:"YYYY-MM-DD 形式 ([separator]。既定は -)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式 ([separator]。既定は :)",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},coalesce:{description:"null / undefined の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},nullIfEmpty:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},Aw=2,Nw=Object.freeze({$trackDependency:"$dependOn",$untrackDependency:"$untracked"});function _w(){return{version:2,syntax:{bindAttribute:s.bindAttributeName,tagName:s.tagNames.state,pathDelimiter:d,wildcard:u,delimiters:{binding:";",propValue:":",modifier:g,filter:m},structuralDirectives:Array.from(pe),modifiers:{flags:v,keyValue:S,eventNamePrefix:k},indexParam:{prefix:M,maxDepth:f},bindingTypes:{elseKeyword:I,spread:P,eventPropertyPrefix:k,explicitPropertyPrefix:d,propNamespaces:{eventToken:A,command:_,class:T,attr:E,style:C}}},filters:Object.keys(cf),filterMeta:kw,filterAliases:tf,declarationAliases:Rc,apiAliases:Nw,reservedLifecycle:[j,L,W,D,B],reservedStateApi:[z,F,q,V,H,U,K,G,J,Q,X,Z,ee]}}const Tw=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),Ew=Object.freeze([]);function Cw(e){if(!s.enableContractAnalyzer)return Ew;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))Tw.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?Mw(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,Ow,e=>{t.push(e),null!==Tt&&Tt(e)}),t}function Mw(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 Ow(e){const t=tt(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{bg as Ssr,ol as TRUSTED_TYPES_POLICY_SLOT,ku as VERSION,Aw as WCS_MANIFEST_VERSION,Cw as analyzeContract,Iw as bootstrapState,zl as buildBindings,tf as builtinFilterAliases,kw as builtinFilterMeta,Pw as defineState,Yl as getBindingsReady,r as getConfig,sl as getTrustedTypesPolicy,_w as getWcsManifest,rl as setTrustedTypesPolicy};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|