@wcstack/state 3.2.0 → 3.3.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 +106 -76
- package/README.md +107 -77
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.d.ts +45 -8
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/manifest.d.ts +28 -5
- package/dist/manifest.esm.js +253 -246
- package/dist/parser.d.ts +16 -2
- package/dist/parser.esm.js +223 -50
- package/dist/split/chunks/binder.js +1 -1
- package/dist/split/chunks/binder.js.map +1 -1
- package/dist/split/chunks/checkDependency.js +1 -1
- package/dist/split/chunks/declarationAliases.js +1 -1
- package/dist/split/chunks/declarationAliases.js.map +1 -1
- package/dist/split/chunks/declarationHooks.js +2 -0
- package/dist/split/chunks/declarationHooks.js.map +1 -0
- package/dist/split/chunks/featureBridge.js +2 -0
- package/dist/split/chunks/featureBridge.js.map +1 -0
- package/dist/split/chunks/filterRegistry.js +1 -1
- package/dist/split/chunks/filterRegistry.js.map +1 -1
- package/dist/split/chunks/getAllPropertyDescriptors.js +1 -1
- package/dist/split/chunks/getAllPropertyDescriptors.js.map +1 -1
- package/dist/split/chunks/lifecycleHooks.js +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 +10 -2
- package/dist/split/core.js +1 -1
- package/dist/split/core.js.map +1 -1
- package/dist/split/features/devtools.js +1 -1
- package/dist/split/features/devtools.js.map +1 -1
- package/dist/split/features/diagnostics.js +1 -1
- package/dist/split/features/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/dist/wcs-manifest.json +36 -21
- package/package.json +1 -1
- package/dist/split/chunks/mount.js +0 -2
- package/dist/split/chunks/mount.js.map +0 -1
- package/dist/split/chunks/watchRuntime.js +0 -2
- package/dist/split/chunks/watchRuntime.js.map +0 -1
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n;function s(){return o}const r=Symbol.for("wcstack.binder");const i=Symbol.for("wcstack.binder.pending"),a=Symbol.for("wcstack.binder.taken");function l(){const e=function(){const e=globalThis[r];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;const t=function(){const e=globalThis;let t=e[i];return void 0===t&&(t=[],e[i]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[a];return void 0===t&&(t=new WeakSet,e[a]=t),t}();for(const t of n)o.add(t),e.bind(t)}const c=".",d="*",u=128,f=128,h="#",p="|",g="prevent",m="stop",y="ro",w=Object.freeze([g,m,y]),b="init",v="sync",$=Object.freeze([b,v]),x="else",S="...",P="on",I="eventToken",A="state",N="command",k="class",_="attr",T="style",C="$",E={};for(let e=0;e<u;e++)E[`${C}${e+1}`]=e;const M=Object.freeze(E),O="$connectedCallback",R="$disconnectedCallback",j="$renderedCallback",L="$errorCallback",W="$stateReadyCallback",D="$bindables",B="$commands",z="$commandTokens",F="$command",q="$eventTokens",V="$on",H="$stream",U="$watch",G="$scan",K="$recursion",J="**",X="$listKeys",Y="$streamStatus",Q="$streamError",Z="data-wc-definition",ee=/\{\{\s*(.+?)\s*\}\}/g,te=new Set(["SCRIPT","STYLE"]);function ne(e){if(!o.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&te.has(e.parentElement.tagName)||oe(e)}(e);const t=Array.from(e.querySelectorAll("template"));for(const e of t)if("http://www.w3.org/2000/svg"===e.namespaceURI){const t=document.createElement("template"),n=Array.from(e.childNodes);for(let e=0;e<n.length;e++){const o=n[e];t.content.appendChild(o)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),ne(t.content)}else ne(e.content)}function oe(e){const t=e.data;if(ee.lastIndex=0,!ee.test(t))return;ee.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=ee.exec(t));){o.index>s&&n.appendChild(document.createTextNode(t.slice(s,o.index)));const e=o[1];n.appendChild(document.createComment(`@@: ${e}`)),s=o.index+o[0].length}s<t.length&&n.appendChild(document.createTextNode(t.slice(s))),e.parentNode.replaceChild(n,e)}function se(e){throw new Error(`[@wcstack/state] ${e}`)}const re=new Map;let ie=0;function ae(e){let t=re.get(e);return void 0!==t||(-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] "${e}" uses "${J}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`),t=Object.freeze(new le(e)),re.set(e,t)),t}class le{id=++ie;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(e){const t=t=>e===t?this:ae(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===d&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),c.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=u,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function ce(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;const o=new Array(t.length+1),s=new Array(t.length+1);for(let e=0;e<=t.length;e++)o[e]=e;for(let n=1;n<=e.length;n++){s[0]=n;for(let r=1;r<=t.length;r++){const i=e[n-1]===t[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let e=0;e<=t.length;e++)o[e]=s[e]}return o[t.length]}function de(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ce(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ue=" Validate statically: npx @wcstack/lint <file>.",fe=new Set(["if","elseif","else","for"]),he={not:()=>e=>!e},pe={input:new Map,output:new Map},ge={input:new Map,output:new Map},me={input:new Map,output:new Map},ye=new Map;function we(e,t,n,o){const s=pe[e],r=ge[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}for(const t of Object.keys(o??{}))me[e].set(t,o[t]);ye.clear()}function be(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=ye.get(s);if(void 0!==r)return r;const i=me[n].get(e)??e,a=pe[n].get(i)??he[i];void 0===a&&se(`[wcs/filter-unknown] filter not found: ${e}.${de(e,function(e){return[...new Set([...Object.keys(he),...pe[e].keys()])]}(n))}${ue}`);const l=ge[n].get(i);void 0!==l&&(t.length<l[0]||t.length>l[1])&&se(t.length<l[0]?`[wcs/filter-arity] filter "${e}" requires at least ${l[0]} argument(s) (${t.length} given).${ue}`:`[wcs/filter-arity] filter "${e}" accepts at most ${l[1]} argument(s) (${t.length} given).${ue}`);const c=a(t,o);return ye.set(s,c),c}function ve(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const $e=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function xe(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:$e.test(e)?Number(e):e)}function Se(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=ve(o,i,a);t.push(e),n.push(xe(e,r)),o="",r=!1,i=-1,a=-1};for(let t=0;t<e.length;t++){const n=e[t];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&se(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ue}`);const c=ve(o,i,a);return(c||r)&&(t.push(c),n.push(xe(c,r))),{args:t,literals:n}}function Pe(e,t){return e.map(t=>{const n=t.indexOf("("),o=t.lastIndexOf(")");-1!==n&&-1===o&&se(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==o&&-1===n&&se(`Invalid filter format: missing opening parenthesis in "${t}"`);const s=(-1===n?t:t.substring(0,n)).trim();if(0===s.length&&se(`[wcs/binding-syntax] an empty filter in "${e.join("|")}" — remove the extra "|" or name the filter.${ue}`),-1===n)return{filterName:s,args:[],literals:[]};return{filterName:s,...Se(t.substring(n+1,o))}})}const Ie=e=>e.trim(),Ae=e=>"'"===e||'"'===e;function Ne(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if(Ae(s))n=s;else if(s===t)return o}return-1}function ke(e,t){const n=[];let o=null,s=0;for(let r=0;r<e.length;r++){const i=e[r];null!==o?i===o&&(o=null):Ae(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const _e=new Map;function Te(e){const t=Ne(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),_e.has(s)?r=_e.get(s):(o=ke(s,p).map(Ie),r=Pe(o),_e.set(s,r))):n=e.trim();const i=n.split(h).map(Ie);i.length>2&&se(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${h}" — write "${i[0]}${h}${i.slice(1).join(",")}".${ue}`);const[a,l]=i,d=a.split(c).map(Ie);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(Ie):[],inFilters:r}}const Ce=new Map;function Ee(e){const t=Ne(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ce.has(s)?r=Ce.get(s):(o=ke(s,p).map(Ie),r=Pe(o),Ce.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&se(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);return{statePathName:n,statePathInfo:ae(n),outFilters:r}}const Me=new Set([x,"if","elseif","for",S]),Oe=new Set([k,_,T,N,I]);function Re(e){const[...t]=function(e){return ke(e,";")}(e).map(Ie).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&se(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(h)[0].split(p)[0].trim();if(s!==n&&Me.has(s)&&se(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ue}`),n===x){o.length>0&&se(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ue}`);const t=ae("#else");return{propName:x,propSegments:[x],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===S){const t=Ee(o);return t.outFilters.length>0&&se(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&se(`Invalid spread binding "${e}": spread target path is required.`),{propName:S,propSegments:[S],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ee(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Ee(o);return{...Te(n),...e,bindingType:s}}{const e=Ee(o),t=Te(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Oe.has(o[0]))&&se(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Oe].join(", ")}).${ue}`),{...t,propName:o.join(c),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===I||t.propSegments[0].startsWith(P)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>fe.has(e.bindingType))&&se(`[wcs/template-syntax] Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${ue}`)}return n}const je=new WeakMap,Le=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),We=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function De(e){const t=je.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=We.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Le.has(r)?(je.set(e,s[2]),s[2]):null}function Be(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ee(e),bindingType:"text"}}const ze=new WeakMap,Fe=new WeakSet;let qe=0;async function Ve(e){const t=function(e){let t,n=ze.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++qe,promise:o,resolve:t},ze.set(e,n),Fe.has(e)&&n.resolve(),n}(e);await t.promise}function He(e){const t=ze.get(e);void 0===t?Fe.add(e):t.resolve()}const Ue=new WeakMap;function Ge(e){const t=Ue.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{Ue.set(e,n)}}function Ke(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Je(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Ke(t);if(void 0!==n)return Ke(n)}return Ke(globalThis.customElements)}function Xe(e,t){e.upgrade?.(t)}function Ye(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=tt(s.properties,Qe);if(null===r)return null;const i=void 0===s.inputs?new Map:tt(s.inputs,Ze);if(null===i)return null;const a=void 0===s.commands?new Map:tt(s.commands,et);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Qe(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function Ze(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function et(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function tt(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function nt(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ae(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ot(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function st(e,t,n={}){const s=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&se("Spread binding requires an element node.");const t=e,o=Ge(t);null===o&&se(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Je(t);null===a&&se(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||se(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Xe(a,t);const l=Ye(t);null===l&&se(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=nt(e,c);i.add(t),r.push(t)}for(const e of l.declaredInputs.keys()){if(d.has(e))continue;d.add(e);const t=nt(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=ot(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=ot(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.debug&&i.has(r[t])){const o=r[a.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[t])}return l}function rt(e,t){let n=e;for(let e=0;e<t.length;e++){let o=t[e];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function it(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:be(s.filterName,s.args,t,s.literals??s.args)})}return n}const at=new WeakMap;function lt(e){return at.get(e)||null}function ct(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function dt(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!ct(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function ut(e,t){for(let n=0;n<t.length;n++){const o=t[n];if(o!==e&&o.contains(e))return!0}return!1}function ft(e){const t=[],n=dt(e),s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==De(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&ut(e,n)||t.push(e)}return t}const ht=new WeakSet;function pt(e,t,n,o){const s=st(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ge(e):null;return null===n&&se("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}ht.add(e);const r=function(e,t){const n=[];for(const o of t){const t=it(o.inFilters,"input"),s=it(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:e});else{const r=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:r})}}return n}(e,function(e,t){return void 0===t?e:e.map(e=>null!=e.uuid?e:t(e))}(s,o));return function(e,t){at.set(e,t)}(e,r),He(e),{bindings:r,deferred:null}}function gt(e,t){const n=ft(e),o=[],s=[];for(const e of n){if(ht.has(e))continue;const n=pt(e,Ta(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function mt(e){ht.add(e)}function yt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){ht.delete(e)}(t);return pt(t,n,{allowDeferred:!1},o).bindings}const wt=new WeakMap;let bt=null;function vt(e){let t=e;for(;t;){const e=wt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==bt&&t instanceof ShadowRoot&&(n=bt(t)),t=n}return null}function $t(e,t){null!==t?wt.set(e,t):wt.delete(e)}let xt=null;const St=new WeakMap;function Pt(e){return St.get(e)??[]}function It(e,t){St.set(e,t)}function At(e){return St.has(e)}const Nt=new WeakMap;let kt=null,_t=0;function Tt(e){return Nt.get(e)??[]}function Ct(e,t){null===kt?Nt.set(e,t):kt.set(e,t)}function Et(){_t++,null===kt&&(kt=new Map)}function Mt(){if(0!==_t&&(_t--,!(_t>0||null===kt))){for(const[e,t]of kt)Nt.set(e,t);kt=null}}function Ot(e){return(kt?.has(e)??!1)||Nt.has(e)}const Rt=Symbol("$$setLoopContext"),jt=Symbol("$$getByAddress"),Lt=Symbol("$$hasByAddress"),Wt=Symbol("$$setByAddress"),Dt=Symbol("$$connectedCallback"),Bt=Symbol("$$disconnectedCallback"),zt=Symbol("$$updatedCallback"),Ft=Symbol("$$errorCallback"),qt=new WeakMap,Vt=new WeakMap;class Ht{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Ut(e,t){if(null===t){let t=Vt.get(e);return void 0!==t||(t=new Ht(e,null),Vt.set(e,t)),t}{let n=qt.get(t);void 0===n&&(n=new WeakMap,qt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Ht(e,t),n.set(e,o)),o}}const Gt=new WeakMap;function Kt(e,t){let n=Gt.get(e);void 0===n&&(n=new Map,Gt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Jt(e,t)),n.set(t,o)),o}class Jt{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Xt(e,t){return Ut(Kt(e,t.pathInfo),t.listIndex)}function Yt(e,t,n){return Ut(Kt(e,t),n)}const Qt=new WeakMap;function Zt(e,t){null===t?Qt.delete(e):Qt.set(e,t)}function en(e){return Qt.get(e)||null}const tn=new Map;function nn(e,t){let n,o;if(0===e.wildcardCount||0===t.wildcardCount)return 0;if(1===e.wildcardCount&&t.wildcardCount>0&&t.wildcardPathSet.has(e.path))return 1;e.id<t.id?(n=e,o=t):(n=t,o=e);const s=`${n.path}\t${o.path}`;let r=tn.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,tn.set(s,r),r}function on(e,t,n){return t<0||t>=n?null:e.at(t-n)}function sn(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const rn=new WeakMap;function an(e){const t=vt(e.node);if(null===t)return null;let n=rn.get(t);if(void 0===n)n=new WeakMap,rn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=nn(t.pathInfo,e.statePathInfo);return n>0&&(o=on(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const ln=new WeakMap;function cn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=en(n);null===t?se(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function dn(e,t){let n=null;if(n=ln.get(e)||null,null!==n)return n;const o=cn(e,t),s=an(e),r=xa(o);return null===r&&se("No state tree found on this root for binding."),n=Yt(r,e.statePathInfo,s),ln.set(e,n),n}function un(e){ln.delete(e)}const fn=new WeakMap;function hn(e,t){const n=fn.get(e);void 0===n?fn.set(e,t):n instanceof Set?n.add(t):n!==t&&fn.set(e,new Set([n,t])),null!==xt&&xt({type:"state:binding-added",absoluteAddress:e,binding:t})}function pn(e,t){const n=fn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&fn.delete(e),null!==xt&&xt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const gn=new WeakMap;function mn(e){const t=fn.get(e);return void 0!==t?t:null!==e.listIndex?gn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const yn=new WeakMap,wn=new WeakMap;class bn{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===d?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=vn(e,t)}}function vn(e,t){if(null===t){let t=wn.get(e);return void 0!==t||(t=new bn(e,null),wn.set(e,t)),t}{let n=yn.get(t);void 0===n&&(n=new WeakMap,yn.set(t,n));let o=n.get(e);return void 0!==o||(o=new bn(e,t),n.set(e,o)),o}}const $n=new WeakMap;function xn(e){let t=null;if(t=$n.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=an(e);null===n&&se(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=vn(e.statePathInfo,n)}else t=vn(e.statePathInfo,null);return $n.set(e,t),t}function Sn(e){$n.delete(e)}function Pn(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const In=new Map,An=Pn();function Nn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function kn(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function _n(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=kn(e),s=Nn(e,o);let r=In.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const e of n)r=e.filterFn(r);const i=xa(o.getRootNode());null===i&&se("No state tree found on this root for two-way binding.");const a=vt(o);i.createState("writable",e=>{e[Rt](a,()=>{let n=e[t];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(e[t]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(e[t]=n.toSpliced(o,1))}else e[t]=s?[r]:[]})})},In.set(s,r)),e.node.addEventListener(o,r),An.add(s,e),!0}var t,n;return!1}function Tn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Cn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Tn(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class En{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)t.push(n(...e));return t}}class Mn extends En{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==xt&&xt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const On=new WeakMap;function Rn(e,t){let n=On.get(e);void 0===n&&(n=new Map,On.set(e,n));let o=n.get(t);return void 0===o&&(o=new Mn(t,e),n.set(t,o)),o}const jn=new WeakMap;function Ln(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Ge(t),o=Je(t);if(null!==n&&void 0===o?.get(n))return null===o&&se(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(jn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||se('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Ge(e)?null:Ye(e)}(t);null===r&&se(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&se(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${de(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(g)&&e.preventDefault(),c.includes(m)&&e.stopPropagation();const n=xa(t.getRootNode());null===n&&se("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||se(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${de(l,n.eventTokenNames)}${ue}`);const o=vt(t);n.createStateAsync("writable",async t=>{Cn(t[Rt](o,()=>{const s=null!==o?sn(o.listIndex,o.pathInfo.wildcardCount):[];return Rn(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),jn.set(e,{eventName:a,handler:d}),!0}class Wn extends En{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==xt&&xt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Dn(e){return e instanceof Wn}const Bn=new Map,zn=Pn();function Fn(e){const t=e.propModifiers.filter(e=>e===g||e===m).sort().join(",");return`${e.statePathName}::${t}`}const qn=(e,t,n)=>o=>{t.includes(g)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=xa(r);null===i&&se("No state tree found on this root for event handler.");const a=vt(s),l=e.startsWith(F+".");i.createStateAsync("writable",async t=>{const c=t[Rt](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const e=i.addressHooks;if(e){const t=e.handlerScope;for(let e=0;e<t.length;e++)c=t[e](i,s,r,a,c)}}const d=null!==a?sn(a.listIndex,c):[];if(l){const s=t[jt](vn(n,null));return Dn(s)||se(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...d)}const u=t[e];return"function"!=typeof u&&se(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Cn(c,`"${e}"`)})};function Vn(e){if(!e.propName.startsWith(P))return!1;const t=Fn(e);let n=Bn.get(t);void 0===n&&(n=qn(e.statePathName,e.propModifiers,e.statePathInfo),Bn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),zn.add(t,e),!0}function Hn(e){if(!e.propName.startsWith(P))return!1;const t=Fn(e),n=Bn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==zn.countOf(t)&&(zn.remove(t,e)&&Bn.delete(t),!0)}const Un=new Map,Gn=Pn();function Kn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Jn(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function Xn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=Jn(e),s=Kn(e,o);let r=Un.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const e of n)s=e.filterFn(s);const r=xa(o.getRootNode());null===r&&se("No state tree found on this root for two-way binding.");const i=vt(o);r.createState("writable",e=>{e[Rt](i,()=>{e[t]=s})})},Un.set(s,r)),e.node.addEventListener(o,r),Gn.add(s,e),!0}var t,n;return!1}const Yn=new Set(["radio","checkbox"]),Qn=new Set(["value","valueAsNumber","valueAsDate"]);function Zn(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(Yn.has(e)&&"checked"===t)return!0;if(Qn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ge(n);if(null!==s){const e=Je(n)?.get(s);void 0===e&&se(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ye(n);if(o?.knownProperties.has(t))return!0}return!1}let eo=1,to=1,no=1;const oo=new WeakMap;function so(e,t,n){let o=oo.get(e);void 0===o&&(o=new Map,oo.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=eo++,o.set(s,r)),r}function ro(e,t){return"to-element"===t?2*e:2*e+1}const io=new Set;function ao(e){return{transactionId:to++,originBindingId:e,visitedEdges:io,hop:0}}function lo(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let co=null;function uo(){return co}function fo(e,t){const n=co;co=e;try{return t()}finally{co=n}}const ho=[];let po=!1;const go=new Map,mo=Pn(),yo=new WeakMap,wo=e=>e.detail,bo=new WeakMap;function vo(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function $o(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ge(e.node);if(null!==n){const o=Je(e.node)?.get(n);void 0===o&&se(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ye(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function xo(e){if(null!==Ge(e.node)){const t=Ye(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??wo}return null}function So(e){if(null===Ge(e.node))return!1;const t=Ye(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const Po=(e,t,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==wo||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=bo.get(e);void 0===r&&(r=new Set,bo.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=yo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=so(a,e,t),s=function(e,t){for(let n=ho.length-1;n>=0;n--){const o=ho[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==xt&&xt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:ro(n,"to-state"),node:a,member:e}));const r=ro(n,"to-state"),i=uo();if(null!==i&&i.visitedEdges.has(r))return void(null!==xt&&xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=lo(i??ao(n),r)}const f=xa(a.getRootNode());null===f&&se("No state tree found on this root for two-way binding.");const h=vt(a),p=()=>{r&&(po=!0);try{f.createState("writable",e=>{e[Rt](h,()=>{e[t]=c})})}finally{r&&(po=!1)}};null!==u?fo(u,p):p()};const Io=new WeakSet;function Ao(e){Io.add(e)}function No(e){return!!Io.has(e)&&(Io.delete(e),!0)}const ko=new WeakMap;function _o(e,t){const n=ko.get(e);return!(void 0===n||n<t)&&(n===t?ko.delete(e):ko.set(e,n-t),!0)}const To=new WeakSet;function Co(e){To.add(e)}function Eo(e){return!!To.has(e)&&(To.delete(e),!0)}let Mo=0;function Oo(){Mo--}function Ro(){return Mo>0}class jo{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const Lo=new WeakMap;function Wo(e){let t=Lo.get(e);return void 0===t&&(t=new jo(e),Lo.set(e,t)),t}function Do(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==b&&s!==v&&se(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&se(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Bo(e){return e.propModifiers.some(e=>e.includes("="))}const zo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Fo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function qo(e,t){return"state"===e&&"call"===t?zo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Vo(e){if(!o.enableDirectionalInitialSync)return Bo(e)&&se("init=/sync= modifiers require enableDirectionalInitialSync."),zo;const t=null===(n=Do(e,b))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:se(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":se(`Invalid sync modifier value "${e}".`)}(Do(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&se("Event bindings only allow init=none."),"call"===s?Fo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===N)return qo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&se(`Binding type "${e.bindingType}" does not support init=${t}.`),qo(t??"state",s);const r=Ye(e.node);if(null===r)return qo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||se(`Property "${e.propName}" is not declared by wcBindable.`);const l=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||se(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||se(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Ho(e,t){return"auto"!==t?t:function(e){const t=xa(e.replaceNode.getRootNode());null===t&&se("No state tree found on this root for binding.");const n=xn(e);let o=!1;return t.createState("readonly",e=>{o=e[Lt](n)}),o}(e)?"state":"element"}let Uo=0,Go=0;const Ko=["active","disposed","failed"],Jo=new WeakMap,Xo=new WeakMap,Yo=new WeakMap,Qo=new WeakMap,Zo=new WeakMap;function es(e,t){const n=Zo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Zo.set(e,new Set([n,t]))):Zo.set(e,t)}function ts(e){return Zo.has(e)}function ns(e,t){const n=Zo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function os(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))os(n,t)}function ss(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class rs{root;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}handleMutations(e){const t=[],n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.removedNodes;if(0===r.length||!_o(s.target,r.length))for(let e=0;e<r.length;e++)t.push(r[e]);const i=s.addedNodes;for(let e=0;e<i.length;e++)n.push(i[e])}const o=[];for(const e of t)No(e)||os(e,e=>{ns(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Eo(e)&&!Ro()||os(e,e=>{ns(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&ca(o)}}const is=new WeakMap;function as(e){let t=is.get(e);return void 0===t&&(t=new rs(e),is.set(e,t)),t}function ls(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function cs(e,t,n){const o=xa(cn(e,n));null===o&&se("No state tree found on this root for binding.");const s=Kt(o,e.statePathInfo);return function(e,t,n){let o=gn.get(e);void 0===o&&(o=new WeakMap,gn.set(e,o));const s=o.get(t);void 0===s?o.set(t,n):s instanceof Set?s.add(n):s!==n&&o.set(t,new Set([s,n])),null!==xt&&xt({type:"state:binding-added",absoluteAddress:Ut(e,t),binding:n})}(s,t,e),s}function ds(e,t){const n=dn(e,t);return hn(n,e),n}function us(e,t,n,o){null!==t?pn(t,e):function(e,t,n){const o=gn.get(e);if(void 0===o)return;const s=o.get(t);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(t),null!==xt&&xt({type:"state:binding-removed",absoluteAddress:Ut(e,t),binding:n}))}(n,o,e),Sn(e),un(e)}function fs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class hs{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=this.rowOf(e),i=null===o?-1:o.bindings.indexOf(e);if(null!==o&&0===o.phases[i]){const t=o;this.observe(e.replaceNode),s.registerAddress&&null===t.addresses[i]&&null===t.patternPathInfos[i]&&(t.registered=!0,this.registerRowSlot(t,i));continue}const a=Xo.get(e);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(e,s,n),r.push(e)):(this.observe(a.anchor),s.registerAddress&&null===a.address&&null===a.patternListIndex&&(a.options.registerAddress=!0,this.registerAddress(a)),"active"===a.phase&&this.settleInitialRecord(a),this.settleConnectedSnapshot(a))}return r.filter(e=>this.shouldApplyState(e))}activate(e,t){if(ss(t)&&as(t),null===this.rowPlan)for(const n of e){const e=Xo.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!o.enableDirectionalInitialSync)return Bo(e)&&Vo(e),!0;const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0){if(!t.registered)return!0;if(2===t.phases[n])return!1;const e=t.plan.slots[n];return 1&t.flags[n]?"state"===e.authority||!e.policy.outputOnly:(t.flags[n]|=1,"state"===e.authority)}}const n=Xo.get(e);return void 0===n||n.session!==this||(!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority)))}getRecord(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0)return{id:64*t.id+n,info:e,generation:t.generation,phase:Ko[t.phases[n]],teardowns:null};const o=Xo.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=Xo.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(fs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Je(e);null===s&&se(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),es(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Wo(s).wait(t,()=>{if(a())try{Xe(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0)return void this.disposeRowSlot(t,n)}const n=Xo.get(e);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(e){for(let t=0;t<e.length;t++)this.disposeBinding(e[t]);if(!(this.rows.size>0))for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}destroyRow(e){const t=e.length>0?this.rowOf(e[0]):null;null!==t?(this.destroyRowRecord(t),this.rows.delete(t)):this.destroyRecords()}destroyRowRecord(e){for(let t=0;t<e.bindings.length;t++){const n=e.addresses[t];null!==n&&(pn(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){for(const e of Array.from(this.rows))for(let t=0;t<e.bindings.length;t++)this.disposeRowSlot(e,t);for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(pn(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.rows)for(let n=0;n<t.bindings.length;n++)0===t.phases[n]&&e(t.bindings[n].node);for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.rows)for(let n=0;n<t.bindings.length;n++){if(0!==t.phases[n])continue;if(null===t.addresses[n]&&null===t.patternPathInfos[n])continue;const o=t.bindings[n];this.unregisterRowSlot(t,n),this.registerRowSlot(t,n),this.shouldApplyState(o)&&e.push(o)}for(const t of this.records){if("active"!==t.phase)continue;const n=t.info;if(null===t.address&&null===t.patternListIndex)continue;const o="for"===n.bindingType?dn(n):null;if(us(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=dn(n);e!==o&&At(o)&&It(e,Pt(o)),e!==o&&Ot(o)&&Ct(e,Tt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return ss(t)?t:null}(e);null!==t&&as(t)}handleMutations(e,t,n){for(const n of t)os(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)os(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&ca(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=Xo.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Qo.get(t);void 0===e&&(e=ls(t),Qo.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;es(n,this);const o=this.knownMapFor(n);let s=Qo.get(e);void 0===s&&(s=ls(e),Qo.set(e,s));const r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}initializeRow(e,t){this.rowPlan=e;const n=e.slots,o=t.length,s={id:++Uo,session:this,generation:++Go,plan:e,bindings:t,registered:!1,phases:new Array(o).fill(0),flags:new Array(o).fill(0),addresses:new Array(o).fill(null),patternPathInfos:new Array(o).fill(null),patternListIndexes:new Array(o).fill(null)};this.rows.add(s);for(let e=0;e<o;e++){const o=t[e],r=o.replaceNode;if(es(r,this),this.addKnownRowBinding(r,o,e),Jo.set(o,s),n[e].isEvent){try{Vn(o)}catch(t){throw s.phases[e]=2,t}s.flags[e]|=2}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++Go,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{Vn(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}o.flags[e]|=2}this.registerRowSlot(o,e,n)}}rowOf(e){const t=Jo.get(e);return void 0!==t&&t.session===this?t:null}registerRowSlot(e,t,n){if(null!==e.addresses[t]||null!==e.patternPathInfos[t])return;const o=e.bindings[t],s=an(o);null!==s?(e.patternPathInfos[t]=cs(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=ds(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(us(e.bindings[t],n,o,e.patternListIndexes[t]),e.addresses[t]=null,e.patternPathInfos[t]=null,e.patternListIndexes[t]=null)}disposeRowSlot(e,t){if(1!==e.phases[t]){e.phases[t]=1,this.runRowSlotTeardowns(e,t);for(let t=0;t<e.phases.length;t++)if(0===e.phases[t])return;this.rows.delete(e)}}runRowSlotTeardowns(e,t){try{this.unregisterRowSlot(e,t)}catch{}if(2&e.flags[t]){e.flags[t]&=-3;try{Hn(e.bindings[t])}catch{}}}addKnownRowBinding(e,t,n){const o=this.knownBindingsByNode.get(e);if(void 0===o)return void this.knownBindingsByNode.set(e,t);if(o instanceof Map)return void o.set("@plan:"+n,t);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,t),this.knownBindingsByNode.set(e,s)}start(e,t,n){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const o=this.optionsByBinding.get(e)??{...t},s={id:++Uo,info:e,generation:++Go,phase:"discovered",teardowns:null,session:this,anchor:e.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Xo.set(e,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;Vn(t)?e.eventAttached=!0:t.propSegments[0]!==I?(Xn(t)&&fs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=Jn(e),n=Kn(e,t),o=Un.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Gn.countOf(n)&&(Gn.remove(n,e)&&Un.delete(n),!0))}return!1}(t)),_n(t)&&fs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=kn(e),n=Nn(e,t),o=In.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==An.countOf(n)&&(An.remove(n,e)&&In.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Zn(t.node,t.propName)&&-1===t.propModifiers.indexOf(y)){const n=function(e,t,n){let o=yo.get(e);void 0===o&&(o=new Map,yo.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&yo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});fs(e,n)}!function(e){const t=Ge(e.node);if(null!==t){const n=Je(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&se(`CustomElementRegistry is unavailable for <${t}>.`))}if(Zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=$o(e),n=xo(e),o=So(e),s=vo(e,t,null!==n,o);let r=go.get(s);void 0===r&&(r=Po(e.propName,e.statePathName,e.inFilters,n,o),go.set(s,r)),e.node.addEventListener(t,r),mo.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Ln(t)&&fs(e,()=>function(e){if(e.propSegments[0]!==I)return!1;const t=jn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),jn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Ge(e.info.node);if(null===n)return void t();const o=Je(e.info.node);if(null===o&&se(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=Wo(o).wait(n,()=>{if(this.isAlive(e,s))try{Xe(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});fs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Vo(e.info),n=Ho(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void Mo++;this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending&&(e.observationPending=!1,Oo()),t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=xa(e.node.getRootNode());null===o&&se("No state tree found on this root for initial binding sync.");const s=vt(e.node);o.createState("writable",t=>{t[Rt](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=an(n);if(null!==o?(e.patternPathInfo=cs(n,o,t),e.patternListIndex=o):e.address=ds(n,t),!e.options.registerPathInfo)return;const s=xa(n.replaceNode.getRootNode());null===s&&se("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&Xo.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,Oo());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{us(t,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=Ge(e.node);if(null!==t){const n=Je(e.node),o=n?.get(t);if(void 0===o)return}if(Zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=$o(e),n=vo(e,t,null!==xo(e),So(e)),o=go.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),mo.remove(n,e)&&go.delete(n)}}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{Hn(t)}catch{}}}}function ps(e){let t=Yo.get(e);return void 0===t&&(t=new hs(e),Yo.set(e,t)),t}function gs(e){return Xo.get(e)?.session??Jo.get(e)?.session??null}let ms=null;function ys(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ws=Object.freeze([]);const bs=new WeakMap;const vs=new WeakMap;function $s(e){return vs.get(e)??[]}function xs(e,t){vs.set(e,t)}const Ss=new WeakMap;function Ps(e){return Ss.get(e)??[]}function Is(e,t){Ss.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});let As=0;function Ns(){return`u${(As++).toString(36)}`}let ks=0,_s=0;const Ts=Symbol("wcs.listIndex.noValue");class Cs{uuid=Ns();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ts,this._index=t,this._version=ks,this._chainGeneration=_s}get index(){return this._index}set index(e){this._index=e,this._version=++ks,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(e){this._value=e}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=ks),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===_s||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=_s),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++ks,_s++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Es(e,t,n=e){return new Cs(e,t,n)}function Ms(e,t){e.reparent(t)}function Os(e){return e.homeParentListIndex}function Rs(e,t){e.value=t}function js(e,t){const n=e.value;return n!==Ts&&n===t.value}const Ls=new WeakMap,Ws=new WeakSet;function Ds(e){return Ws.has(e)}function Bs(e,t){const n=Os(e),o=e.parentListIndex;return null===n||n===o||Ws.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Ws.has(e)&&!Ws.has(n)&&n.position===e.position&&js(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Ws.has(e)&&!Ws.has(t)}(o,t)?t:null:n}function zs(e){const t=Ls.get(e);return void 0===t?null:t}function Fs(e,t){const n=Ls.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Bs(o,t);if(null!==e)for(const t of n)Ms(t,e)}return n}function qs(e,t){null!==t?Ls.set(e,t):Ls.delete(e)}const Vs=new WeakMap;function Hs(e,t){null===t?Vs.delete(e):Vs.set(e,t)}function Us(e){const t=Vs.get(e);t&&(t.dirty=!0)}const Gs=Symbol.for("wcstack.transition-runner");function Ks(e){const t=globalThis[Gs];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}function Js(e,t,n){const o=Ks(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Xs=[],Ys=[];function Qs(e){Ys.includes(e)||Ys.push(e)}function Zs(e,t=0){const n=Xs.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Xs.push(o):Xs.splice(n,0,o)}function er(e){queueMicrotask(()=>{throw e})}class tr{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Ys.length;t++)Ys[t](e);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Et(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){const o=new Map,s=new Set;for(let t=0;t<e.length;t++){const n=e[t],r=o.get(n.absoluteAddress);null!==xt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&xt({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];o.has(t)||o.set(t,null)}const r=[],i=new Map;o.forEach((e,t)=>{if(null!==e&&e.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),void(null!==xt&&xt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=mn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(r.push(t),null!==e&&i.set(t,e));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==e&&i.set(n,e))});try{const e=()=>{i.size>0?ca(r,i):ca(r)};if(t()||0===r.length)e();else{const t=Js("state",e);void 0!==t&&t.catch(er)}}finally{Mt(),function(e){for(const t of Xs.slice())t.listener(e)}(s)}}}const nr=new tr;function or(){return nr}const sr=new WeakMap,rr=new WeakMap,ir=new WeakMap,ar=new WeakMap;let lr=!1;const cr=new WeakMap,dr=new WeakMap,ur=new WeakMap,fr=[];function hr(e,t){const n=pr(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ae(t).cumulativePaths;if(o.length<2)return;let s=ur.get(e);void 0===s&&ur.set(e,s=new Map);for(let e=0;e<o.length-1;e++){let n=s.get(o[e]);void 0===n&&s.set(o[e],n=new Set),n.add(t)}}function pr(e){let t=sr.get(e);return void 0===t&&sr.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function gr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function mr(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function yr(e,t,n,o){const s=function(e,t){let n=e.byPath.get(t);return void 0===n&&e.byPath.set(t,n=new Map),n}(e,t);let r=rr.get(o);if(void 0===r&&rr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(mr(s,e,o),r.set(t,n),gr(s,n,o)),!1}return r.set(t,n),gr(s,n,o),!0}function wr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function br(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&wr(ir,o.listIndex,r),null!==r.levelListIndex&&wr(ar,r.levelListIndex,r))}function vr(e,t,n,o,s){lr=!0;const r=pr(e);hr(e,t);br(r,t,s,o,yr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function $r(e,t){pr(e).tracked.add(t)}function xr(e,t,n){if("number"!=typeof t)return;const o=e.indexes[t];if(void 0!==o)for(const t of e.getters)n.push(Xt(e.stateElement,vn(t,o)))}function Sr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Pr(e,t,n,o,s){const r=sr.get(e),i=r?.byPath.get(t),a=cr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return fr;const l=r.lastValue.has(t),c=r.lastValue.get(t);r.lastValue.set(t,s);const d=[],u=!n||!Object.is(o,s),f=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&Sr(i.get(o),d),f&&Sr(i.get(c),d),u&&Sr(i.get(s),d)),void 0!==a)for(const e of a)n&&xr(e,o,d),f&&xr(e,c,d),u&&xr(e,s,d);return d}function Ir(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Ar(e,t,n){const o=sr.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())Sr(e,n);const s=cr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)xr(e,t,n)}function Nr(e){const t=ar.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function kr(e){if(!lr)return;const t=ir.get(e);if(void 0!==t){ir.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=rr.get(o),r=s.get(n);s.delete(n),mr(sr.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Nr(e)}}}function _r(e,t,n){if(!lr)return;const o=ar.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=sr.get(e),i=o.byPath.get(s);mr(i,t,r),gr(i,n,r),rr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Us(r),or().enqueueAbsoluteAddress(r,null))}}const Tr=new WeakMap,Cr=Object.freeze([]),Er=new Set;function Mr(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Cr,s=Array.isArray(n)&&n.length>0?n:Cr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Cr,o=Array.isArray(t)&&t.length>0?t:Cr;let s=Tr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Fs(o,e)||[],a=i.length>0?Os(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Er,deleteIndexSet:new Set(i),addIndexSet:Er};let t=Fs(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Es(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:Er,deleteIndexSet:Er,addIndexSet:new Set(t)}}if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:Er,deleteIndexSet:Er,addIndexSet:Er};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=Es(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=Tr.get(e);o||(o=new WeakMap,Tr.set(e,o)),o.set(t,n)}(o,s,l),qs(s,l.newIndexes))}}(e,t,n);!function(e,t){for(let n=0;n<e.length;n++){if(e[n].index!==n){const t=e[n].index;e[n].index=n,_r(e[n],t,n)}Rs(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Cr),function(e){for(const t of e)Ws.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)kr(e);return function(e){for(const t of e)Ws.delete(t)}(o.newIndexes),function(e,t){if(!lr||e===t)return;const n=dr.get(e);if(void 0===n)return;dr.delete(e);const o=dr.get(t);dr.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=pr(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=e[n],r=t[n];if(s!==r)for(const e of[s,r])if(void 0!==e&&!Ds(e))for(const t of o.getters){const n=Xt(o.stateElement,vn(t,e));Us(n),or().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function Or(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const e of i)a.add(n[e]);return a}const Rr=new WeakSet;const jr=new WeakMap;function Lr(e){return jr.get(e)??null}function Wr(e,t){jr.set(e,t)}const Dr=new WeakMap;function Br(e){return Dr.get(e)??[]}function zr(e,t){Dr.set(e,t)}function Fr(e,t){const n=Br(e);for(const e of n)$t(e,t)}const qr=new WeakMap;const Vr=new WeakMap;function Hr(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function Ur(e,t,n,o,s){const r=function(e,t,n){let o=Vr.get(e);void 0===o&&Vr.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths;let a,l=!1;for(let e=0;e<t.length;e++){const c=t[e];if(!n.shouldApplyState(c))continue;const d=r[e];if(null===d||Hr(d.prefixes,i)){aa(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[jt](o),l=!0);const u=d.tail;let f=a;for(let e=0;e<u.length;e++){if(null==f){f=void 0;break}f=f[u[e]]}ia(c,s,f)}}function Gr(e,t,n){Fr(e,t);const o=$s(e),s=Lr(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return qr.get(e)??null}(e);if(null!==r)return void Ur(r,o,s,t,n)}for(const e of o){if(null===s){hn(dn(e),e)}(null===s||s.shouldApplyState(e))&&aa(e,n)}}function Kr(e){if(!e.mounted)return;const t=$s(e),n=Lr(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{pn(dn(o),o)}}!function(e){const t=Br(e);for(let e=0;e<t.length;e++)$t(t[e],null)}(e)}function Jr(){return Object.freeze(new Set)}const Xr=new WeakMap,Yr=Jr();function Qr(e,t){const n=Xr.get(e);n?n.add(t):Xr.set(e,new Set([t]))}function Zr(e){const t=Xr.get(e);return void 0!==t?t:Yr}function ei(e,t){const n=Xr.get(e);n&&(n.delete(t),0===n.size&&Xr.delete(e))}function ti(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:be(s.filterName,s.args,t,s.literals??s.args)})}return n}function ni(e){return{...e,inFilters:ti(e.inFilters,"input"),outFilters:ti(e.outFilters,"output")}}const oi=new Set(["if","elseif","else","for"]);class si{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t;const n=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)n.push(t);this._childNodeArray=n,this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(e){const t=this._childNodeArray;for(let n=0;n<t.length;n++){const o=t[n];Co(o),e.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const e=this._firstNode,t=this._lastNode;if(null===e||null===t||null===e.parentNode)return this._childNodeArray;const n=[];for(let o=e;null!==o;o=o.nextSibling)if(n.push(o),o===t)return n;return this._childNodeArray}mountAfter(e){const t=e.parentNode;if(t){let n=e;for(const e of this._movableNodes()){if(n.nextSibling!==e){Co(e);const o=t;e.parentNode===t&&"function"==typeof o.moveBefore?o.moveBefore(e,n.nextSibling):t.insertBefore(e,n.nextSibling)}n=e}}this._mounted=!0}tryDestroy(){const e=Lr(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow($s(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Ao(n),n.parentNode.removeChild(n))}const n=$s(this);for(let e=0;e<n.length;e++){const t=n[e];oi.has(t.bindingType)&&Zr(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Lr(this);null!==e&&(e.isRowSession?e.disposeBindings($s(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=$s(this);for(let t=0;t<e.length;t++){const n=e[t];oi.has(n.bindingType)&&Zr(n.node).forEach(e=>{e.unmount()}),Sn(n),un(n)}}unmount(){{const e=Lr(this);null!==e&&(e.isRowSession?e.disposeBindings($s(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Ao(e),e.parentNode.removeChild(e));const e=$s(this);for(let t=0;t<e.length;t++){const n=e[t];oi.has(n.bindingType)&&Zr(n.node).forEach(e=>{e.unmount()}),Sn(n),un(n)}this._mounted=!1}}function ri(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function ii(e){const t=document.createDocumentFragment(),n=new si(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function ai(e,t,n){const o=document.importNode(t.fragment,!0),s=t.nodeInfos,r=new Array(s.length);for(let e=0;e<s.length;e++){const t=rt(o,s[e].nodePath);null===t&&se(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),mt(t),He(t),r[e]=t}const i=n.slots,a=new Array(i.length),l=[];for(let e=0;e<i.length;e++){const t=i[e],n=r[t.nodeIndex],o={...t.template,node:n,replaceNode:n};a[e]=o,t.isIndexBinding&&l.push(o)}const c=function(e,t,n){let o=ua.get(n);void 0!==o&&o.currentRowPlan===e||(o=new hs,ua.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new si(o);return Wr(d,c),xs(d,a),function(e,t){qr.set(e,t)}(d,n),Is(d,l),zr(d,r),Qr(e.node,d),d}function li(e){void 0!==e.uuid&&null!==e.uuid||se("BindingInfo.uuid is null.");const n=_a(e.uuid);n||se(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&ri(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=rt(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===N||s===I)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ge(r))return null;if("prop"===o&&Zn(r,e.propName))return null;const i=ni(e);let a;try{a=Vo({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:t,template:i,isEvent:"event"===o,isIndexBinding:e.statePathName in M,policy:a,authority:a.authority})}}return{directional:t,slots:n}}(n)),null!==r)return ai(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=rt(e,s.nodePath);if(null===t&&se(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),ht.has(t))continue;const r=pt(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new hs,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new si(i,s);Wr(l,a.bindingSession),xs(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in M&&c.push(e);return Is(l,c),zr(l,a.nodes),Qr(e.node,l),l}const ci=new WeakSet,di=Symbol.for("wcstack.state.view-transition-naming");function ui(){const e=Ks("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function fi(e,t,n){const o=function(e){const t=e.firstNode;if(null===t)return null;const n=e.lastNode;for(let e=t;null!==e;e=e.nextSibling){if(e.nodeType===Node.ELEMENT_NODE)return e;if(e===n)break}return null}(e);if(null===o||ci.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[di]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(ci.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${t}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${t}`))}const hi=new WeakMap,pi=new WeakMap,gi=new WeakMap,mi=new WeakMap;function yi(e,t,n){!function(e,t,n){let o=pi.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,pi.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function wi(e,t){hi.set(e,t)}function bi(e){return e.nodeType===Node.ELEMENT_NODE||(e.nodeType===Node.TEXT_NODE?""!==(e.textContent?.trim()??""):e.nodeType===Node.COMMENT_NODE&&e.data.startsWith("@@wcs-"))}function vi(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function $i(e,t,n){if(o=t,!Rr.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const xi=new Set(["if","elseif","else","for"]);function Si(e,t){for(const n of $s(e))if(t.appliedBindingSet.delete(n),xi.has(n.bindingType))for(const e of Zr(n.node))Si(e,t)}function Pi(e){for(const t of $s(e)){if(!xi.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Zr(t.node))Pi(n),e&&n.mounted&&(Kr(n),n.unmount(),ei(t.node,n))}}function Ii(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ai(e,n,s){const r=Boolean(s);let i;const a=Zr(e.node);i=0===a.size?li(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Ii(e)}`),Kr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Ii(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);Gr(i,vt(e.node),n);const t=ui();null!==t&&fi(i,"branch",t)}}const Ni=new WeakMap;function ki(e){return Ni.get(e)??[]}const _i=new Set;const Ti=Symbol.for("wcstack.trustedTypes.policy");function Ci(){const e=globalThis[Ti];return null===e||"object"!=typeof e?null:e}function Ei(e){globalThis[Ti]=e}let Mi;let Oi=!1;function Ri(e,t){if(Oi)return;if(!function(){if(void 0!==Mi)return Mi;if(!("trustedTypes"in globalThis))return Mi=!1,Mi;try{document.createElement("div").innerHTML="<i></i>",Mi=!1}catch{Mi=!0}return Mi}())return;Oi=!0;const n="function"==typeof Ci()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${t}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:e,property:t})}const ji={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}},Li=new Set(["textContent","innerText","innerHTML"]);function Wi(e,n,s){if(void 0===s&&1===e.propSegments.length&&Li.has(e.propSegments[0])&&(s=""),void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==s){null!==ms&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Ge(r)&&ms.rememberOverwrittenObject(r,c,d);const t="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let e=!1;try{r[c]=t?function(e){if("string"!=typeof e)return e;const t=Ci(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Ri(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=Ge(e);if(null===n)return null;const o=Je(e)?.get(n);if(void 0===o)return null;const s=Ye(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Zn(r,c)){const t=so(r,c,e.statePathName),o=ro(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??uo()??ao(t);if(a.visitedEdges.has(o))null!==xt&&xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=lo(a,o);fo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:no++,writtenValue:n};ho.push({receipt:i,node:e});try{return r()}finally{ho.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=ji[c];e?e(r,s):(!function(e,t,n){let o=Ni.get(e);o||(o=[],Ni.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,_i.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));null!==ms&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ge(r)&&(u in d?ms.rememberOverwrittenValue(r,c,u,d[u]):ms.recordInjectedKey(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const Di=new WeakSet;function Bi(e,t,n){}function zi(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}function Fi(e,t,n){const o=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),s=t.length>0?t+c:"";for(const e of n){if(s.length>0&&!e.startsWith(s))continue;const t=e.slice(s.length);t.length>0&&-1===t.indexOf(c)&&o.push(t)}return o}const qi={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Vi={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Hi(e,t,n,o){return`[wcs/index-arity] ${e}("${t}") requires ${"$resolve"===e?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${ue}`}function Ui(e,t){return`[wcs/recursion-anchor] "${e}" does not match the declared recursion anchor "${t}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function Gi(e,t){return`$setAll("${e}") ${t}`}function Ki(e,t,n){return`[wcs/wildcard-rank] ${e} needs ${t} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${ue}`}function Ji(e,t){const n=xn(t);if(n.pathInfo.path in M){const e=vt(t.node);return null===e&&se(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&se("ListIndex not found for loopContext:");const n=M[t];void 0===n&&se(`Invalid index name: ${t}`);const o=on(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&se(Ki(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[jt](n)}const Xi=new WeakSet;function Yi(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Qi=Object.freeze({[k]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&se("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[_]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[T]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[N]:function(e,t,n){Dn(n)||se("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=bs.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||se('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Ge(e);if(null===t)return null;const n=Je(e)?.get(t);return void 0===n&&se(`Custom element <${t}> is not defined for command binding.`),Ye(e)}(r);null===a&&se(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||se(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${de(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),bs.delete(e));const l=new WeakRef(r);let c=null;c=o.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void bs.delete(e);const o=n[i];return"function"!=typeof o&&se(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),bs.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Zi={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Di.has(e.replaceNode)){Di.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,n,o){const s=e.statePathInfo,r=an(e),i=dn(e),a=Pt(i),l=a.length>0&&!pi.has(e.node)?[]:a,c=Mr(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=pi.get(e.node);const f=void 0!==u?$i(u,l,c):null,h=Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=mi.get(e.node);if(void 0===t){const n=hi.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(bi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(bi(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),mi.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){ko.set(e,(ko.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return gi.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;c.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(Kr(o),Pi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?ei(e.node,o):(Kr(o),o.unmount(),function(e,t){let n=gi.get(e.node);void 0===n&&(n=[],gi.set(e.node,n)),n.length<1e3?n.push(t):ei(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(pi.delete(e.node),u=void 0)}let g=e.node;const m=ae(s.path+"."+d),y=n.stateElement.loopContextStack,w=Or(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&g.isConnected&&null===f&&(b=document.createDocumentFragment(),Zt(b,n.rootNode));const v=t(),$=ui(),x=e.uuid??"",S=gi.get(e.node);for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const r=vn(m,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=li(e):Si(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`));else{if(g.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);g.parentNode.insertBefore(e,g.nextSibling),g=e}o.mountAfter(g)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??g;n.parentNode.insertBefore(e,n.nextSibling)}}Gr(o,r,n),null!==$&&fi(o,"row",$)}),void 0===o&&se(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)){const e=n.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](n.stateElement,o)}}}else{if(o=void 0!==u?u.get(t)??null:null,c.changeIndexSet.has(t)){const e=Ps(o);for(const t of e)aa(t,n)}null===o&&se(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&vi(g,o.firstNode)||g.nextSibling===o.firstNode||o.mountAfter(g),e){const e=o,s=vn(m,t);y.createLoopContext(s,t=>{Gr(e,t,n)})}}g=o.lastNode||g,void 0===u&&(u=new WeakMap,pi.set(e.node,u)),u.set(t,o)}hi.set(e.node,g),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Zt(b,null))},if:Ai,else:Ai,elseif:Ai,radio:function(e,t,n){const o=e.node,s=ys(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=ys(o.value,e.inFilters),r=Array.isArray(n)?n:ws;o.checked=r.includes(s)}},ea=new WeakMap,ta=new WeakMap,na=new WeakMap;function oa(){}function sa(e){const t=ms;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Bi;if(t.isDeclared(n,o))return oa}return Wi}function ra(e,t){ia(e,t,Ji(t.state,e))}function ia(e,t,n){const o=ys(n,e.outFilters);if(!0===ta.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=ea.get(e);if(void 0===s){if(ea.has(e))return s=sa(e),s===Bi&&ea.set(e,s),void s(e,t,o);if(s=Zi[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Qi[t],ea.set(e,s),void 0===s){Ge(e.replaceNode)?(s=sa(e),s===Bi&&ea.set(e,s)):(s=Wi,ea.set(e,s))}}if(s===Wi){if("SELECT"===e.node.tagName){const n=e.propSegments[0];if("value"===n||"selectedIndex"===n)return t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement}),void ta.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function aa(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=dn(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=gs(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==na.get(e)){const t=Ge(e.replaceNode);if(t&&void 0===Je(e.replaceNode)?.get(t))return void function(e,t){if(Xi.has(e))return;Xi.add(e);const n=()=>{Xi.delete(e);const t=gs(e);(null===t||t.shouldApplyState(e))&&ca([e])},o=n=>{Xi.delete(e),Yi(t,n)},s=gs(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Xi.delete(e),r()})||(Xi.delete(e),r()))}const r=Je(e.replaceNode);if(null===r)return Xi.delete(e),void Yi(t,new Error("CustomElementRegistry is unavailable."));Wo(r).wait(t,()=>{e.replaceNode.isConnected?n():Xi.delete(e)},o)}(e,t);na.set(e,!0)}if(!0===t.sameRootVerified)return void ra(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=en(o),null===o&&se("Root node for fragment not found for binding.")),o!==t.rootNode){const n=xa(o);null===n&&se("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};ra(e,r)})}else ra(e,t)}function la(e,t,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:e.statePathName,bindingType:e.bindingType,node:e.node},r=o.get(n);void 0===r?o.set(n,[{error:t,info:s}]):r.push({error:t,info:s})}else console.error(`[@wcstack/state] binding "${e.bindingType}: ${e.statePathName}" failed to apply; the rest of this batch continues.`,{node:e.node,error:t});null!==xt&&xt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function ca(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=en(d),null===d&&se("Root node for fragment not found for binding."));const u=xa(d);null===u&&se("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{aa(n,f)}catch(e){la(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{Wi(e,{propagationContextByBinding:t},n)}catch(t){la(e,t,o??null,c)}for(const[e,t]of i.entries())It(e,t),Ct(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[zt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Ft](n,o)}catch(e){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:e,original:n,node:o.node})}})}function da(e,t,n){const[o,s,r]=gt(e,n),i=ps(e);for(const e of o)$t(e,t);ca(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=yt(o);0!==e.length&&($t(o.node,t),ca(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const ua=new WeakMap;async function fa(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Je(e);null===s&&se(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(ct(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function ha(e){if(e===document)await fa(document),ne(document),Ua(document,document),da(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await Ve(t.host),await fa(t),ne(t),Ua(t,t),da(t,null)}}const pa={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function ga(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${pa[e]??e}" before the state is defined.`}let ma=null;function ya(e){return null===ma&&se(ga("ssr",e)),ma}const wa=new WeakMap,ba=new WeakMap,va=new Set,$a=[];function xa(e){return wa.get(e)??null}function Sa(e){return ba.get(e)??Promise.resolve()}const Pa=new WeakSet;function Ia(e){Pa.add(e)}function Aa(e,n){const s=wa.get(e);if(null===n){if(void 0===s)return;wa.delete(e),va.delete(s),null!==xt&&xt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await ya('the "enable-ssr" attribute').hydrate(e)||await ha(e)}else await ha(e);Ia(e),Qa(),t()}catch(e){n(e)}})});ba.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await ha(e),Ia(e),Qa(),t()}catch(e){n(e)}})});ba.set(e,t)}}void 0!==s&&se('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),wa.set(e,n),va.add(n);for(let t=0;t<$a.length;t++)$a[t](e,n);null!==xt&&xt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Na=new Map;function ka(e,t,n){if(null===n)Na.delete(e);else{Na.set(e,n);const o=xa(t);null===o&&se("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const t of e.parseBindTextResults)o.setPathInfo(t.statePathName,t.bindingType)}}function _a(e){return Na.get(e)||null}function Ta(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Re(t.getAttribute(o.bindAttributeName)||"");return t.localName===o.tagNames.state&&t.hasAttribute("mount")?n.filter(e=>e.propSegments[0]!==A):n}if(e.nodeType===Node.COMMENT_NODE){const t=De(e);null===t&&se("Comment node binding text not found.");const n=_a(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Be(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Ca;function Ea(){return Ca??={filterName:"not",args:[]}}const Ma=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Oa(e,t){const n=t+c+d,o=e.indexOf("|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+c+s.slice(1)}return r.length>0?s+r:s}function Ra(e,t){const n=Ma.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Oa(s,t)+r}function ja(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Oa(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function La(e,t){return ja(e,t)}function Wa(e,t){const n=o.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Ra(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=ja(r,t);e!==r&&o.setAttribute(n,e)}}}function Da(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}function Ba(e){const t=[],n=ft(e);for(const e of n){const n=Ta(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:Da(o),parseBindTextResults:n})}return t}function za(e){const t=Array.from(e.childNodes);for(const n of t)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&e.removeChild(n)}}const Fa=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),qa=Ea();function Va(e,t){const n=t.outFilters;return{...t,outFilters:[...n,qa],bindingType:e}}function Ha(e,t,n,o,s,r=!0){za(t),"string"==typeof o&&Wa(t,o),Ua(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ba(t)};return void 0!==s&&function(e,t,n){for(const o of e)for(let e=0;e<o.parseBindTextResults.length;e++){const s=o.parseBindTextResults[e];null==s.uuid&&(o.parseBindTextResults[e]=t(s,n))}}(i.nodeInfos,s,o),i}function Ua(e,t,n,s){const r=o.commentElsePrefix,i=dt(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=La(i,n));let a=Re(i)[0];const d=Fa.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Ns();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&se("'else' binding found without preceding 'if' or 'elseif' binding."),a=Va("else",l.parseBindTextResult),p=Ha(e,f,a,g,s,!1),ka(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Da(o),parseBindTextResults:Ta(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&se("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ha(e,f,a,g,s),ka(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=Ns(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Va("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Da(n),parseBindTextResults:Ta(n)}),ka(o,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:Da(m),parseBindTextResults:Ta(m)})):t.replaceWith(m)}else{p=Ha(e,f,a,g,s),ka(h,e,p);const n=document.createComment(`@@${d}:${h}`);t.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}const Ga=()=>`[${o.bindAttributeName}]`;function Ka(e){if(ts(e))return!0;if(!Ja(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(Ga());return null!==t&&ts(t)}function Ja(e){return 1===e.nodeType}function Xa(e){if(Ka(e))return;ne(e),Ua(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);da(t&&s?n:e,null)}const Ya=[];function Qa(){const e=Ya.splice(0,Ya.length);for(const t of e)Xa(t);l()}const Za={protocol:"wcs-binder",version:1,bind:function(e){var t;Ja(e)&&!Ka(e)&&(t=e.getRootNode(),Pa.has(t)?Xa(e):Ya.push(e))}};const el="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let tl=0;async function nl(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++tl}\n`;let s=!1;const r=e=>{e.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+o],{type:"application/javascript"}),s=URL.createObjectURL(t);try{n=await import(s)}finally{URL.revokeObjectURL(s)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+o)));n=await import(`data:application/javascript;base64,${t}`)}}catch(e){throw new Error(function(e,t,n){const o=t?.message??String(t);return n?`The inline <script> of state "${e}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${el}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${el}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function ol(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){se(`Failed to load script file: ${e}`)}}class sl{_loopContextStack=Array(f).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&se("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=f&&se("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&se("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const e=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==e&&se("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&se(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=t(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const rl={$updatedCallback:j,$streams:H},il=new WeakSet;function al(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function ll(e){if(!il.has(e)){for(const t of Object.keys(rl)){if(!(t in e))continue;const n=rl[t];n in e&&se(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".`);const o=al(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}il.add(e)}}const cl=new WeakMap;function dl(e,t){let n=cl.get(e);void 0===n&&(n=new Map,cl.set(e,n));let o=n.get(t);return void 0===o&&(o=new Wn(t,e),n.set(t,o)),o}const ul=new WeakMap;function fl(e){const t=ul.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return dl(e,n)},has:(t,n)=>"string"==typeof n&&e.commandTokenNames.has(n),ownKeys:()=>Array.from(e.commandTokenNames),getOwnPropertyDescriptor(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:dl(e,n)}},set(){se("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){se("$command namespace is read-only; deleting from it is not allowed.")}});return ul.set(e,n),n}const hl=Symbol("wcs.notHandled"),pl=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],gl=new Map;function ml(e,t){gl.set(e,t)}const yl=new Map;let wl=[],bl=[];function vl(e,t){yl.set(e,t),wl=Array.from(yl.values()).sort((e,t)=>e.order-t.order),bl=wl.slice().reverse()}function $l(e,t){for(let n=0;n<wl.length;n++)wl[n].activate?.(e,t)}function xl(e){"readonly"===e.mutability&&se("This state is readonly.")}const Sl=new Map;class Pl{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice();let o=0,s=0,r=0,i="none";const a=[];for(let e=0;e<t.length;e++){const i=t[e];if("*"===i)n[e]="*",a.push(null),o++,r++;else{const t=Number(i);Number.isNaN(t)||(n[e]="*",a.push(t),s++,r++)}}const l=ae(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=e,this.segments=t,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Il(e){let t;return Sl.get(e)??(Sl.set(e,t=new Pl(e)),t)}function Al(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[t];return void 0===o||null===n.listIndex?null:on(n.listIndex,o,n.pathInfo.wildcardCount)}function Nl(e,t){if(!e.untracking&&e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=nn(t.pathInfo,o);if(e>0){let r=!1;const i=t.listIndex??null,a=n.listIndex??null;for(let n=0;n<e;n++){if((null!==i?on(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?on(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function kl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function _l(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](e,t,n,o,s);if(a!==hl)return a}}return hl}function Tl(e,t,n,o,s){if(t.pathInfo.segments[0]===F)return function(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}(fl(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=_l(s,t,null,n,o);if(r!==hl)return r;se(function(e,t,n){return`[${qi.binding}] Path "${e}" does not exist on the state tree.${de(e,Fi(t,"",n))}${ue}`}(t.pathInfo.path,e,s.getterPaths))}const r=El(e,t.parentAddress,n,o);if(null==r)return;const i=t.pathInfo.segments[t.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==d&&!(i in Object(r))){const e=_l(s,t,Object(r),n,o);if(e!==hl)return e}if(i===d){const e=t.listIndex?.index??se(Ki(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(r,e)}return Reflect.get(r,i)}if(!s.getterPaths.has(t.pathInfo.path))return Reflect.get(e,t.pathInfo.path);o.pushAddress(t);try{return Reflect.get(e,t.pathInfo.path,n)}finally{o.popAddress()}}function Cl(e,t,n,o,s){const r=Xt(s,t),i=function(e){return Vs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Tl(e,t,n,o,s);return Hs(r,{value:l,dirty:!1,generation:a}),l}function El(e,t,n,o){Nl(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const e=r.read;for(let r=0;r<e.length;r++){const i=e[r](s,t,n,o);if(i!==hl)return i}}return kl(s,t)?Cl(e,t,n,o,s):Tl(e,t,n,o,s)}function Ml(e,t,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=vn(f,r),p=Xt(n.stateElement,h),g=Tt(p),m=El(e,h,t,n),y=Mr(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??se(`ListIndex not found at index ${w} of ${f.path}`);s+1<o.length?a(o,s+1,e,l,c+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[e,t]of i.entries())Ct(e,Array.isArray(t)?t:[]);return l}function Ol(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Fs(El(e,vn(a,r),t,n),r);null==l&&se(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??se(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Rl(e,t,n,o){"object"==typeof e&&null!==e||se(`${X} list "${t}": ${n} row at index ${o} must be a plain object (got ${null===e?"null":typeof e}).`);const s=Object.getPrototypeOf(e);s!==Object.prototype&&null!==s&&se(`${X} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function jl(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&se(`${X} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function Ll(e,t,n,o){const s=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){const a=e[i];Rl(a,n,o,i);const l=jl(a,t,n,o,i);r.has(l)&&se(`${X} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Wl(e,t){const n=[];for(const o of Object.keys(t))Object.is(e[o],t[o])||n.push({field:o,value:t[o]});for(const o of Object.keys(e))Object.hasOwn(t,o)||null==e[o]||n.push({field:o,value:null});return n}function Dl(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=El(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===d){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const Bl=new WeakMap;function zl(e,t){null===t?Bl.delete(e):Bl.set(e,t)}function Fl(e,t,n){const s=vn(ae(e.wildcardParentPaths[t]),n),r=Xt(e.stateElement,s),i=Tt(r),a=e.stateProxy[jt](s),l=Mr(s.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${t}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)Fl(e,t+1,n)}const ql=[];function Vl(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:ql,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:ql,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Hl=[];function Ul(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Hl;let s=null;const r=t+c;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ae(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Hl}function Gl(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=ae(r);if(e.listPathSet.has(o)&&s.lastSegment===d){const i=e.stateProxy[jt](t),a=Xt(e.stateElement,t),l=Tt(a),c=Mr(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Vl(e,o,0,0,c);for(const t of d.fullRows){const o=vn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=Ul(e,r,s);if(null===t)for(const t of d.movedRows){const o=vn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=vn(s,o);e.result.add(t),n.push(t)}}}else{const o=vn(s,t.listIndex);e.result.add(o),n.push(o)}}const r=e.dynamicMap.get(o);if(r)for(const o of r){const s=ae(o),r=[];if(s.wildcardCount>0){const n=nn(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&se(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=on(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Fl(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&se(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=on(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=vn(s,t);e.result.add(o),n.push(o)}}}function Kl(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&se(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),n(a),i.length=0,Gl(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}(u,t,a);for(const[e,t]of u.observedListValueByAbsAddress)Ct(e,t);return Array.from(u.result)}function Jl(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](e,t,n,o,s)}}function Xl(e,t,n){const o=e.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Yl(e,t,n){const o=e.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Ql(e,t,n,s,r,i){const a=function(e,t){return!0===sr.get(e)?.byPath.has(t)||!0===cr.get(e)?.has(t)}(e,t),l=function(e,t){return!0===ur.get(e)?.has(t)}(e,t);if(!a&&!l)return;const c=or(),u=o.enablePropagationContext?uo()??null:null,f=e=>{Us(e),c.enqueueAbsoluteAddress(e,u)};a&&Pr(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=ae(t).segments.length,r=[];for(const i of ur.get(e).get(t)){const t=ae(i).segments.slice(s);if(t.includes(d))Ar(e,i,r);else for(const s of Pr(e,i,!0,Ir(n,t),Ir(o,t)))r.push(s)}return r}(e,t,n?s:i(),r).forEach(f)}function Zl(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?uo()??ao(-1):null,c=or();c.enqueueAbsoluteAddress(t,l),i&&Us(t),Kl(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Xt(s.stateElement,t);Us(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function ec(e,t,n,o,s){s&&(e.getterPaths.has(t)?Us(n):Hs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function tc(e,t,n,o,s,r,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=El(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??se(Ki(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(i,e,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t),r.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{Zl(t,n,s,r,i,a)}}function nc(e,t,n,o,s,r,i,a){const l=t.parentAddress??se(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=El(e,l,s,r)??[];let f=(h=u,Bl.get(h)??null);var h;if(null===f){const e=zs(u)??[];f={value:[...u],listIndexes:[...e]},zl(u,f)}try{return tc(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=El(e,l,s,r)??[],a=Array.isArray(i)?zs(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:Es(l.listIndex,-1);a[h]=p;if(new Set(i).size===f.value.length){for(let e=0;e<a.length;e++)a[e].index=e;zl(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=or(),l=Xt(i,e);Pt(l)===n&&(qs(t.value,t.listIndexes),It(l,t.value),function(e){Rr.add(e)}(t.value));a.enqueueRenderOnlyAddress(l);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=ae(e.pathInfo.path+c+d);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=vn(f,n),d=Xt(i,c);if(void 0===l){const n=Yt(i,f,t.listIndexes[e]??null);Yl(i,d,n),Zl(c,d,s,r,null,kl(i,c),"full");continue}Kl(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Xt(i,e);Us(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(l,f,i,a,s,r)}}}function oc(e,t,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(t.pathInfo.path);if(void 0!==i){const r=El(e,t,o,s),a=function(e,t,n,o){const s=Ll(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Ll(r,t,e,"current"),a=new Map;for(let e=0;e<r.length;e++)a.set(i[e],r[e]);const l=new Array(o.length),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=a.get(s[e]);void 0!==n&&n!==t?(l[e]=n,c.push({position:e,oldRow:n,newRow:t})):l[e]=t}return c.length>0?{list:l,matched:c}:null}(t.pathInfo.path,i,r,n);if(null!==a)return function(e,t,n,o,s,r){const i=t.pathInfo.path,a=t.listIndex;null===zs(o)&&Mr(a,null,o);const l=Mr(a,o,n.list),u=sc(e,t,n.list,s,r,i),f=ae(i+c+d);for(const t of n.matched){const n=Wl(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?oc(e,vn(ae(f.path+c+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return sc(e,t,n,o,s,null)}function sc(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==hl)return i}}const u=!!po&&(po=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=El(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===d?t.listIndex?.index:e;let p,g=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in f,t=void 0!==h?f[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}Ql(a,l,g,p,n,()=>f[h]);const m=kl(a,t),y=Xt(a,t);null!==xt&&xt({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:g}),Jl(a,l,y,p,g);let w=!1;try{if(void 0===h&&se(Ki(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==d&&!(h in f)){const e=c.writeMissing;for(let o=0;o<e.length;o++){w=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==hl)return i;w=!1}}return Reflect.set(f,h,n)}finally{Zl(t,y,s,r,i,m),w?Us(y):ec(a,l,y,n,m),Xl(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=El(e,t,s,r);if(Dl(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Ql(a,l,h,f,n,()=>El(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),g=kl(a,t),m=Xt(a,t);null!==xt&&xt({type:"state:write",absoluteAddress:m,value:n,oldValue:f,hasOldValue:h}),Jl(a,l,m,f,h);try{return p?nc(e,t,m,n,s,r,i,g):tc(e,t,m,n,s,r,i,g)}finally{p||ec(a,l,m,n,g),Xl(a,t.pathInfo,{value:n})}}function rc(e,t,n,o){return(t,s,...r)=>{const i=ae(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}s.length!==i.wildcardParentPathInfos.length&&se(Hi("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=vn(i,Ol(e,n,o,i,s));if(0===r.length)return El(e,a,n,o);xl(o),oc(e,a,r[0],n,o)}}function ic(e,t,n,o){const s=rc(e,0,n,o);return(t,r)=>{const i=ae(t);if(void 0===r||Array.isArray(r)||se(`$getAll("${t}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&se(Hi("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=Al(o,i.wildcardPaths[e]);if(t){r=sn(t,t.length);break}}if(void 0===r){const e=o.addressStackLength>0?o.lastAddressStack:null,n=e?.listIndex??null;i.wildcardCount>0&&null!==e&&null!==n&&n.length>0&&se(function(e,t){return`$getAll("${e}") was called without indexes inside the loop context of "${t}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(t,e.pathInfo.path)),r=[]}}const a=Ml(e,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let e=0;e<a.length;e++)l.push(s(i.path,a[e]));return l}}function ac(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Al(o,s.wildcardPaths.at(-1)??se(`lastWildcardPath is null: ${t.pathInfo.path}`))??se(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??se(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Fs(El(e,vn(i,s),n,o),s)??se(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??se(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??se(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":se(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function lc(e,t,n,o){return(t,s,r,i)=>{xl(o);const a=ae(t);Array.isArray(s)||se(Gi(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&se(Hi("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&se(Gi(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&se(Gi(t,"requires an array as the value when { spread: true } is set."));const d=Ml(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&se(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=Ol(e,n,o,a,d[t]);u.push(vn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(El(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(oc(e,s,i,n,o),f++)}return f}}function cc(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of ae(t).cumulativePaths)if(n.has(e))return!0;return!1}const dc=/^\$\d+$/,uc=`${Y}${c}`,fc=`${Q}${c}`,hc=new WeakMap;function pc(e,t,n,o){const s=M[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&dc.test(t)&&se(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${C}1 to ${C}128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&se(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack,n=e?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=e?.listIndex;null==r&&se(`ListIndex not found: ${t.toString()}`);let i=s;const a=e.pathInfo,l=o.stateElement?.addressHooks;if(l){const t=l.indexShift;for(let n=0;n<t.length;n++)i+=t[n](o,e)}const c=on(r,i,a.wildcardCount);return c?.index??se(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,t,n,e);if(i!==hl)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>ic(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>lc(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=Il(t),i=ac(e,r,n,o),a=vn(r.pathInfo,i),l=Xt(s,a),c=or();c.enqueueAbsoluteAddress(l),Kl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Xt(s,e);Us(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>rc(e,0,n,o)(t,s,...r);case"$dependOn":case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] ${String(t)}("${e}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&se(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??se("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==e&&s.addDynamicDependency(e,n.path)}}(0,t,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(cc(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&$r(o.stateElement,e),Object.is(n[e],t);let r;o.beginUntrack();try{r=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&vr(o.stateElement,e,t,Xt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=cc(o.stateElement,e);let i,a=r?n[e]:void 0;o.beginUntrack();try{r||(a=n[e]),i=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?$r(o.stateElement,e):vr(o.stateElement,e,i,Xt(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||se(`$eqIndex("${e}") needs a list row scope.`);const r=on(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&se(`$eqIndex("${e}", ${t}): no list index at that level.`),cc(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&$r(o.stateElement,e),Object.is(n[e],r.index);const i=t===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[e],i&&(l=n[s.pathInfo.wildcardParentPaths[t-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const t=i?zs(l):null;null!==t?function(e,t,n,o,s){lr=!0,pr(e).lastValue.set(t,s),hr(e,t);let r=cr.get(e);void 0===r&&cr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=dr.get(o);void 0===l?dr.set(o,l=[]):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a&&(a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a)),a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){lr=!0;const r=pr(e);hr(e,t),br(r,t,s,o,yr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Xt(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untracked":case"$untrackDependency":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case F:return fl(o.stateElement)}if(!t.startsWith(uc)&&!t.startsWith(fc))return}const r=Il(t),i=ac(e,r,n,o),a=vn(r.pathInfo,i);return El(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=hc.get(e);return void 0===t&&(t=new Map,hc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Rt:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&se("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case jt:i=t=>El(e,t,n,o);break;case Lt:i=t=>Dl(e,t,n,o);break;case Wt:i=(t,s)=>oc(e,t,s,n,o);break;case Dt:i=()=>async function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Bt:i=()=>function(e,t,n){const o=Reflect.get(e,R);"function"==typeof o&&o.call(n)}(e,0,n);break;case zt:i=t=>function(e,t,n,o){const s=Reflect.get(e,j);let r;if("function"==typeof s){const e=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,s=t.path;if(-1===s.indexOf("#")&&(e.add(s),t.wildcardCount>0)){const e=sn(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}r=s.call(n,Array.from(e),i)}const i=o.stateElement?.addressHooks;if(i){const e=i.updated;for(let s=0;s<e.length;s++)e[s](o.stateElement,t,n)}return r}(e,t,n,o);break;case Ft:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,L);"function"==typeof s&&s.call(o,t,n)}(e,t,o,n);break;default:return Reflect.get(e,t,n)}return s.set(t,i),i}}class gc{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=xa(e);null===n&&se("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&se("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=f&&(this._hasRepeatedAddress()&&se(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),se(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=e}_hasRepeatedAddress(){const e=new Set;for(let t=0;t<=this._addressStackIndex;t++){const n=this._addressStack[t];if(n){if(e.has(n))return!0;e.add(n)}}return!1}_tailAddressPaths(){const e=[];for(let t=this._addressStackIndex;t>=0&&e.length<8;t--){const n=this._addressStack[t];n&&e.push(n.pathInfo.path)}return e}_describeAddressCycle(){const e=this._tailAddressPaths();return`${Array.from(new Set(e)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&se(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return pc(e,t,n,this)}set(e,t,n,o){return xl(this),function(e,t,n,o,s){if("string"==typeof t){const r=Il(t),i=ac(e,r,o,s);return oc(e,vn(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}}const mc=Promise.resolve(),yc=new Map;let wc=[];function bc(e,t){yc.set(e,t),wc=Array.from(yc.values()).sort((e,t)=>e.order-t.order)}function vc(e,t){return se(ga(e,t))}const $c="undefined"==typeof HTMLElement?class{}:HTMLElement;function xc(e){const t=[];let n=e;for(;n&&n!==Object.prototype;)t.push(n),n=Object.getPrototypeOf(n);const o={};for(let e=t.length-1;e>=0;e--)Object.assign(o,Object.getOwnPropertyDescriptors(t[e]));return o}let Sc=null;const Pc=new Set(["for","if","elseif","else"]);function Ic(e,n,o){const s=new Map;for(const e of o){const t=ae(e);if(null===t.lastWildcardPath)continue;const n=s.get(t.lastWildcardPath);void 0===n?s.set(t.lastWildcardPath,[t]):n.push(t)}const r=[],i=new Set,a=t=>{const n=Xt(e,t);if(i.has(n))return;i.add(n);const o=mn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(vn(n,t.listIndex))}};Et();try{if(e.createState("readonly",t=>{for(const o of n){const n=vn(ae(o),null);a(n);try{Kl(e,n,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",a)}catch{}}}),0===r.length)return;const o=function(e){const t=[],n=[];for(const o of e)Pc.has(o.bindingType)?t.push(o):n.push(o);return t.sort((e,t)=>0!==(e.replaceNode.compareDocumentPosition(t.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),t.concat(n)}(r),s=()=>{ca(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Js("state",s);void 0!==i&&i.catch(er)}finally{Mt()}}class Ac extends $c{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Sa(e)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new sl}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&se(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){ll(e);const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[z];if(void 0===n)return t;Array.isArray(n)||se(`${z} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||se(`${z} entries must be non-empty strings.`),e===F&&se(`${z} entry "${e}" conflicts with the reserved namespace name "${F}".`),t.has(e)&&se(`${z} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[q];if(void 0===n)return t;Array.isArray(n)||se(`${q} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||se(`${q} entries must be non-empty strings.`),t.has(e)&&se(`${q} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[X];if(void 0===t)return null;"object"==typeof t&&null!==t||se(`${X} must be an object mapping list paths to key specs.`);const n=new Map;for(const[e,o]of Object.entries(t)){0===e.length&&se(`${X} entry path must be a non-empty string.`);const t=e.split(c);t.some(e=>0===e.length)&&se(`${X} entry "${e}" must not contain empty path segments.`),t[t.length-1]===d&&se(`${X} entry "${e}" must be the list path itself, not the element path (drop the trailing "${c}${d}").`),-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] ${X} entry "${e}" uses "${J}", which ${X} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${c}${d}${c}children").`),"function"!=typeof o?("string"!=typeof o&&se(`${X} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&se(`${X} entry "${e}" key field name must be a non-empty string.`),(o.includes(c)||o.includes(d))&&se(`${X} entry "${e}" key field name "${o}" must be a flat property name ("${c}" / "${d}" are not allowed).`),o in Object.prototype&&se(`${X} entry "${e}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(e,o)):n.set(e,o)}return n.size>0?n:null}(e);var i;n.set("eventTokenNames",s),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&Sc?.reset(this),this._hasUpdatedCallback=j in e,this._hasErrorCallback=L in e,i=this,On.delete(i),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[V];if(void 0!==o){"object"==typeof o&&null!==o||se(`${V} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||se(`${V} entry "${t}" is not declared in $eventTokens.${de(t,n)}`),"function"!=typeof s&&se(`${V} entry "${t}" must be a function.`),Rn(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const a=function(e){const t=new Set,n=new Set,o=xc(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterPaths:t,setterPaths:n}}(e);for(const e of a.getterPaths)this._getterPaths.add(e);for(const e of a.setterPaths)this._setterPaths.add(e);!function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].register?.(e,t,n)}(this,e,n),$l(this,null),this._resolveLoading?.()}attributeChangedCallback(e,t,n){this._initialized&&t!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===t?"absent":`"${t}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?ya('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){se("Failed to parse JSON from script element:"+e)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const e=this.getAttribute("json");return JSON.parse(e)}{const e=this.querySelector('script[type="module"]');if(e)return await nl(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){try{const t=await fetch(e);return t.ok||se(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e);if(e&&e.endsWith(".js"))return await ol(e);se(`Unsupported src file type: ${e}`)}}catch(e){se(`Failed to initialize state: ${e}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,n]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=n}return await this._loadingPromise,null!==this._rootNode&&(Aa(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),se(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===xa(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),ba.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<wc.length;o++)wc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{O in e&&await e[Dt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{R in e&&e[Bt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<wc.length;t++)if(!0===wc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||xa(this._rootNode)===this||Aa(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const e=function(e){for(let t=0;t<wc.length;t++){const n=wc[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(Z))try{vc("dcc",`a <${o.tagNames.state}> inside a [${Z}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{vc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<wc.length;t++){const n=wc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&vc("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let s=!1;try{s=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!s)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const e=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(e)}if(this.hasAttribute("enable-ssr")&&!t()||e!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await ya('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}$l(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<wc.length;t++)if(!0===wc[t].disconnecting?.(e))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(e,t){for(let n=0;n<wc.length;n++)wc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Aa(this.rootNode,null),e=this,ul.delete(e),function(e){for(let t=0;t<bl.length;t++)bl[t].deactivate?.(e)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(e=>(ll(e),e))}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t,this.attachAddressHooks("watch",U)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&se(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),t.set(n,o);this._listKeys=t}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(e){this._listPaths.add(e)}findStateDescriptor(e){return zi(this._state,e)}defineTreeAccessor(e,t){Object.defineProperty(this._state,e,t),"function"==typeof t.get&&this._getterPaths.add(e),"function"==typeof t.set&&this._setterPaths.add(e),this.setPathInfo(e,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&se("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(e,t){const n=function(e,t){const n=gl.get(e);return void 0===n&&se(ga(e,`"${t}"`)),n}(e,t);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(e,t){for(let n=0;n<pl.length;n++){const o=pl[n],s=t[o];if(void 0===s)continue;const r=e[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(e){this.attachAddressHooks("scopes",e)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e,this.attachAddressHooks("dcc",D)}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){return this._addDependency(this._dynamicDependency,e,t)}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+d)),!this._pathSet.has(e)){const t=ae(e);if(this._pathSet.add(e),Sc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ae(e.parentPath)}}}_rebuildPathInfo(){for(const[e,t]of Array.from(this._pathRegistrations))t.bound&&!this._generatedPaths.has(e)&&this.setPathInfo(e,t.bindingType)}_createState(e,t,n){try{const o=function(e,t,n){const o=new gc(e,n);return new Proxy(t,o)}(e,this._state,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(e){this._indexDependentGetterPaths.add(e)}setInitialState(e){if(!this._initialized)return this._initializeFailed&&se(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);!function(e){for(let t=0;t<wc.length;t++)wc[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&se("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const t=this.__state;this._state=e;const n=function(e){const t=new Set;for(const n of e)if(void 0!==n)for(const[e,o]of Object.entries(xc(n)))e.startsWith("$")||e.includes(d)||"function"==typeof o.value||t.add(e);return t}([t,e]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(e){Ic(this,e,this._pathRegistrations.keys())}}const Nc=[];function kc(e=customElements){for(let t=0;t<Nc.length;t++)Nc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,Ac)}function _c(e){if("string"==typeof e?.locale)return e;const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}function Tc(e,t){const o=_c(e);var s;o&&((s=o).tagNames&&Object.assign(n.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(n.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(n.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(n.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(n.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(n.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(n.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(n.locale=s.locale),"boolean"==typeof s.debug&&(n.debug=s.debug),"boolean"==typeof s.enableMustache&&(n.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(n.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(n.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(n.sameValueGuard=s.sameValueGuard)),kc(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=Za)}()}function Cc(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function Ec(e,t){for(const n of e)if(Cc(t,n.innerSegments))return n;return null}function Mc(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+c+n.join(c)}let Oc=0;const Rc=["$watch",H,"$scan","$listKeys",j,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],jc=new Set;function Lc(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function Wc(e,t,n,o,s,r=new Set){0===n.length&&se(`Cannot build a mount record without host bindings for "${t}".`),ll(s);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(c);a.has(n)&&se("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(y)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++Oc,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)e.innerSegments.length>0&&p.add(e.innerSegments[0]);const g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?u:l.outerPathInfo.path+c+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function Dc(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function Bc(e,t){const n=Ec(e.entries,t);return null===n?null:Mc(n,t)}function zc(e,t){return e.markerBasePath+c+t}function Fc(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+c+n;s.set(n,{accessorName:o,indexShift:ae(r).wildcardCount-ae(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function qc(e,t){return!e.injectedKeys.has(t)&&!e.mappedKeys.has(t)&&("function"==typeof e.stateObject[t]&&!e.getterKeys.has(t)||Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t))}function Vc(e,t){return`Path "${t}" in <${e.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${e.entries.filter(e=>e.innerSegments.length>0).map(e=>e.innerSegments.join(c)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${Dc(t)}: path") or declare the key on the component state.`}const Hc=/^\$(\d+)$/;function Uc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=Dc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||qc(e,o))return null;const s=function(e,t){return Ec(e.entries,t)}(e,t.split(c));return null!==s&&s.readonly?s:null}function Gc(e,t){const n=Uc(e,t);if(null!==n){const o=0===n.innerSegments.length?"":c+n.innerSegments.join(c);se(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${y}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${y} from the mount.`)}return Kc(e,t)}function Kc(e,t){const n=t[0];if("$"===n||"#"===n)return t;if(e.getterKeys.has(t)||e.setterKeys.has(t))return function(e,t){const n=t.split(c);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===d){o=e;break}if(-1===o)return Fc(e,e.markerBasePath,t,t),zc(e,t);if(qc(e,n[0]))return Fc(e,e.markerBasePath,t,t),zc(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Bc(e,s);null===i&&se(Vc(e,t)),0===r.length&&se(`Wildcard-terminal accessor "${t}" on mounted <${e.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const a=i+c+e.marker;return Fc(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=Dc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return zc(e,t);if(qc(e,o))return zc(e,t);const s=Bc(e,t.split(c));if(null!==s)return s;se(Vc(e,t))}function Jc(e,t,n){let o;const s=Hc.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ae(Kc(e,t)).wildcardCount-ae(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Kc(e,t.statePathName),"for"===t.bindingType){const n=ae(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+c+d,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(y)&&null!==Uc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ae(o),...i?{propModifiers:[...r,y]}:{}}:t}function Xc(e,t,n,o,s){if(void 0===o)return;const r=ae(n).wildcardCount-ae(t).wildcardCount;return 0===r?o:(s.length<r&&se(`Cannot resolve "${t}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const Yc=new WeakMap,Qc=new WeakMap;const Zc=new WeakMap;const ed=new FinalizationRegistry(function(e){const t=e.byMarker.get(e.marker);if(void 0!==t&&void 0===t.deref()&&e.byMarker.delete(e.marker),void 0!==e.getterPaths)for(const t of e.addedGetterPaths)e.getterPaths.delete(t)}),td=new WeakMap;function nd(e){return td.get(e)??null}let od=!1;function sd(){od||(od=!0,bt=e=>Yc.has(e)?e.host:null)}function rd(e){const t=Zc.get(e);if(void 0===t)return[];const n=[];for(const e of t.values()){const t=e.deref();void 0!==t&&n.push(t)}return n}function id(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Zc.get(e);if(void 0===o)return null;const s=t.indexOf(c,n),r=-1===s?t.slice(n):t.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const ad="3.2.0",ld=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function cd(e,t,n,o){return{node:e,propName:t.propName,statePathName:t.statePathName,bindingType:t.bindingType,inFilters:t.inFilters,outFilters:t.outFilters,origin:n,raw:o}}function dd(e){const t=function(e){const t=sr.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:cr.get(e)}}(e);if(null===t)return[];const n=new Set([...t.byPath.keys(),...t.tracked]);if(void 0!==t.watchers)for(const e of t.watchers.keys())n.add(e);const o=[];for(const e of[...n].sort()){const n=t.byPath.get(e);let s=0;if(void 0!==n)for(const e of n.values())s+=e.size;o.push({path:e,tracked:t.tracked.has(e),rows:s,keys:n?.size??0,lists:t.watchers?.get(e)?.size??0,lastValue:t.lastValue.get(e)})}return o}const ud="__WCSTACK_DEVTOOLS_HOOK__";function fd(){const e=globalThis,t=e[ud];if(void 0!==t)return 2!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 2. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:2,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[ud]=n,n}const hd=e=>{null!==xt&&xt({type:"state:update-batch",addresses:e})};function pd(e){const t=null!==xt;!function(e){xt=e}(e);const n=null!==e;n&&!t?Zs(hd,0):!n&&t&&function(e){const t=Xs.findIndex(t=>t.listener===e);-1!==t&&Xs.splice(t,1)}(hd)}function gd(e){return{rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency,watchPaths:e.watchPaths??null,keyedListPaths:void 0===e.listKeys||null===e.listKeys?null:new Set(e.listKeys.keys())}}function md(e){return xa(e)??se("devtools: no state tree on this root")}let yd=null;function wd(){if(t())return;if(null!==yd)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:ad,getStateElements(){const e=[];for(const t of va)e.push(gd(t));return e},overlays:e=>rd(md(e)).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join("."),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]})),keyedSubscriptions:e=>dd(md(e)),keys(e){const t=md(e),n=[];return t.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}n.push(t)}}),n},read(e,t,n){let o;return md(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){md(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>function(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=[...e.inFilters,...e.outFilters].map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=_a(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(cd(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=st(t,Re(n));for(const o of e)r(cd(t,o,"attribute",n))}catch{}continue}const t=ld.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=_a(s);if(null===a){if(n===o.commentTextPrefix)try{r(cd(e,Be(s),"comment",s))}catch{}}else r(cd(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:pd};yd=e,fd().register(e)}const bd={name:"devtools",install(){wd()}},vd=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),$d=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const xd=new WeakMap;const Sd=new WeakMap,Pd=new WeakSet,Id=new WeakMap;function Ad(e,t,n,o){console.warn(`[@wcstack/state] [${qi[n]}] ${Vi[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${de(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ue}`),null!==xt&&xt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Nd={check:function(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=e.addressHooks;if(s){const t=s.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const r=ae(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=xd.get(e);return void 0===n&&(n=new Set,xd.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const i=function(e,t,n){if(void 0!==zi(e,t))return $d;const o=ae(t).segments;let s=e,r="";for(let t=0;t<o.length;t++){const i=o[t],a=r;if(r=0===t?i:r+c+i,t>0&&t<o.length-1&&void 0!==zi(e,r))return vd;if(Object(s)!==s)return vd;if(i===d){if(!Array.isArray(s)||0===s.length)return vd;s=s[0];continue}const l=zi(s,i);if(void 0===l)return{existence:"missing",missingSegment:i,candidates:Fi(s,a,n)};if("function"==typeof l.get)return t===o.length-1?$d:vd;s=l.value}return $d}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===Id.get(e)?.has(t)}(e,n)||("binding"!==o?Ad(e,n,o,i):function(e,t,n){let o=Sd.get(e);void 0===o&&(o=new Map,Sd.set(e,o));if(o.set(t,n),Pd.has(e))return;Pd.add(e),setTimeout(()=>function(e){Pd.delete(e);const t=Sd.get(e);if(void 0===t)return;Sd.delete(e);for(const[n,o]of t)Ad(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){xd.delete(e),Sd.delete(e)},markExported:function(e,t){let n=Id.get(e);void 0===n&&(n=new Set,Id.set(e,n)),n.add(t),Sd.get(e)?.delete(t)}};let kd=!1;function _d(){kd||(kd=!0,function(e){Sc=e}(Nd))}const Td={name:"diagnostics",install(){_d()}};function Cd(e){se(`filter ${e} requires at least one option`)}function Ed(e){se(`filter ${e} requires a number as option`)}function Md(e){se(`filter ${e} requires a number value`)}function Od(e){se(`filter ${e} requires a date value`)}const Rd={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function jd(e){return!(!e||isNaN(Number(e)))}const Ld={eq:(e,t)=>{const n=e?.[0]??Cd("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(jd(n)||Ed("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Cd("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(jd(n)||Ed("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>("boolean"!=typeof e&&se(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??Cd("lt");return jd(t)||Ed("lt"),e=>("number"!=typeof e&&Md("lt"),e<Number(t))},le:e=>{const t=e?.[0]??Cd("le");return jd(t)||Ed("le"),e=>("number"!=typeof e&&Md("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??Cd("gt");return jd(t)||Ed("gt"),e=>("number"!=typeof e&&Md("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??Cd("ge");return jd(t)||Ed("ge"),e=>("number"!=typeof e&&Md("ge"),e>=Number(t))},add:e=>{const t=e?.[0]??Cd("add");return jd(t)||Ed("add"),e=>("number"!=typeof e&&Md("add"),e+Number(t))},sub:e=>{const t=e?.[0]??Cd("sub");return jd(t)||Ed("sub"),e=>("number"!=typeof e&&Md("sub"),e-Number(t))},mul:e=>{const t=e?.[0]??Cd("mul");return jd(t)||Ed("mul"),e=>("number"!=typeof e&&Md("mul"),e*Number(t))},div:e=>{const t=e?.[0]??Cd("div");return jd(t)||Ed("div"),e=>("number"!=typeof e&&Md("div"),e/Number(t))},mod:e=>{const t=e?.[0]??Cd("mod");return jd(t)||Ed("mod"),e=>("number"!=typeof e&&Md("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&Md("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??Cd("clamp");jd(t)||Ed("clamp");const n=e?.[1]??Cd("clamp");jd(n)||Ed("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&Md("clamp"),Math.min(Math.max(e,o),s))},toFixed:e=>{const t=e?.[0]??"0";return jd(t)||Ed("toFixed"),e=>("number"!=typeof e&&Md("toFixed"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Md("locale"),e.toLocaleString(t??o.locale))},upper:e=>e=>String(e).toUpperCase(),lower:e=>e=>String(e).toLowerCase(),capitalize:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??Cd("slice");jd(n)||Ed("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(jd(o)||Ed("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??Cd("substr");jd(t)||Ed("substr");const n=e?.[1]??Cd("substr");return jd(n)||Ed("substr"),e=>String(e).substr(Number(t),Number(n))},padStart:e=>{const t=e?.[0]??Cd("padStart");jd(t)||Ed("padStart");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},padEnd:e=>{const t=e?.[0]??Cd("padEnd");jd(t)||Ed("padEnd");const n=e?.[1]??" ";return e=>String(e).padEnd(Number(t),n)},repeat:e=>{const t=e?.[0]??Cd("repeat");return jd(t)||Ed("repeat"),e=>String(e).repeat(Number(t))},reverse:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??Cd("truncate");jd(t)||Ed("truncate");const n=Number(t),o=e?.[1]??"…";return e=>{const t=String(e);return t.length<=n?t:t.slice(0,n)+o}},join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||se(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=e?.[0]??"0";return jd(t)||Ed("round"),e=>{"number"!=typeof e&&Md("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return jd(t)||Ed("floor"),e=>{"number"!=typeof e&&Md("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return jd(t)||Ed("ceil"),e=>{"number"!=typeof e&&Md("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return jd(t)||Ed("percent"),e=>("number"!=typeof e&&Md("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??Cd("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Od("ymd");const n=e.getFullYear().toString(),o=(e.getMonth()+1).toString().padStart(2,"0"),s=e.getDate().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},hms:e=>{const t=e?.[0]??":";return e=>{e instanceof Date||Od("hms");const n=e.getHours().toString().padStart(2,"0"),o=e.getMinutes().toString().padStart(2,"0"),s=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!e,truthy:e=>e=>!!e,defaults:(e,t)=>{const n=e?.[0]??Cd("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Cd("coalesce"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e??o},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),nullIfEmpty:e=>e=>""===e?null:e},Wd={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},Dd=Ld,Bd=Ld;let zd=!1;const Fd={name:"formats",install(){zd||(zd=!0,we("input",Bd,Wd,Rd),we("output",Dd,Wd,Rd))}};function qd(e){return-1!==e.indexOf(J)}function Vd(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+c;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(qd(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function Hd(e){return 0===e.length?e:c+Kd(e.slice(1))}function Ud(e,t,n){const o=c+e.repeat,s=t.length<=n.length?t:n,r=t.length<=n.length?n:t;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let e=0;e<i.length;e+=o.length)if(!i.startsWith(o,e))return!1;return!0}function Gd(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(Ud(e,t,n.slice(0,o)))return!0;return!1}function Kd(e){const t=e.split(c);for(let e=0;e<t.length;e++)t[e]===d||Number.isNaN(Number(t[e]))||(t[e]=d);return t.join(c)}function Jd(e,t){const n=e.repeat.split(c),o=c+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===c+e.repeatList+c+"length")return!0;for(let e=1;e<n.length;e++)if(s===c+n.slice(0,e).join(c))return!0;return!1}function Xd(e,t,n){n<0&&se(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=c+e.repeat;const s=o+t;let r=0;for(const e of s.split(c))e===d&&r++;return r>u&&se(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function Yd(e,t){return Xd(e,"",t)}function Qd(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const o=n.slice(e.anchor.length,n.length-t.length);if(0===o.length)return 0;const s=c+e.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function Zd(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=t.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const o=c+n.repeat;let s=0,r=n.anchor.length;for(;t.startsWith(o,r);)r+=o.length,s++;return r!==t.length&&46!==t.charCodeAt(r)?null:s}(t,n.pathInfo.path)}function eu(e,t,n){const o=e.recursionRegistry,s=Vd(o.spec,n);null===s&&se(Ui(n,o.spec.recursiveAnchor));const r=Zd(t,o);return null===r&&se(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function tu(e,t,n,o,s){const r=o.spec,i=[],a=new Map,l=[],d=r.repeatList,u=r.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void i.push(vn(e,n));const s=g(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function g(o,s,i){const l=vn(o,s),c=Xt(n.stateElement,l),u=El(e,l,t,n),h=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&se(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&se(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${d}" array.`),o})(o.path,u,i),p=Mr(s,Tt(c),u);return a.set(c,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=l[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:ae(n),childListPathInfo:ae(r+c+d)};return l[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(vn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,ae(u),null);for(const[e,t]of a)Ct(e,t);return i}function nu(e,t,n,o,s,r,i){xl(n);const a=n.stateElement.recursionRegistry,l=Vd(a.spec,o);null===l&&se(Ui(o,a.spec.recursiveAnchor));const c=Hd(l);Array.isArray(s)||se(Gi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&se(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&se(Gi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&se(Gi(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(e,t,n){Jd(e,n)&&se(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const d=a.conflictingRecursiveGetter(c);null!==d&&se(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${d}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const u=tu(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(oc(e,u[o],r,t,n),f++);return f}const ou={write(e,t){if(!0!==e.hasRecursion)return hl;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&se(`[wcs/recursion-readonly] "${t.pathInfo.path}" writes into the recursive getter "${n}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),hl},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return hl;if("$getAll"===t)return(t,s)=>{if(qd(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Vd(r.spec,o);null===i&&se(Ui(o,r.spec.recursiveAnchor)),Array.isArray(s)||se(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&se(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=tu(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(El(e,a[o],t,n));return l}(o,n,e,t,s);t=eu(e.stateElement,e,t)}return ic(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>qd(t)?nu(o,n,e,t,s,r,i):lc(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&qd(t)){const s=Il(eu(e.stateElement,e,t)),r=ac(o,s,n,e);return El(o,vn(s.pathInfo,r),n,e)}return hl}};let su=!1;function ru(e,t){"string"==typeof t&&0!==t.length||se(`[wcs/recursion-declaration-invalid] ${K} ${e} must be a non-empty string.`);const n=t.split(c);n.some(e=>0===e.length)&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain empty path segments.`),n.length<2&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must name a list element: a property path ending with "${c}${d}" (for example "nodes${c}${d}").`),n[n.length-1]!==d&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must end with "${c}${d}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===d&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must have exactly one "${d}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===J&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain "${J}" — the declaration is what gives "${J}" its meaning.`),isNaN(Number(n[o]))||se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const iu=new WeakSet;function au(e){return"function"==typeof e.get&&iu.has(e.get)}function lu(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&au(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}!function(e,t,n){for(const o of n){const n=ae(o),s=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void Hs(Yt(e,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=t;for(const e of s[i].segments.slice(a))l=l?.[e];if(!Array.isArray(l))return;const c=zs(l);if(null===c)return;const d=Math.min(c.length,l.length);for(let e=0;e<d;e++)r(l[e],c[e],i+1)};r(t,null,0)}}(e,t,n)}}const cu="[wcs/recursion-declaration-invalid]";class du{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(e,t){this.spec=e;const n=xc(t);for(const[t,o]of Object.entries(n)){if(!qd(t))continue;"function"==typeof o.set&&se(`${cu} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&se(`${cu} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Vd(e,t);null===n&&se(Ui(t,e.recursiveAnchor)),0===n.length&&se(`${cu} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),Jd(e,Hd(n))&&se(`${cu} "${t}" names the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${e.recursiveAnchor}${c}total").`),this._definitions.set(t,{recursivePath:t,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(qd(t)||au(n))continue;const e=this._matchExpansion(t);null!==e&&se(`${cu} "${t}" is already defined on the state, so the recursive getter "${e}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const e=Array.from(this._definitions.values());for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)Ud(this.spec,e[t].suffix,e[n].suffix)&&se(`${cu} "${e[t].recursivePath}" and "${e[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(e){for(const t of this._definitions.values())if(Gd(this.spec,t.suffix,e))return t.recursivePath;return null}recursiveGetterOwningPath(e){const t=this._ownerByPathInfo.get(e);if(void 0!==t)return t;const n=this.recursiveGetterOwning(e.path);return this._ownerByPathInfo.set(e,n),n}recursiveGetterOwning(e){const t=this._accessors.get(e);if(void 0!==t)return t.recursivePath;const n=Kd(e),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let e=n.lastIndexOf(c);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(c,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==Qd(this.spec,t.suffix,e))return t.recursivePath;return null}materializeForPathInfo(e,t){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(t);if(void 0!==n)return n;const o=this.materializeFor(e,t.path);return this._accessorByPathInfo.set(t,o),o}materializeFor(e,t){const n=this._accessors.get(t);if(void 0!==n)return n;if(!t.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const e of this._definitions.values()){const n=Qd(this.spec,e.suffix,t);null!==n&&(null!==o&&se(`"${t}" matches both "${o.recursivePath}" and "${e.recursivePath}".`),o=e,s=n)}return null===o?null:this._define(e,o,s,t)}_define(e,t,n,o){const s=e.findStateDescriptor(o);void 0===s||au(s)||se(`"${o}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:t.recursivePath,depth:n}),i=t.get,a=function(){return i.call(this)};var l;return l=a,iu.add(l),e.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(e,n),this._accessors.set(o,r),r}_registerListPaths(e,t){for(const n of function(e,t){const n=[];n.push(e.anchorList);for(let o=0;o<t;o++)n.push(Yd(e,o)+c+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return lu(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let o=n[t];return void 0===o&&(o=Xd(this.spec,e,t),n[t]=o),o}accessorFor(e){return this._accessors.get(e)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const uu="recursionSpec",fu="recursionRegistry",hu={order:5,validateEarly(e,t,n){const o=function(e){const t=e[K];if(void 0===t)return null;"object"==typeof t&&null!==t||se(`[wcs/recursion-declaration-invalid] ${K} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&se(`[wcs/recursion-declaration-invalid] ${K} must declare exactly one anchor; it is empty.`),n.length>1&&se(`[wcs/recursion-declaration-invalid] ${K} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];ru("anchor",o),"string"!=typeof s&&se(`[wcs/recursion-declaration-invalid] ${K} entry "${o}" must map to the repeating sub-path as a string (for example "children${c}${d}").`),ru("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(c)),i=s.slice(0,s.lastIndexOf(c)),a=r+c+J;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(uu,o),n.set(fu,null===o?null:new du(o,t))},preCommit(e,t,n){const o=e.recursionRegistry;if(null!==o)for(const t of o.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(fu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",K)},apply(e,t,n){const o=n.get(uu)??null;null!==o&&e.addListPath(o.anchorList)}};let pu=!1;function gu(){pu||(pu=!0,su||(su=!0,ml("recursion",ou)),vl("recursion",hu))}const mu={name:"recursion",install(){gu()}};const yu={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let wu=!1;function bu(e){return function(){const t=this.stateElement;if(!t)return;if(!0!==t.initialized)return;let n;try{t.createState("readonly",t=>{n=t[e]})}catch(t){return void console.warn(`[@wcstack/state] DCC getter "${e}" failed:`,t)}return n}}function vu(e){return function(t){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})}):n.createState("writable",n=>{n[e]=t}))}}function $u(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[e](...t)}).then(()=>o)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[e](...t)}),o})}}function xu(e){return e.startsWith("$")}function Su(e,t){return Object.keys(e).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof e[n].value;return"method"===t?o:!o})}function Pu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||se(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||se(`${t} entries must be non-empty strings.`),e.startsWith("$")&&se(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&se(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Iu(e){ll(e);const t=Pu(e,D)??[],n=Pu(e,B)??[],o=xc(e),s=function(e){const t=e[H];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),r=[];for(const e of t){const t=o[e];if(void 0===t){if(s.has(e)){r.push(e);continue}se(`${D} entry "${e}" is not declared on the state.${de(e,Su(o,"value"))}`)}"function"==typeof t.value&&se(`${D} entry "${e}" is a method. Declare it in ${B} instead.`)}for(const e of n){const t=o[e];void 0===t&&se(`${B} entry "${e}" is not declared on the state.${de(e,Su(o,"method"))}`),"function"!=typeof t.value&&se(`${B} entry "${e}" is not a method. Declare it in ${D} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function Au(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||se(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Je(e);null!==r&&"function"==typeof r.define||se(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&se(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=Iu(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,g=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(Z))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=Je(this._shadow);return null!==e&&Xe(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(wu||(wu=!0,ml("dcc",yu)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${D} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=xc(n);for(const[e,t]of Object.entries(m)){if(xu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=$u(e,o)}else n.get=bu(e),n.set=vu(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:bu(e),set:vu(e)});r.define(s,g)}async function Nu(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&se(`"bind-component" cannot be used inside a [${Z}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){try{if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await ol(t);se(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await nl(n,t.tagName.toLowerCase());se(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){se(`DCC: Failed to load state: ${e}`)}}(o,t);Au(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const ku={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Z)?Nu(e,t.host,t):null}};let _u=!1;const Tu=new WeakMap;function Cu(e,t,n){let o=Tu.get(e);void 0===o&&(o=new Map,Tu.set(e,o));const s=o.get(t);null!=s&&se(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function Eu(e,t){if(null===e)return!1;const n=Tu.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+c)||e.startsWith(t+c))return!0;return!1}const Mu=new WeakMap;const Ou=[];function Ru(e,t,n,o){if(t.length>0){const s=n.split(c),r=Ec(t,s);if(null!==r)return o&&r.readonly&&se(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${A}.${r.innerSegments.join(c)}#${y}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${y} from the injection.`),Mc(r,s)}return e+c+n}function ju(e,t,n){for(const e of t){const t=e.outerPathInfo.path;if(n===t)return e.innerSegments.join(c);if(n.startsWith(t+c))return e.innerSegments.join(c)+n.slice(t.length)}return n===e?"":n.startsWith(e+c)?n.slice(e.length+1):null}function Lu(e,t,n=Ou){return new Proxy({},{get(o,s){if("string"==typeof s&&"then"!==s){if("$"===s[0]){if("$postUpdate"===s||"$getAll"===s){const o=s;return(s,...r)=>t[o](Ru(e,n,s,!1),...r)}return"$setAll"===s?(o,...s)=>t.$setAll(Ru(e,n,o,!0),...s):"$resolve"===s?(o,...s)=>t.$resolve(Ru(e,n,o,s.length>1),...s):t[s]}return t[Ru(e,n,s,!1)]}},set:(o,s,r)=>("string"!=typeof s||(t[Ru(e,n,s,!0)]=r),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Wu=new WeakMap,Du=[];const Bu=new WeakMap,zu=new WeakSet;function Fu(e){console.error(`[@wcstack/state] volume "${e.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),e.onGrafted(null)}let qu=null;const Vu=new WeakMap,Hu=new Set;function Uu(e,t,n,o){let s=Vu.get(e);if(void 0===s){if(!o)return null;s=new Map,Vu.set(e,s)}let r=s.get(t);if(void 0===r){if(!o)return null;r=new Map,s.set(t,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function Gu(e,t){if(!e.component.isConnected)return!1;const n=vt(e.component)?.listIndex??null;if(null===t)return null===n;let o=n;for(;null!==o;){if(o===t)return!0;o=o.parentListIndex}return!1}function Ku(e,t,n,o){const s=Uu(e,t,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&Gu(n,t)?n:null}(r,o);if(null!==e)return{record:e,entry:r.entry}}let i=null,a=null;for(const e of s.holders){const r=e.ref.deref();void 0!==r?Gu(r,o)&&(null!==a&&se(`[wcs/mount-export-ambiguous] "${t}${c}${n}" is exported by two mounted components on the same instance: <${a.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=e,a=r):s.holders.delete(e)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function Ju(e){const t=e.parentStateElement,n=vt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Rt](n,()=>{e.$postUpdate(o.exportedPath)})})}const Xu=new WeakMap;class Yu{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return vn(ae(this.markerParentPath+c+e),this.listIndex)}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(Kc(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Gc(e,t):Kc(e,t),a=Xc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Gc(e,t):Kc(e,t),l=Xc(0,t,a,r,n);return o[s](a,l,...i)}}return this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return Nl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[Kc(this.record,t)]}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n);const s=this.accessorNameFor(t);if(void 0!==s){this.record.setterKeys.has(s)||se(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(t)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(e,t)?(e[t]=n,!0):(this.receiver[Gc(this.record,t)]=n,!0)}has(e,t){if("string"!=typeof t)return Reflect.has(e,t);if("$"===t[0]||"#"===t[0])return!1;if(void 0!==this.accessorNameFor(t))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return!0;if("function"==typeof this.record.stateObject[t])return!0}try{return Kc(this.record,t),!0}catch{return!1}}}function Qu(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Xu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Xu.set(e,n)),null===t)return n.noIndex??={...e.privateSnapshot};let o=n.byListIndex.get(t);return void 0===o&&(o={...e.privateSnapshot},n.byListIndex.set(t,o)),o}(e,t.listIndex):{};return new Proxy(i,new Yu(e,s,t.listIndex,r,n,o))}function Zu(e){const t=e.parentStateElement,n=(t,n)=>{const o=vt(e.component);let s;return t[Rt](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(Kc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Gc(e,n):Kc(e,n),l=vt(e.component)?.listIndex.indexes??[],c=Xc(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:Kc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Gc(e,s)]=r})}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return Kc(e,n),!0}catch{return!1}}})}function ef(e,t){const n=function(e){return Yc.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&se(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&ps(t).dispose(),function(e,t){sd(),Yc.set(e,t),td.set(t,e);let n=Zc.get(t.parentStateElement);void 0===n&&(n=new Map,Zc.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Qc.get(t.component);void 0===o&&(o=new Map,Qc.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&ed.register(t,{byMarker:n,marker:t.marker,getterPaths:t.parentStateElement.getterPaths,addedGetterPaths:t.addedGetterPaths}),t.parentStateElement.markHasMounts?.()}(t,e),t instanceof ShadowRoot&&function(e,t){const n=wa.get(e);if(void 0!==n){if(n===t)return;se("A state tree is already registered on this root.")}wa.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Jc(e,t,n);ne(t);const o=vt(e.component);Ua(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),da(t,o,n)}(e,t),function(e){if(e.exports.size>0||null===e.rootEntry)return;const t=new Set([...e.getterKeys,...e.setterKeys]);for(const n of t){let t;try{t=Kc(e,n)}catch{continue}const o=t.indexOf(c+e.marker);if(-1===o)continue;const s=t.slice(0,o+1+e.marker.length),r=t.slice(s.length+1),i=t.slice(0,o)+c+r,a=ae(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Uu(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),Sc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=vt(e.component);if(e.delta>0&&null===t)return;const n=e.component.tagName.toLowerCase();for(const o of e.exports.values()){const s=`${n}|${o.exportedPath}`;if(Hu.has(s))continue;const r=ae(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Rt](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Hu.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${e.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(e),Ju(e),o=t,s=Promise.resolve(),ba.set(o,s),s.then(()=>Ia(o),()=>{})}function tf(e,t){const n=ps(t),o=vt(e.component);n.forEachActiveBindingNode(e=>$t(e,o));ca(n.rebindAddresses()),Ju(e)}function nf(e,t){if(function(e){const t=Zc.get(e);return void 0!==t&&t.size>0}(t))for(const n of rd(t)){if(!of(n.component,e))continue;const t=nd(n);null!==t&&tf(n,t)}}function of(e,t){for(let n=t.firstNode;null!==n;n=n.nextSibling){if(n===e||n.contains(e))return!0;if(n===t.lastNode)break}return!1}const sf={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=id(e,t.pathInfo.path);if(null!==s)return Qu(s,t,n,o)}return hl},readMissing(e,t,n,o,s){if(null===n){if(Eu(e.rootNode??null,t.pathInfo.path))return;return hl}if(!0===e.hasMounts){const n=Ku(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Qu(e,vn(ae(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return hl},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=Mu.get(e);if(void 0===n||0===n.size)return null;const o=t+c;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&se(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return hl},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Ku(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Qu(e,vn(ae(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return hl},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=id(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(c,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const s=-1===o?t:t.slice(0,o),r=-1===o?"":t.slice(o+1),i=e.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:e.delta}(e,o)}return 0},handlerScope(e,t,n,o,s){if(!0!==e.hasMounts)return s;const r=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=Yc.get(n);if(void 0!==e)return e;n=n.parentNode}return Yc.get(t)??null}(t,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(e,t,n){const o=function(e){return Wu.get(e)??Du}(e);for(const s of o){const o=new Set,r={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(-1!==t.indexOf("#"))continue;const i=ju(s.mountPath,s.injections,t);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const e=sn(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(Lu(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>Eu(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){nf(t,e)}};let rf=!1;const af=new WeakMap;function lf(e){let t=af.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},af.set(e,t)),t}function cf(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Tu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function df(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{Cu(n,s,e)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return xa(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function uf(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&se('"mount" requires a non-empty tree path.');const t=ae(e);for(const n of t.segments)0===n.length&&se(`"mount" path "${e}" has an empty segment.`),n===d&&se(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&se(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],s=new Set;for(const r of Re(e)){if(r.propSegments[0]!==A)continue;const e=r.propSegments.slice(1),i=r.statePathInfo,a=e=>se(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> "${r.propName}: ${r.statePathName}": ${e}`);1===e.length&&e[0]&&e[0]!==d&&"$"!==e[0][0]&&"#"!==e[0][0]||a(`inject one key at a time ("${A}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(r.inFilters.length>0||r.outFilters.length>0)&&a("an injection takes no filters."),r.propModifiers.some(e=>e!==y)&&a(`an injection accepts only #${y}.`),s.has(e[0])&&a(`"${e[0]}" is injected twice.`),s.add(e[0]),n.push({innerSegments:e,outerPathInfo:i,readonly:r.propModifiers.includes(y)})}return n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&se('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),Cu(s,r,e),xa(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===xa(s)&&function(e,t){const n=()=>{if(null!==xa(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&cf(e,t),e.settleInitialization()};let l;try{l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const c=e.connectedRootNode??null;null!==c&&df(e,t,c)?function(e,t,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};if(null!==t)return void yp(t,a);bp(),function(e,t){if(zu.has(e))return void Fu(t);let n=Bu.get(e);void 0===n&&(n=[],Bu.set(e,n)),n.push(t)}(e,a)}(c,xa(c),r,l,a,()=>df(e,t,c),i):a(null)}const ff={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=lf(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{Cu(n,t.mountPath,e),xa(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,mc}return uf(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=lf(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&xa(n)===t.graftInfo.rootStateElement&&pp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==af.get(e)?.initializing)return;const t=e.getAttribute("mount");se(`Cannot replace the state of <${o.tagNames.state} mount="${t}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${t}" on the root state instead.`)},initializeFailed(e,t){!function(e){zu.add(e);const t=Bu.get(e);if(void 0!==t){Bu.delete(e);for(const e of t)Fu(e)}}(t)},initializeFailureCleared(e,t){!function(e){zu.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=lf(e);return null!==t.graftInfo&&pp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,cf(e,t)),e.clearConnectedRootNode(),!0}};let hf=!1;const pf=new WeakMap;function gf(e,t){let n=pf.get(e);n||(n=new Set,pf.set(e,n)),n.add(t)}const mf=new WeakMap;const yf=new WeakMap,wf=new WeakMap;const bf=new WeakMap;const vf={isComplete:function(e,t){return!0===pf.get(e)?.has(t)},isDeclared:function(e,t){return!0===mf.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=yf.get(e);o||(o=new Map,yf.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=wf.get(e);o||(o=new Map,wf.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)},rememberOverwrittenValue:function(e,t,n,o){let s=bf.get(e);s||(s=new Map,bf.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function $f(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),o=Object.getOwnPropertyDescriptors(e);for(const e in o){const t=o[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,o),n}(e)}const xf=new WeakMap;class Sf{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=xf.get(e);return n?n.get(t)??null:null}(e,t)??se("State element not found for web component.")}get(e,t,n){if("string"==typeof t){let e;return this._innerStateElement.createState("readonly",n=>{e=n[t]}),e}return Reflect.get(e,t,n)}set(e,t,n,o){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,o)}}const Pf=e=>()=>e;function If(e,t,n,o){!function(e,t,n){let o=xf.get(e);o||(o=new Map,xf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState($f(o));const s=function(e,t){const n=new Sf(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Pf(s),enumerable:!0,configurable:!0}),gf(t,n),Af(t,n)}function Af(e,t){if(W in e){const n=e[W];"function"==typeof n?n.call(e,t).catch(e=>{se(`Error in ${W}: ${e instanceof Error?e.message:String(e)}`)}):se(`${W} is not a function.`)}}const Nf=new Set;function kf(e,t){Nf.has(e)||(Nf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function _f(e){const t=e.rootEntry,n=vt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Rt](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Tf=new WeakMap;function Cf(e,t){e.landInitialization(),se(t)}async function Ef(e,t){const n=e;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?Ge(a):null;null!==a&&null!==l||se(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||Cf(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(e=>n.hasAttribute(e));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&se(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(e,t){let n=mf.get(e);n||(n=new Set,mf.set(e,n)),n.add(t)}(a,d);const u=Je(a);null===u&&se(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await Ve(a),d in a||se(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||se(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=yf.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==h&&function(e,t){if(!e.hasAttribute(o.bindAttributeName))return!1;const n=lt(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(a,d)&&(a[d]=h,f=h),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(lt(a)??[]).some(e=>e.propSegments[0]===d)||Cf(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(o.bindAttributeName)){const o=(lt(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=xa(a.getRootNode())??Cf(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,Qc.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(function(e,t,n){const o=bf.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;bf.get(e).delete(t)}}(a,d,f),u=Wc(a,d,o,c,f,function(e,t){return wf.get(e)?.get(t)}(a,d)),function(e){const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=_f(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;kf(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}(u)),t.mountRecord=u,n.parentNode!==i)return;try{ef(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Zu(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),gf(a,d)}return Af(a,d),function(e){const t=Rc.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(J)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;jc.has(n)||(jc.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${e.stateProp} declares ${t.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(u),void Lc(u,"$connectedCallback")}}If(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const Mf={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=Tf.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Tf.set(e,t)),t}(e);return Ef(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Tf.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&tf(n,o)}),Lc(n,"$connectedCallback"),!0},disconnecting(e){const t=Tf.get(e);return void 0!==t&&null!==t.mountRecord&&(Lc(t.mountRecord,"$disconnectedCallback"),Ju(t.mountRecord),e.clearConnectedRootNode(),!0)}};let Of=!1;function Rf(){Of||(Of=!0,bc("bindComponent",Mf),ms=vf)}const jf=new WeakMap,Lf=new Set,Wf=new Set;function Df(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Bf(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function zf(e){return jf.get(e)}function Ff(e){qf(e),jf.delete(e)}function qf(e){Lf.delete(e),Wf.delete(e)}const Vf=new WeakMap,Hf=new WeakMap,Uf=new Set,Gf=new Map;function Kf(e){return Vf.get(e)??Gf}function Jf(e){Uf.add(e),function(e){const t=jf.get(e);void 0!==t&&(Df(t)&&Lf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Wf.add(e))}(e)}const Xf=new Map;function Yf(e){return Hf.get(e)??Xf}function Qf(e){0===e.length&&se(`[wcs/watch-declaration-invalid] ${U} entry name must be a non-empty state path.`),e.startsWith("$")&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not start with "$" (reserved namespace).${ue}`),e.includes("@")&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ue}`),e in Object.prototype&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ae(e);for(const n of t.segments)0===n.length&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" has an empty path segment.${ue}`);return t.wildcardCount>u&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Zf(e,t){const n=t[U];if(void 0===n)return null;"object"==typeof n&&null!==n||se(`[wcs/watch-declaration-invalid] ${U} must be an object mapping state paths to handler functions.${ue}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&se(`[wcs/watch-declaration-invalid] ${U} entry "${t}" must be a function.${ue}`);const n=Qf(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Vf.set(e,t)}(e,o),s.size>0?s:null}let eh=0,th=0;function nh(e){eh=e+1}function oh(){eh=0}function sh(){eh>th&&(th=eh)}const rh=new WeakMap;function ih(e,t,n){let o=rh.get(e);void 0===o&&(o=new Map,rh.set(e,o)),o.set(t,n)}const ah=new Map;function lh(e,t){ah.has(e)||ah.set(e,t)}function ch(e){return ah.get(e)}const dh={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||lh(n,o)},swapped(e,t,n){var o;o=n,ah.has(o)&&lh(t,ch(n))}};function uh(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ds(t))return!0;return!1}function fh(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[jt](vn(t.wildcardParentPathInfos[i],r)),l=zs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=on(o,i,t.wildcardCount);if(l!==c&&!js(l,c)){if(Ds(c))return"gone";s="replaced"}r=l}return s}function hh(e,t,n){const o=new Map;for(const s of n){const n=fh(e,t,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),e=>e.row)}const ph=new Set;function gh(e){ph.delete(e)}function mh(){return ph}const yh=Symbol("wcs-stream-last-notified-uncertain"),wh=new WeakMap;function bh(e,t){const n=wh.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function vh(e,t){const n=wh.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:yh,error:Object.is(o.error,null)?null:yh})}const $h=new WeakMap;function xh(e){return $h.get(e)??new Map}function Sh(e){gh(e);const t=$h.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,vh(e,n.name)}const Ph=new WeakSet;let Ih=0;function Ah(e){return zf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Nh(e){if(0===Wf.size)return;if(t=e.absolutePathInfo.stateElement,!Wf.has(t))return;var t;const n=Ah(e);if(void 0!==n)for(const e of n)kh(e)}function kh(e){Ph.has(e)||(Ph.add(e),Ih++)}function _h(e){return!!Ph.delete(e)&&(Ih--,!0)}const Th=/^(?:0|[1-9]\d*)$/;function Ch(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Eh(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return null;const t=Object.getPrototypeOf(e);if(Array.isArray(e)){return t===Array.prototype&&Reflect.ownKeys(e).every(t=>"length"===t||"string"==typeof t&&Th.test(t)&&Ch(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Ch(e,t))?"object":null}function Mh(e,t){const n=Eh(e);if(null===n)return e;const o=e,s=t.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(e.length):null===Object.getPrototypeOf(e)?Object.create(null):{},t.set(o,r);for(const e of Object.keys(o))r[e]=Mh(o[e],t);return r}function Oh(e){return Mh(e,new Map)}function Rh(e,t,n){if(Object.is(e,t))return!0;const o=Eh(t);if(null===o||"object"!=typeof e||null===e)return!1;const s=e,r=t;if("array"===o){if(!Array.isArray(e)||e.length!==t.length)return!1}else if(Array.isArray(e)||Object.keys(s).length!==Object.keys(r).length)return!1;if(Eh(e)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let t=0;t<e.length;t++)if(!Rh(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&Rh(s[e],r[e],n))}function jh(e,t){return Rh(e,t,new Map)}const Lh=new WeakMap;function Wh(e,t){if("function"!=typeof t)return;const n=Lh.get(t);void 0===n?Lh.set(t,new Set([e])):n.add(e)}const Dh={"read-source":e=>`${G} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${G} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${G} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${G} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${G} could not write the output "${e}".`},Bh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function zh(e,t,n){null!==xt&&xt({type:"state:watch-error",phase:t,path:`${G}.${e}`,error:n})}function Fh(e,t,n){console.error(`[@wcstack/state] ${Dh[n](e)}`,t),zh(e,Bh[n],t)}function qh(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Vh(e,t){t.then(void 0,()=>{}),Fh(e,new TypeError(`${G} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Hh=new WeakSet;const Uh=Object.freeze([]);function Gh(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function Kh(e,t){let n=0;for(;n<e.indexes.length-1&&e.indexes[n]===t.indexes[n];)n++;return e.indexes[n]-t.indexes[n]}function Jh(e,t){return t.has(e.stateElement)&&!0===zf(e.stateElement)?.entries.has(e.entry)}function Xh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Yh(n,e))||_h(t)}function Yh(e,t){return or().hasQueuedPath(e,t)}function Qh(e,t){!function(e,t,n){if(0!==Ih)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=Ah(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||_h(t)}}(e,t,Yh)}function Zh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function ep(e,t,n){if(!Jh(e,n))return Xh(e),null;const{stateElement:o,entry:s}=e;if(e.reset)return{group:e,next:s.initial};const r=s.source;if(function(e,t){for(const n of t.pathInfo.cumulativePaths)if(e.getterPaths.has(n))return!0;return!1}(o,r))return function(e,t,n){if(Hh.has(e))return;Hh.add(e);const o=`[wcs/scan-source-computed] ${G} entry "${t}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),zh(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=xh(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name],o=0===r.pathInfo.wildcardCount?e.rows:hh(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Kh)){let n;try{n=Zh(t,r,e)}catch(e){Fh(s.name,e,"read-source");continue}const o=a(l,n,ch(e.absAddress),...e.indexes);if(qh(o))return void Vh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){Fh(s.name,e,i.failure)}return i.plan}function tp(e,t){const{group:n}=e;if(!Jh(n,t))return void Xh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||_h(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!jh(o,s.initial):!Object.is(o,e.next)){const o=n.reset?Oh(s.initial):e.next;t[s.name]=o,Wh(s.name,o)}})}catch(e){Fh(s.name,e,"write")}}function np(e,t,n){if(Qh(e,t),0===Lf.size)return Uh;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=zf(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=sn(n.listIndex,r.wildcardCount)}for(const s of i)Gh(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)Gh(o,e,t).reset=!0}if(0===o.size)return Uh;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];nh(n);try{for(const n of s){const o=ep(n,e,t);null!==o&&r.push(o)}}finally{oh()}return r}function op(e){fp(),(0!==Kf(e).size||0!==Yf(e).size||function(e){const t=jf.get(e);return void 0!==t&&Df(t)}(e))&&(Jf(e),function(e){const t=[];for(const n of Kf(e).values())sp(e,n)&&t.push(n);for(const n of Yf(e).values())for(const o of n)sp(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{ih(e,Yt(e,o.pathInfo,null),n[o.path])}catch(t){ip(e,o.path,"prime",t)}})}(e))}function sp(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const rp={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function ip(e,t,n,o){console.error(`[@wcstack/state] $watch ${rp[n]} "${t}" threw.`,o),null!==xt&&xt({type:"state:watch-error",phase:n,path:t,error:o})}function ap(e){const t=Uf;try{if(0===t.size)return void Qh(e,t);const n=function(){const e=th;return th=0,e}();if(n>32){Qh(e,null);const t=Array.from(e,e=>e.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:t}),void(null!==xt&&xt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){nh(n);try{for(const n of e)tp(n,t)}finally{oh()}}}(np(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Kf(e).get(s),i=Yf(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=sn(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(cp);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(uh(o.absAddress.listIndex)||s?.entry===o.entry&&lp(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(hh(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){ip(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);nh(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Kf(e.stateElement).get(e.entry.path)===e.entry,o=!0===Yf(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&dp(e)}}finally{oh()}}(e,t,n)}finally{ah.clear()}}function lp(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function cp(e,t){if(e.entry.order!==t.entry.order)return e.entry.order-t.entry.order;const n=Math.min(e.indexes.length,t.indexes.length);for(let o=0;o<n;o++)if(e.indexes[o]!==t.indexes[o])return e.indexes[o]-t.indexes[o];return e.indexes.length-t.indexes.length}function dp(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=sp(t,n);try{t.createState("writable",e=>{let i;try{i=function(e,t,n){if(0===t.pathInfo.wildcardCount)return e[t.path];return e.$resolve(t.path,n)}(e,n,s)}catch(e){return void ip(0,n.path,"evaluate",e)}const a=r?function(e,t){return rh.get(e)?.get(t)}(t,o):ch(o);r&&ih(t,o,i),null!==xt&&xt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){ip(0,n.path,"handler",e)}}let up=!1;function fp(){up||(up=!0,ml("watch",dh),vl("watch",hp),Zs(ap,10),Qs(sh))}const hp={order:10,register(e,t){var n;n=e,Uf.delete(n),qf(n),Vf.delete(n),function(e){rh.delete(e)}(e);const o=Zf(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?U:G)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&op(e)},deactivate(e){var t;t=e,Uf.delete(t),qf(t)}};function pp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Lu(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function gp(e,t,n,o){const s=n[U];if(void 0!==s){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(s)){const s=Ru(t,o,a,!1),c=function(e,n,...s){l.call(Lu(t,this,o),e,n,...s)};n.push({path:s,pathInfo:ae(s),handler:c,order:1e6+i++}),r.add(s),e.setPathInfo(s,"prop","watch")}n.length>0&&(!function(e,t){let n=Hf.get(e);void 0===n&&(n=new Map,Hf.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}(e,n),e.addVolumeWatchPaths?.(r),op(e))}const r=n[X];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(Ru(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[j];"function"==typeof i&&(!function(e,t){let n=Wu.get(e);void 0===n&&(n=[],Wu.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,injections:o,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[e]&&console.warn(`[@wcstack/state] volume "${t}" declares ${e}, which volumes do not support. Declare it on the root state instead.`)}function mp(e,t,n,o=[]){ll(n),function(e,t,n,o){for(const e of o){const o=e.innerSegments[0],s=Object.getOwnPropertyDescriptor(n,o);void 0===s||"function"!=typeof s.get&&"function"!=typeof s.set&&"function"!=typeof s.value||se(`Volume "${t}" declares "${o}" as an accessor or a method and also injects it ("${A}.${o}: ${e.outerPathInfo.path}"). Rename one of them.`)}const s=n[U];if(void 0!==s){"object"==typeof s&&null!==s||se(`${U} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(s))"function"!=typeof t&&se(`${U} entry "${e}" must be a function.`),Qf(e)}const r=n[X];if(void 0!==r){"object"==typeof r&&null!==r||se(`${X} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(r)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&se(`${X} entry "${n}" must map a list path to a field name or a key function.`);const r=Ru(t,o,n,!1);e.listKeys?.has(r)&&se(`${X} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[H]&&se(`Volume "${t}" declares ${H}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&se(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[K]&&se(`Volume "${t}" declares ${K}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const e of Object.keys(xc(n)))-1!==e.indexOf(J)&&se(`Volume "${t}" declares "${e}", which uses "${J}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n,o);const{data:s,accessors:r}=function(e,t){const n={},o=new Map;for(const[s,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))s.startsWith("$")||t.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(e=>e.innerSegments[0]))),i=ae(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;se(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let t=0;t<i.segments.length-1;t++){const o=i.segments[t],s=""===n?o in e:void 0!==e[n+c+o];n=""===n?o:n+c+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;se(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=s}),function(e,t){let n=Mu.get(e);void 0===n&&(n=new Set,Mu.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+c+n,i=s.get,a=s.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(Lu(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(Lu(t,this,o),e)}),e.defineTreeAccessor(r,l)}gp(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(Lu(t,e,o))}catch(e){return void console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)}n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n,injections:o}}function yp(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=mp(e,t.mountPath,t.volumeState,t.injections)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let wp=!1;function bp(){var e;wp||(wp=!0,rf||(rf=!0,ml("scopes",sf)),hf||(hf=!0,bc("scopes",ff)),Rf(),qu=yp,e=vp,$a.includes(e)||$a.push(e))}function vp(e,t){(function(e){const t=Tu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){zu.delete(e);const n=Bu.get(e);if(void 0===n||0===n.length||null===qu)return;Bu.delete(e);const o=qu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const $p={name:"scopes",install(){bp(),_u||(_u=!0,bc("dcc",ku))}},xp=/^@@wcs-(?:for|if|elseif|else):[^-]/,Sp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,Pp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Ip=/^@@wcs-text-start:(.+)$/;function Ap(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Np extends $c{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=ad.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static find(e){const t=o.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=Ap(JSON.stringify(t)),e.appendChild(n);const s=Array.from(Na.keys());for(const t of s){const n=_a(t);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",t);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),e.appendChild(s)}const r=Array.from(_i);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=ki(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=Ap(JSON.stringify(t)),e.appendChild(n)}}_i.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Sp.test(e.data)||Pp.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;xp.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=Ip.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(o.tagNames.ssr),s=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;Sp.test(e.data)&&i.push(e)}for(const e of i){const t=Sp.exec(e.data),n=`@@wcs-${t[1]}-end:${t[2]}`;let o=e.nextSibling;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=e}e.remove()}Np.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(xp.test(e.data)){const t=e.data.split(":")[1];l.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of l){const n=s.get(t);if(n){const t=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&t.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const c=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of c)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const kp={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",ad),Np.buildContent(o,Np.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const _p=new Set(["for","if","elseif","else"]);function Tp(e){const t=new hs;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=gt(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function Cp(e,t,n){for(const o of t)"event"===o.bindingType||_p.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in M||ae(o.statePathName).wildcardCount>n||e.push(o)}function Ep(e,t,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function Mp(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Re(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,Ea()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;za(a),"string"==typeof l&&Wa(a,l),Ua(n,a,l);ka(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Ba(a)})}}const Op={hydrate:async function(e){await fa(e);const t=e.querySelectorAll(o.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${ad}". Falling back to full render.`),Np.cleanupDom(e),!1}for(const n of t)Mp(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=Sp.exec(e.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let d=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:l,nodes:c})}return t}(document.body),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=ii(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=Tp(s.nodes);Wr(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");xs(t,r),zr(t,i);const l=[];for(const e of r)e.statePathName in M&&l.push(e);if(Is(t,l),"for"===s.type&&null!==s.index){const i=Ep(e,"for",s.uuid);if(i){const e=Es(null,s.index);yi(i,e,t),wi(i,s.nodes[s.nodes.length-1]),Qr(i,t);const l=ae(s.path+"."+d);Fr(t,vn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Cp(o,r,l.wildcardCount);let c=n.get(s.uuid);c||(c=[],n.set(s.uuid,c)),c.push(e)}}else{const n=Ep(e,s.type,s.uuid);n&&(Qr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Cp(o,r,0))}}for(const[t,o]of n){const n=Ep(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=_a(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=xa(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&qs(t,o)})}return o}(document.body,n);Np.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());Np.restoreTextBindings(document.body);const[i,a]=gt(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||($t(e,null),t.setAttribute("data-wcs-completed",""))}else $t(e,null);const l=[],c=[],u=ps(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(_p.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(d))continue;l.push(e)}for(const e of c)if("for"===e.bindingType){const t=dn(e),n=xa(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(It(t,o),Ct(t,o))})}ca([...l,...s]);for(const{el:e,parent:t,next:n}of r)t.insertBefore(e,n);const f=e.querySelectorAll(o.tagNames.ssr);for(const t of f){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=Np.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Sa(e.rootNode);const t=Np.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",ad),Np.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let Rp=!1;function jp(){var t;Rp||(Rp=!0,ma=Op,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Np)},Nc.includes(t)||Nc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=kp)}())}const Lp={name:"ssr",install(){jp()}},Wp="[wcs/scan-declaration-invalid]",Dp=Object.freeze([]);function Bp(e){return`${G} entry "${e}"`}function zp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Fp(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${d}${d}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${ue}`}function qp(e,t,n){0===n.length&&se(`${Wp} ${e} "${t}" must be a non-empty state path.${ue}`),n.startsWith("$")&&se(`${Wp} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ue}`),n.includes("@")&&se(`${Wp} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ue}`),n in Object.prototype&&se(`${Wp} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ue}`);const o=ae(n);for(const s of o.segments)0===s.length&&se(`${Wp} ${e} ${t} "${n}" has an empty path segment.${ue}`);return o.wildcardCount>u&&se(`${Wp} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Vp(e,t,n,o){const s=Bp(e);0===e.length&&se(`${Wp} ${G} entry name must be a non-empty string.${ue}`),(e.includes(c)||e.includes(d))&&se(`${Wp} ${s} must be a flat property name ("${c}" and "${d}" are not allowed). The output is a property the runtime owns.${ue}`),e.startsWith("$")&&se(`${Wp} ${s} must not start with "$" (reserved namespace).${ue}`),e in Object.prototype&&se(`${Wp} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ue}`),t.has(e)&&se(`${Wp} ${s} conflicts with a getter declared on the state.${ue}`),n.has(e)&&se(`${Wp} ${s} conflicts with a setter declared on the state.${ue}`),o.has(e)&&se(`${Wp} ${s} conflicts with the ${H} entry of the same name — each output has exactly one owner.${ue}`)}function Hp(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Lh.get(t)?.has(e)}(e,o)&&se(`${Wp} ${Bp(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ue}`)}function Up(e,t,n,o,s,r){const i=Bp(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&se(`${Wp} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ue}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||se(`${Wp} ${i} "on" must be a non-empty event-token name.${ue}`),n.has(e)||se(`${Wp} ${i} on "${e}" is not declared in ${q}.${de(e,n)}${ue}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&se(`${Wp} ${i} "from" must be a state path string.${ue}`);const u=qp(i,"from",d),f=zp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&se(Fp(i,"from",d,f));const h=zp(u,s);return null!==h&&se(function(e,t,n){return`${Wp} ${e} from "${t}" ${n===t?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${ue}`}(i,d,h)),(d===e||d.startsWith(e+c))&&se(`${Wp} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ue}`),{kind:"path",path:d,pathInfo:u}}function Gp(e,t,n,o){if(void 0===t)return Dp;const s=Bp(e);Array.isArray(t)||se(`${Wp} ${s} "resetOn" must be an array of state paths.${ue}`);const r=[];for(const e of t){"string"!=typeof e&&se(`${Wp} ${s} "resetOn" must contain only state path strings.${ue}`);const t=qp(s,"resetOn",e);t.wildcardCount>0&&se(`${Wp} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${ue}`);const i=zp(t,o);null!==i&&se(Fp(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&se(`${Wp} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ue}`),"path"===n.kind&&e.startsWith(n.path+c)&&se(`${Wp} ${s} resetOn "${e}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${ue}`),r.push(e)}return r}function Kp(e,t,n=null){const o=e[G];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&se(`${Wp} ${G} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ue}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(xc(e)))"function"==typeof n.get?s.add(t):"function"==typeof n.set&&i.add(t),"function"==typeof n.set&&r.add(t),"function"==typeof n.value&&a.set(t,n.value);const l=function(e){ll(e);const t=e[H];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),c=[];let d=0;for(const[e,u]of Object.entries(o)){Vp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&se(`${Wp} ${Bp(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ue}`);const o=u;Hp(e,a,o);const f=Up(e,o,t,s,i,n);"initial"in o||se(`${Wp} ${Bp(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ue}`),"function"!=typeof o.fold&&se(`${Wp} ${Bp(e)} fold must be a function.${ue}`);const h=Gp(e,o.resetOn,f,s);c.push({name:e,source:f,fold:o.fold,initial:o.initial,resetOn:h,order:d++})}return function(e){const t=new Set(e.map(e=>e.name)),n=new Map;for(const o of e){for(const e of o.resetOn){const n=ae(e).segments[0];t.has(n)&&se(`${Wp} ${Bp(o.name)} resetOn "${e}" reads the ${G} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ue}`)}if("path"===o.source.kind){const e=o.source.pathInfo.segments[0];t.has(e)&&n.set(o.name,e)}}for(const e of n.keys()){const o=[e];let s=n.get(e);for(;void 0!==s&&o.length<=t.size;)s===e&&se(`${Wp} ${G} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ue}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Jp(e){const t=e.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[e.name];i="threw";const a=function(e){return Ph.has(e)}(e),l=a&&!jh(n,e.initial)?Oh(e.initial):n,c=t(l,o,...s);if(qh(c))return void Vh(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Wh(e.name,c)),a&&_h(e)}catch(t){Fh(e.name,t,i)}}}function Xp(e,t,n){const o=function(e,t){Ff(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Bf(n,e.source.path,e);for(const t of e.resetOn)Bf(o,t,e),"event"===e.source.kind&&Bf(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return jf.set(e,r),r}(e,t);for(const o of t){const t=n.get(o.name);"event"===o.source.kind&&void 0!==t&&(o.resetOn.some(n=>t.includes(n)&&or().hasQueuedPath(e,n))&&kh(o))}const s=new Set;for(const t of o.byFromPath.keys())s.add(t),e.setPathInfo(t,"prop","scan");for(const t of o.byResetPath.keys())e.setPathInfo(t,"prop","scan");return s.size>0?s:null}const Yp="scanEntries",Qp={order:8,validate(e,t,n){const o=Kp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Yp,o)},applyEarly(e,t,n){const o=n.get(Yp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=Oh(n.initial);e[n.name]=t,Wh(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Rn(e,n.source.tokenName).subscribe(Jp(n))}(e,o))},register(e,t,n){const o=n.get(Yp)??null,s=function(e){const t=new Map,n=zf(e);if(void 0!==n)for(const e of n.entries)_h(e)&&t.set(e.name,e.resetOn);return Ff(e),t}(e);e.setScanPaths?.(null===o?null:Xp(e,o,s))}};let Zp=!1;const eg=Object.freeze([]),tg=Object.freeze([]);function ng(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??eg,i=e.dynamicDependency.get(n)??eg,a=t.byFromPath.get(n)??tg;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const og=(e,t)=>t,sg=new Set;function rg(e,t){ll(t);const n=t[H];if(void 0===n)return void bh(e,sg);"object"==typeof n&&null!==n||se(`${H} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&se(`${H} entry name must be a non-empty string.`),s.includes(c)&&se(`${H} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.includes(d)&&se(`${H} entry "${s}" must be a flat property name ("${d}" is not allowed).`),s.startsWith("$")&&se(`${H} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&se(`${H} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&se(`${H} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&se(`${H} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||se(`${H} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&se(`${H} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&se(`${H} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&se(`${H} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&se(`${H} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??og,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in t||(t[s]=a.definition.initial),o.set(s,a)}!function(e,t){$h.set(e,t)}(e,o),bh(e,new Set(o.keys()))}const ig=new WeakMap,ag=new WeakMap;function lg(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=xh(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&xh(e).has(n),ownKeys:()=>Array.from(xh(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=xh(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){se(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){se(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function cg(e){const t=ig.get(e);if(void 0!==t)return t;const n=lg(e,Y,e=>e.status);return ig.set(e,n),n}function dg(e){const t=ag.get(e);if(void 0!==t)return t;const n=lg(e,Q,e=>e.error);return ag.set(e,n),n}function ug(e){ig.delete(e),ag.delete(e)}let fg=null;function hg(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}const pg={read(e,t){!function(e,t){null!==fg&&fg.add(Xt(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===Y?hg(cg(e),t.pathInfo.segments):n===Q?hg(dg(e),t.pathInfo.segments):hl},get:(e,t)=>t===Y?cg(e.stateElement):t===Q?dg(e.stateElement):hl};async function gg(e,t,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",i)}}function mg(e){Sg();const t=xh(e);if(0!==t.size){!function(e){ph.add(e)}(e);for(const n of t.values())yg(e,n)}}function yg(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=fg,s=new Set;let r;fg=s;try{e.createState("readonly",e=>{r=n(e)})}finally{fg=o}r instanceof Promise&&se(`${H} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${Y}${c}${t.name}`,a=`${Q}${c}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||se(`${H} entry "${t.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&se(`${H} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);!function(e,t){const n=zf(e);if(void 0!==n&&0!==t.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==t.name)continue;const s=ng(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&se(`[wcs/scan-feedback-loop] ${H} entry "${t.name}" args read "${n}", which is derived from the ${G} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(e,t),e.createState("writable",e=>{e[t.name]=t.definition.initial}),wg(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{e[t.name]=s.fold(e[t.name],n)})},done(){wg(e,t,"done",null)},fail(o){wg(e,t,"error",o),n.abort()}};gg(s.source,o,n.signal,r)}function wg(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return wh.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=wh.get(e);void 0===s&&(s=new Map,wh.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${Y}${c}${t.name}`),i&&e.$postUpdate(`${Q}${c}${t.name}`)}))}function bg(e){const t=mh();if(0===t.size)return;const n=[];for(const o of t)for(const t of xh(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&xh(e).get(o.name)===o)try{yg(e,o)}catch(n){o.controller?.abort(),t.has(e)&&xh(e).get(o.name)===o&&wg(e,o,"error",n)}}let vg=!1;const $g=new WeakMap,xg={order:20,apply(e,t){var n;ug(e),Sh(n=e),gh(n),$h.delete(n),rg(e,t),void 0!==t[H]&&e.attachAddressHooks?.("streams",H)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return mg(e),void $g.set(e,e.connectGeneration??0)}n===e.connectGeneration&&$g.get(e)!==n&&mg(e)}},deactivate(e){Sh(e),ug(e)}};function Sg(){vg||(vg=!0,ml("streams",pg),vl("streams",xg),Zs(bg,20))}const Pg=[Fd,{name:"temporal",install(){fp(),Zp||(Zp=!0,vl("scan",Qp),Qs(Nh)),Sg()}},mu,$p,Lp,bd,Td];function Ig(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(Pg),Tc(e,t)}function Ag(e){return e}const Ng={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"ブール値を反転",hasArgs:!1,resultType:"boolean",acceptTypes:["boolean"],minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},add:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},sub:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},toFixed:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},upper:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lower:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},capitalize:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},padStart:{description:"先頭を埋める (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},padEnd:{description:"末尾を埋める (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},repeat:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},reverse:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator])",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},time:{description:"ロケール形式の時刻",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},datetime:{description:"ロケール形式の日時",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},ymd:{description:"YYYY-MM-DD 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},coalesce:{description:"null / undefined の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},nullIfEmpty:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},kg=1;function _g(){return{version:1,syntax:{bindAttribute:o.bindAttributeName,tagName:o.tagNames.state,pathDelimiter:c,wildcard:d,delimiters:{binding:";",propValue:":",modifier:h,filter:p},structuralDirectives:Array.from(fe),modifiers:{flags:w,keyValue:$,eventNamePrefix:P},indexParam:{prefix:C,maxDepth:u},bindingTypes:{elseKeyword:x,spread:S,eventPropertyPrefix:P,explicitPropertyPrefix:c,propNamespaces:{eventToken:I,command:N,class:k,attr:_,style:T}}},filters:Object.keys(Dd),filterMeta:Ng,filterAliases:Rd,reservedLifecycle:[O,R,j,L,W],reservedStateApi:[D,B,z,F,q,V,H,U,G,X,K,Y,Q]}}const Tg=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),Cg=Object.freeze([]);function Eg(e){if(!o.enableContractAnalyzer)return Cg;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))Tg.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?Mg(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,Og,e=>{t.push(e),null!==xt&&xt(e)}),t}function Mg(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function Og(e){const t=Je(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{Np as Ssr,Ti as TRUSTED_TYPES_POLICY_SLOT,ad as VERSION,kg as WCS_MANIFEST_VERSION,Eg as analyzeContract,Ig as bootstrapState,ha as buildBindings,Ng as builtinFilterMeta,Ag as defineState,Sa as getBindingsReady,s as getConfig,Ci as getTrustedTypesPolicy,_g as getWcsManifest,Ei as setTrustedTypesPolicy};
|
|
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};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|