wcstack 3.1.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/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.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,s=Symbol.for("wcstack.binder"),r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");const a=".",l="*",c=128,u=128,d="#",h="|",f="prevent",p="stop",m="ro",g="init",y="sync",b="else",w="...",v="on",_="eventToken",$="state",S="command",x="class",P="attr",N="style",k={};for(let t=0;t<c;t++)k[`$${t+1}`]=t;const I=Object.freeze(k),A="$connectedCallback",E="$disconnectedCallback",C="$updatedCallback",T="$errorCallback",M="$stateReadyCallback",O="$bindables",L="$commands",R="$commandTokens",j="$command",D="$eventTokens",W="$on",z="$streams",B="$watch",F="$scan",H="$recursion",q="**",U="$listKeys",G="$streamStatus",V="$streamError",K="data-wc-definition",J=/\{\{\s*(.+?)\s*\}\}/g,Q=new Set(["SCRIPT","STYLE"]);function X(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&Q.has(t.parentElement.tagName)||Y(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),X(e.content)}else X(t.content)}function Y(t){const e=t.data;if(J.lastIndex=0,!J.test(e))return;J.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=J.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}function Z(t){throw new Error(`[@wcstack/state] ${t}`)}const tt=new Map;let et=0;function nt(t){let e=tt.get(t);return void 0!==e||(-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] "${t}" uses "${q}", 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.`),e=Object.freeze(new ot(t)),tt.set(t,e)),e}class ot{id=++et;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:nt(e),n=t.split("."),o=[],s=[],r=[],i={},a=[],c=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===l&&(r.push(h),i[h]=p,a.push(e(h)),c.push(f),u.push(e(f)),d.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,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=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=u,this.wildcardParentPathInfoSet=new Set(u),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}}function st(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function rt(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=st(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const it=" Validate statically: npx @wcstack/lint <file>.",at=new Set(["if","elseif","else","for"]),lt={not:()=>t=>!t},ct={input:new Map,output:new Map},ut={input:new Map,output:new Map},dt=new Map;function ht(t,e,n){const o=ct[t],s=ut[t];for(const t of Object.keys(e)){o.set(t,e[t]);const r=n?.[t];void 0===r?s.delete(t):s.set(t,r)}dt.clear()}function ft(t,e,n,o=e){const s=`${t}${JSON.stringify(o)}:${n}`,r=dt.get(s);if(void 0!==r)return r;const i=ct[n].get(t)??lt[t];void 0===i&&Z(`[wcs/filter-unknown] filter not found: ${t}.${rt(t,function(t){return[...new Set([...Object.keys(lt),...ct[t].keys()])]}(n))}${it}`);const a=ut[n].get(t);void 0!==a&&(e.length<a[0]||e.length>a[1])&&Z(e.length<a[0]?`[wcs/filter-arity] filter "${t}" requires at least ${a[0]} argument(s) (${e.length} given).${it}`:`[wcs/filter-arity] filter "${t}" accepts at most ${a[1]} argument(s) (${e.length} given).${it}`);const l=i(e,o);return dt.set(s,l),l}function pt(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const mt=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function gt(t,e){return e?t:"true"===t||"false"!==t&&("null"===t?null:mt.test(t)?Number(t):t)}function yt(t){const e=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const t=pt(o,i,a);e.push(t),n.push(gt(t,r)),o="",r=!1,i=-1,a=-1};for(let e=0;e<t.length;e++){const n=t[e];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&Z(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${t})". Close the quote.${it}`);const c=pt(o,i,a);return(c||r)&&(e.push(c),n.push(gt(c,r))),{args:e,literals:n}}function bt(t,e){return t.map(e=>{const n=e.indexOf("("),o=e.lastIndexOf(")");-1!==n&&-1===o&&Z(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==o&&-1===n&&Z(`Invalid filter format: missing opening parenthesis in "${e}"`);const s=(-1===n?e:e.substring(0,n)).trim();return 0===s.length&&Z(`[wcs/binding-syntax] an empty filter in "${t.join("|")}" — remove the extra "|" or name the filter.${it}`),-1===n?{filterName:s,args:[],literals:[]}:{filterName:s,...yt(e.substring(n+1,o))}})}const wt=t=>t.trim(),vt=t=>"'"===t||'"'===t;function _t(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(null!==n)s===n&&(n=null);else if(vt(s))n=s;else if(s===e)return o}return-1}function $t(t,e){const n=[];let o=null,s=0;for(let r=0;r<t.length;r++){const i=t[r];null!==o?i===o&&(o=null):vt(i)?o=i:i===e&&(n.push(t.slice(s,r)),s=r+1)}return n.push(t.slice(s)),n}const St=new Map;function xt(t){const e=_t(t,h);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),St.has(s)?r=St.get(s):(o=$t(s,h).map(wt),r=bt(o),St.set(s,r))):n=t.trim();const i=n.split(d).map(wt);i.length>2&&Z(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${d}" — write "${i[0]}${d}${i.slice(1).join(",")}".${it}`);const[l,c]=i,u=l.split(a).map(wt);return{propName:l,propSegments:u,propModifiers:c?c.split(",").map(wt):[],inFilters:r}}const Pt=new Map;function Nt(t){const e=_t(t,h);let n="",o=[],s="",r=[];return-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Pt.has(s)?r=Pt.get(s):(o=$t(s,h).map(wt),r=bt(o),Pt.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&Z(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`),{statePathName:n,statePathInfo:nt(n),outFilters:r}}const kt=new Set([b,"if","elseif","for",w]),It=new Set([x,P,N,S,_]);function At(t){const[...e]=function(t){return $t(t,";")}(t).map(wt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&Z(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim(),s=n.split(d)[0].split(h)[0].trim();if(s!==n&&kt.has(s)&&Z(`[wcs/binding-syntax] "${t}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${it}`),n===b){o.length>0&&Z(`[wcs/binding-syntax] "${t}": "else" takes no value — write "else:".${it}`);const e=nt("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===w){const e=Nt(o);return e.outFilters.length>0&&Z(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&Z(`Invalid spread binding "${t}": spread target path is required.`),{propName:w,propSegments:[w],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Nt(o),bindingType:n};if("radio"===s||"checkbox"===s){const t=Nt(o);return{...xt(n),...t,bindingType:s}}{const t=Nt(o),e=xt(n);if(""===e.propSegments[0]&&e.propSegments.length>1){const o=e.propSegments.slice(1);return(o.includes("")||It.has(o[0]))&&Z(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...It].join(", ")}).${it}`),{...e,propName:o.join(a),propSegments:o,...t,bindingType:"prop"}}return e.propSegments[0]===_||e.propSegments[0].startsWith(v)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>at.has(t.bindingType))&&Z(`[wcs/template-syntax] Invalid bindText: "${t}". '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">).${it}`),n}const Et=new WeakMap,Ct=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Tt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Mt(t){const e=Et.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Tt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Ct.has(r)?(Et.set(t,s[2]),s[2]):null}function Ot(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Nt(t),bindingType:"text"}}const Lt=new WeakMap,Rt=new WeakSet;let jt=0;async function Dt(t){const e=function(t){let e,n=Lt.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++jt,promise:o,resolve:e},Lt.set(t,n),Rt.has(t)&&n.resolve(),n}(t);await e.promise}function Wt(t){const e=Lt.get(t);void 0===e?Rt.add(t):e.resolve()}const zt=new WeakMap;function Bt(t){const e=zt.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{zt.set(t,n)}}function Ft(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Ht(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Ft(e);if(void 0!==n)return Ft(n)}return Ft(globalThis.customElements)}function qt(t,e){t.upgrade?.(e)}function Ut(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.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=Jt(s.properties,Gt);if(null===r)return null;const i=void 0===s.inputs?new Map:Jt(s.inputs,Vt);if(null===i)return null;const a=void 0===s.commands?new Map:Jt(s.commands,Kt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Gt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function Vt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function Kt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function Jt(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function Qt(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:nt(n),inFilters:[],outFilters:[],bindingType:"prop"}}function Xt(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function Yt(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&Z("Spread binding requires an element node.");const e=t,o=Bt(e);null===o&&Z(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Ht(e);if(null===a&&Z(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||Z(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}qt(a,e);const l=Ut(e);null===l&&Z(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=Qt(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=Qt(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=Xt(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=Xt(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function Zt(t,e){let n=t;for(let t=0;t<e.length;t++){let o=e[t];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function te(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o];n.push({filterName:s.filterName,args:s.args,filterFn:ft(s.filterName,s.args,e,s.literals??s.args)})}return n}const ee=new WeakMap;function ne(t){return ee.get(t)||null}function oe(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function se(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!oe(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function re(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function ie(t){const e=[],n=se(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Mt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&re(t,n)||e.push(t)}return e}const ae=new WeakSet;function le(t,e,n,o){const s=Yt(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Bt(t):null;return null===n&&Z("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}ae.add(t);const r=function(t,e){const n=[];for(const o of e){const e=te(o.inFilters,"input"),s=te(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:t});else{const r=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:r})}}return n}(t,function(t,e){return void 0===e?t:t.map(t=>null!=t.uuid?t:e(t))}(s,o));return function(t,e){ee.set(t,e)}(t,r),Wt(t),{bindings:r,deferred:null}}function ce(t,e){const n=ie(t),o=[],s=[];for(const t of n){if(ae.has(t))continue;const n=le(t,aa(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function ue(t){ae.add(t)}function de(t){const{node:e,parseResults:n,transform:o}=t;return function(t){ae.delete(t)}(e),le(e,n,{allowDeferred:!1},o).bindings}const he=new WeakMap;let fe=null;function pe(t){let e=t;for(;e;){const t=he.get(e);if(t)return t;let n=e.parentNode;null===n&&null!==fe&&e instanceof ShadowRoot&&(n=fe(e)),e=n}return null}function me(t,e){null!==e?he.set(t,e):he.delete(t)}let ge=null;const ye=new WeakMap;function be(t){return ye.get(t)??[]}function we(t,e){ye.set(t,e)}function ve(t){return ye.has(t)}const _e=new WeakMap;let $e=null,Se=0;function xe(t){return _e.get(t)??[]}function Pe(t,e){null===$e?_e.set(t,e):$e.set(t,e)}function Ne(){Se++,null===$e&&($e=new Map)}function ke(){if(0!==Se&&(Se--,!(Se>0||null===$e))){for(const[t,e]of $e)_e.set(t,e);$e=null}}function Ie(t){return($e?.has(t)??!1)||_e.has(t)}const Ae=Symbol("$$setLoopContext"),Ee=Symbol("$$getByAddress"),Ce=Symbol("$$hasByAddress"),Te=Symbol("$$setByAddress"),Me=Symbol("$$connectedCallback"),Oe=Symbol("$$disconnectedCallback"),Le=Symbol("$$updatedCallback"),Re=Symbol("$$errorCallback"),je=new WeakMap,De=new WeakMap;class We{absolutePathInfo;listIndex;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}}function ze(t,e){if(null===e){let e=De.get(t);return void 0!==e||(e=new We(t,null),De.set(t,e)),e}{let n=je.get(e);void 0===n&&(n=new WeakMap,je.set(e,n));let o=n.get(t);return void 0!==o||(o=new We(t,e),n.set(t,o)),o}}const Be=new WeakMap;function Fe(t,e){let n=Be.get(t);void 0===n&&(n=new Map,Be.set(t,n));let o=n.get(e);return void 0===o&&(o=Object.freeze(new He(t,e)),n.set(e,o)),o}class He{pathInfo;stateElement;constructor(t,e){this.pathInfo=e,this.stateElement=t}}function qe(t,e){return ze(Fe(t,e.pathInfo),e.listIndex)}function Ue(t,e,n){return ze(Fe(t,e),n)}const Ge=new WeakMap;function Ve(t,e){null===e?Ge.delete(t):Ge.set(t,e)}function Ke(t){return Ge.get(t)||null}const Je=new Map;function Qe(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=Je.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Je.set(s,r)),r}function Xe(t,e,n){return e<0||e>=n?null:t.at(e-n)}function Ye(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const Ze=new WeakMap;function tn(t){const e=pe(t.node);if(null===e)return null;let n=Ze.get(e);if(void 0===n)n=new WeakMap,Ze.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Qe(e.pathInfo,t.statePathInfo);return n>0&&(o=Xe(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const en=new WeakMap;function nn(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Ke(n);null===e?Z(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function on(t,e){let n=null;if(n=en.get(t)||null,null!==n)return n;const o=nn(t,e),s=tn(t),r=Zi(o);return null===r&&Z("No state tree found on this root for binding."),n=Ue(r,t.statePathInfo,s),en.set(t,n),n}function sn(t){en.delete(t)}const rn=new WeakMap;function an(t,e){const n=rn.get(t);void 0===n?rn.set(t,e):n instanceof Set?n.add(e):n!==e&&rn.set(t,new Set([n,e])),null!==ge&&ge({type:"state:binding-added",absoluteAddress:t,binding:e})}function ln(t,e){const n=rn.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&rn.delete(t),null!==ge&&ge({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const cn=new WeakMap;function un(t){const e=rn.get(t);return void 0!==e?e:null!==t.listIndex?cn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const dn=new WeakMap,hn=new WeakMap;class fn{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=pn(t,e)}}function pn(t,e){if(null===e){let e=hn.get(t);return void 0!==e||(e=new fn(t,null),hn.set(t,e)),e}{let n=dn.get(e);void 0===n&&(n=new WeakMap,dn.set(e,n));let o=n.get(t);return void 0!==o||(o=new fn(t,e),n.set(t,o)),o}}const mn=new WeakMap;function gn(t){let e=null;if(e=mn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=tn(t);null===n&&Z(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=pn(t.statePathInfo,n)}else e=pn(t.statePathInfo,null);return mn.set(t,e),e}function yn(t){mn.delete(t)}function bn(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const wn=new Map,vn=bn();function _n(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function $n(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}function Sn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function xn(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Sn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class Pn{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)e.push(n(...t));return e}}class Nn extends Pn{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==ge&&ge({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const kn=new WeakMap;function In(t,e){let n=kn.get(t);void 0===n&&(n=new Map,kn.set(t,n));let o=n.get(e);return void 0===o&&(o=new Nn(e,t),n.set(e,o)),o}const An=new WeakMap;class En extends Pn{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==ge&&ge({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function Cn(t){return t instanceof En}const Tn=new Map,Mn=bn();function On(t){const e=t.propModifiers.filter(t=>t===f||t===p).sort().join(",");return`${t.statePathName}::${e}`}function Ln(t){if(!t.propName.startsWith(v))return!1;const e=On(t);let n=Tn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(f)&&o.preventDefault(),e.includes(p)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Zi(r);null===i&&Z("No state tree found on this root for event handler.");const a=pe(s),l=t.startsWith(j+".");i.createStateAsync("writable",async e=>{const c=e[Ae](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const t=i.addressHooks;if(t){const e=t.handlerScope;for(let t=0;t<e.length;t++)c=e[t](i,s,r,a,c)}}const u=null!==a?Ye(a.listIndex,c):[];if(l){const s=e[Ee](pn(n,null));return Cn(s)||Z(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...u)}const d=e[t];return"function"!=typeof d&&Z(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});xn(c,`"${t}"`)})})(t.statePathName,t.propModifiers,t.statePathInfo),Tn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Mn.add(e,t),!0}function Rn(t){if(!t.propName.startsWith(v))return!1;const e=On(t),n=Tn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);return t.node.removeEventListener(o,n),0!==Mn.countOf(e)&&(Mn.remove(e,t)&&Tn.delete(e),!0)}const jn=new Map,Dn=bn();function Wn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function zn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}const Bn=new Set(["radio","checkbox"]),Fn=new Set(["value","valueAsNumber","valueAsDate"]);function Hn(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(Bn.has(t)&&"checked"===e)return!0;if(Fn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Bt(n);if(null!==s){const t=Ht(n)?.get(s);void 0===t&&Z(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Ut(n);if(o?.knownProperties.has(e))return!0}return!1}let qn=1,Un=1,Gn=1;const Vn=new WeakMap;function Kn(t,e,n){let o=Vn.get(t);void 0===o&&(o=new Map,Vn.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=qn++,o.set(s,r)),r}function Jn(t,e){return"to-element"===e?2*t:2*t+1}const Qn=new Set;function Xn(t){return{transactionId:Un++,originBindingId:t,visitedEdges:Qn,hop:0}}function Yn(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let Zn=null;function to(){return Zn}function eo(t,e){const n=Zn;Zn=t;try{return e()}finally{Zn=n}}const no=[];let oo=!1;const so=new Map,ro=bn(),io=new WeakMap,ao=t=>t.detail,lo=new WeakMap;function co(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function uo(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Bt(t.node);if(null!==n){const o=Ht(t.node)?.get(n);void 0===o&&Z(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ut(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}function ho(t){if(null!==Bt(t.node)){const e=Ut(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??ao}return null}function fo(t){if(null===Bt(t.node))return!1;const e=Ut(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const po=new WeakSet;function mo(t){po.add(t)}function go(t){return!!po.has(t)&&(po.delete(t),!0)}const yo=new WeakMap;function bo(t,e){const n=yo.get(t);return!(void 0===n||n<e||(n===e?yo.delete(t):yo.set(t,n-e),0))}const wo=new WeakSet;function vo(t){wo.add(t)}function _o(t){return!!wo.has(t)&&(wo.delete(t),!0)}let $o=0;function So(){$o--}function xo(){return $o>0}class Po{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.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),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const No=new WeakMap;function ko(t){let e=No.get(t);return void 0===e&&(e=new Po(t),No.set(t,e)),e}function Io(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==g&&s!==y&&Z(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&Z(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Ao(t){return t.propModifiers.some(t=>t.includes("="))}const Eo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Co=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function To(t,e){return"state"===t&&"call"===e?Eo:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Mo(t){if(!o.enableDirectionalInitialSync)return Ao(t)&&Z("init=/sync= modifiers require enableDirectionalInitialSync."),Eo;const e=null===(n=Io(t,g))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:Z(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":Z(`Invalid sync modifier value "${t}".`)}(Io(t,y));if("event"===t.bindingType)return null!==e&&"none"!==e&&Z("Event bindings only allow init=none."),"call"===s?Co:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===S)return To("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&Z(`Binding type "${t.bindingType}" does not support init=${e}.`),To(e??"state",s);const r=Ut(t.node);if(null===r)return To(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||Z(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||Z(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||Z(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let Oo=0,Lo=0;const Ro=["active","disposed","failed"],jo=new WeakMap,Do=new WeakMap,Wo=new WeakMap,zo=new WeakMap,Bo=new WeakMap;function Fo(t,e){const n=Bo.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Bo.set(t,new Set([n,e]))):Bo.set(t,e)}function Ho(t){return Bo.has(t)}function qo(t,e){const n=Bo.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Uo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Uo(n,e)}function Go(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class Vo{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.removedNodes;if(0===r.length||!bo(s.target,r.length))for(let t=0;t<r.length;t++)e.push(r[t]);const i=s.addedNodes;for(let t=0;t<i.length;t++)n.push(i[t])}const o=[];for(const t of e)go(t)||Uo(t,t=>{qo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)_o(t)&&!xo()||Uo(t,t=>{qo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&zi(o)}}const Ko=new WeakMap;function Jo(t){let e=Ko.get(t);return void 0===e&&(e=new Vo(t),Ko.set(t,e)),e}function Qo(t){const e=t.inFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|"),n=t.outFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function Xo(t,e,n){const o=Zi(nn(t,n));null===o&&Z("No state tree found on this root for binding.");const s=Fe(o,t.statePathInfo);return function(t,e,n){let o=cn.get(t);void 0===o&&(o=new WeakMap,cn.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==ge&&ge({type:"state:binding-added",absoluteAddress:ze(t,e),binding:n})}(s,e,t),s}function Yo(t,e){const n=on(t,e);return an(n,t),n}function Zo(t,e,n,o){null!==e?ln(e,t):function(t,e,n){const o=cn.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==ge&&ge({type:"state:binding-removed",absoluteAddress:ze(t,e),binding:n}))}(n,o,t),yn(t),sn(t)}function ts(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class es{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=this.rowOf(t),i=null===o?-1:o.bindings.indexOf(t);if(null!==o&&0===o.phases[i]){const e=o;this.observe(t.replaceNode),s.registerAddress&&null===e.addresses[i]&&null===e.patternPathInfos[i]&&(e.registered=!0,this.registerRowSlot(e,i));continue}const a=Do.get(t);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(t,s,n),r.push(t)):(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(t=>this.shouldApplyState(t))}activate(t,e){if(Go(e)&&Jo(e),null===this.rowPlan)for(const n of t){const t=Do.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return Ao(t)&&Mo(t),!0;const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0){if(!e.registered)return!0;if(2===e.phases[n])return!1;const t=e.plan.slots[n];return 1&e.flags[n]?"state"===t.authority||!t.policy.outputOnly:(e.flags[n]|=1,"state"===t.authority)}}const n=Do.get(t);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(t){const e=this.rowOf(t),n=null===e?-1:e.bindings.indexOf(t);if(null!==e&&n>=0)return{id:64*e.id+n,info:t,generation:e.generation,phase:Ro[e.phases[n]],teardowns:null};const o=Do.get(t);return o?.session===this?o:null}addTeardown(t,e){const n=Do.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(ts(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=Ht(t);null===s&&Z(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Fo(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,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=ko(s).wait(e,()=>{if(a())try{qt(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0)return void this.disposeRowSlot(e,n)}const n=Do.get(t);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(t){for(let e=0;e<t.length;e++)this.disposeBinding(t[e]);if(!(this.rows.size>0))for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}destroyRow(t){const e=t.length>0?this.rowOf(t[0]):null;null!==e?(this.destroyRowRecord(e),this.rows.delete(e)):this.destroyRecords()}destroyRowRecord(t){for(let e=0;e<t.bindings.length;e++){const n=t.addresses[e];null!==n&&(ln(n,t.bindings[e]),t.addresses[e]=null),t.phases[e]=1}}dispose(){for(const t of Array.from(this.rows))for(let e=0;e<t.bindings.length;e++)this.disposeRowSlot(t,e);for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.rows)this.destroyRowRecord(t);this.rows.clear();for(const t of this.records)null!==t.address&&(ln(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.rows)for(let n=0;n<e.bindings.length;n++)0===e.phases[n]&&t(e.bindings[n].node);for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];for(const e of this.rows)for(let n=0;n<e.bindings.length;n++){if(0!==e.phases[n])continue;if(null===e.addresses[n]&&null===e.patternPathInfos[n])continue;const o=e.bindings[n];this.unregisterRowSlot(e,n),this.registerRowSlot(e,n),this.shouldApplyState(o)&&t.push(o)}for(const e of this.records){if("active"!==e.phase)continue;const n=e.info;if(null===e.address&&null===e.patternListIndex)continue;const o="for"===n.bindingType?on(n):null;if(Zo(n,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null,this.registerAddress(e),null!==o){const t=on(n);t!==o&&ve(o)&&we(t,be(o)),t!==o&&Ie(o)&&Pe(t,xe(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return Go(e)?e:null}(t);null!==e&&Jo(e)}handleMutations(t,e,n){for(const n of e)Uo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Uo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&zi(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Do.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=zo.get(e);void 0===t&&(t=Qo(e),zo.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Fo(n,this);const o=this.knownMapFor(n);let s=zo.get(t);void 0===s&&(s=Qo(t),zo.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n=t.slots,o=e.length,s={id:++Oo,session:this,generation:++Lo,plan:t,bindings:e,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 t=0;t<o;t++){const o=e[t],r=o.replaceNode;if(Fo(r,this),this.addKnownRowBinding(r,o,t),jo.set(o,s),n[t].isEvent){try{Ln(o)}catch(e){throw s.phases[t]=2,e}s.flags[t]|=2}}}activatePlanRows(t,e,n){const o=e.length>0?this.rowOf(e[0]):null;if(null===o||o.bindings!==e){for(const t of e)this.initialize([t],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=t.slots;let r=!1;for(let t=0;t<e.length;t++)if(0===o.phases[t])null===o.addresses[t]&&null===o.patternPathInfos[t]&&this.registerRowSlot(o,t,n);else{if(r||(o.generation=++Lo,r=!0,this.rows.add(o)),o.phases[t]=0,o.flags[t]=0,s[t].isEvent){try{Ln(e[t])}catch(e){throw o.phases[t]=2,this.runRowSlotTeardowns(o,t),e}o.flags[t]|=2}this.registerRowSlot(o,t,n)}}rowOf(t){const e=jo.get(t);return void 0!==e&&e.session===this?e:null}registerRowSlot(t,e,n){if(null!==t.addresses[e]||null!==t.patternPathInfos[e])return;const o=t.bindings[e],s=tn(o);null!==s?(t.patternPathInfos[e]=Xo(o,s,n),t.patternListIndexes[e]=s):t.addresses[e]=Yo(o,n)}unregisterRowSlot(t,e){const n=t.addresses[e],o=t.patternPathInfos[e];null===n&&null===o||(Zo(t.bindings[e],n,o,t.patternListIndexes[e]),t.addresses[e]=null,t.patternPathInfos[e]=null,t.patternListIndexes[e]=null)}disposeRowSlot(t,e){if(1!==t.phases[e]){t.phases[e]=1,this.runRowSlotTeardowns(t,e);for(let e=0;e<t.phases.length;e++)if(0===t.phases[e])return;this.rows.delete(t)}}runRowSlotTeardowns(t,e){try{this.unregisterRowSlot(t,e)}catch{}if(2&t.flags[e]){t.flags[e]&=-3;try{Rn(t.bindings[e])}catch{}}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++Oo,info:t,generation:++Lo,phase:"discovered",teardowns:null,session:this,anchor:t.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};Do.set(t,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(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;Ln(e)?t.eventAttached=!0:e.propSegments[0]!==_?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=zn(t),s=Wn(t,o);let r=jn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.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 t of n)s=t.filterFn(s);const r=Zi(o.getRootNode());null===r&&Z("No state tree found on this root for two-way binding.");const i=pe(o);r.createState("writable",t=>{t[Ae](i,()=>{t[e]=s})})},jn.set(s,r)),t.node.addEventListener(o,r),Dn.add(s,t),!0}var e,n;return!1}(e)&&ts(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=zn(t),n=Wn(t,e),o=jn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Dn.countOf(n)&&(Dn.remove(n,t)&&jn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=$n(t),s=_n(t,o);let r=wn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.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 t of n)r=t.filterFn(r);const i=Zi(o.getRootNode());null===i&&Z("No state tree found on this root for two-way binding.");const a=pe(o);i.createState("writable",t=>{t[Ae](a,()=>{let n=t[e];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(t[e]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(t[e]=n.toSpliced(o,1))}else t[e]=s?[r]:[]})})},wn.set(s,r)),t.node.addEventListener(o,r),vn.add(s,t),!0}var e,n;return!1}(e)&&ts(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=$n(t),n=_n(t,e),o=wn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==vn.countOf(n)&&(vn.remove(n,t)&&wn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Hn(e.node,e.propName)&&-1===e.propModifiers.indexOf(m)){const n=function(t,e,n){let o=io.get(t);void 0===o&&(o=new Map,io.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&io.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});ts(t,n)}!function(t){const e=Bt(t.node);if(null!==e){const n=Ht(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&Z(`CustomElementRegistry is unavailable for <${e}>.`))}if(Hn(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const e=uo(t),n=ho(t),s=fo(t),r=co(t,e,null!==n,s);let i=so.get(r);void 0===i&&(i=((t,e,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!==ao||r||function(t,e,n){const o=t[e];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${e} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,e)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${e}" key while element.${e} is ${typeof o}`),null===s)return;let r=lo.get(t);void 0===r&&(r=new Set,lo.set(t,r)),r.has(e)||(r.add(e),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${t.tagName.toLowerCase()}> "${e}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${e}, or (e) => e.target.${e}) on that wcBindable property.`))}(a,t,l);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const t of n)c=t.filterFn(c);const u=io.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(o.enablePropagationContext){const n=Kn(a,t,e),s=function(t,e){for(let n=no.length-1;n>=0;n--){const o=no[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==ge&&ge({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Jn(n,"to-state"),node:a,member:t}));const r=Jn(n,"to-state"),i=to();if(null!==i&&i.visitedEdges.has(r))return void(null!==ge&&ge({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=Yn(i??Xn(n),r)}const h=Zi(a.getRootNode());null===h&&Z("No state tree found on this root for two-way binding.");const f=pe(a),p=()=>{r&&(oo=!0);try{h.createState("writable",t=>{t[Ae](f,()=>{t[e]=c})})}finally{r&&(oo=!1)}};null!==d?eo(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),so.set(r,i)),t.node.addEventListener(e,i),ro.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==_)return!1;const e=t.node,n=Bt(e),o=Ht(e);if(null!==n&&void 0===o?.get(n))return null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(An.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||Z('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Bt(t)?null:Ut(t)}(e);null===r&&Z(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&Z(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${rt(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,c=t.propModifiers,u=t=>{c.includes(f)&&t.preventDefault(),c.includes(p)&&t.stopPropagation();const n=Zi(e.getRootNode());null===n&&Z("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||Z(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${rt(l,n.eventTokenNames)}${it}`);const o=pe(e);n.createStateAsync("writable",async e=>{xn(e[Ae](o,()=>{const s=null!==o?Ye(o.listIndex,o.pathInfo.wildcardCount):[];return In(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,u),An.set(t,{eventName:a,handler:u}),!0})(e)&&ts(t,()=>function(t){if(t.propSegments[0]!==_)return!1;const e=An.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),An.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Bt(t.info.node);if(null===n)return void e();const o=Ht(t.info.node);if(null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=ko(o).wait(n,()=>{if(this.isAlive(t,s))try{qt(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});ts(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Mo(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=Zi(t.replaceNode.getRootNode());null===e&&Z("No state tree found on this root for binding.");const n=gn(t);let o=!1;return e.createState("readonly",t=>{o=t[Ce](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void $o++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,So()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=Zi(t.node.getRootNode());null===o&&Z("No state tree found on this root for initial binding sync.");const s=pe(t.node);o.createState("writable",e=>{e[Ae](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=tn(n);if(null!==o?(t.patternPathInfo=Xo(n,o,e),t.patternListIndex=o):t.address=Yo(n,e),!t.options.registerPathInfo)return;const s=Zi(n.replaceNode.getRootNode());null===s&&Z("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Do.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,So());const e=t.info;if(null!==t.address||null!==t.patternListIndex)try{Zo(e,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=Bt(t.node);if(null!==e){const n=Ht(t.node),o=n?.get(e);if(void 0===o)return}if(Hn(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const e=uo(t),n=co(t,e,null!==ho(t),fo(t)),o=so.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),ro.remove(n,t)&&so.delete(n)}}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{Rn(e)}catch{}}}}function ns(t){let e=Wo.get(t);return void 0===e&&(e=new es(t),Wo.set(t,e)),e}function os(t){return Do.get(t)?.session??jo.get(t)?.session??null}let ss=null;function rs(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const is=Object.freeze([]),as=new WeakMap,ls=new WeakMap;function cs(t){return ls.get(t)??[]}function us(t,e){ls.set(t,e)}const ds=new WeakMap;function hs(t){return ds.get(t)??[]}function fs(t,e){ds.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let ps=0;function ms(){return`u${(ps++).toString(36)}`}let gs=0,ys=0;const bs=Symbol("wcs.listIndex.noValue");class ws{uuid=ms();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=bs,this._index=e,this._version=gs,this._chainGeneration=ys}get index(){return this._index}set index(t){this._index=t,this._version=++gs,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(t){this._value=t}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=gs),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===ys||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=ys),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++gs,ys++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function vs(t,e,n=t){return new ws(t,e,n)}function _s(t,e){t.reparent(e)}function $s(t){return t.homeParentListIndex}function Ss(t,e){t.value=e}function xs(t,e){const n=t.value;return n!==bs&&n===e.value}const Ps=new WeakMap,Ns=new WeakSet;function ks(t){return Ns.has(t)}function Is(t){const e=Ps.get(t);return void 0===e?null:e}function As(t,e){const n=Ps.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o){const t=function(t,e){const n=$s(t),o=t.parentListIndex;return null===n||n===o||Ns.has(n)?function(t,e,n){return null!==t&&null!==n&&n!==e&&!!Ns.has(t)&&!Ns.has(n)&&n.position===t.position&&xs(n,t)}(n,o,e)||function(t,e){return t!==e&&null!==t&&null!==e&&t.position===e.position&&Ns.has(t)&&!Ns.has(e)}(o,e)?e:null:n}(o,e);if(null!==t)for(const e of n)_s(e,t)}return n}function Es(t,e){null!==e?Ps.set(t,e):Ps.delete(t)}const Cs=new WeakMap;function Ts(t,e){null===e?Cs.delete(t):Cs.set(t,e)}function Ms(t){const e=Cs.get(t);e&&(e.dirty=!0)}const Os=Symbol.for("wcstack.transition-runner");function Ls(t){const e=globalThis[Os];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}function Rs(t,e,n){const o=Ls(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const js=[],Ds=[];function Ws(t){Ds.includes(t)||Ds.push(t)}function zs(t,e=0){const n=js.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?js.push(o):js.splice(n,0,o)}function Bs(t){queueMicrotask(()=>{throw t})}const Fs=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){for(let e=0;e<Ds.length;e++)Ds[e](t);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(t){const e=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(t),e&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Ne(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(t,e)})}hasQueuedPath(t,e){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===t&&n.absoluteAddress.absolutePathInfo.pathInfo.path===e)}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t,n=[]){const o=new Map,s=new Set;for(let e=0;e<t.length;e++){const n=t[e],r=o.get(n.absoluteAddress);null!==ge&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&ge({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 t=0;t<n.length;t++){const e=n[t];o.has(e)||o.set(e,null)}const r=[],i=new Map;o.forEach((t,e)=>{if(null!==t&&t.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,transactionId:t.transactionId,hop:t.hop,maxHops:32}),void(null!==ge&&ge({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop}));const n=un(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(r.push(e),null!==t&&i.set(e,t));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==t&&i.set(n,t))});try{const t=()=>{i.size>0?zi(r,i):zi(r)};if(e()||0===r.length)t();else{const e=Rs("state",t);void 0!==e&&e.catch(Bs)}}finally{ke(),function(t){for(const e of js.slice())e.listener(t)}(s)}}};function Hs(){return Fs}const qs=new WeakMap,Us=new WeakMap,Gs=new WeakMap,Vs=new WeakMap;let Ks=!1;const Js=new WeakMap,Qs=new WeakMap,Xs=new WeakMap,Ys=[];function Zs(t,e){const n=tr(t);if(n.recorded.has(e))return;n.recorded.add(e);const o=nt(e).cumulativePaths;if(o.length<2)return;let s=Xs.get(t);void 0===s&&Xs.set(t,s=new Map);for(let t=0;t<o.length-1;t++){let n=s.get(o[t]);void 0===n&&s.set(o[t],n=new Set),n.add(e)}}function tr(t){let e=qs.get(t);return void 0===e&&qs.set(t,e={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),e}function er(t,e,n){let o=t.get(e);void 0===o&&t.set(e,o=new Set),o.add(n)}function nr(t,e,n){const o=t.get(e);o.delete(n),0===o.size&&t.delete(e)}function or(t,e,n,o){const s=function(t,e){let n=t.byPath.get(e);return void 0===n&&t.byPath.set(e,n=new Map),n}(t,e);let r=Us.get(o);if(void 0===r&&Us.set(o,r=new Map),r.has(e)){const t=r.get(e);return Object.is(t,n)||(nr(s,t,o),r.set(e,n),er(s,n,o)),!1}return r.set(e,n),er(s,n,o),!0}function sr(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function rr(t,e,n,o,s,r){t.lastValue.set(e,n),s&&(null!==o.listIndex&&sr(Gs,o.listIndex,r),null!==r.levelListIndex&&sr(Vs,r.levelListIndex,r))}function ir(t,e,n,o,s){Ks=!0;const r=tr(t);Zs(t,e),rr(r,e,s,o,or(r,e,n,o),{stateElement:t,path:e,absAddress:o,levelListIndex:null})}function ar(t,e){tr(t).tracked.add(e)}function lr(t,e,n){if("number"!=typeof e)return;const o=t.indexes[e];if(void 0!==o)for(const e of t.getters)n.push(qe(t.stateElement,pn(e,o)))}function cr(t,e){if(void 0!==t)for(const n of t)e.push(n)}function ur(t,e,n,o,s){const r=qs.get(t),i=r?.byPath.get(e),a=Js.get(t)?.get(e);if(void 0===r||void 0===i&&void 0===a)return Ys;const l=r.lastValue.has(e),c=r.lastValue.get(e);r.lastValue.set(e,s);const u=[],d=!n||!Object.is(o,s),h=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&cr(i.get(o),u),h&&cr(i.get(c),u),d&&cr(i.get(s),u)),void 0!==a)for(const t of a)n&&lr(t,o,u),h&&lr(t,c,u),d&&lr(t,s,u);return u}function dr(t,e){let n=t;for(const t of e){if("object"!=typeof n||null===n)return;n=n[t]}return n}function hr(t,e,n){const o=qs.get(t).byPath.get(e);if(void 0!==o)for(const t of o.values())cr(t,n);const s=Js.get(t)?.get(e);if(void 0!==s)for(const t of s)for(let e=0;e<t.indexes.length;e++)lr(t,e,n)}function fr(t){const e=Vs.get(t.levelListIndex),n=e.indexOf(t);e.splice(n,1)}function pr(t){if(!Ks)return;const e=Gs.get(t);if(void 0!==e){Gs.delete(t);for(const t of e){const{stateElement:e,path:n,absAddress:o}=t,s=Us.get(o),r=s.get(n);s.delete(n),nr(qs.get(e).byPath.get(n),r,o),null!==t.levelListIndex&&fr(t)}}}function mr(t,e,n){if(!Ks)return;const o=Vs.get(t);if(void 0!==o)for(const{stateElement:t,path:s,absAddress:r}of o){const o=qs.get(t),i=o.byPath.get(s);nr(i,e,r),er(i,n,r),Us.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,e)||Object.is(a,n))&&(Ms(r),Hs().enqueueAbsoluteAddress(r,null))}}const gr=new WeakMap,yr=Object.freeze([]),br=new Set;function wr(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:yr,s=Array.isArray(n)&&n.length>0?n:yr,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:yr,o=Array.isArray(e)&&e.length>0?e:yr;let s=gr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=As(o,t)||[],a=i.length>0?$s(i[0]):t;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:br,deleteIndexSet:new Set(i),addIndexSet:br};let e=As(s,t);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=vs(t,n,a);e.push(o)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:br,deleteIndexSet:br,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:br,deleteIndexSet:br,addIndexSet:br};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],u=n.get(l),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=vs(t,o,a);e.push(n),c.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:c}}finally{void 0!==l&&(function(t,e,n){let o=gr.get(t);o||(o=new WeakMap,gr.set(t,o)),o.set(e,n)}(o,s,l),Es(s,l.newIndexes))}}(t,e,n);!function(t,e){for(let n=0;n<t.length;n++){if(t[n].index!==n){const e=t[n].index;t[n].index=n,mr(t[n],e,n)}Ss(t[n],e[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:yr),function(t){for(const e of t)Ns.add(e)}(o.deleteIndexSet);for(const t of o.deleteIndexSet)pr(t);return function(t){for(const e of t)Ns.delete(e)}(o.newIndexes),function(t,e){if(!Ks||t===e)return;const n=Qs.get(t);if(void 0===n)return;Qs.delete(t);const o=Qs.get(e);Qs.set(e,void 0===o?n:o.concat(n));for(const o of n){o.indexes=e;const n=tr(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=t[n],r=e[n];if(s!==r)for(const t of[s,r])if(void 0!==t&&!ks(t))for(const e of o.getters){const n=qe(o.stateElement,pn(e,t));Ms(n),Hs().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}const vr=new WeakSet,_r=new WeakMap;function $r(t){return _r.get(t)??null}function Sr(t,e){_r.set(t,e)}const xr=new WeakMap;function Pr(t){return xr.get(t)??[]}function Nr(t,e){xr.set(t,e)}function kr(t,e){const n=Pr(t);for(const t of n)me(t,e)}const Ir=new WeakMap,Ar=new WeakMap;function Er(t,e){for(let n=0;n<t.length;n++)if(e.has(t[n]))return!0;return!1}function Cr(t,e,n){kr(t,e);const o=cs(t),s=$r(t);if(null!==s&&(s.activate(o,n.rootNode),null!==e&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(t){return Ir.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=Ar.get(t);void 0===o&&Ar.set(t,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=e.map((e,o)=>{const s=t.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=e.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const t of a){if("*"===t)return null;c+="."+t,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(t,e,o.pathInfo.path),i=s.stateElement.getterPaths;let a,l=!1;for(let t=0;t<e.length;t++){const c=e[t];if(!n.shouldApplyState(c))continue;const u=r[t];if(null===u||Er(u.prefixes,i)){Di(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[Ee](o),l=!0);const d=u.tail;let h=a;for(let t=0;t<d.length;t++){if(null==h){h=void 0;break}h=h[d[t]]}ji(c,s,h)}}(r,o,s,e,n)}for(const t of o)null===s&&an(on(t),t),(null===s||s.shouldApplyState(t))&&Di(t,n)}function Tr(t){if(!t.mounted)return;const e=cs(t),n=$r(t);for(let t=0;t<e.length;t++){const o=e[t];null!==n?n.disposeBinding(o):ln(on(o),o)}!function(t){const e=Pr(t);for(let t=0;t<e.length;t++)me(e[t],null)}(t)}const Mr=new WeakMap,Or=Object.freeze(new Set);function Lr(t,e){const n=Mr.get(t);n?n.add(e):Mr.set(t,new Set([e]))}function Rr(t){const e=Mr.get(t);return void 0!==e?e:Or}function jr(t,e){const n=Mr.get(t);n&&(n.delete(e),0===n.size&&Mr.delete(t))}function Dr(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o];n.push({filterName:s.filterName,args:s.args,filterFn:ft(s.filterName,s.args,e,s.literals??s.args)})}return n}function Wr(t){return{...t,inFilters:Dr(t.inFilters,"input"),outFilters:Dr(t.outFilters,"output")}}const zr=new Set(["if","elseif","else","for"]);class Br{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e;const n=[];for(let e=t.firstChild;null!==e;e=e.nextSibling)n.push(e);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(t){const e=this._childNodeArray;for(let n=0;n<e.length;n++){const o=e[n];vo(o),t.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){vo(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=$r(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRow(cs(this));const e=this._childNodeArray;for(let t=0;t<e.length;t++){const n=e[t];null!==n.parentNode&&(mo(n),n.parentNode.removeChild(n))}const n=cs(this);for(let t=0;t<n.length;t++){const e=n[t];zr.has(e.bindingType)&&Rr(e.node).forEach(t=>{t.tryDestroy()||t.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const t=$r(this);null!==t&&(t.isRowSession?t.disposeBindings(cs(this)):t.dispose())}this._teardownBindings()}_teardownBindings(){const t=cs(this);for(let e=0;e<t.length;e++){const n=t[e];zr.has(n.bindingType)&&Rr(n.node).forEach(t=>{t.unmount()}),yn(n),sn(n)}}unmount(){{const t=$r(this);null!==t&&(t.isRowSession?t.disposeBindings(cs(this)):t.dispose())}for(const t of this._childNodeArray)null!==t.parentNode&&(mo(t),t.parentNode.removeChild(t));const t=cs(this);for(let e=0;e<t.length;e++){const n=t[e];zr.has(n.bindingType)&&Rr(n.node).forEach(t=>{t.unmount()}),yn(n),sn(n)}this._mounted=!1}}function Fr(t){const e=document.createDocumentFragment(),n=new Br(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function Hr(t){void 0!==t.uuid&&null!==t.uuid||Z("BindingInfo.uuid is null.");const n=ia(t.uuid);n||Z(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=Zt(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===S||s===_)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Bt(r))return null;if("prop"===o&&Hn(r,t.propName))return null;const i=Wr(t);let a;try{a=Mo({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:e,template:i,isEvent:"event"===o,isIndexBinding:t.statePathName in I,policy:a,authority:a.authority})}}return{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=Zt(o,s[t].nodePath);null===e&&Z(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),ue(e),Wt(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e,n){let o=Fi.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new es,Fi.set(n,o)),o.initializeRow(t,e),o}(n,a,t.node),u=new Br(o);return Sr(u,c),us(u,a),function(t,e){Ir.set(t,e)}(u,n),fs(u,l),Nr(u,r),Lr(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=Zt(t,s.nodePath);if(null===e&&Z(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),ae.has(e))continue;const r=le(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new es;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new Br(i,s);Sr(l,a.bindingSession),us(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in I&&c.push(t);return fs(l,c),Nr(l,a.nodes),Lr(t.node,l),l}const qr=new WeakSet,Ur=Symbol.for("wcstack.state.view-transition-naming");function Gr(){const t=Ls("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Vr(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||qr.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[Ur]??={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.`)):(qr.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const Kr=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,Xr=new WeakMap;function Yr(t,e,n){!function(t,e,n){let o=Jr.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Jr.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Zr(t,e){Kr.set(t,e)}function ti(t){return t.nodeType===Node.ELEMENT_NODE||(t.nodeType===Node.TEXT_NODE?""!==(t.textContent?.trim()??""):t.nodeType===Node.COMMENT_NODE&&t.data.startsWith("@@wcs-"))}function ei(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const ni=new Set(["if","elseif","else","for"]);function oi(t,e){for(const n of cs(t))if(e.appliedBindingSet.delete(n),ni.has(n.bindingType))for(const t of Rr(n.node))oi(t,e)}function si(t){for(const e of cs(t)){if(!ni.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of Rr(e.node))si(n),t&&n.mounted&&(Tr(n),n.unmount(),jr(e.node,n))}}function ri(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function ii(t,n,s){const r=Boolean(s);let i;const a=Rr(t.node);i=0===a.size?Hr(t):a.values().next().value;const l=e(),c=t.uuid??"",u=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${ri(t)}`),Tr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${ri(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);Cr(i,pe(t.node),n);const e=Gr();null!==e&&Vr(i,"branch",e)}}const ai=new WeakMap;function li(t){return ai.get(t)??[]}const ci=new Set,ui=Symbol.for("wcstack.trustedTypes.policy");function di(){const t=globalThis[ui];return null===t||"object"!=typeof t?null:t}let hi,fi=!1;const pi={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}},mi=new Set(["textContent","innerText","innerHTML"]);function gi(t,n,s){if(void 0===s&&1===t.propSegments.length&&mi.has(t.propSegments[0])&&(s=""),void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0],u=r[c];if(u!==s){null!==ss&&null!==u&&"object"==typeof u&&null!==s&&"object"==typeof s&&null!==Bt(r)&&ss.rememberOverwrittenObject(r,c,u);const e="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let t=!1;try{r[c]=e?function(t){if("string"!=typeof t)return t;const e=di(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(fi)return;if(!function(){if(void 0!==hi)return hi;if(!("trustedTypes"in globalThis))return hi=!1,hi;try{document.createElement("div").innerHTML="<i></i>",hi=!1}catch{hi=!0}return hi}())return;fi=!0;const n="function"==typeof di()?.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 "${e}" 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:t,property:e})}(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=Bt(t);if(null===n)return null;const o=Ht(t)?.get(n);if(void 0===o)return null;const s=Ut(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&Hn(r,c)){const e=Kn(r,c,t.statePathName),o=Jn(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??to()??Xn(e);if(a.visitedEdges.has(o))null!==ge&&ge({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=Yn(a,o);eo(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Gn++,writtenValue:n};no.push({receipt:i,node:t});try{return r()}finally{no.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=pi[c];t?t(r,s):(function(t,e,n){let o=ai.get(t);o||(o=[],ai.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,s),a=r,ci.add(a))}return}var a,l;const c=i[0];let u=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==u)return;u=u[e]}const d=i[i.length-1],h=u[d];if(h!==s){if(Object.isFrozen(u))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:s}));null!==ss&&2===i.length&&"object"==typeof u&&null!==u&&null!==Bt(r)&&(d in u?ss.rememberOverwrittenValue(r,c,d,u[d]):ss.recordInjectedKey(r,c,d));try{u[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:s,error:t})}}}const yi=new WeakSet;function bi(t,e,n){}function wi(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function vi(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),s=e.length>0?e+a:"";for(const t of n){if(s.length>0&&!t.startsWith(s))continue;const e=t.slice(s.length);e.length>0&&-1===e.indexOf(a)&&o.push(e)}return o}const _i={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},$i={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Si(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${it}`}function xi(t,e){return`[wcs/recursion-anchor] "${t}" does not match the declared recursion anchor "${e}". 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 Pi(t,e){return`$setAll("${t}") ${e}`}function Ni(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} 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.${it}`}const ki=new WeakSet;function Ii(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Ai=Object.freeze({[x]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&Z("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[P]:function(t,e,n){const o=t.node,s=t.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[N]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[S]:function(t,e,n){Cn(n)||Z("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=as.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||Z('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Bt(t);if(null===e)return null;const n=Ht(t)?.get(e);return void 0===n&&Z(`Custom element <${e}> is not defined for command binding.`),Ut(t)}(r);null===a&&Z(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||Z(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${rt(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),as.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void as.delete(t);const o=n[i];return"function"!=typeof o&&Z(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),as.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Ei={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!yi.has(t.replaceNode)){yi.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,r=tn(t),i=on(t),a=be(i),c=a.length>0&&!Jr.has(t.node)?[]:a,u=wr(r,c,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let d=Jr.get(t.node);const h=void 0!==d?function(t,e,n){if(o=e,!vr.has(o))return null;var o;let s=null;for(let e=0;e<n.newIndexes.length;e++){const o=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?t.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}(d,c,u):null,f=Array.isArray(c)&&c.length===u.deleteIndexSet.size&&u.deleteIndexSet.size>0;if(f&&null===h&&null!==t.node.parentNode){let e=Xr.get(t.node);if(void 0===e){const n=Kr.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(ti(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(ti(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n),Xr.set(t.node,e)}if(e){const e=t.node.parentNode;!function(t,e){yo.set(t,(yo.get(t)??0)+e)}(e,e.childNodes.length),e.textContent="",e.appendChild(t.node)}}let p=f?1e3-function(t){return Qr.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==d){const e=d;u.deleteIndexSet.forEach(n=>{const o=e.get(n);void 0!==o&&(null!==h&&h.reused.has(o)?(Tr(o),si(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?jr(t.node,o):(Tr(o),o.unmount(),function(t,e){let n=Qr.get(t.node);void 0===n&&(n=[],Qr.set(t.node,n)),n.length<1e3?n.push(e):jr(t.node,e)}(t,o),p-=1),f||e.delete(n))}),f&&(Jr.delete(t.node),d=void 0)}let m=t.node;const g=nt(s.path+"."+l),y=n.stateElement.loopContextStack,b=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.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(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?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 t of i)a.add(n[t]);return a}(u);let w=null;u.newIndexes.length==u.addIndexSet.size&&u.newIndexes.length>0&&m.isConnected&&null===h&&(w=document.createDocumentFragment(),Ve(w,n.rootNode));const v=e(),_=Gr(),$=t.uuid??"",S=Qr.get(t.node);for(const e of u.newIndexes){let o;if(u.addIndexSet.has(e)){const r=pn(g,e);if(y.createLoopContext(r,r=>{if(o=h?.byAddedIndex.get(e)??(void 0!==S?S.pop():void 0),void 0===o?o=Hr(t):oi(o,n),null!==w)v&&w.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`)),o.appendTo(w),v&&w.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const t=document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`);m.parentNode.insertBefore(t,m.nextSibling),m=t}o.mountAfter(m)}if(v){const t=document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`),n=o.lastNode??m;n.parentNode.insertBefore(t,n.nextSibling)}}Cr(o,r,n),null!==_&&Vr(o,"row",_)}),void 0===o&&Z(`Content not found for ListIndex: ${e.index} at path "${s.path}"`),null!==h&&h.reused.has(o)){const t=n.stateElement.addressHooks;if(t){const e=t.rowReused;for(let t=0;t<e.length;t++)e[t](n.stateElement,o)}}}else{if(o=void 0!==d?d.get(e)??null:null,u.changeIndexSet.has(e)){const t=hs(o);for(const e of t)Di(e,n)}null===o&&Z(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==b&&b.has(e)&&ei(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),t){const t=o,s=pn(g,e);y.createLoopContext(s,e=>{Cr(t,e,n)})}}m=o.lastNode||m,void 0===d&&(d=new WeakMap,Jr.set(t.node,d)),d.set(e,o)}Kr.set(t.node,m),null!==w&&(t.node.parentNode.insertBefore(w,t.node.nextSibling),Ve(w,null))},if:ii,else:ii,elseif:ii,radio:function(t,e,n){const o=t.node,s=rs(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=rs(o.value,t.inFilters),r=Array.isArray(n)?n:is;o.checked=r.includes(s)}},Ci=new WeakMap,Ti=new WeakMap,Mi=new WeakMap;function Oi(){}function Li(t){const e=ss;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return bi;if(e.isDeclared(n,o))return Oi}return gi}function Ri(t,e){ji(t,e,function(t,e){const n=gn(e);if(n.pathInfo.path in I){const t=pe(e.node);return null===t&&Z(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&Z("ListIndex not found for loopContext:");const n=I[e];void 0===n&&Z(`Invalid index name: ${e}`);const o=Xe(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&Z(Ni(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Ee](n)}(e.state,t))}function ji(t,e,n){const o=rs(n,t.outFilters);if(!0===Ti.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=Ci.get(t);if(void 0===s){if(Ci.has(t))return s=Li(t),s===bi&&Ci.set(t,s),void s(t,e,o);if(s=Ei[t.bindingType],void 0===s){const e=t.propSegments[0];s=Ai[e],Ci.set(t,s),void 0===s&&(Bt(t.replaceNode)?(s=Li(t),s===bi&&Ci.set(t,s)):(s=gi,Ci.set(t,s)))}if(s===gi&&"SELECT"===t.node.tagName){const n=t.propSegments[0];if("value"===n||"selectedIndex"===n)return e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement}),void Ti.set(t,!0)}s(t,e,o)}else s(t,e,o)}function Di(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=on(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=os(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Mi.get(t)){const e=Bt(t.replaceNode);if(e&&void 0===Ht(t.replaceNode)?.get(e))return void function(t,e){if(ki.has(t))return;ki.add(t);const n=()=>{ki.delete(t);const e=os(t);(null===e||e.shouldApplyState(t))&&zi([t])},o=n=>{ki.delete(t),Ii(e,n)},s=os(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{ki.delete(t),r()})||(ki.delete(t),r()))}const r=Ht(t.replaceNode);if(null===r)return ki.delete(t),void Ii(e,new Error("CustomElementRegistry is unavailable."));ko(r).wait(e,()=>{t.replaceNode.isConnected?n():ki.delete(t)},o)}(t,e);Mi.set(t,!0)}if(!0===e.sameRootVerified)return void Ri(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Ke(o),null===o&&Z("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Zi(o);null===n&&Z("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};Ri(t,r)})}else Ri(t,e)}function Wi(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==ge&&ge({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function zi(t,e,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<t.length;){let n=t[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 u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=Ke(u),null===u&&Z("Root node for fragment not found for binding."));const d=Zi(u);null===d&&Z("No state tree found on this root for binding."),d.createState("readonly",o=>{const h={rootNode:u,stateElement:d,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Di(n,h)}catch(t){Wi(n,t,d,c)}s++;const e=t[s];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{gi(t,{propagationContextByBinding:e},n)}catch(e){Wi(t,e,o??null,c)}for(const[t,e]of i.entries())we(t,e),Pe(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[Le](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[Re](n,o)}catch(t){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:t,original:n,node:o.node})}})}function Bi(t,e,n){const[o,s,r]=ce(t,n),i=ns(t);for(const t of o)me(t,e);zi(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=de(o);0!==t.length&&(me(o.node,e),zi(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const Fi=new WeakMap;async function Hi(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Ht(t);null===s&&Z(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(oe(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function qi(t){if(t===document)await Hi(document),X(document),Sa(document,document),Bi(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await Dt(e.host),await Hi(e),X(e),Sa(e,e),Bi(e,null)}}const Ui={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function Gi(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${Ui[t]??t}" before the state is defined.`}let Vi=null;function Ki(t){return null===Vi&&Z(Gi("ssr",t)),Vi}const Ji=new WeakMap,Qi=new WeakMap,Xi=new Set,Yi=[];function Zi(t){return Ji.get(t)??null}function ta(t){return Qi.get(t)??Promise.resolve()}const ea=new WeakSet;function na(t){ea.add(t)}function oa(t,n){const s=Ji.get(t);if(null===n){if(void 0===s)return;Ji.delete(t),Xi.delete(s),null!==ge&&ge({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{o&&await Ki('the "enable-ssr" attribute').hydrate(t)||await qi(t),na(t),Aa(),e()}catch(t){n(t)}})});Qi.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await qi(t),na(t),Aa(),e()}catch(t){n(t)}})});Qi.set(t,e)}}void 0!==s&&Z('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Ji.set(t,n),Xi.add(n);for(let e=0;e<Yi.length;e++)Yi[e](t,n);null!==ge&&ge({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}const sa=new Map;function ra(t,e,n){if(null===n)sa.delete(t);else{sa.set(t,n);const o=Zi(e);null===o&&Z("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function ia(t){return sa.get(t)||null}function aa(t){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=At(e.getAttribute(o.bindAttributeName)||"");return e.localName===o.tagNames.state&&e.hasAttribute("mount")?n.filter(t=>t.propSegments[0]!==$):n}if(t.nodeType===Node.COMMENT_NODE){const e=Mt(t);null===e&&Z("Comment node binding text not found.");const n=ia(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Ot(e),s=null):s=e,[{...o,uuid:s}]}return[]}let la;function ca(){return la??={filterName:"not",args:[]}}const ua=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function da(t,e){const n=e+a+l,o=t.indexOf("|");let s,r;if(-1!==o?(s=t.slice(0,o).trim(),r=t.slice(o)):(s=t.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return t;s=n+a+s.slice(1)}return r.length>0?s+r:s}function ha(t,e){const n=ua.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+da(s,e)+r}function fa(t,e){const n=t.split(";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=n.indexOf(":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=da(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function pa(t,e){return fa(t,e)}function ma(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=ha(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=fa(r,e);t!==r&&o.setAttribute(n,t)}}}function ga(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}function ya(t){const e=[],n=ie(t);for(const t of n){const n=aa(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:ga(o),parseBindTextResults:n})}return e}function ba(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const wa=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),va=ca();function _a(t,e){const n=e.outFilters;return{...e,outFilters:[...n,va],bindingType:t}}function $a(t,e,n,o,s,r=!0){ba(e),"string"==typeof o&&ma(e,o),Sa(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:ya(e)};return void 0!==s&&function(t,e,n){for(const o of t)for(let t=0;t<o.parseBindTextResults.length;t++){const s=o.parseBindTextResults[t];null==s.uuid&&(o.parseBindTextResults[t]=e(s,n))}}(i.nodeInfos,s,o),i}function Sa(t,e,n,s){const r=o.commentElsePrefix,i=se(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],u=[];for(;a.nextNode();){const t=a.currentNode;u.push(t)}for(const e of u){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=pa(i,n));let a=At(i)[0];const u=wa.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=ms();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&Z("'else' binding found without preceding 'if' or 'elseif' binding."),a=_a("else",l.parseBindTextResult),p=$a(t,h,a,m,s,!1),ra(f,t,p);const n=c.at(-1),o=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:ga(o),parseBindTextResults:aa(o)})):e.replaceWith(o)}else if("elseif"===d){null===l&&Z("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=$a(t,h,a,m,s),ra(f,t,p);const n=document.createComment(`@@${u}:${f}`),o=ms(),i={fragment:document.createDocumentFragment(),parseBindTextResult:_a("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ga(n),parseBindTextResults:aa(n)}),ra(o,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:ga(g),parseBindTextResults:aa(g)})):e.replaceWith(g)}else{p=$a(t,h,a,m,s),ra(f,t,p);const n=document.createComment(`@@${u}:${f}`);e.replaceWith(n)}"if"===d?(c.length=0,l=p):"elseif"===d?l=p:"else"===d&&(l=null,c.length=0)}}const xa=()=>`[${o.bindAttributeName}]`;function Pa(t){if(Ho(t))return!0;if(!Na(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(xa());return null!==e&&Ho(e)}function Na(t){return 1===t.nodeType}function ka(t){if(Pa(t))return;X(t),Sa(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Bi(e&&s?n:t,null)}const Ia=[];function Aa(){const t=Ia.splice(0,Ia.length);for(const e of t)ka(e);!function(){const t=function(){const t=globalThis[s];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[r];return void 0===e&&(e=[],t[r]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[i];return void 0===e&&(e=new WeakSet,t[i]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const Ea={protocol:"wcs-binder",version:1,bind:function(t){var e;Na(t)&&!Pa(t)&&(e=t.getRootNode(),ea.has(e)?ka(t):Ia.push(t))}},Ca="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ta=0;async function Ma(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++Ta}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" 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 ${Ca}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${Ca}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Oa(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){Z(`Failed to load script file: ${t}`)}}class La{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&Z("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=u&&Z("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&Z("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&Z("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&Z(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(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 Ra=new WeakMap;function ja(t,e){let n=Ra.get(t);void 0===n&&(n=new Map,Ra.set(t,n));let o=n.get(e);return void 0===o&&(o=new En(e,t),n.set(e,o)),o}const Da=new WeakMap;function Wa(t){const e=Da.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return ja(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:ja(t,n)}},set(){Z("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){Z("$command namespace is read-only; deleting from it is not allowed.")}});return Da.set(t,n),n}const za=Symbol("wcs.notHandled"),Ba=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Fa=new Map;function Ha(t,e){Fa.set(t,e)}const qa=new Map;let Ua=[],Ga=[];function Va(t,e){qa.set(t,e),Ua=Array.from(qa.values()).sort((t,e)=>t.order-e.order),Ga=Ua.slice().reverse()}function Ka(t,e){for(let n=0;n<Ua.length;n++)Ua[n].activate?.(t,e)}function Ja(t){"readonly"===t.mutability&&Z("This state is readonly.")}const Qa=new Map;class Xa{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=nt(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Ya(t){let e;return Qa.get(t)??(Qa.set(t,e=new Xa(t)),e)}function Za(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:Xe(n.listIndex,o,n.pathInfo.wildcardCount)}function tl(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=Qe(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?Xe(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?Xe(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}function el(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function nl(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](t,e,n,o,s);if(a!==za)return a}}return za}function ol(t,e,n,o,s){if(e.pathInfo.segments[0]===j)return function(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}(Wa(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){if(null===e.parentAddress){const r=nl(s,e,null,n,o);if(r!==za)return r;Z(function(t,e,n){return`[${_i.binding}] Path "${t}" does not exist on the state tree.${rt(t,vi(e,"",n))}${it}`}(e.pathInfo.path,t,s.getterPaths))}const r=sl(t,e.parentAddress,n,o);if(null==r)return;const i=e.pathInfo.segments[e.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==l&&!(i in Object(r))){const t=nl(s,e,Object(r),n,o);if(t!==za)return t}if(i===l){const t=e.listIndex?.index??Z(Ni(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(r,t)}return Reflect.get(r,i)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}function sl(t,e,n,o){tl(o,e),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,e.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const t=r.read;for(let r=0;r<t.length;r++){const i=t[r](s,e,n,o);if(i!==za)return i}}return el(s,e)?function(t,e,n,o,s){const r=qe(s,e),i=function(t){return Cs.get(t)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=ol(t,e,n,o,s);return Ts(r,{value:l,dirty:!1,generation:a}),l}(t,e,n,o,s):ol(t,e,n,o,s)}function rl(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,u,d)=>{const h=o[s]??null;if(null===h)return void d.push(u);const f=pn(h,r),p=qe(n.stateElement,f),m=xe(p),g=sl(t,f,e,n),y=wr(r,m,g).newIndexes,b=l[c]??null;if(i.set(p,g),null===b)for(let t=0;t<y.length;t++){const e=y[t];a(o,s+1,e,l,c+1,u.concat(e.index),d)}else{const t=y[b]??Z(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,u.concat(t.index),d):d.push(u.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Pe(t,Array.isArray(e)?e:[]);return l}function il(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=As(sl(t,pn(a,r),e,n),r);null==l&&Z(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??Z(`ListIndex not found at index ${c} of ${a.path}`)}return r}function al(t,e,n,o){"object"==typeof t&&null!==t||Z(`${U} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&Z(`${U} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function ll(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&Z(`${U} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function cl(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];al(a,n,o,i);const l=ll(a,e,n,o,i);r.has(l)&&Z(`${U} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function ul(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function dl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const r=sl(t,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=e.pathInfo.lastSegment;if(i===l){const t=e.listIndex?.index;return"number"==typeof t&&t in r}return i in r}const hl=new WeakMap;function fl(t,e){null===e?hl.delete(t):hl.set(t,e)}function pl(t,e,n){const s=pn(nt(t.wildcardParentPaths[e]),n),r=qe(t.stateElement,s),i=xe(r),a=t.stateProxy[Ee](s),l=wr(s.listIndex,i,a);t.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(l,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)pl(t,e+1,n)}const ml=[];function gl(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:ml,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:ml,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const yl=[];function bl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return yl;let s=null;const r=e+a;for(const t of o){if(t!==e&&!t.startsWith(r))continue;const o=nt(t);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??yl}function wl(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const r of s){const s=nt(r);if(t.listPathSet.has(o)&&s.lastSegment===l){const i=t.stateProxy[Ee](e),a=qe(t.stateElement,e),l=xe(a),c=wr(e.listIndex,l,i);t.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const u=gl(t,o,0,0,c);for(const e of u.fullRows){const o=pn(s,e);t.result.add(o),n.push(o)}if(null!==u.movedRows){const e=bl(t,r,s);if(null===e)for(const e of u.movedRows){const o=pn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of u.movedRows)for(const s of e){const e=pn(s,o);t.result.add(e),n.push(e)}}}else{const o=pn(s,e.listIndex);t.result.add(o),n.push(o)}}const r=t.dynamicMap.get(o);if(r)for(const o of r){const s=nt(o),r=[];if(s.wildcardCount>0){const n=Qe(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=Xe(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};pl(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=Xe(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=pn(s,e);t.result.add(o),n.push(o)}}}function vl(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&Z(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),d={ranks:u,stateElement:t,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(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,wl(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(d,e,a);for(const[t,e]of d.observedListValueByAbsAddress)Pe(t,e);return Array.from(d.result)}function _l(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](t,e,n,o,s)}}function $l(t,e,n){const o=t.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function Sl(t,e,n){const o=t.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function xl(t,e,n,s,r,i){const a=function(t,e){return!0===qs.get(t)?.byPath.has(e)||!0===Js.get(t)?.has(e)}(t,e),c=function(t,e){return!0===Xs.get(t)?.has(e)}(t,e);if(!a&&!c)return;const u=Hs(),d=o.enablePropagationContext?to()??null:null,h=t=>{Ms(t),u.enqueueAbsoluteAddress(t,d)};a&&ur(t,e,n,s,r).forEach(h),c&&function(t,e,n,o){const s=nt(e).segments.length,r=[];for(const i of Xs.get(t).get(e)){const e=nt(i).segments.slice(s);if(e.includes(l))hr(t,i,r);else for(const s of ur(t,i,!0,dr(n,e),dr(o,e)))r.push(s)}return r}(t,e,n?s:i(),r).forEach(h)}function Pl(t,e,n,s,r,i,a="diff"){const l=o.enablePropagationContext?to()??Xn(-1):null,c=Hs();c.enqueueAbsoluteAddress(e,l),i&&Ms(e),vl(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=qe(s.stateElement,e);Ms(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Nl(t,e,n,o,s){s&&(t.getterPaths.has(e)?Ms(n):Ts(n,{value:o,dirty:!1,generation:t.stateGeneration}))}function kl(t,e,n,o,s,r,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const i=sl(t,n,s,r),a=e.pathInfo.segments[e.pathInfo.segments.length-1];if(a===l){const t=e.listIndex?.index??Z(Ni(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(i,t,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);r.pushAddress(e),r.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{Pl(e,n,s,r,i,a)}}function Il(t,e,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(e.pathInfo.path);if(void 0!==i){const r=sl(t,e,o,s),c=function(t,e,n,o){const s=cl(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=cl(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,i,r,n);if(null!==c)return function(t,e,n,o,s,r){const i=e.pathInfo.path,c=e.listIndex;null===Is(o)&&wr(c,null,o);const u=wr(c,o,n.list),d=Al(t,e,n.list,s,r,i),h=nt(i+a+l);for(const e of n.matched){const n=ul(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const i of n)void 0!==o?Il(t,pn(nt(h.path+a+i.field),o),i.value,s,r):e.oldRow[i.field]=i.value}return d}(t,e,c,r,o,s)}}return Al(t,e,n,o,s,null)}function Al(t,e,n,s,r,i){const c=r.stateElement,u=e.pathInfo.path,d=c.addressHooks;if(d){const t=d.write;for(let o=0;o<t.length;o++){const i=t[o](c,e,n,s,r);if(i!==za)return i}}const h=!!oo&&(oo=!1,!0);if(!(u in t)&&null!==e.parentAddress&&!c.elementPaths.has(u)){const a=sl(t,e.parentAddress,s,r);if("object"==typeof a&&null!==a){const t=e.pathInfo.lastSegment,f=t===l?e.listIndex?.index:t;let p,m=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==f&&f in a,e=void 0!==f?a[f]:void 0;if(t&&Object.is(e,n))return!0;p=e,m=!0}xl(c,u,m,p,n,()=>a[f]);const g=el(c,e),y=qe(c,e);null!==ge&&ge({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:m}),_l(c,u,y,p,m);let b=!1;try{if(void 0===f&&Z(Ni(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),d&&0!==d.writeMissing.length&&t!==l&&!(f in a)){const t=d.writeMissing;for(let o=0;o<t.length;o++){b=!0;const i=t[o](c,e,a,f,n,s,r);if(i!==za)return i;b=!1}}return Reflect.set(a,f,n)}finally{Pl(e,y,s,r,i,g),b?Ms(y):Nl(c,u,y,n,g),$l(c,e.pathInfo,{value:n})}}}let f,p=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=sl(t,e,s,r);if(dl(t,e,s,r)&&Object.is(o,n))return!0;f=o,p=!0}xl(c,u,p,f,n,()=>sl(t,e,s,r));const m=c.elementPaths.has(e.pathInfo.path),g=el(c,e),y=qe(c,e);null!==ge&&ge({type:"state:write",absoluteAddress:y,value:n,oldValue:f,hasOldValue:p}),_l(c,u,y,f,p);try{return m?function(t,e,n,o,s,r,i,c){const u=e.parentAddress??Z(`address.parentAddress is undefined path: ${e.pathInfo.path}`),d=sl(t,u,s,r)??[];let h=(f=d,hl.get(f)??null);var f;if(null===h){const t=Is(d)??[];h={value:[...d],listIndexes:[...t]},fl(d,h)}try{return kl(t,e,n,o,s,r,i,c)}finally{const n=h.value.indexOf(o),i=sl(t,u,s,r)??[],c=Array.isArray(i)?Is(i)??[]:[],f=e.listIndex.index,p=-1!==n?h.listIndexes[n]:vs(u.listIndex,-1);if(c[f]=p,new Set(i).size===h.value.length){for(let t=0;t<c.length;t++)c[t].index=t;fl(d,null),function(t,e,n,o,s,r){const i=r.stateElement,c=Hs(),u=qe(i,t);be(u)===n&&(Es(e.value,e.listIndexes),we(u,e.value),function(t){vr.add(t)}(e.value)),c.enqueueRenderOnlyAddress(u);const d=new Map;e.listIndexes.forEach((t,e)=>d.set(t,e));const h=nt(t.pathInfo.path+a+l);for(let t=0;t<o.length;t++){const n=o[t],a=d.get(n);if(a===t)continue;const l=pn(h,n),u=qe(i,l);if(void 0===a){const n=Ue(i,h,e.listIndexes[t]??null);Sl(i,u,n),Pl(l,u,s,r,null,el(i,l),"full");continue}vl(i,l,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",t=>{const e=qe(i,t);Ms(e),c.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}}(u,h,i,c,s,r)}}}(t,e,y,n,s,r,i,g):kl(t,e,y,n,s,r,i,g)}finally{m||Nl(c,u,y,n,g),$l(c,e.pathInfo,{value:n})}}function El(t,e,n,o){return(e,s,...r)=>{const i=nt(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&Z(Si("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=pn(i,il(t,n,o,i,s));if(0===r.length)return sl(t,a,n,o);Ja(o),Il(t,a,r[0],n,o)}}function Cl(t,e,n,o){const s=El(t,0,n,o);return(e,r)=>{const i=nt(e);if(void 0===r||Array.isArray(r)||Z(`$getAll("${e}") 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 t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&Z(Si("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Za(o,i.wildcardPaths[t]);if(e){r=Ye(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&Z(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", 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).`}(e,t.pathInfo.path)),r=[]}}const a=rl(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}function Tl(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Za(o,s.wildcardPaths.at(-1)??Z(`lastWildcardPath is null: ${e.pathInfo.path}`))??Z(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??Z(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=As(sl(t,pn(i,s),n,o),s)??Z(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??Z(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??Z(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":Z(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function Ml(t,e,n,o){return(e,s,r,i)=>{Ja(o);const a=nt(e);Array.isArray(s)||Z(Pi(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&Z(Si("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&Z(Pi(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&Z(Pi(e,"requires an array as the value when { spread: true } is set."));const u=rl(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&Z(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,u.length,r.length));const d=[];for(let e=0;e<u.length;e++){const s=il(t,n,o,a,u[e]);d.push(pn(a,s))}let h=0;for(let e=0;e<d.length;e++){const s=d[e];let i;i=c?r(sl(t,s,n,o),...u[e]):l?r[e]:r,void 0!==i&&(Il(t,s,i,n,o),h++)}return h}}function Ol(t,e){const n=t.getterPaths;if(0===n.size)return!1;for(const t of nt(e).cumulativePaths)if(n.has(t))return!0;return!1}const Ll=/^\$\d+$/,Rl=`${G}${a}`,jl=`${V}${a}`,Dl=new WeakMap;class Wl{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Zi(t);null===n&&Z("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&Z("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&Z(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),Z(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const n=this._addressStack[e];if(n){if(t.has(n))return!0;t.add(n)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&Z(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return function(t,e,n,o){const s=I[e];if(void 0===s&&"string"==typeof e&&36===e.charCodeAt(0)&&Ll.test(e)&&Z(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&Z(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&Z(`ListIndex not found: ${e.toString()}`);let i=s;const a=t.pathInfo,l=o.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let n=0;n<e.length;n++)i+=e[n](o,t)}const c=Xe(r,i,a.wildcardCount);return c?.index??Z(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,e,n,t);if(i!==za)return i}}if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>Cl(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>Ml(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=Ya(e),i=Tl(t,r,n,o),a=pn(r.pathInfo,i),l=qe(s,a),c=Hs();c.enqueueAbsoluteAddress(l),vl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=qe(s,t);Ms(e),c.enqueueAbsoluteAddress(e)});const u=s.addressHooks;if(u){const t=u.written;for(let e=0;e<t.length;e++)t[e](s,a.pathInfo)}}}(t,0,n,o)(e);case"$resolve":return(e,s,...r)=>El(t,0,n,o)(e,s,...r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] $trackDependency("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&Z(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??Z("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(e.path)&&e.path!==t&&n.addDynamicDependency(t,e.path)}}(0,0,0,o)(t);case"$eq":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Ol(o.stateElement,t))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&ar(o.stateElement,t),Object.is(n[t],e);let r;o.beginUntrack();try{r=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&ir(o.stateElement,t,e,qe(o.stateElement,s),r),Object.is(r,e)};case"$eqPath":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Ol(o.stateElement,t);let i,a=r?n[t]:void 0;o.beginUntrack();try{r||(a=n[t]),i=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?ar(o.stateElement,t):ir(o.stateElement,t,i,qe(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(t,e=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||Z(`$eqIndex("${t}") needs a list row scope.`);const r=Xe(s.listIndex,e-1,s.pathInfo.wildcardCount);if(null===r&&Z(`$eqIndex("${t}", ${e}): no list index at that level.`),Ol(o.stateElement,t))return o.stateElement.getterPaths.has(s.pathInfo.path)&&ar(o.stateElement,t),Object.is(n[t],r.index);const i=e===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[t],i&&(l=n[s.pathInfo.wildcardParentPaths[e-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const e=i?Is(l):null;null!==e?function(t,e,n,o,s){Ks=!0,tr(t).lastValue.set(e,s),Zs(t,e);let r=Js.get(t);void 0===r&&Js.set(t,r=new Map);let i=r.get(e);void 0===i&&r.set(e,i=new Set);let a,l=Qs.get(o);void 0===l?Qs.set(o,l=[]):a=l.find(n=>n.stateElement===t&&n.path===e),void 0===a&&(a={stateElement:t,path:e,indexes:o,getters:new Set},l.push(a),i.add(a)),a.getters.add(n)}(o.stateElement,t,s.pathInfo,e,a):function(t,e,n,o,s){Ks=!0;const r=tr(t);Zs(t,e),rr(r,e,s,o,or(r,e,n.index,o),{stateElement:t,path:e,absAddress:o,levelListIndex:n})}(o.stateElement,t,r,qe(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case j:return Wa(o.stateElement)}if(!e.startsWith(Rl)&&!e.startsWith(jl))return}const r=Ya(e),i=Tl(t,r,n,o),a=pn(r.pathInfo,i);return sl(t,a,n,o)}if("symbol"==typeof e){const s=function(t){let e=Dl.get(t);return void 0===e&&(e=new Map,Dl.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case Ae:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&Z("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case Ee:i=e=>sl(t,e,n,o);break;case Ce:i=e=>dl(t,e,n,o);break;case Te:i=(e,s)=>Il(t,e,s,n,o);break;case Me:i=()=>async function(t,e,n){const o=Reflect.get(t,A);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Oe:i=()=>function(t,e,n){const o=Reflect.get(t,E);"function"==typeof o&&o.call(n)}(t,0,n);break;case Le:i=e=>function(t,e,n,o){const s=Reflect.get(t,C);let r;if("function"==typeof s){const t=new Set,i={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,s=e.path;if(-1===s.indexOf("#")&&(t.add(s),e.wildcardCount>0)){const t=Ye(n.listIndex,e.wildcardCount),o=i[s];void 0===o?i[s]=[t]:o.push(t)}}r=s.call(n,Array.from(t),i)}const i=o.stateElement?.addressHooks;if(i){const t=i.updated;for(let s=0;s<t.length;s++)t[s](o.stateElement,e,n)}return r}(t,e,n,o);break;case Re:i=(e,o)=>function(t,e,n,o){const s=Reflect.get(t,T);"function"==typeof s&&s.call(o,e,n)}(t,e,o,n);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}(t,e,n,this)}set(t,e,n,o){return Ja(this),function(t,e,n,o,s){if("string"==typeof e){const r=Ya(e),i=Tl(t,r,o,s);return Il(t,pn(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}}const zl=Promise.resolve(),Bl=new Map;let Fl=[];function Hl(t,e){Bl.set(t,e),Fl=Array.from(Bl.values()).sort((t,e)=>t.order-e.order)}function ql(t,e){return Z(Gi(t,e))}const Ul="undefined"==typeof HTMLElement?class{}:HTMLElement;function Gl(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}let Vl=null;const Kl=new Set(["for","if","elseif","else"]);class Jl extends Ul{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return ta(t)}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 La}();_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(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&Z(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){const e=this.__state,n=function(){const t=new Map;return{get:e=>t.get(e),set(e,n){t.set(e,n)}}}();n.set("previousState",e),function(t,e,n){for(let o=0;o<Ua.length;o++)Ua[o].validateEarly?.(t,e,n)}(this,t,n);const o=function(t){const e=new Set,n=t[R];if(void 0===n)return e;Array.isArray(n)||Z(`${R} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Z(`${R} entries must be non-empty strings.`),t===j&&Z(`${R} entry "${t}" conflicts with the reserved namespace name "${j}".`),e.has(t)&&Z(`${R} entry "${t}" is duplicated.`),e.add(t);return e}(t),s=function(t){const e=new Set,n=t[D];if(void 0===n)return e;Array.isArray(n)||Z(`${D} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Z(`${D} entries must be non-empty strings.`),e.has(t)&&Z(`${D} entry "${t}" is duplicated.`),e.add(t);return e}(t),r=function(t){const e=t[U];if(void 0===e)return null;"object"==typeof e&&null!==e||Z(`${U} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&Z(`${U} entry path must be a non-empty string.`);const e=t.split(a);e.some(t=>0===t.length)&&Z(`${U} entry "${t}" must not contain empty path segments.`),e[e.length-1]===l&&Z(`${U} entry "${t}" must be the list path itself, not the element path (drop the trailing "${a}${l}").`),-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] ${U} entry "${t}" uses "${q}", which ${U} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${a}${l}${a}children").`),"function"!=typeof o?("string"!=typeof o&&Z(`${U} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&Z(`${U} entry "${t}" key field name must be a non-empty string.`),(o.includes(a)||o.includes(l))&&Z(`${U} entry "${t}" key field name "${o}" must be a flat property name ("${a}" / "${l}" are not allowed).`),o in Object.prototype&&Z(`${U} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t);n.set("eventTokenNames",s),function(t,e,n){for(let o=0;o<Ua.length;o++)Ua[o].validate?.(t,e,n)}(this,t,n),function(t,e,n){for(let o=0;o<Ua.length;o++)Ua[o].preCommit?.(t,e,n)}(this,t,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=t,void 0!==e&&Vl?.reset(this),this._hasUpdatedCallback=C in t,this._hasErrorCallback=T in t,kn.delete(this),function(t,e,n){for(let o=0;o<Ua.length;o++)Ua[o].applyEarly?.(t,e,n)}(this,t,n),function(t,e,n){const o=e[W];if(void 0!==o){"object"==typeof o&&null!==o||Z(`${W} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||Z(`${W} entry "${e}" is not declared in $eventTokens.${rt(e,n)}`),"function"!=typeof s&&Z(`${W} entry "${e}" must be a function.`),In(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const i=function(t){const e=new Set,n=new Set,o=Gl(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of i.getterPaths)this._getterPaths.add(t);for(const t of i.setterPaths)this._setterPaths.add(t);!function(t,e,n){for(let o=0;o<Ua.length;o++)Ua[o].apply?.(t,e,n)}(this,t,n),this._listKeys=r,this._rebuildPathInfo(),function(t,e,n){for(let o=0;o<Ua.length;o++)Ua[o].register?.(t,e,n)}(this,t,n),Ka(this,null),this._resolveLoading?.()}attributeChangedCallback(t,e,n){this._initialized&&e!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===e?"absent":`"${e}"`}, 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")?Ki('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){Z("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await Ma(t,o.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||Z(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await Oa(t);Z(`Unsupported src file type: ${t}`)}}catch(t){Z(`Failed to initialize state: ${t}`)}}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}return await this._loadingPromise,null!==this._rootNode&&(oa(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),Z(t)}_failInitializeLoudly(t,e=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),e&&null!==this._rootNode&&null===Zi(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),Qi.set(t,n)}(this._rootNode,t),function(t,e,n){for(let o=0;o<Fl.length;o++)Fl[o].initializeFailed?.(t,e,n)}(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{A in t&&await t[Me]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{E in t&&t[Oe]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(t){for(let e=0;e<Fl.length;e++)if(!0===Fl[e].reconnecting?.(t))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Zi(this._rootNode)===this||oa(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(t){for(let e=0;e<Fl.length;e++){const n=Fl[e].connecting?.(t);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const n=this.parentNode;if(n instanceof ShadowRoot&&n.host.hasAttribute(K))try{ql("dcc",`a <${o.tagNames.state}> inside a [${K}] host`)}catch(t){this._failInitializeLoudly(t)}if(this.hasAttribute("mount"))try{ql("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}let s=!1;try{const t=function(t){for(let e=0;e<Fl.length;e++){const n=Fl[e].preparing?.(t);if(null!=n)return n}return null}(this);null===t&&this.hasAttribute("bind-component")&&ql("scopes",'the "bind-component" attribute'),s=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(s)return;let r=!1;try{r=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!r)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!e()||t!==this._connectGeneration||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await Ki('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Ka(this,t),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!function(t){for(let e=0;e<Fl.length;e++)if(!0===Fl[e].disconnecting?.(t))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(t,e){for(let n=0;n<Fl.length;n++)Fl[n].initializeFailureCleared?.(t,e)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{oa(this.rootNode,null),Da.delete(this),function(t){for(let e=0;e<Ga.length;e++)Ga[e].deactivate?.(t)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource()}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}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(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e,this.attachAddressHooks("watch",B)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&Z(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return wi(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&Z("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const n=function(t,e){const n=Fa.get(t);return void 0===n&&Z(Gi(t,`"${e}"`)),n}(t,e);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(t,e){for(let n=0;n<Ba.length;n++){const o=Ba[n],s=e[o];if(void 0===s)continue;const r=t[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",O)}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(t);void 0===o?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:o.bound||"binding"===n})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+l)),!this._pathSet.has(t)){const e=nt(t);if(this._pathSet.add(t),Vl?.check(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=nt(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,n){try{const o=function(t,e,n){const o=new Wl(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&Z(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);!function(t){for(let e=0;e<Fl.length;e++)Fl[e].replacingState?.(t)}(this),(this._hasGraftedVolumes||this._hasMounts)&&Z("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const e=this.__state;this._state=t;const n=function(t){const e=new Set;for(const n of t)if(void 0!==n)for(const[t,o]of Object.entries(Gl(n)))t.startsWith("$")||t.includes(l)||"function"==typeof o.value||e.add(t);return e}([e,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){!function(t,n,o){const s=new Map;for(const t of o){const e=nt(t);if(null===e.lastWildcardPath)continue;const n=s.get(e.lastWildcardPath);void 0===n?s.set(e.lastWildcardPath,[e]):n.push(e)}const r=[],i=new Set,a=e=>{const n=qe(t,e);if(i.has(n))return;i.add(n);const o=un(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==e.listIndex){const t=s.get(e.pathInfo.path);if(void 0!==t)for(const n of t)a(pn(n,e.listIndex))}};Ne();try{if(t.createState("readonly",e=>{for(const o of n){const n=pn(nt(o),null);a(n);try{vl(t,n,t.staticDependency,t.dynamicDependency,t.listPaths,e,"new",a)}catch{}}}),0===r.length)return;const o=function(t){const e=[],n=[];for(const o of t)Kl.has(o.bindingType)?e.push(o):n.push(o);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(n)}(r),s=()=>{zi(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=Rs("state",s);void 0!==i&&i.catch(Bs)}finally{ke()}}(this,t,this._pathRegistrations.keys())}}const Ql=[];function Xl(t,e){const r=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(t);var i;r&&((i=r).tagNames&&Object.assign(n.tagNames,i.tagNames),"string"==typeof i.bindAttributeName&&(n.bindAttributeName=i.bindAttributeName),"string"==typeof i.commentTextPrefix&&(n.commentTextPrefix=i.commentTextPrefix),"string"==typeof i.commentForPrefix&&(n.commentForPrefix=i.commentForPrefix),"string"==typeof i.commentIfPrefix&&(n.commentIfPrefix=i.commentIfPrefix),"string"==typeof i.commentElseIfPrefix&&(n.commentElseIfPrefix=i.commentElseIfPrefix),"string"==typeof i.commentElsePrefix&&(n.commentElsePrefix=i.commentElsePrefix),"string"==typeof i.locale&&(n.locale=i.locale),"boolean"==typeof i.debug&&(n.debug=i.debug),"boolean"==typeof i.enableMustache&&(n.enableMustache=i.enableMustache),"boolean"==typeof i.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=i.enableDirectionalInitialSync),"boolean"==typeof i.enablePropagationContext&&(n.enablePropagationContext=i.enablePropagationContext),"boolean"==typeof i.enableContractAnalyzer&&(n.enableContractAnalyzer=i.enableContractAnalyzer),"boolean"==typeof i.sameValueGuard&&(n.sameValueGuard=i.sameValueGuard)),function(t=customElements){for(let e=0;e<Ql.length;e++)Ql[e](t);t.get(o.tagNames.state)||t.define(o.tagNames.state,Jl)}(e),function(){const t=globalThis;void 0===t[s]&&(t[s]=Ea)}()}function Yl(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function Zl(t,e){for(const n of t)if(Yl(e,n.innerSegments))return n;return null}function tc(t,e){const n=e.slice(t.innerSegments.length);return 0===n.length?t.outerPathInfo.path:t.outerPathInfo.path+a+n.join(a)}let ec=0;const nc=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],oc=new Set;function sc(t,e){const n=t.stateObject[e];if("function"==typeof n)try{const o=t.component[t.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function rc(t){const e=t.indexOf(a);return-1===e?t:t.slice(0,e)}function ic(t,e){const n=Zl(t.entries,e);return null===n?null:tc(n,e)}function ac(t,e){return t.markerBasePath+a+e}function lc(t,e,n,o){let s=t.accessorBySuffixByMarkerParent.get(e);void 0===s&&(s=new Map,t.accessorBySuffixByMarkerParent.set(e,s));const r=e+a+n;s.set(n,{accessorName:o,indexShift:nt(r).wildcardCount-nt(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(r),t.addedGetterPaths.add(r))}function cc(t,e){return!t.injectedKeys.has(e)&&!t.mappedKeys.has(e)&&("function"==typeof t.stateObject[e]&&!t.getterKeys.has(e)||Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function uc(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(a)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${rc(e)}: path") or declare the key on the component state.`}const dc=/^\$(\d+)$/;function hc(t,e){const n=e[0];if("$"===n||"#"===n)return null;if(t.getterKeys.has(e)||t.setterKeys.has(e))return null;const o=rc(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||cc(t,o))return null;const s=function(t,e){return Zl(t.entries,e)}(t,e.split(a));return null!==s&&s.readonly?s:null}function fc(t,e){const n=hc(t,e);if(null!==n){const o=0===n.innerSegments.length?"":a+n.innerSegments.join(a);Z(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${m}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${m} from the mount.`)}return pc(t,e)}function pc(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(a);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===l){o=t;break}if(-1===o)return lc(t,t.markerBasePath,e,e),ac(t,e);if(cc(t,n[0]))return lc(t,t.markerBasePath,e,e),ac(t,e);const s=n.slice(0,o+1),r=n.slice(o+1),i=ic(t,s);null===i&&Z(uc(t,e)),0===r.length&&Z(`Wildcard-terminal accessor "${e}" on mounted <${t.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 c=i+a+t.marker;return lc(t,c,r.join(a),e),c+a+r.join(a)}(t,e);const o=rc(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return ac(t,e);if(cc(t,o))return ac(t,e);const s=ic(t,e.split(a));if(null!==s)return s;Z(uc(t,e))}function mc(t,e,n,o,s){if(void 0===o)return;const r=nt(n).wildcardCount-nt(e).wildcardCount;return 0===r?o:(s.length<r&&Z(`Cannot resolve "${e}" 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 gc=new WeakMap,yc=new WeakMap,bc=new WeakMap,wc=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)}),vc=new WeakMap;function _c(t){return vc.get(t)??null}let $c=!1;function Sc(t){const e=bc.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}function xc(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=bc.get(t);if(void 0===o)return null;const s=e.indexOf(a,n),r=-1===s?e.slice(n):e.slice(n,s),i=o.get(r);if(void 0===i)return null;const l=i.deref();return void 0===l?(o.delete(r),null):l}const Pc="3.1.0",Nc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function kc(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const Ic="__WCSTACK_DEVTOOLS_HOOK__";const Ac=t=>{null!==ge&&ge({type:"state:update-batch",addresses:t})};function Ec(t){const e=null!==ge;!function(t){ge=t}(t);const n=null!==t;n&&!e?zs(Ac,0):!n&&e&&function(t){const e=js.findIndex(e=>e.listener===t);-1!==e&&js.splice(e,1)}(Ac)}function Cc(t){return{rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function Tc(t){return Zi(t)??Z("devtools: no state tree on this root")}let Mc=null;function Oc(){if(e())return;if(null!==Mc)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Pc,getStateElements(){const t=[];for(const e of Xi)t.push(Cc(e));return t},overlays:t=>Sc(Tc(t)).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join("."),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]})),keyedSubscriptions:t=>function(t){const e=function(t){const e=qs.get(t);return void 0===e?null:{byPath:e.byPath,lastValue:e.lastValue,tracked:e.tracked,watchers:Js.get(t)}}(t);if(null===e)return[];const n=new Set([...e.byPath.keys(),...e.tracked]);if(void 0!==e.watchers)for(const t of e.watchers.keys())n.add(t);const o=[];for(const t of[...n].sort()){const n=e.byPath.get(t);let s=0;if(void 0!==n)for(const t of n.values())s+=t.size;o.push({path:t,tracked:e.tracked.has(t),rows:s,keys:n?.size??0,lists:e.watchers?.get(t)?.size??0,lastValue:e.lastValue.get(t)})}return o}(Tc(t)),keys(t){const e=Tc(t),n=[];return e.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}n.push(e)}}),n},read(t,e,n){let o;return Tc(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){Tc(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=[...t.inFilters,...t.outFilters].map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=ia(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(kc(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=Yt(e,At(n));for(const o of t)r(kc(e,o,"attribute",n))}catch{}continue}const e=Nc.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=ia(s);if(null===a){if(n===o.commentTextPrefix)try{r(kc(t,Ot(s),"comment",s))}catch{}}else r(kc(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:Ec};Mc=t,function(){const t=globalThis,e=t[Ic];if(void 0!==e)return 2!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 2. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:2,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[Ic]=n,n}().register(t)}const Lc={name:"devtools",install(){Oc()}},Rc=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),jc=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])}),Dc=new WeakMap,Wc=new WeakMap,zc=new WeakSet,Bc=new WeakMap;function Fc(t,e,n,o){console.warn(`[@wcstack/state] [${_i[n]}] ${$i[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${rt(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${it}`),null!==ge&&ge({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const Hc={check:function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=t.addressHooks;if(s){const e=s.suppressPathDiagnostic;for(let o=0;o<e.length;o++)if(e[o](t,n))return}const r=nt(n).segments;if("binding"===o&&r.length<2)return;if(function(t,e){let n=Dc.get(t);return void 0===n&&(n=new Set,Dc.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const i=function(t,e,n){if(void 0!==wi(t,e))return jc;const o=nt(e).segments;let s=t,r="";for(let e=0;e<o.length;e++){const i=o[e],c=r;if(r=0===e?i:r+a+i,e>0&&e<o.length-1&&void 0!==wi(t,r))return Rc;if(Object(s)!==s)return Rc;if(i===l){if(!Array.isArray(s)||0===s.length)return Rc;s=s[0];continue}const u=wi(s,i);if(void 0===u)return{existence:"missing",missingSegment:i,candidates:vi(s,c,n)};if("function"==typeof u.get)return e===o.length-1?jc:Rc;s=u.value}return jc}(e,n,t.getterPaths);"missing"===i.existence&&(function(t,e){return!0===Bc.get(t)?.has(e)}(t,n)||("binding"!==o?Fc(0,n,o,i):function(t,e,n){let o=Wc.get(t);void 0===o&&(o=new Map,Wc.set(t,o)),o.set(e,n),zc.has(t)||(zc.add(t),setTimeout(()=>function(t){zc.delete(t);const e=Wc.get(t);if(void 0!==e){Wc.delete(t);for(const[t,n]of e)Fc(0,t,"binding",n)}}(t),0))}(t,n,i)))},reset:function(t){Dc.delete(t),Wc.delete(t)},markExported:function(t,e){let n=Bc.get(t);void 0===n&&(n=new Set,Bc.set(t,n)),n.add(e),Wc.get(t)?.delete(e)}};let qc=!1;const Uc={name:"diagnostics",install(){qc||(qc=!0,Vl=Hc)}};function Gc(t){Z(`filter ${t} requires at least one option`)}function Vc(t){Z(`filter ${t} requires a number as option`)}function Kc(t){Z(`filter ${t} requires a number value`)}function Jc(t){Z(`filter ${t} requires a date value`)}function Qc(t){return!(!t||isNaN(Number(t)))}const Xc={eq:(t,e)=>{const n=t?.[0]??Gc("eq"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?(Qc(n)||Vc("eq"),t===Number(n)):"string"==typeof t?t===n:t===o},ne:(t,e)=>{const n=t?.[0]??Gc("ne"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?(Qc(n)||Vc("ne"),t!==Number(n)):"string"==typeof t?t!==n:t!==o},not:t=>t=>("boolean"!=typeof t&&Z("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??Gc("lt");return Qc(e)||Vc("lt"),t=>("number"!=typeof t&&Kc("lt"),t<Number(e))},le:t=>{const e=t?.[0]??Gc("le");return Qc(e)||Vc("le"),t=>("number"!=typeof t&&Kc("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??Gc("gt");return Qc(e)||Vc("gt"),t=>("number"!=typeof t&&Kc("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??Gc("ge");return Qc(e)||Vc("ge"),t=>("number"!=typeof t&&Kc("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??Gc("inc");return Qc(e)||Vc("inc"),t=>("number"!=typeof t&&Kc("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??Gc("dec");return Qc(e)||Vc("dec"),t=>("number"!=typeof t&&Kc("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??Gc("mul");return Qc(e)||Vc("mul"),t=>("number"!=typeof t&&Kc("mul"),t*Number(e))},div:t=>{const e=t?.[0]??Gc("div");return Qc(e)||Vc("div"),t=>("number"!=typeof t&&Kc("div"),t/Number(e))},mod:t=>{const e=t?.[0]??Gc("mod");return Qc(e)||Vc("mod"),t=>("number"!=typeof t&&Kc("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&Kc("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??Gc("clamp");Qc(e)||Vc("clamp");const n=t?.[1]??Gc("clamp");Qc(n)||Vc("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&Kc("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return Qc(e)||Vc("fix"),t=>("number"!=typeof t&&Kc("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&Kc("locale"),t.toLocaleString(e??o.locale))},uc:t=>t=>String(t).toUpperCase(),lc:t=>t=>String(t).toLowerCase(),cap:t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)},trim:t=>t=>String(t).trim(),slice:t=>{const e=[],n=t?.[0]??Gc("slice");Qc(n)||Vc("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(Qc(o)||Vc("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??Gc("substr");Qc(e)||Vc("substr");const n=t?.[1]??Gc("substr");return Qc(n)||Vc("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??Gc("pad");Qc(e)||Vc("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??Gc("rep");return Qc(e)||Vc("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??Gc("truncate");Qc(e)||Vc("truncate");const n=Number(e),o=t?.[1]??"…";return t=>{const e=String(t);return e.length<=n?e:e.slice(0,n)+o}},join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||Z("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=t?.[0]??"0";return Qc(e)||Vc("round"),t=>{"number"!=typeof t&&Kc("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return Qc(e)||Vc("floor"),t=>{"number"!=typeof t&&Kc("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return Qc(e)||Vc("ceil"),t=>{"number"!=typeof t&&Kc("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return Qc(e)||Vc("percent"),t=>("number"!=typeof t&&Kc("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??Gc("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||Jc("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||Jc("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||Jc("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||Jc("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||Jc("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!t,truthy:t=>t=>!!t,defaults:(t,e)=>{const n=t?.[0]??Gc("defaults"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t||o},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),null:t=>t=>""===t?null:t},Yc={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],inc:[0,1],dec:[0,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],fix:[0,1],locale:[0,1],uc:[0,0],lc:[0,0],cap:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],pad:[1,2],rep:[1,1],rev:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],boolean:[0,0],number:[0,0],string:[0,0],null:[0,0]},Zc=Xc,tu=Xc;let eu=!1;const nu={name:"formats",install(){eu||(eu=!0,ht("input",tu,Yc),ht("output",Zc,Yc))}};function ou(t){return-1!==t.indexOf(q)}function su(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+a;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(ou(o))return null;const s=o.slice(1).split(a);return s[0]===l||s.some(t=>0===t.length)?null:o}function ru(t){return 0===t.length?t:a+lu(t.slice(1))}function iu(t,e,n){const o=a+t.repeat,s=e.length<=n.length?e:n,r=e.length<=n.length?n:e;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 t=0;t<i.length;t+=o.length)if(!i.startsWith(o,t))return!1;return!0}function au(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(a,o-1))if(iu(t,e,n.slice(0,o)))return!0;return!1}function lu(t){const e=t.split(a);for(let t=0;t<e.length;t++)e[t]===l||Number.isNaN(Number(e[t]))||(e[t]=l);return e.join(a)}function cu(t,e){const n=t.repeat.split(a),o=a+t.repeat;let s=e;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===a+t.repeatList+a+"length")return!0;for(let t=1;t<n.length;t++)if(s===a+n.slice(0,t).join(a))return!0;return!1}function uu(t,e,n){n<0&&Z(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=a+t.repeat;const s=o+e;let r=0;for(const t of s.split(a))t===l&&r++;return r>c&&Z(`[wcs/recursion-depth-exceeded] Recursion on "${t.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 du(t,e){return uu(t,"",e)}function hu(t,e,n){if(!n.startsWith(t.anchor))return null;if(e.length>0&&!n.endsWith(e))return null;if(n.length<t.anchor.length+e.length)return null;const o=n.slice(t.anchor.length,n.length-e.length);if(0===o.length)return 0;const s=a+t.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function fu(t,e,n){const o=t.recursionRegistry,s=su(o.spec,n);null===s&&Z(xi(n,o.spec.recursiveAnchor));const r=function(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=e.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(t,e){const n=t.spec;if(!e.startsWith(n.anchor))return null;const o=a+n.repeat;let s=0,r=n.anchor.length;for(;e.startsWith(o,r);)r+=o.length,s++;return r!==e.length&&46!==e.charCodeAt(r)?null:s}(e,n.pathInfo.path)}(e,o);return null===r&&Z(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function pu(t,e,n,o,s){const r=o.spec,i=[],l=new Map,c=[],u=r.repeatList,d=r.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void i.push(pn(t,n));const s=m(o[e],n,null).rows;for(let n=0;n<s.length;n++)p(t,e+1,s[n])};function m(o,s,i){const a=pn(o,s),c=qe(n.stateElement,a),d=sl(t,a,e,n),f=null===i?null:((t,e,n)=>{if(!Array.isArray(e)||0===e.length)return null;const o=e;return h.has(o)&&Z(`[wcs/recursion-cycle] "${t}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&Z(`[wcs/recursion-shared-list] "${t}" 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 "${u}" array.`),o})(o.path,d,i),p=wr(s,xe(c),d);return l.set(c,Array.isArray(d)?d:[]),null!==f&&null!==i&&i.add(f),{rows:p.newIndexes,tracked:f}}const g=(t,e,n)=>{const{rows:r,tracked:l}=m(e,n,f);if(0===r.length)return;const d=(t=>{const e=c[t];if(void 0!==e)return e;const n=o.concretePathAt(s,t),r=0===s.length?n:o.concretePathAt("",t),i={nodePath:r,concretePathInfo:nt(n),childListPathInfo:nt(r+a+u)};return c[t]=i,i})(t),y=l;h.add(y);const b=d.concretePathInfo.wildcardCount===t+1;for(let e=0;e<r.length;e++){const n=r[e];b?i.push(pn(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,nt(d),null);for(const[t,e]of l)Pe(t,e);return i}const mu={write(t,e){if(!0!==t.hasRecursion)return za;const n=t.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);return null!==n&&Z(`[wcs/recursion-readonly] "${e.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.`),za},get(t,e,n,o){if(!0!==t.stateElement.hasRecursion)return za;if("$getAll"===e)return(e,s)=>{if(ou(e)){if(void 0!==s)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=su(r.spec,o);null===i&&Z(xi(o,r.spec.recursiveAnchor)),Array.isArray(s)||Z(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&Z(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=pu(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(sl(t,a[o],e,n));return l}(o,n,t,e,s);e=fu(t.stateElement,t,e)}return Cl(o,0,n,t)(e,s)};if("$setAll"===e)return(e,s,r,i)=>ou(e)?function(t,e,n,o,s,r,i){Ja(n);const a=n.stateElement.recursionRegistry,l=su(a.spec,o);null===l&&Z(xi(o,a.spec.recursiveAnchor));const c=ru(l);Array.isArray(s)||Z(Pi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&Z(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&Z(Pi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&Z(Pi(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(t,e,n){cu(t,n)&&Z(`[wcs/recursion-structural-write] "${e}" writes the recursion structure itself (a node, its "${t.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 u=a.conflictingRecursiveGetter(c);null!==u&&Z(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${u}", 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 d=pu(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(Il(t,d[o],r,e,n),h++);return h}(o,n,t,e,s,r,i):Ml(o,0,n,t)(e,s,r,i);if(36!==e.charCodeAt(0)&&ou(e)){const s=Ya(fu(t.stateElement,t,e)),r=Tl(o,s,n,t);return sl(o,pn(s.pathInfo,r),n,t)}return za}};let gu=!1;function yu(t,e){"string"==typeof e&&0!==e.length||Z(`[wcs/recursion-declaration-invalid] ${H} ${t} must be a non-empty string.`);const n=e.split(a);n.some(t=>0===t.length)&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain empty path segments.`),n.length<2&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must name a list element: a property path ending with "${a}${l}" (for example "nodes${a}${l}").`),n[n.length-1]!==l&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must end with "${a}${l}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===l&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must have exactly one "${l}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===q&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain "${q}" — the declaration is what gives "${q}" its meaning.`),isNaN(Number(n[o]))||Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const bu=new WeakSet;function wu(t){return"function"==typeof t.get&&bu.has(t.get)}const vu="[wcs/recursion-declaration-invalid]";class _u{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(t,e){this.spec=t;const n=Gl(e);for(const[e,o]of Object.entries(n)){if(!ou(e))continue;"function"==typeof o.set&&Z(`${vu} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&Z(`${vu} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=su(t,e);null===n&&Z(xi(e,t.recursiveAnchor)),0===n.length&&Z(`${vu} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${a}total"), not the node.`),cu(t,ru(n))&&Z(`${vu} "${e}" names the recursion structure itself (a node, its "${t.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 "${t.recursiveAnchor}${a}total").`),this._definitions.set(e,{recursivePath:e,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(t){for(const[e,n]of Object.entries(t)){if(ou(e)||wu(n))continue;const t=this._matchExpansion(e);null!==t&&Z(`${vu} "${e}" is already defined on the state, so the recursive getter "${t}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const t=Array.from(this._definitions.values());for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)iu(this.spec,t[e].suffix,t[n].suffix)&&Z(`${vu} "${t[e].recursivePath}" and "${t[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(t){for(const e of this._definitions.values())if(au(this.spec,e.suffix,t))return e.recursivePath;return null}recursiveGetterOwningPath(t){const e=this._ownerByPathInfo.get(t);if(void 0!==e)return e;const n=this.recursiveGetterOwning(t.path);return this._ownerByPathInfo.set(t,n),n}recursiveGetterOwning(t){const e=this._accessors.get(t);if(void 0!==e)return e.recursivePath;const n=lu(t),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 t=n.lastIndexOf(a);null===s&&t>this.spec.anchor.length;t=n.lastIndexOf(a,t-1))s=this._matchExpansion(n.slice(0,t))}return this._ownerByPath.set(n,s),s}_matchExpansion(t){for(const e of this._definitions.values())if(null!==hu(this.spec,e.suffix,t))return e.recursivePath;return null}materializeForPathInfo(t,e){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(e);if(void 0!==n)return n;const o=this.materializeFor(t,e.path);return this._accessorByPathInfo.set(e,o),o}materializeFor(t,e){const n=this._accessors.get(e);if(void 0!==n)return n;if(!e.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const t of this._definitions.values()){const n=hu(this.spec,t.suffix,e);null!==n&&(null!==o&&Z(`"${e}" matches both "${o.recursivePath}" and "${t.recursivePath}".`),o=t,s=n)}return null===o?null:this._define(t,o,s,e)}_define(t,e,n,o){const s=t.findStateDescriptor(o);void 0===s||wu(s)||Z(`"${o}" is already defined on the state, so the recursive getter "${e.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:e.recursivePath,depth:n}),i=e.get,a=function(){return i.call(this)};var l;return l=a,bu.add(l),t.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(t,n),this._accessors.set(o,r),r}_registerListPaths(t,e){for(const n of function(t,e){const n=[];n.push(t.anchorList);for(let o=0;o<e;o++)n.push(du(t,o)+a+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){const n=new Set(this._accessors.keys());return function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&wu(n)&&delete e[t]}for(const e of[t.staticDependency,t.dynamicDependency]){for(const t of n)e.delete(t);for(const[t,o]of e){let s=null;for(let t=0;t<o.length;t++)n.has(o[t])?s??=o.slice(0,t):s?.push(o[t]);null!==s&&(0===s.length?e.delete(t):e.set(t,s))}}!function(t,e,n){for(const o of n){const n=nt(o),s=n.wildcardParentPathInfos,r=(e,o,i)=>{if(i===s.length)return void Ts(Ue(t,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=e;for(const t of s[i].segments.slice(a))l=l?.[t];if(!Array.isArray(l))return;const c=Is(l);if(null===c)return;const u=Math.min(c.length,l.length);for(let t=0;t<u;t++)r(l[t],c[t],i+1)};r(e,null,0)}}(t,e,n)}}(t,e,n),n}concretePathAt(t,e){let n=this._concreteBySuffix.get(t);void 0===n&&(n=[],this._concreteBySuffix.set(t,n));let o=n[e];return void 0===o&&(o=uu(this.spec,t,e),n[e]=o),o}accessorFor(t){return this._accessors.get(t)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const $u="recursionSpec",Su="recursionRegistry",xu={order:5,validateEarly(t,e,n){const o=function(t){const e=t[H];if(void 0===e)return null;"object"==typeof e&&null!==e||Z(`[wcs/recursion-declaration-invalid] ${H} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(e);0===n.length&&Z(`[wcs/recursion-declaration-invalid] ${H} must declare exactly one anchor; it is empty.`),n.length>1&&Z(`[wcs/recursion-declaration-invalid] ${H} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];yu("anchor",o),"string"!=typeof s&&Z(`[wcs/recursion-declaration-invalid] ${H} entry "${o}" must map to the repeating sub-path as a string (for example "children${a}${l}").`),yu("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(a)),i=s.slice(0,s.lastIndexOf(a)),c=r+a+q;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:c,anchorList:r,repeatList:i})}(e);n.set($u,o),n.set(Su,null===o?null:new _u(o,e))},preCommit(t,e,n){const o=t.recursionRegistry;if(null!==o)for(const e of o.forgetGenerated(t,n.get("previousState")))t.addGeneratedPath?.(e);const s=n.get(Su)??null;t.setRecursionRegistry?.(s),null!==s&&t.attachAddressHooks?.("recursion",H)},apply(t,e,n){const o=n.get($u)??null;null!==o&&t.addListPath(o.anchorList)}};let Pu=!1;const Nu={name:"recursion",install(){Pu||(Pu=!0,gu||(gu=!0,Ha("recursion",mu)),Va("recursion",xu))}},ku={written:function(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let Iu=!1;function Au(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function Eu(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function Cu(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function Tu(t){return t.startsWith("$")}function Mu(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function Ou(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||Z(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||Z(`${e} entries must be non-empty strings.`),t.startsWith("$")&&Z(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&Z(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function Lu(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||Z(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Ht(t);null!==r&&"function"==typeof r.define||Z(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&Z(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const t of Array.from(e.childNodes))i.content.appendChild(a.importNode(t,!0));const l=e.mode,{bindables:c,commands:u,streamBackedBindables:d}=function(t){const e=Ou(t,O)??[],n=Ou(t,L)??[],o=Gl(t),s=function(t){const e=t[z];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}Z(`${O} entry "${t}" is not declared on the state.${rt(t,Mu(o,"value"))}`)}"function"==typeof e.value&&Z(`${O} entry "${t}" is a method. Declare it in ${L} instead.`)}for(const t of n){const e=o[t];void 0===e&&Z(`${L} entry "${t}" is not declared on the state.${rt(t,Mu(o,"method"))}`),"function"!=typeof e.value&&Z(`${L} entry "${t}" is not a method. Declare it in ${O} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||u.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(K))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=Ht(this._shadow);return null!==t&&qt(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(m.bindableEventMap).length>0){const e=t.querySelector(p);e?(Iu||(Iu=!0,Ha("dcc",ku)),e.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${O} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=Gl(n);for(const[t,e]of Object.entries(g)){if(Tu(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=Cu(t,o)}else n.get=Au(t),n.set=Eu(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:Au(t),set:Eu(t)});r.define(s,m)}const Ru={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(K)?async function(t,e,n){const o=t;try{o.hasAttribute("bind-component")&&Z(`"bind-component" cannot be used inside a [${K}] host. DCC state comes from the template, not from a component property.`);const s=await async function(t,e){try{if(t.hasAttribute("src")){const e=t.getAttribute("src");if(e.endsWith(".js"))return await Oa(e);Z(`DCC: Unsupported src type: ${e}`)}const n=t.querySelector('script[type="module"]');if(n)return await Ma(n,e.tagName.toLowerCase());Z(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}catch(t){Z(`DCC: Failed to load state: ${t}`)}}(o,e);Lu(e,n,s),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}(t,e.host,e):null}};let ju=!1;const Du=new WeakMap;function Wu(t,e,n){let o=Du.get(t);void 0===o&&(o=new Map,Du.set(t,o));null!=o.get(e)&&Z(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function zu(t,e){if(null===t)return!1;const n=Du.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+a)||t.startsWith(e+a))return!0;return!1}const Bu=new WeakMap,Fu=[];function Hu(t,e,n,o){if(e.length>0){const s=n.split(a),r=Zl(e,s);if(null!==r)return o&&r.readonly&&Z(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${$}.${r.innerSegments.join(a)}#${m}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${m} from the injection.`),tc(r,s)}return t+a+n}function qu(t,e,n){for(const t of e){const e=t.outerPathInfo.path;if(n===e)return t.innerSegments.join(a);if(n.startsWith(e+a))return t.innerSegments.join(a)+n.slice(e.length)}return n===t?"":n.startsWith(t+a)?n.slice(t.length+1):null}function Uu(t,e,n=Fu){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)=>e[o](Hu(t,n,s,!1),...r)}return"$setAll"===s?(o,...s)=>e.$setAll(Hu(t,n,o,!0),...s):"$resolve"===s?(o,...s)=>e.$resolve(Hu(t,n,o,s.length>1),...s):e[s]}return e[Hu(t,n,s,!1)]}},set:(o,s,r)=>("string"!=typeof s||(e[Hu(t,n,s,!0)]=r),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Gu=new WeakMap,Vu=[],Ku=new WeakMap,Ju=new WeakSet;function Qu(t){console.error(`[@wcstack/state] volume "${t.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>.`),t.onGrafted(null)}let Xu=null;const Yu=new WeakMap,Zu=new Set;function td(t,e,n,o){let s=Yu.get(t);if(void 0===s){if(!o)return null;s=new Map,Yu.set(t,s)}let r=s.get(e);if(void 0===r){if(!o)return null;r=new Map,s.set(e,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 ed(t,e){if(!t.component.isConnected)return!1;const n=pe(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function nd(t,e,n,o){const s=td(t,e,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&ed(n,e)?n:null}(r,o);if(null!==t)return{record:t,entry:r.entry}}let i=null,l=null;for(const t of s.holders){const r=t.ref.deref();void 0!==r?ed(r,o)&&(null!==l&&Z(`[wcs/mount-export-ambiguous] "${e}${a}${n}" is exported by two mounted components on the same instance: <${l.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=t,l=r):s.holders.delete(t)}return null===i||null===l?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:l,entry:i.entry})}function od(t){const e=t.parentStateElement,n=pe(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[Ae](n,()=>{t.$postUpdate(o.exportedPath)})})}const sd=new WeakMap;class rd{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,s,r){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return pn(nt(this.markerParentPath+a+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(pc(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,s,...r)=>{const i=r.length>0?fc(t,e):pc(t,e),a=mc(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a="$setAll"===s?fc(t,e):pc(t,e),l=mc(0,e,a,r,n);return o[s](a,l,...i)}}return this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return tl(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[pc(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||Z(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),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(t,e)?(t[e]=n,!0):(this.receiver[fc(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return pc(this.record,e),!0}catch{return!1}}}function id(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=sd.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},sd.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(i,new rd(t,s,e.listIndex,r,n,o))}function ad(t,e){const n=function(t){return gc.get(t)??null}(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&Z(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&ns(e).dispose(),function(t,e){$c||($c=!0,fe=t=>gc.has(t)?t.host:null),gc.set(t,e),vc.set(e,t);let n=bc.get(e.parentStateElement);void 0===n&&(n=new Map,bc.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=yc.get(e.component);void 0===o&&(o=new Map,yc.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&wc.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}(e,t),e instanceof ShadowRoot&&function(t,e){const n=Ji.get(t);if(void 0!==n){if(n===e)return;Z("A state tree is already registered on this root.")}Ji.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const s=dc.exec(e.statePathName);if(null!==s){const r=function(t,e){return void 0===e?t.delta:nt(pc(t,e)).wildcardCount-nt(e).wildcardCount}(t,n);o=0===r?e.statePathName:`$${Number(s[1])+r}`}else if(o=pc(t,e.statePathName),"for"===e.bindingType){const n=nt(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+a+l,n)}const r=e.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(m)&&null!==hc(t,e.statePathName);return o!==e.statePathName||i?{...e,statePathName:o,statePathInfo:nt(o),...i?{propModifiers:[...r,m]}:{}}:e}(t,e,n);X(e);const o=pe(t.component);Sa(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),Bi(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=pc(t,n)}catch{continue}const o=e.indexOf(a+t.marker);if(-1===o)continue;const s=e.slice(0,o+1+t.marker.length),r=e.slice(s.length+1),i=e.slice(0,o)+a+r,l=nt(i);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:e,exportedPath:i};t.exports.set(i,c),td(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,i),Vl?.markExported(t.parentStateElement,i)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=pe(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const s=`${n}|${o.exportedPath}`;if(Zu.has(s))continue;const r=nt(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[Ae](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Zu.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.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.`))}}(t),od(t),o=e,s=Promise.resolve(),Qi.set(o,s),s.then(()=>na(o),()=>{})}function ld(t,e){const n=ns(e),o=pe(t.component);n.forEachActiveBindingNode(t=>me(t,o)),zi(n.rebindAddresses()),od(t)}function cd(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const ud={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const s=xc(t,e.pathInfo.path);if(null!==s)return id(s,e,n,o)}return za},readMissing(t,e,n,o,s){if(null===n){if(zu(t.rootNode??null,e.pathInfo.path))return;return za}if(!0===t.hasMounts){const n=nd(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s){const r=id(t,pn(nt(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(n.record,n.entry,e.listIndex,o,s)}return za},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=Bu.get(t);if(void 0===n||0===n.size)return null;const o=e+a;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&Z(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return za},writeMissing(t,e,n,o,s,r,i){if(!0===t.hasMounts){const n=nd(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s,r){const i=id(t,pn(nt(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(n.record,n.entry,e.listIndex,s,r,i)}return za},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=xc(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(a,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const s=-1===o?e:e.slice(0,o),r=-1===o?"":e.slice(o+1),i=t.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:t.delta}(t,o)}return 0},handlerScope(t,e,n,o,s){if(!0!==t.hasMounts)return s;const r=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=gc.get(n);if(void 0!==t)return t;n=n.parentNode}return gc.get(e)??null}(e,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(t,e,n){const o=function(t){return Gu.get(t)??Vu}(t);for(const s of o){const o=new Set,r={};for(const n of e){if(n.absolutePathInfo.stateElement!==t)continue;const e=n.absolutePathInfo.pathInfo.path;if(-1!==e.indexOf("#"))continue;const i=qu(s.mountPath,s.injections,e);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const t=Ye(n.listIndex,a);(r[i]??=[]).push(t)}}if(o.size>0)try{s.callback.call(Uu(s.mountPath,n,s.injections),Array.from(o),r)}catch(t){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>zu(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(function(t){const e=bc.get(t);return void 0!==e&&e.size>0}(e))for(const n of Sc(e)){if(!cd(n.component,t))continue;const e=_c(n);null!==e&&ld(n,e)}}(e,t)}};let dd=!1;const hd=new WeakMap;function fd(t){let e=hd.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},hd.set(t,e)),e}function pd(t,e){null!==e.slotRootNode&&(function(t,e,n){const o=Du.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function md(t,e,n){if(e.slotRootNode===n)return!0;const s=e.mountPath;try{Wu(n,s,t)}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 Zi(n)?.markHasVolume?.(),e.slotRootNode=n,!0}const gd={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=fd(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{Wu(n,e.mountPath,t),Zi(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,zl}return async function(t,e){const n=t,s=t.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(t){0===t.length&&Z('"mount" requires a non-empty tree path.');const e=nt(t);for(const n of e.segments)0===n.length&&Z(`"mount" path "${t}" has an empty segment.`),n===l&&Z(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&Z(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),i=function(t,e){const n=[],s=new Set;for(const r of At(t)){if(r.propSegments[0]!==$)continue;const t=r.propSegments.slice(1),i=r.statePathInfo,a=t=>Z(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${e}"> "${r.propName}: ${r.statePathName}": ${t}`);1===t.length&&t[0]&&t[0]!==l&&"$"!==t[0][0]&&"#"!==t[0][0]||a(`inject one key at a time ("${$}.<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(t=>t!==m)&&a(`an injection accepts only #${m}.`),s.has(t[0])&&a(`"${t[0]}" is injected twice.`),s.add(t[0]),n.push({innerSegments:t,outerPathInfo:i,readonly:r.propModifiers.includes(m)})}return n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&Z('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),Wu(s,r,t),Zi(s)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=s}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===Zi(s)&&function(t,e){const n=()=>{if(null!==Zi(t))return;const n=t.querySelectorAll(o.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> 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=t.ownerDocument??t;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&pd(t,e),t.settleInitialization()};let c;try{c=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void a(null)}const u=t.connectedRootNode??null;null!==u&&md(t,e,u)?function(t,e,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};null===e?(yf(),function(t,e){if(Ju.has(t))return void Qu(e);let n=Ku.get(t);void 0===n&&(n=[],Ku.set(t,n)),n.push(e)}(t,a)):mf(e,a)}(u,Zi(u),r,c,a,()=>md(t,e,u),i):a(null)}(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=fd(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&Zi(n)===e.graftInfo.rootStateElement&&ff(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==hd.get(t)?.initializing)return;const e=t.getAttribute("mount");Z(`Cannot replace the state of <${o.tagNames.state} mount="${e}"> 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 "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){Ju.add(t);const e=Ku.get(t);if(void 0!==e){Ku.delete(t);for(const t of e)Qu(t)}}(e)},initializeFailureCleared(t,e){!function(t){Ju.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=fd(t);return null!==e.graftInfo&&ff(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,pd(t,e)),t.clearConnectedRootNode(),!0}};let yd=!1;const bd=new WeakMap;function wd(t,e){let n=bd.get(t);n||(n=new Set,bd.set(t,n)),n.add(e)}const vd=new WeakMap,_d=new WeakMap,$d=new WeakMap,Sd=new WeakMap,xd={isComplete:function(t,e){return!0===bd.get(t)?.has(e)},isDeclared:function(t,e){return!0===vd.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=_d.get(t);o||(o=new Map,_d.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=$d.get(t);o||(o=new Map,$d.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)},rememberOverwrittenValue:function(t,e,n,o){let s=Sd.get(t);s||(s=new Map,Sd.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}};const Pd=new WeakMap;class Nd{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=Pd.get(t);return n?n.get(e)??null:null}(t,e)??Z("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const kd=t=>()=>t;function Id(t,e,n,o){!function(t,e,n){let o=Pd.get(t);o||(o=new Map,Pd.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(function(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}(o));const s=function(t,e){const n=new Nd(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:kd(s),enumerable:!0,configurable:!0}),wd(e,n),Ad(e,n)}function Ad(t,e){if(M in t){const n=t[M];"function"==typeof n?n.call(t,e).catch(t=>{Z(`Error in ${M}: ${t instanceof Error?t.message:String(t)}`)}):Z(`${M} is not a function.`)}}const Ed=new Set;function Cd(t,e){Ed.has(t)||(Ed.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Td(t){const e=t.rootEntry,n=pe(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Ae](n,()=>{o=t[e.outerPathInfo.path]})}),o}const Md=new WeakMap;function Od(t,e){t.landInitialization(),Z(e)}async function Ld(t,e){const n=t;if(n.hasAttribute("bind-component")){const i=n.parentNode,l=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,c=l?Bt(l):null;null!==l&&null!==c||Z(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||l.hasAttribute(o.bindAttributeName)||Od(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const u=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&u.push('<script type="module">'),u.length>0&&Z(`"bind-component" cannot be combined with ${u.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(t,e){let n=vd.get(t);n||(n=new Set,vd.set(t,n)),n.add(e)}(l,d);const h=Ht(l);null===h&&Z(`CustomElementRegistry is unavailable for <${c}>.`),await h.whenDefined(c.toLowerCase()),l.hasAttribute(o.bindAttributeName)&&await Dt(l),d in l||Z(`Component does not have property "${d}" for state binding.`);let f=l[d];"object"==typeof f&&null!==f||Z(`Component property "${d}" is not an object for state binding.`);const p=function(t,e){const n=_d.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(l,d);if(void 0!==p&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=ne(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(l,d)&&(l[d]=p,f=p),e.boundComponent=l,e.boundComponentStateProp=d,t.setBoundComponent(l,d),i instanceof ShadowRoot||(ne(l)??[]).some(t=>t.propSegments[0]===d)||Od(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${d}: path").`),l.hasAttribute(o.bindAttributeName)){const o=(ne(l)??[]).filter(t=>t.propSegments[0]===d);if(o.length>0){const u=Zi(l.getRootNode())??Od(t,`No state tree found on this root for mount host <${c}>.`);let h=(s=l,r=d,yc.get(s)?.get(r)??null);const p=null!==h;if(null===h&&(function(t,e,n){const o=Sd.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;Sd.get(t).delete(e)}}(l,d,f),h=function(t,e,n,o,s,r=new Set){0===n.length&&Z(`Cannot build a mount record without host bindings for "${e}".`);const i=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(a);l.has(n)&&Z("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(m)};i.push(o),0===e.length&&(c=o)}i.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++ec,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(s),p=new Set;for(const t of i)t.innerSegments.length>0&&p.add(t.innerSegments[0]);const g={};for(const t of Object.keys(s))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof s[t]&&(r.has(t)||p.has(t)||(g[t]=s[t]));return{id:u,marker:d,component:t,stateProp:e,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?d:c.outerPathInfo.path+a+d,stateObject:s,getterKeys:h,setterKeys:f,injectedKeys:r,mappedKeys:p,privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(l,d,o,u,f,function(t,e){return $d.get(t)?.get(e)}(l,d)),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp;let s,r=!1;for(const i of e){if(null===t.rootEntry)continue;if(r||(s=Td(t),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const e=t.rootEntry.outerPathInfo.path;Cd(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${e}.${i}" (${o}: ${e}). Remove the default to read the tree, or rename it to keep it private.`)}}(h)),e.mountRecord=h,n.parentNode!==i)return;try{ad(h,i instanceof ShadowRoot?i:l)}catch(e){throw t.landInitialization(),e}if(!p){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=pe(t.component);let s;return e[Ae](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(t,e,n){const o=t.parentStateElement,s=(t,e)=>{let s;return o.createState(t,t=>{s=n(t,()=>e(t))}),s};return"$postUpdate"===e?e=>s("readonly",n=>n.$postUpdate(pc(t,e))):(n,o,...r)=>{const i="$setAll"===e||"$resolve"===e&&r.length>0,a=i?fc(t,n):pc(t,n),l=pe(t.component)?.listIndex.indexes??[],c=mc(0,n,a,"$resolve"===e?o??[]:o,l);return s(i?"writable":"readonly",t=>t[e](a,c,...r))}}(t,s,n);let r;return e.createState("readonly",e=>{r=n(e,()=>e["$"===s[0]?s:pc(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:fc(t,s)]=r})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return pc(t,n),!0}catch{return!1}}})}(h);Object.defineProperty(l,d,{get:()=>t,enumerable:!0,configurable:!0}),wd(l,d)}return Ad(l,d),function(t){const e=nc.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(q)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;oc.has(n)||(oc.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.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.`))}(h),void sc(h,"$connectedCallback")}}Id(t,e.boundComponent,e.boundComponentStateProp,f)}var s,r}const Rd={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=Md.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Md.set(t,e)),e}(t);return Ld(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=Md.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&ld(n,o)}),sc(n,"$connectedCallback"),!0},disconnecting(t){const e=Md.get(t);return void 0!==e&&null!==e.mountRecord&&(sc(e.mountRecord,"$disconnectedCallback"),od(e.mountRecord),t.clearConnectedRootNode(),!0)}};let jd=!1;const Dd=new WeakMap,Wd=new Set,zd=new Set;function Bd(t){return t.byFromPath.size>0||t.byResetPath.size>0}function Fd(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function Hd(t){return Dd.get(t)}function qd(t){Ud(t),Dd.delete(t)}function Ud(t){Wd.delete(t),zd.delete(t)}const Gd=new WeakMap,Vd=new WeakMap,Kd=new Set,Jd=new Map;function Qd(t){return Gd.get(t)??Jd}const Xd=new Map;function Yd(t){return Vd.get(t)??Xd}function Zd(t){0===t.length&&Z(`[wcs/watch-declaration-invalid] ${B} entry name must be a non-empty state path.`),t.startsWith("$")&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not start with "$" (reserved namespace).${it}`),t.includes("@")&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${it}`),t in Object.prototype&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=nt(t);for(const n of e.segments)0===n.length&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" has an empty path segment.${it}`);return e.wildcardCount>c&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" exceeds the maximum wildcard depth (128).`),e}let th=0,eh=0;function nh(t){th=t+1}function oh(){th=0}function sh(){th>eh&&(eh=th)}const rh=new WeakMap;function ih(t,e,n){let o=rh.get(t);void 0===o&&(o=new Map,rh.set(t,o)),o.set(e,n)}const ah=new Map;function lh(t,e){ah.has(t)||ah.set(t,e)}function ch(t){return ah.get(t)}const uh={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||lh(n,o)},swapped(t,e,n){var o;o=n,ah.has(o)&&lh(e,ch(n))}};function dh(t){for(let e=t;null!==e;e=e.parentListIndex)if(ks(e))return!0;return!1}function hh(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[Ee](pn(e.wildcardParentPathInfos[i],r)),l=Is(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=Xe(o,i,e.wildcardCount);if(l!==c&&!xs(l,c)){if(ks(c))return"gone";s="replaced"}r=l}return s}function fh(t,e,n){const o=new Map;for(const s of n){const n=hh(t,e,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(),t=>t.row)}const ph=new Set;function mh(t){ph.delete(t)}const gh=Symbol("wcs-stream-last-notified-uncertain"),yh=new WeakMap;function bh(t,e){const n=yh.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function wh(t,e){const n=yh.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:gh,error:Object.is(o.error,null)?null:gh})}const vh=new WeakMap;function _h(t){return vh.get(t)??new Map}function $h(t){mh(t);const e=vh.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,wh(t,n.name)}const Sh=new WeakSet;let xh=0;function Ph(t){return Hd(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function Nh(t){if(0===zd.size)return;if(e=t.absolutePathInfo.stateElement,!zd.has(e))return;var e;const n=Ph(t);if(void 0!==n)for(const t of n)kh(t)}function kh(t){Sh.has(t)||(Sh.add(t),xh++)}function Ih(t){return!!Sh.delete(t)&&(xh--,!0)}const Ah=/^(?:0|[1-9]\d*)$/;function Eh(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function Ch(t){if("object"!=typeof t||null===t||Object.isFrozen(t))return null;const e=Object.getPrototypeOf(t);return Array.isArray(t)?e===Array.prototype&&Reflect.ownKeys(t).every(e=>"length"===e||"string"==typeof e&&Ah.test(e)&&Eh(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&Eh(t,e))?null:"object"}function Th(t,e){const n=Ch(t);if(null===n)return t;const o=t,s=e.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(t.length):null===Object.getPrototypeOf(t)?Object.create(null):{},e.set(o,r);for(const t of Object.keys(o))r[t]=Th(o[t],e);return r}function Mh(t){return Th(t,new Map)}function Oh(t,e,n){if(Object.is(t,e))return!0;const o=Ch(e);if(null===o||"object"!=typeof t||null===t)return!1;const s=t,r=e;if("array"===o){if(!Array.isArray(t)||t.length!==e.length)return!1}else if(Array.isArray(t)||Object.keys(s).length!==Object.keys(r).length)return!1;if(Ch(t)!==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 e=0;e<t.length;e++)if(!Oh(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&Oh(s[t],r[t],n))}function Lh(t,e){return Oh(t,e,new Map)}const Rh=new WeakMap;function jh(t,e){if("function"!=typeof e)return;const n=Rh.get(e);void 0===n?Rh.set(e,new Set([t])):n.add(t)}const Dh={"read-source":t=>`${F} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-output":t=>`${F} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${F} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${F} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${F} could not write the output "${t}".`},Wh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function zh(t,e,n){null!==ge&&ge({type:"state:watch-error",phase:e,path:`${F}.${t}`,error:n})}function Bh(t,e,n){console.error(`[@wcstack/state] ${Dh[n](t)}`,e),zh(t,Wh[n],e)}function Fh(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function Hh(t,e){e.then(void 0,()=>{}),Bh(t,new TypeError(`${F} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const qh=new WeakSet,Uh=Object.freeze([]);function Gh(t,e,n){let o=t.get(n);return void 0===o&&(o={stateElement:e,entry:n,rows:[],reset:!1},t.set(n,o)),o}function Vh(t,e){let n=0;for(;n<t.indexes.length-1&&t.indexes[n]===e.indexes[n];)n++;return t.indexes[n]-e.indexes[n]}function Kh(t,e){return e.has(t.stateElement)&&!0===Hd(t.stateElement)?.entries.has(t.entry)}function Jh(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Qh(n,t))||Ih(e)}function Qh(t,e){return Hs().hasQueuedPath(t,e)}function Xh(t,e){!function(t,e,n){if(0!==xh)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=Ph(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||Ih(e)}}(t,e,Qh)}function Yh(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function Zh(t,e,n){if(!Kh(t,n))return Jh(t),null;const{stateElement:o,entry:s}=t;if(t.reset)return{group:t,next:s.initial};const r=s.source;if(function(t,e){for(const n of e.pathInfo.cumulativePaths)if(t.getterPaths.has(n))return!0;return!1}(o,r))return function(t,e,n){if(qh.has(t))return;qh.add(t);const o=`[wcs/scan-source-computed] ${F} entry "${e}" 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(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=_h(t).get(e);if(void 0===o)return!1;for(const t of o.depAddresses)if(n.has(t))return!0;return!1}(o,r.pathInfo.segments[0],e))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",e=>{const n=e[s.name],o=0===r.pathInfo.wildcardCount?t.rows:fh(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(Vh)){let n;try{n=Yh(e,r,t)}catch(t){Bh(s.name,t,"read-source");continue}const o=a(l,n,ch(t.absAddress),...t.indexes);if(Fh(o))return void Hh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){Bh(s.name,t,i.failure)}return i.plan}function tf(t,e){const{group:n}=t;if(!Kh(n,e))return void Jh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Ih(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!Lh(o,s.initial):!Object.is(o,t.next)){const o=n.reset?Mh(s.initial):t.next;e[s.name]=o,jh(s.name,o)}})}catch(t){Bh(s.name,t,"write")}}function ef(t){df(),(0!==Qd(t).size||0!==Yd(t).size||function(t){const e=Dd.get(t);return void 0!==e&&Bd(e)}(t))&&(function(t){Kd.add(t),function(t){const e=Dd.get(t);void 0!==e&&(Bd(e)&&Wd.add(t),function(t){return t.eventResetByPath.size>0}(e)&&zd.add(t))}(t)}(t),function(t){const e=[];for(const n of Qd(t).values())nf(t,n)&&e.push(n);for(const n of Yd(t).values())for(const o of n)nf(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{ih(t,Ue(t,o.pathInfo,null),n[o.path])}catch(e){sf(t,o.path,"prime",e)}})}(t))}function nf(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const of={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function sf(t,e,n,o){console.error(`[@wcstack/state] $watch ${of[n]} "${e}" threw.`,o),null!==ge&&ge({type:"state:watch-error",phase:n,path:e,error:o})}function rf(t){const e=Kd;try{if(0===e.size)return void Xh(t,e);const n=function(){const t=eh;return eh=0,t}();if(n>32){Xh(t,null);const e=Array.from(t,t=>t.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:e}),void(null!==ge&&ge({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}!function(t,e,n){if(0!==t.length){nh(n);try{for(const n of t)tf(n,e)}finally{oh()}}}(function(t,e,n){if(Xh(t,e),0===Wd.size)return Uh;const o=new Map;for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=Hd(t);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let e=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;e=Ye(n.listIndex,r.wildcardCount)}for(const s of i)Gh(o,t,s).rows.push({absAddress:n,indexes:e})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const e of a)Gh(o,t,e).reset=!0}if(0===o.size)return Uh;const s=Array.from(o.values()).sort((t,e)=>t.entry.order-e.entry.order),r=[];nh(n);try{for(const n of s){const o=Zh(n,t,e);null!==o&&r.push(o)}}finally{oh()}return r}(t,e,n),e,n),function(t,e,n){const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=Qd(t).get(s),i=Yd(t).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const e of a){let s=[];if(e.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=Ye(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(lf);const s=function(t){let e=null;for(let n=0;n<t.length;n++){const o=t[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=t[n-1];(dh(o.absAddress.listIndex)||s?.entry===o.entry&&af(s.indexes,o.indexes))&&(e??=new Set).add(o.entry)}if(null===e)return t;const n=new Set;for(const o of e){const e=t.filter(t=>t.entry===o),s=e[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(fh(t,o.pathInfo,e));for(const t of e)s.has(t)||n.add(t)})}catch(t){sf(0,o.path,"evaluate",t);for(const t of e)n.add(t)}}return t.filter(t=>!n.has(t))}(o);nh(n);try{for(const t of s){if(!e.has(t.stateElement))continue;const n=Qd(t.stateElement).get(t.entry.path)===t.entry,o=!0===Yd(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&cf(t)}}finally{oh()}}(t,e,n)}finally{ah.clear()}}function af(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function lf(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function cf(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=nf(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void sf(0,n.path,"evaluate",t)}const a=r?function(t,e){return rh.get(t)?.get(e)}(e,o):ch(o);r&&ih(e,o,i),null!==ge&&ge({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){sf(0,n.path,"handler",t)}}let uf=!1;function df(){uf||(uf=!0,Ha("watch",uh),Va("watch",hf),zs(rf,10),Ws(sh))}const hf={order:10,register(t,e){var n;n=t,Kd.delete(n),Ud(n),Gd.delete(n),function(t){rh.delete(t)}(t);const o=function(t,e){const n=e[B];if(void 0===n)return null;"object"==typeof n&&null!==n||Z(`[wcs/watch-declaration-invalid] ${B} must be an object mapping state paths to handler functions.${it}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${e}" must be a function.${it}`);const n=Zd(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){Gd.set(t,e)}(t,o),s.size>0?s:null}(t,e);t.setWatchPaths?.(o),null===o&&null==t.scanPaths||t.attachAddressHooks?.("watch",null!==o?B:F)},activate(t,n){e()||null==t.connectedRootNode||(null===n?!0===t.initialized:n===t.connectGeneration)&&ef(t)},deactivate(t){var e;e=t,Kd.delete(e),Ud(e)}};function ff(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(Uu(t.mountPath,o,t.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function pf(t,e,n,o=[]){!function(t,e,n,o){for(const t of o){const o=t.innerSegments[0],s=Object.getOwnPropertyDescriptor(n,o);void 0===s||"function"!=typeof s.get&&"function"!=typeof s.set&&"function"!=typeof s.value||Z(`Volume "${e}" declares "${o}" as an accessor or a method and also injects it ("${$}.${o}: ${t.outerPathInfo.path}"). Rename one of them.`)}const s=n[B];if(void 0!==s){"object"==typeof s&&null!==s||Z(`${B} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(s))"function"!=typeof e&&Z(`${B} entry "${t}" must be a function.`),Zd(t)}const r=n[U];if(void 0!==r){"object"==typeof r&&null!==r||Z(`${U} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(r)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&Z(`${U} entry "${n}" must map a list path to a field name or a key function.`);const r=Hu(e,o,n,!1);t.listKeys?.has(r)&&Z(`${U} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n.$streams&&Z(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&Z(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[H]&&Z(`Volume "${e}" declares ${H}, 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 t of Object.keys(Gl(n)))-1!==t.indexOf(q)&&Z(`Volume "${e}" declares "${t}", which uses "${q}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n,o);const{data:s,accessors:r}=function(t,e){const n={},o=new Map;for(const[s,r]of Object.entries(Object.getOwnPropertyDescriptors(t)))s.startsWith("$")||e.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(t=>t.innerSegments[0]))),i=nt(e),l=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(l)return;Z(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],s=""===n?o in t:void 0!==t[n+a+o];n=""===n?o:n+a+o,s||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(l)return;Z(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=s}),function(t,e){let n=Bu.get(t);void 0===n&&(n=new Set,Bu.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,s]of r){const r=e+a+n,i=s.get,l=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(Uu(e,this,o))}),"function"==typeof l&&(c.set=function(t){l.call(Uu(e,this,o),t)}),t.defineTreeAccessor(r,c)}!function(t,e,n,o){const s=n[B];if(void 0!==s){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(s)){const s=Hu(e,o,a,!1),c=function(t,n,...s){l.call(Uu(e,this,o),t,n,...s)};n.push({path:s,pathInfo:nt(s),handler:c,order:1e6+i++}),r.add(s),t.setPathInfo(s,"prop","watch")}n.length>0&&(function(t,e){let n=Vd.get(t);void 0===n&&(n=new Map,Vd.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}(t,n),t.addVolumeWatchPaths?.(r),ef(t))}const r=n[U];if(void 0!==r){const n=new Map;for(const[t,s]of Object.entries(r))n.set(Hu(e,o,t,!1),s);t.mergeVolumeListKeys?.(n)}const i=n[C];"function"==typeof i&&(function(t,e){let n=Gu.get(t);void 0===n&&(n=[],Gu.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,injections:o,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}(t,e,n,o);const c=n.$connectedCallback;return"function"==typeof c&&t.createState("writable",t=>{let n;try{n=c.call(Uu(e,t,o))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n,injections:o}}function mf(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=pf(t,e.mountPath,e.volumeState,e.injections)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}let gf=!1;function yf(){var t;gf||(gf=!0,dd||(dd=!0,Ha("scopes",ud)),yd||(yd=!0,Hl("scopes",gd)),jd||(jd=!0,Hl("bindComponent",Rd),ss=xd),Xu=mf,t=bf,Yi.includes(t)||Yi.push(t))}function bf(t,e){(function(t){const e=Du.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){Ju.delete(t);const n=Ku.get(t);if(void 0===n||0===n.length||null===Xu)return;Ku.delete(t);const o=Xu;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const wf={name:"scopes",install(){yf(),ju||(ju=!0,Hl("dcc",Ru))}},vf=/^@@wcs-(?:for|if|elseif|else):[^-]/,_f=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,$f=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Sf=/^@@wcs-text-start:(.+)$/;function xf(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Pf extends Ul{_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(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=Pc.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=o.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(e,t);if(void 0!==o&&"function"==typeof o.get)continue;const s=e[t];"function"!=typeof s&&(n[t]=s)}return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=xf(JSON.stringify(e)),t.appendChild(n);const s=Array.from(sa.keys());for(const e of s){const n=ia(e);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",e);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),t.appendChild(s)}const r=Array.from(ci);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=li(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const t of o)i[t.propName]=t.value;e[s]=i}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=xf(JSON.stringify(e)),t.appendChild(n)}}ci.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(_f.test(t.data)||$f.test(t.data))&&n.push(t)}for(const t of n)t.remove()}static removeStructuralComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;vf.test(t.data)&&n.push(t)}for(const t of n)t.remove()}static restoreTextBindings(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode,o=Sf.exec(t.data);o&&n.push({comment:t,path:o[1]})}for(const{comment:t,path:e}of n){const n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}const r=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const t=r.currentNode;_f.test(t.data)&&i.push(t)}for(const t of i){const e=_f.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}Pf.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(vf.test(t.data)){const e=t.data.split(":")[1];l.push({comment:t,uuid:e})}}for(const{comment:t,uuid:e}of l){const n=s.get(e);if(n){const e=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&e.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)e.content.appendChild(r);else for(const t of Array.from(n.childNodes))e.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(e,t)}}const c=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of c)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const Nf={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of s){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Pc),Pf.buildContent(o,Pf.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}},kf=new Set(["for","if","elseif","else"]);function If(t){const e=new es;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i]=ce(s),a=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:e}}function Af(t,e,n){for(const o of e)"event"===o.bindingType||kf.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in I||nt(o.statePathName).wildcardCount>n||t.push(o)}function Ef(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const t=i.currentNode;if(t.data===r)return t}return null}function Cf(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=At(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,ca()],bindingType:"else"}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;ba(a),"string"==typeof l&&ma(a,l),Sa(n,a,l),ra(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:ya(a)})}}const Tf={hydrate:async function(t){await Hi(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${Pc}". Falling back to full render.`),Pf.cleanupDom(t),!1}for(const n of e)Cf(t,n);const n=function(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const t of o){const n=_f.exec(t.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 u=t.nextSibling;const d=`@@wcs-${o}-end:${s}`;for(;u&&(u.nodeType!==Node.COMMENT_NODE||u.data!==d);)c.push(u),u=u.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body),s=function(t,e){const n=new Map,o=[];for(const s of e){if(0===s.nodes.length)continue;const e=Fr(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=If(s.nodes);Sr(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");us(e,r),Nr(e,i);const c=[];for(const t of r)t.statePathName in I&&c.push(t);if(fs(e,c),"for"===s.type&&null!==s.index){const i=Ef(t,"for",s.uuid);if(i){const t=vs(null,s.index);Yr(i,t,e),Zr(i,s.nodes[s.nodes.length-1]),Lr(i,e);const c=nt(s.path+"."+l);kr(e,pn(c,t)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Af(o,r,c.wildcardCount);let u=n.get(s.uuid);u||(u=[],n.set(s.uuid,u)),u.push(t)}}else{const n=Ef(t,s.type,s.uuid);n&&(Lr(n,e),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Af(o,r,0))}}for(const[e,o]of n){const n=Ef(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=ia(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Zi(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&Es(e,o)})}return o}(document.body,n);Pf.removeBlockBoundaryComments(document.body);const r=[];for(const t of e)t.parentNode&&(r.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());Pf.restoreTextBindings(document.body);const[i,a]=ce(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(me(t,null),e.setAttribute("data-wcs-completed",""))}else me(t,null);const c=[],u=[],d=ns(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(kf.has(t.bindingType))u.push(t);else{if(t.statePathName.includes(l))continue;c.push(t)}for(const t of u)if("for"===t.bindingType){const e=on(t),n=Zi(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&(we(e,o),Pe(e,o))})}zi([...c,...s]);for(const{el:t,parent:e,next:n}of r)e.insertBefore(t,n);const h=t.querySelectorAll(o.tagNames.ssr);for(const e of h){const n=e.hydrateProps;for(const[e,o]of Object.entries(n)){const n=t.querySelector(`[data-wcs-ssr-id="${e}"]`);if(n)for(const[t,e]of Object.entries(o))n[t]=e}}const f=t.querySelectorAll("[data-wcs-completed]");for(const t of f)t.removeAttribute("data-wcs-completed");return!0},loadState(t){const e=t.parentNode;if(!e)return null;const n=Pf.find(e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(t){await ta(t.rootNode);const e=Pf.extractStateData(t),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",Pc),Pf.buildContent(n,e),t.parentNode?.insertBefore(n,t)}};let Mf=!1;const Of={name:"ssr",install(){!function(){var e;Mf||(Mf=!0,Vi=Tf,e=t=>{t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,Pf)},Ql.includes(e)||Ql.push(e),function(){const e=globalThis;void 0===e[t]&&(e[t]=Nf)}())}()}},Lf="[wcs/scan-declaration-invalid]",Rf=Object.freeze([]);function jf(t){return`${F} entry "${t}"`}function Df(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function Wf(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${l}${l}`)?`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.${it}`}function zf(t,e,n){0===n.length&&Z(`${Lf} ${t} "${e}" must be a non-empty state path.${it}`),n.startsWith("$")&&Z(`${Lf} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${it}`),n.includes("@")&&Z(`${Lf} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${it}`),n in Object.prototype&&Z(`${Lf} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${it}`);const o=nt(n);for(const s of o.segments)0===s.length&&Z(`${Lf} ${t} ${e} "${n}" has an empty path segment.${it}`);return o.wildcardCount>c&&Z(`${Lf} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function Bf(t,e,n,o){const s=jf(t);0===t.length&&Z(`${Lf} ${F} entry name must be a non-empty string.${it}`),(t.includes(a)||t.includes(l))&&Z(`${Lf} ${s} must be a flat property name ("${a}" and "${l}" are not allowed). The output is a property the runtime owns.${it}`),t.startsWith("$")&&Z(`${Lf} ${s} must not start with "$" (reserved namespace).${it}`),t in Object.prototype&&Z(`${Lf} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${it}`),e.has(t)&&Z(`${Lf} ${s} conflicts with a getter declared on the state.${it}`),n.has(t)&&Z(`${Lf} ${s} conflicts with a setter declared on the state.${it}`),o.has(t)&&Z(`${Lf} ${s} conflicts with the ${z} entry of the same name — each output has exactly one owner.${it}`)}function Ff(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!function(t,e){return"function"==typeof e&&!0===Rh.get(e)?.has(t)}(t,o)&&Z(`${Lf} ${jf(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${it}`)}function Hf(t,e,n,o,s,r){const i=jf(t),l=void 0!==e.from,c=void 0!==e.on;if(l===c&&Z(`${Lf} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${it}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||Z(`${Lf} ${i} "on" must be a non-empty event-token name.${it}`),n.has(t)||Z(`${Lf} ${i} on "${t}" is not declared in ${D}.${rt(t,n)}${it}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&Z(`${Lf} ${i} "from" must be a state path string.${it}`);const d=zf(i,"from",u),h=Df(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&Z(Wf(i,"from",u,h));const f=Df(d,s);return null!==f&&Z(function(t,e,n){return`${Lf} ${t} from "${e}" ${n===e?"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.${it}`}(i,u,f)),(u===t||u.startsWith(t+a))&&Z(`${Lf} ${i} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${it}`),{kind:"path",path:u,pathInfo:d}}function qf(t,e,n,o){if(void 0===e)return Rf;const s=jf(t);Array.isArray(e)||Z(`${Lf} ${s} "resetOn" must be an array of state paths.${it}`);const r=[];for(const t of e){"string"!=typeof t&&Z(`${Lf} ${s} "resetOn" must contain only state path strings.${it}`);const e=zf(s,"resetOn",t);e.wildcardCount>0&&Z(`${Lf} ${s} resetOn "${t}" must not contain "${l}" — a reset returns the whole output to "initial".${it}`);const i=Df(e,o);null!==i&&Z(Wf(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&Z(`${Lf} ${s} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${it}`),"path"===n.kind&&t.startsWith(n.path+a)&&Z(`${Lf} ${s} resetOn "${t}" 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.${it}`),r.push(t)}return r}function Uf(t){const e=t.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[t.name];i="threw";const a=function(t){return Sh.has(t)}(t),l=a&&!Lh(n,t.initial)?Mh(t.initial):n,c=e(l,o,...s);if(Fh(c))return void Hh(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,jh(t.name,c)),a&&Ih(t)}catch(e){Bh(t.name,e,i)}}}const Gf="scanEntries",Vf={order:8,validate(t,e,n){const o=function(t,e,n=null){const o=t[F];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&Z(`${Lf} ${F} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${it}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(Gl(t)))"function"==typeof n.get?s.add(e):"function"==typeof n.set&&i.add(e),"function"==typeof n.set&&r.add(e),"function"==typeof n.value&&a.set(e,n.value);const l=function(t){const e=t[z];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];let u=0;for(const[t,d]of Object.entries(o)){Bf(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&Z(`${Lf} ${jf(t)} must be an object ({ from | on, initial, fold, resetOn? }).${it}`);const o=d;Ff(t,a,o);const h=Hf(t,o,e,s,i,n);"initial"in o||Z(`${Lf} ${jf(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${it}`),"function"!=typeof o.fold&&Z(`${Lf} ${jf(t)} fold must be a function.${it}`);const f=qf(t,o.resetOn,h,s);c.push({name:t,source:h,fold:o.fold,initial:o.initial,resetOn:f,order:u++})}return function(t){const e=new Set(t.map(t=>t.name)),n=new Map;for(const o of t){for(const t of o.resetOn){const n=nt(t).segments[0];e.has(n)&&Z(`${Lf} ${jf(o.name)} resetOn "${t}" reads the ${F} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${it}`)}if("path"===o.source.kind){const t=o.source.pathInfo.segments[0];e.has(t)&&n.set(o.name,t)}}for(const t of n.keys()){const o=[t];let s=n.get(t);for(;void 0!==s&&o.length<=e.size;)s===t&&Z(`${Lf} ${F} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${it}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}(e,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Gf,o)},applyEarly(t,e,n){const o=n.get(Gf)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=Mh(n.initial);t[n.name]=e,jh(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&In(t,n.source.tokenName).subscribe(Uf(n))}(t,o))},register(t,e,n){const o=n.get(Gf)??null,s=function(t){const e=new Map,n=Hd(t);if(void 0!==n)for(const t of n.entries)Ih(t)&&e.set(t.name,t.resetOn);return qd(t),e}(t);t.setScanPaths?.(null===o?null:function(t,e,n){const o=function(t,e){qd(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&Fd(n,t.source.path,t);for(const e of t.resetOn)Fd(o,e,t),"event"===t.source.kind&&Fd(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return Dd.set(t,r),r}(t,e);for(const o of e){const e=n.get(o.name);"event"===o.source.kind&&void 0!==e&&o.resetOn.some(n=>e.includes(n)&&Hs().hasQueuedPath(t,n))&&kh(o)}const s=new Set;for(const e of o.byFromPath.keys())s.add(e),t.setPathInfo(e,"prop","scan");for(const e of o.byResetPath.keys())t.setPathInfo(e,"prop","scan");return s.size>0?s:null}(t,o,s))}};let Kf=!1;const Jf=Object.freeze([]),Qf=Object.freeze([]);function Xf(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Jf,i=t.dynamicDependency.get(n)??Jf,a=e.byFromPath.get(n)??Qf;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const Yf=(t,e)=>e,Zf=new Set;const tp=new WeakMap,ep=new WeakMap;function np(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=_h(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&_h(t).has(n),ownKeys:()=>Array.from(_h(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=_h(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){Z(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){Z(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function op(t){const e=tp.get(t);if(void 0!==e)return e;const n=np(t,G,t=>t.status);return tp.set(t,n),n}function sp(t){const e=ep.get(t);if(void 0!==e)return e;const n=np(t,V,t=>t.error);return ep.set(t,n),n}function rp(t){tp.delete(t),ep.delete(t)}let ip=null;function ap(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}const lp={read(t,e){!function(t,e){null!==ip&&ip.add(qe(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===G?ap(op(t),e.pathInfo.segments):n===V?ap(sp(t),e.pathInfo.segments):za},get:(t,e)=>e===G?op(t.stateElement):e===V?sp(t.stateElement):za};function cp(t){gp();const e=_h(t);if(0!==e.size){!function(t){ph.add(t)}(t);for(const n of e.values())up(t,n)}}function up(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=ip,s=new Set;let r;ip=s;try{t.createState("readonly",t=>{r=n(t)})}finally{ip=o}r instanceof Promise&&Z(`${z} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${G}${a}${e.name}`,l=`${V}${a}${e.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==i&&o.path!==l||Z(`${z} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&Z(`${z} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=s,r}(t,e);!function(t,e){const n=Hd(t);if(void 0!==n&&0!==e.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==e.name)continue;const s=Xf(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&Z(`[wcs/scan-feedback-loop] ${z} entry "${e.name}" args read "${n}", which is derived from the ${F} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,e),t.createState("writable",t=>{t[e.name]=e.definition.initial}),dp(t,e,"active",null);const s=e.definition,r={fold(n){t.createState("writable",t=>{t[e.name]=s.fold(t[e.name],n)})},done(){dp(t,e,"done",null)},fail(o){dp(t,e,"error",o),n.abort()}};!async function(t,e,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 t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;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 t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",i)}}(s.source,o,n.signal,r)}function dp(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return yh.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(function(t,e,n,o){let s=yh.get(t);void 0===s&&(s=new Map,yh.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${G}${a}${e.name}`),i&&t.$postUpdate(`${V}${a}${e.name}`)}))}function hp(t){const e=ph;if(0===e.size)return;const n=[];for(const o of e)for(const e of _h(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&_h(t).get(o.name)===o)try{up(t,o)}catch(n){o.controller?.abort(),e.has(t)&&_h(t).get(o.name)===o&&dp(t,o,"error",n)}}let fp=!1;const pp=new WeakMap,mp={order:20,apply(t,e){var n;rp(t),$h(n=t),mh(n),vh.delete(n),function(t,e){const n=e[z];if(void 0===n)return void bh(t,Zf);"object"==typeof n&&null!==n||Z(`${z} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&Z(`${z} entry name must be a non-empty string.`),s.includes(a)&&Z(`${z} entry "${s}" must be a flat property name ("${a}" is not allowed).`),s.includes(l)&&Z(`${z} entry "${s}" must be a flat property name ("${l}" is not allowed).`),s.startsWith("$")&&Z(`${z} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&Z(`${z} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(s)&&Z(`${z} entry "${s}" conflicts with a getter declared on the state.`),t.setterPaths.has(s)&&Z(`${z} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||Z(`${z} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&Z(`${z} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&Z(`${z} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&Z(`${z} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&Z(`${z} entry "${s}" args must be a function.`);const c={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??Yf,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in e||(e[s]=c.definition.initial),o.set(s,c)}!function(t,e){vh.set(t,e)}(t,o),bh(t,new Set(o.keys()))}(t,e),void 0!==e[z]&&t.attachAddressHooks?.("streams",z)},activate(t,n){if(!e()&&null!=t.connectedRootNode){if(null===n){if(!0!==t.initialized)return;return cp(t),void pp.set(t,t.connectGeneration??0)}n===t.connectGeneration&&pp.get(t)!==n&&cp(t)}},deactivate(t){$h(t),rp(t)}};function gp(){fp||(fp=!0,Ha("streams",lp),Va("streams",mp),zs(hp,20))}const yp=[nu,{name:"temporal",install(){df(),Kf||(Kf=!0,Va("scan",Vf),Ws(Nh)),gp()}},Nu,wf,Of,Lc,Uc];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(yp),void Xl(void 0,void 0));const bp={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},wp=!1,vp=[".html"];function _p(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function $p(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let Sp=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const xp={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function Pp(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function Np(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}const kp={static:2,param:1,"catch-all":0};let Ip=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&$p(`${bp.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&$p(`${bp.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=kp[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(xp).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||$p(`${bp.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath,o=await this._guardHandler(e,n,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:Pp(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new Sp("Navigation cancelled by guard.",o);if(!o)throw new Sp("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new Sp("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},Ap=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=_p();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new Ip(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||$p(`${bp.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):$p(`${bp.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&$p(`${bp.route} with fallback attribute must be a direct child of ${bp.router}.`),t.fallbackRoute&&$p(`${bp.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const Ep=Symbol.for("wcstack.trustedTypes.policy"),Cp=Symbol.for("wcstack.trustedTypes.internal"),Tp="wcstack";function Mp(){const t=globalThis[Ep];return null===t||"object"!=typeof t?null:t}let Op=!1;function Lp(t){const e=function(){const t=globalThis,e=t[Cp];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Tp,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof Mp()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Tp}". Allow it in the CSP (\`trusted-types ${Tp};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[Cp]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Mp(),s=o?.createHTML;return"function"==typeof s?(Op||(Op=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Tp}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Tp};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Rp=new Map;let jp=class extends HTMLElement{_uuid=_p();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||$p(`${bp.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Rp.set(t,n),n}catch(e){$p(`${bp.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${bp.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Rp.has(t)?n.innerHTML=Lp(Rp.get(t)||""):n.innerHTML=Lp(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Lp(t):console.warn(`${bp.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&wp}get name(){return this.getAttribute("name")||""}},Dp=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||$p(`${bp.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&wp}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Wp=new Set(["props","states","attr",""]);function zp(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function Bp(t,e){t.hasAttribute("data-bind")||$p(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Wp.has(n)||$p(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&zp(t,e,o)}).catch(()=>{$p(`Failed to define custom element: ${s}`)}):zp(t,e,o)}let Fp=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||$p(`${bp.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${bp.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{Bp(e,t)}),e.hasAttribute("data-bind")&&Bp(e,t))}};function Hp(){return document.createElement(bp.layoutOutlet)}const qp="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Up(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){$p(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${qp}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${qp}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function Gp(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function Vp(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===bp.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),Gp(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===bp.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Up(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===bp.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=Hp();o.layout=n,i=o,a=e}}const c=await Vp(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function Kp(t){const e=new Map;return await Vp(t,t.template.content,[],e)}function Jp(t){return!1!==t.checkVisibility?.()}function Qp(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",n=xp[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)Qp(s,e,n,o)}function Xp(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)Qp(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let Yp=null,Zp=null;function tm(){const t=vp;return 0===t.length?null:(Yp===t&&Zp||(Yp=t,Zp=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Zp)}function em(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=tm();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function nm(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function om(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=tm();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function sm(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function rm(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{Bp(e,t.typedParams)}),n.hasAttribute("data-bind")&&Bp(n,t.typedParams),n.querySelectorAll(bp.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===bp.layoutOutlet&&n.assignParams(t.typedParams)}}function im(t,e){rm(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const am=Symbol.for("wcstack.transition-runner");const lm=Symbol.for("wcstack.binder");function cm(){const t=globalThis[lm];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const um=Symbol.for("wcstack.binder.pending"),dm=Symbol.for("wcstack.binder.taken");function hm(){const t=globalThis;let e=t[dm];return void 0===e&&(e=new WeakSet,t[dm]=e),e}function fm(t){const e=cm();return null===e?(function(){const t=globalThis;let e=t[um];return void 0===e&&(e=[],t[um]=e),e}().push(t),!1):(hm().add(t),e.bind(t),!0)}const pm=new WeakSet,mm="data-wcs";function gm(t,e,n){!pm.has(t)&&function(t){return t.hasAttribute(mm)||null!==t.querySelector(`[${mm}]`)}(t)&&(pm.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==cm()||(o=t,hm().has(o))||console.warn(`[@wcstack/router] ${e} contains ${mm} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function ym(t){for(const e of t.childNodeArray)1===e.nodeType&&(fm(e)||gm(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.'))}async function bm(t,e){try{let t=null;for(const n of e.routes){const o=await n.guardCheck(e);o&&(t=null===t?o:Object.assign({},t,o))}e.data=t}catch(e){if(e instanceof Sp)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function wm(t,e,n,o,s=""){const r=nm(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:s,path:r}),!0;let i=Xp(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:$p(`${bp.router} No route matched for path: ${r}`)),i.lastPath=o,i.search=s;const a=e.lastRoutes,l=await async function(t,e,n){if(!await bm(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||sm(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=im(o,e),n.length>0&&!s.has(o)&&ym(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[am];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",data:i.data??null,search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(Jp(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(Jp(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(t,i),!0)}function vm(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function _m(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function $m(t){return"?"===t?"":t}function Sm(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function xm(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Pm="data-wcs-ssr",Nm="data-wcs-ssr-link",km="@@wcs-route-ph:",Im="@@wcs-route-start:",Am="@@wcs-route-end:",Em=Object.freeze({});class Cm extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Em;_typedParams=Em;_searchParams=Em;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return em(t)}_normalizeBasename(t){return om(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(bp.outlet))return t;const e=document.createElement(bp.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||$p(`${bp.router} has no outlet.`),this._outlet}get template(){return this._template||$p(`${bp.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=Pp(t.search),s=t.data??null,r=this._data!==s,i=!Np(this._params,e),a=this._routeName!==t.routeName,l=!Np(this._searchParams,o),c=this._path!==t.path;r&&(this._data=s),i&&(this._params=e,this._typedParams=n),a&&(this._routeName=t.routeName),l&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,r&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${bp.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${bp.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=_m(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+$m(n.search)+n.hash,r=vm();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(nm(t,this._basename));await wm(this,this.outlet,t,this._path,$m(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(nm(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await wm(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${bp.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await wm(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=xm();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||$p(`${bp.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||$p(`${bp.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await Kp(this),r=!t&&this._outlet.hasAttribute(Pm);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&$p(`${bp.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(Pm);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await wm(this,this.outlet,i,this._path,window.location.search||""),(r||null!==cm())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(bp.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(km)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Im)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith(Am)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=nm(t,this._basename);let d=Xp(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of d.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(Im)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===bp.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(Pm);for(const t of d.routes)rm(t,d);return this.outlet.lastRoutes=d.routes,!await bm(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(t){const e=nm(t,this._basename),n=Xp(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&$p(`${bp.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await wm(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${km}${t.absolutePath}`}),this.outlet.setAttribute(Pm,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${Im}${t.absolutePath}`),s=document.createComment(`${Am}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&fm(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Sm(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),xm()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=vm();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(vm()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Tm=["title","rel","target","download","hreflang","lang","dir"];class Mm extends HTMLElement{static get observedAttributes(){return["to",...Tm]}_childNodeArray=[];_uuid=_p();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(bp.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(bp.router);if(n)return this._router=n;$p(`${bp.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return em(t)}_joinInternalPath(t,e){const n=om(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=_m(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+$m(o)+s}else try{t.href=new URL(e).toString()}catch{$p(`[${bp.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){xm()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Nm)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(Nm),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||Tm.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,xm())return this._updateActiveState(),void n.setAttribute(Nm,"");vm()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!vm()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){vm()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Tm.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=_m(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Om=[],Lm=new Map;let Rm=!1;const jm=new WeakMap;class Dm extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Rm||(this._captureInitialHead(),Rm=!0),Om.push(this),this._reapplyHead()}disconnectedCallback(){const t=Om.indexOf(this);-1!==t&&Om.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||$p("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=jm.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return jm.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Lm.has(t)||Lm.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Om)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Lm.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=Om.length-1;e>=0;e--){const o=Om[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Lm.has(n)&&(t=Lm.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),fm(t)||gm(t,`<${t.tagName.toLowerCase()}> inside <${bp.head}>`,`<${bp.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(bp.layout)||t.define(bp.layout,jp),t.get(bp.layoutOutlet)||t.define(bp.layoutOutlet,Fp),t.get(bp.outlet)||t.define(bp.outlet,Dp),t.get(bp.route)||t.define(bp.route,Ap),t.get(bp.router)||t.define(bp.router,Cm),t.get(bp.link)||t.define(bp.link,Mm),t.get(bp.head)||t.define(bp.head,Dm)}(void 0);const Wm="data-fetchtarget",zm={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Bm=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function Fm(t,e){return e.every(e=>"available"===t.availability.get(e))}const Hm=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let qm=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new Bm("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return Fm(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),u=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",d=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:u,userActivation:d},epoch:e.epoch??0,lastError:e.lastError}}(Hm,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!Fm(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:u="auto",timeout:d=0}=e;let h=null;d>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},d));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===u)s=await n.blob();else if("arrayBuffer"===u)s=await n.arrayBuffer();else if("text"===u)s=await n.text();else if("json"===u)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,d)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},Um=!1;function Gm(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Wm}]`);if(!n)return;const o=n.getAttribute(Wm);if(!o)return;const s=customElements.get(zm.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function Vm(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}const Km=Symbol.for("wcstack.trustedTypes.policy");function Jm(){const t=globalThis[Km];return null===t||"object"!=typeof t?null:t}let Qm,Xm=!1;let Ym=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...qm.wcBindable,properties:[...qm.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new qm(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(zm.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(zm.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&function(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=Jm(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Qm)return Qm;if(!("trustedTypes"in globalThis))return Qm=!1,Qm;try{document.createElement("div").innerHTML="<i></i>",Qm=!1}catch{Qm=!0}return Qm}())return void function(){if(Xm)return;Xm=!0;const t="function"==typeof Jm()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}(t,s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Vm(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Um||(Um=!0,document.addEventListener("click",Gm)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Zm extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class tg extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let eg=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof Ym&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(zm.fetch)||t.define(zm.fetch,Ym),t.get(zm.fetchHeader)||t.define(zm.fetchHeader,Zm),t.get(zm.fetchBody)||t.define(zm.fetchBody,tg),t.get(zm.infiniteScroll)||t.define(zm.infiniteScroll,eg)}(void 0);const ng="data-storagetarget",og={storage:"wcs-storage"},sg="wcs-storage:value-changed",rg="wcs-storage:loading-changed",ig="wcs-storage:error",ag="wcs-storage:error-info-changed",lg="wcs-storage:trigger-changed";let cg=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:sg,semantics:"state",getter:t=>t.detail},{name:"loading",event:rg,semantics:"state"},{name:"error",event:ig,semantics:"state"},{name:"errorInfo",event:ag,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(rg,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(ig,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(ag,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(sg,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},ug=!1;function dg(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${ng}]`);if(!n)return;const o=n.getAttribute(ng);if(!o)return;const s=customElements.get(og.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function hg(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let fg=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...cg.wcBindable,properties:[...cg.wcBindable.properties,{name:"trigger",event:lg,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new cg(this),this._internals=this._initInternals(),this._wireStates({[rg]:t=>({loading:!0===t}),[ig]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(lg,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!hg(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",ug||(ug=!0,document.addEventListener("click",dg)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(og.storage)||t.define(og.storage,fg)}(void 0);const pg="*",mg="vanilla",gg={scanImportmap:!0,loaders:{[mg]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[pg]:mg},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function yg(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function bg(t,e,n){let o;if(null===e||e===pg||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===pg)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[pg],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const wg=new Set,vg=new Map;let _g=new WeakMap;function $g(t){if(t===globalThis.customElements)return vg;let e=_g.get(t);return void 0===e&&(e=new Map,_g.set(t,e)),e}const Sg=new Map;async function xg(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of Sg)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){wg.has(e)||(console.error(`Failed to eager load component '${e}':`,t),wg.add(e))}}function Pg(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function Ng(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&Sg.set(t,e)});const kg=new WeakSet,Ig=new WeakSet;async function Ag(t,e,n){t.shadowRoot&&(kg.has(t)||await async function(t,e,n){kg.add(t),await Mg(t.shadowRoot,e,n)}(t,e,n))}async function Eg(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=$g(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=bg("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),wg.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Cg(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=Ng(t);void 0===o.get(s.name)?(Ig.has(t)||(Ig.add(t),o.whenDefined(s.name).then(async()=>{await Ag(t,e,n)})),a.has(s.name)||wg.has(s.name)||(a.add(s.name),i.push(s))):await Ag(t,e,n)}let l=0;for(const t of i)await Eg(t,e,n,o),l++;return l}async function Tg(t,e,n,o){for(;await Cg(t,e,n,o)>0;);}async function Mg(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return Pg(e)}return Pg(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Tg(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await Tg(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Og extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Og._instance)throw new Error(`${gg.tagNames.autoloader} can only be instantiated once.`);Og._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=yg(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=bg(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(xg(s,o,r))}await Promise.all(n)}(n,gg.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await Mg(document,gg,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Og._instance===this&&(Og._instance=null)}}!function(t=customElements){t.get(gg.tagNames.autoloader)||t.define(gg.tagNames.autoloader,Og)}(void 0);
1
+ const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.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,s=Symbol.for("wcstack.binder"),r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");const a=".",l="*",c=128,u=128,d="#",h="|",f="prevent",p="stop",m="ro",g="init",y="sync",b="else",w="...",v="on",_="eventToken",$="state",S="command",x="class",P="attr",k="style",I={};for(let t=0;t<c;t++)I[`$${t+1}`]=t;const N=Object.freeze(I),A="$connectedCallback",E="$disconnectedCallback",C="$renderedCallback",T="$errorCallback",M="$stateReadyCallback",O="$bindables",L="$commands",R="$commandTokens",j="$command",D="$eventTokens",W="$on",z="$stream",B="$watch",F="$scan",H="$recursion",q="**",U="$listKeys",V="$streamStatus",G="$streamError",K="data-wc-definition",J=/\{\{\s*(.+?)\s*\}\}/g,Q=new Set(["SCRIPT","STYLE"]);function X(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&Q.has(t.parentElement.tagName)||Y(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),X(e.content)}else X(t.content)}function Y(t){const e=t.data;if(J.lastIndex=0,!J.test(e))return;J.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=J.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}function Z(t){throw new Error(`[@wcstack/state] ${t}`)}const tt=new Map;let et=0;function nt(t){let e=tt.get(t);if(void 0!==e)return e;-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] "${t}" uses "${q}", 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(t){let e=1;for(let n=0;n<t.length;n++)t[n]===a&&e++;return e}(t);return n>512&&Z(`[wcs/binding-syntax] "${t}" 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.`),e=Object.freeze(new ot(t)),tt.set(t,e),e}class ot{id=++et;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:nt(e),n=t.split("."),o=[],s=[],r=[],i={},a=[],c=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===l&&(r.push(h),i[h]=p,a.push(e(h)),c.push(f),u.push(e(f)),d.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,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=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=u,this.wildcardParentPathInfoSet=new Set(u),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}}function st(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function rt(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=st(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const it=" Validate statically: npx @wcstack/lint <file>.",at=new Set(["if","elseif","else","for"]);function lt(t,e){return`${JSON.stringify(t)}${JSON.stringify(e)}`}function ct(t){if(0===t.length)return"";let e="";for(let n=0;n<t.length;n++){const o=t[n];n>0&&(e+="|"),e+=`${o.filterName}(${lt(o.args,o.literals??o.args)})`}return e}const ut=new Map([["not",()=>t=>!t]]),dt=new Map([["not",[0,0]]]),ht={input:new Map,output:new Map},ft={input:new Map,output:new Map},pt={input:new Map,output:new Map},mt=new Map;function gt(t,e,n,o){const s=ht[t],r=ft[t];for(const t of Object.keys(e)){s.set(t,e[t]);const o=n?.[t];void 0===o?r.delete(t):r.set(t,o)}const i=o??{},a=pt[t];for(const[t,n]of[...a])Object.prototype.hasOwnProperty.call(e,n)&&i[t]!==n&&a.delete(t);for(const t of Object.keys(i))a.set(t,i[t]);mt.clear()}function yt(t,e,n,o=e){const s=pt[n].get(t)??t,r=`${s}${lt(e,o)}:${n}`,i=mt.get(r);if(void 0!==i)return i;const a=ht[n].get(s)??ut.get(s);if(void 0===a){const e=0===ht[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";Z(`[wcs/filter-unknown] filter not found: ${t}.${rt(t,function(t){return[...new Set([...ut.keys(),...ht[t].keys()])]}(n))}${e}${it}`)}const l=ft[n].get(s)??dt.get(s);void 0!==l&&(e.length<l[0]||e.length>l[1])&&Z(e.length<l[0]?`[wcs/filter-arity] filter "${t}" requires at least ${l[0]} argument(s) (${e.length} given).${it}`:`[wcs/filter-arity] filter "${t}" accepts at most ${l[1]} argument(s) (${e.length} given).${it}`);const c=a(e,o);return mt.set(r,c),c}function bt(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const wt=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function vt(t,e){return e?t:"true"===t||"false"!==t&&("null"===t?null:wt.test(t)?Number(t):t)}function _t(t){const e=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const t=bt(o,i,a);e.push(t),n.push(vt(t,r)),o="",r=!1,i=-1,a=-1};for(let e=0;e<t.length;e++){const n=t[e];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&Z(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${t})". Close the quote.${it}`);const c=bt(o,i,a);return(c||r)&&(e.push(c),n.push(vt(c,r))),{args:e,literals:n}}const $t=t=>t.trim(),St=t=>"'"===t||'"'===t;function xt(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(null!==n)s===n&&(n=null);else if(St(s))n=s;else if(s===e)return o}return-1}function Pt(t,e){const n=[];let o=null,s=0;for(let r=0;r<t.length;r++){const i=t[r];null!==o?i===o&&(o=null):St(i)?o=i:i===e&&(n.push(t.slice(s,r)),s=r+1)}return n.push(t.slice(s)),n}function kt(t,e,n){const o=n??t.join("|");return t.map(t=>{const n=xt(t,"(");let s=function(t){let e=null,n=-1;for(let o=0;o<t.length;o++){const s=t[o];null!==e?s===e&&(e=null):St(s)?e=s:")"===s&&(n=o)}return n}(t);if(-1===s&&(s=t.lastIndexOf(")")),-1!==n&&-1===s&&Z(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${t}".${it}`),-1!==s&&-1===n&&Z(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${t}".${it}`),-1!==s&&s<n&&Z(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${t}".${it}`),-1!==s&&t.slice(s+1).trim().length>0){const e=t.slice(s+1).trim();Z(`[wcs/binding-syntax] "${t}": unexpected "${e}" after the filter's closing ")" — separate filters with "|" (write "${t.slice(0,s+1)}|${e}").${it}`)}const r=(-1===n?t:t.substring(0,n)).trim();if(0===r.length&&Z(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${it}`),r.includes(d)){const[t,n]=r.split(d);Z("input"===e?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${d}${n}" comes before the input filters, not inside one — write "<property>${d}${n}|${t}".${it}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${d}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${t}" here.${it}`)}return-1===n?{filterName:r,args:[],literals:[]}:{filterName:r,..._t(t.substring(n+1,s))}})}const It=new Map;function Nt(t){const e=xt(t,h);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),It.has(s)?r=It.get(s):(o=Pt(s,h).map($t),r=kt(o,"input",t),It.set(s,r))):n=t.trim();const i=n.split(d).map($t);i.length>2&&Z(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${d}" — write "${i[0]}${d}${i.slice(1).join(",")}".${it}`);const[l,c]=i,u=l.split(a).map($t);return u.length>1&&""===u[0]||0!==l.length&&!u.some(t=>0===t.length)||Z(`[wcs/binding-syntax] "${t}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${it}`),{propName:l,propSegments:u,propModifiers:c?c.split(",").map($t):[],inFilters:r}}const At=new Map;function Et(t){const e=xt(t,h);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),At.has(s)?r=At.get(s):(o=Pt(s,h).map($t),r=kt(o,"output",t),At.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&Z(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);const i=n,l=i.startsWith(a),c=l?i.slice(1):i;return(c.length>0&&c.split(a).some(t=>0===t.length)||!l&&0===c.length)&&Z(`[wcs/binding-syntax] "${t}": 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).${it}`),{statePathName:i,statePathInfo:nt(i),outFilters:r}}const Ct=new Set([b,"if","elseif","for",w]),Tt=new Set([x,P,k,S,_,$]);function Mt(t){const[...e]=function(t){return Pt(t,";")}(t).map($t).filter(t=>t.length>0),n=e.map(t=>{const e=xt(t,":");-1===e&&Z(`[wcs/binding-syntax] Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.${it}`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim(),s=n.split(d)[0].split(h)[0].trim();if(s!==n&&Ct.has(s)&&Z(`[wcs/binding-syntax] "${t}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${it}`),n===b){o.length>0&&Z(`[wcs/binding-syntax] "${t}": "else" takes no value — write "else:".${it}`);const e=nt("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===w){0===o.length&&Z(`[wcs/binding-syntax] Invalid spread binding "${t}": spread target path is required.${it}`);const e=Et(o);return e.outFilters.length>0&&Z(`[wcs/binding-syntax] Invalid spread binding "${t}": filters are not allowed on spread targets.${it}`),{propName:w,propSegments:[w],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Et(o),bindingType:n};if("radio"===s||"checkbox"===s){const t=Et(o);return{...Nt(n),...t,bindingType:s}}{const t=Et(o),e=Nt(n);if(""===e.propSegments[0]&&e.propSegments.length>1){const o=e.propSegments.slice(1);return(o.includes("")||Tt.has(o[0]))&&Z(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Tt].join(", ")}).${it}`),{...e,propName:o.join(a),propSegments:o,...t,bindingType:"prop"}}return e.propSegments[0]===_||e.propSegments[0].startsWith(v)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>at.has(t.bindingType))&&Z(`[wcs/template-syntax] Invalid bindText: "${t}". '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">).${it}`),n}const Ot=new WeakMap,Lt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Rt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function jt(t){const e=Ot.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Rt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Lt.has(r)?(Ot.set(t,s[2]),s[2]):null}function Dt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Et(t),bindingType:"text"}}const Wt=new WeakMap,zt=new WeakSet;let Bt=0;async function Ft(t){const e=function(t){let e,n=Wt.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++Bt,promise:o,resolve:e},Wt.set(t,n),zt.has(t)&&n.resolve(),n}(t);await e.promise}function Ht(t){const e=Wt.get(t);void 0===e?zt.add(t):e.resolve()}const qt=new WeakMap;function Ut(t){const e=qt.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{qt.set(t,n)}}function Vt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Gt(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Vt(e);if(void 0!==n)return Vt(n)}return Vt(globalThis.customElements)}function Kt(t,e){t.upgrade?.(e)}function Jt(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.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=Zt(s.properties,Qt);if(null===r)return null;const i=void 0===s.inputs?new Map:Zt(s.inputs,Xt);if(null===i)return null;const a=void 0===s.commands?new Map:Zt(s.commands,Yt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Qt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function Xt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function Yt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function Zt(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function te(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:nt(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ee(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function ne(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&Z("Spread binding requires an element node.");const e=t,o=Ut(e);null===o&&Z(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Gt(e);if(null===a&&Z(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||Z(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Kt(a,e);const l=Jt(e);null===l&&Z(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=te(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=te(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=ee(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=ee(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function oe(t,e){let n=t;for(let t=0;t<e.length;t++){let o=e[t];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function se(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:yt(s.filterName,s.args,e,r)})}return n}function re(t){return{...t,inFilters:se(t.inFilters,"input"),outFilters:se(t.outFilters,"output")}}const ie=new WeakMap;function ae(t){return ie.get(t)||null}function le(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function ce(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!le(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function ue(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function de(t){const e=[],n=ce(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==jt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&ue(t,n)||e.push(t)}return e}const he=new WeakSet;function fe(t,e,n,o){const s=ne(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Ut(t):null;return null===n&&Z("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}he.add(t);const r=function(t,e){const n=[];for(const o of e){const e=se(o.inFilters,"input"),s=se(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:t});else{const r=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:r})}}return n}(t,function(t,e){return void 0===e?t:t.map(t=>null!=t.uuid?t:e(t))}(s,o));return function(t,e){ie.set(t,e)}(t,r),Ht(t),{bindings:r,deferred:null}}function pe(t,e){const n=de(t),o=[],s=[];for(const t of n){if(he.has(t))continue;const n=fe(t,xa(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function me(t){he.add(t)}function ge(t){const{node:e,parseResults:n,transform:o}=t;return function(t){he.delete(t)}(e),fe(e,n,{allowDeferred:!1},o).bindings}const ye=new WeakMap;let be=null;function we(t){let e=t;for(;e;){const t=ye.get(e);if(t)return t;let n=e.parentNode;null===n&&null!==be&&e instanceof ShadowRoot&&(n=be(e)),e=n}return null}function ve(t,e){null!==e?ye.set(t,e):ye.delete(t)}let _e=null;const $e=new WeakMap;function Se(t){return $e.get(t)??[]}function xe(t,e){$e.set(t,e)}function Pe(t){return $e.has(t)}const ke=new WeakMap;let Ie=null,Ne=0;function Ae(t){return ke.get(t)??[]}function Ee(t,e){null===Ie?ke.set(t,e):Ie.set(t,e)}function Ce(){Ne++,null===Ie&&(Ie=new Map)}function Te(){if(0!==Ne&&(Ne--,!(Ne>0||null===Ie))){for(const[t,e]of Ie)ke.set(t,e);Ie=null}}function Me(t){return(Ie?.has(t)??!1)||ke.has(t)}const Oe=Symbol("$$setLoopContext"),Le=Symbol("$$getByAddress"),Re=Symbol("$$hasByAddress"),je=Symbol("$$connectedCallback"),De=Symbol("$$disconnectedCallback"),We=Symbol("$$updatedCallback"),ze=Symbol("$$errorCallback"),Be=new WeakMap,Fe=new WeakMap;class He{absolutePathInfo;listIndex;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}}function qe(t,e){if(null===e){let e=Fe.get(t);return void 0!==e||(e=new He(t,null),Fe.set(t,e)),e}{let n=Be.get(e);void 0===n&&(n=new WeakMap,Be.set(e,n));let o=n.get(t);return void 0!==o||(o=new He(t,e),n.set(t,o)),o}}const Ue=new WeakMap;function Ve(t,e){let n=Ue.get(t);void 0===n&&(n=new Map,Ue.set(t,n));let o=n.get(e);return void 0===o&&(o=Object.freeze(new Ge(t,e)),n.set(e,o)),o}class Ge{pathInfo;stateElement;constructor(t,e){this.pathInfo=e,this.stateElement=t}}function Ke(t,e){return qe(Ve(t,e.pathInfo),e.listIndex)}function Je(t,e,n){return qe(Ve(t,e),n)}const Qe=new WeakMap;function Xe(t,e){null===e?Qe.delete(t):Qe.set(t,e)}function Ye(t){return Qe.get(t)||null}const Ze=new Map;function tn(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=Ze.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Ze.set(s,r)),r}function en(t,e,n){return e<0||e>=n?null:t.at(e-n)}function nn(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const on=new WeakMap;function sn(t){const e=we(t.node);if(null===e)return null;let n=on.get(e);if(void 0===n)n=new WeakMap,on.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=tn(e.pathInfo,t.statePathInfo);return n>0&&(o=en(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const rn=new WeakMap;function an(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Ye(n);null===e?Z(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function ln(t,e){let n=null;if(n=rn.get(t)||null,null!==n)return n;const o=an(t,e),s=sn(t),r=ga(o);return null===r&&Z("No state tree found on this root for binding."),n=Je(r,t.statePathInfo,s),rn.set(t,n),n}function cn(t){rn.delete(t)}const un=new WeakMap;function dn(t,e){const n=un.get(t);void 0===n?un.set(t,e):n instanceof Set?n.add(e):n!==e&&un.set(t,new Set([n,e])),null!==_e&&_e({type:"state:binding-added",absoluteAddress:t,binding:e})}function hn(t,e){const n=un.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&un.delete(t),null!==_e&&_e({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const fn=new WeakMap;function pn(t){const e=un.get(t);return void 0!==e?e:null!==t.listIndex?fn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const mn=new WeakMap,gn=new WeakMap;class yn{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=bn(t,e)}}function bn(t,e){if(null===e){let e=gn.get(t);return void 0!==e||(e=new yn(t,null),gn.set(t,e)),e}{let n=mn.get(e);void 0===n&&(n=new WeakMap,mn.set(e,n));let o=n.get(t);return void 0!==o||(o=new yn(t,e),n.set(t,o)),o}}const wn=new WeakMap;function vn(t){let e=null;if(e=wn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=sn(t);null===n&&Z(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=bn(t.statePathInfo,n)}else e=bn(t.statePathInfo,null);return wn.set(t,e),e}function _n(t){wn.delete(t)}function $n(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const Sn=new Map,xn=$n();function Pn(t,e){const n=ct(t.inFilters);return`${t.statePathName}::${e}::${n}`}function kn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}function In(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function Nn(t,e){console.error(`[wcstack/state] ${e} rejected.`,t)}function An(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)In(t)&&Promise.resolve(t).catch(t=>Nn(t,e))}class En{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)try{e.push(n(...t))}catch(t){e.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,t)}return e}}class Cn extends En{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==_e&&_e({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const Tn=new WeakMap;function Mn(t,e){let n=Tn.get(t);void 0===n&&(n=new Map,Tn.set(t,n));let o=n.get(e);return void 0===o&&(o=new Cn(e,t),n.set(e,o)),o}const On=new WeakMap;class Ln extends En{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==_e&&_e({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function Rn(t){return t instanceof Ln}const jn=new Map,Dn=$n();function Wn(t){const e=t.propModifiers.filter(t=>t===f||t===p).sort().join(",");return`${t.statePathName}::${e}`}function zn(t){return"event"===t.bindingType&&t.propName.startsWith(v)}function Bn(t){if(!zn(t))return!1;const e=Wn(t);let n=jn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(f)&&o.preventDefault(),e.includes(p)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ga(r);null===i&&Z("No state tree found on this root for event handler.");const a=we(s),l=t.startsWith(j+".");i.createStateAsync("writable",async e=>{const c=e[Oe](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const t=i.addressHooks;if(t){const e=t.handlerScope;for(let t=0;t<e.length;t++)c=e[t](i,s,r,a,c)}}const u=null!==a?nn(a.listIndex,c):[];if(l){const s=e[Le](bn(n,null));return Rn(s)||Z(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...u)}const d=e[t];return"function"!=typeof d&&Z(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});An(c,`"${t}"`)}).catch(e=>Nn(e,`"${t}"`))})(t.statePathName,t.propModifiers,t.statePathInfo),jn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Dn.add(e,t),!0}function Fn(t){if(!zn(t))return!1;const e=Wn(t),n=jn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);return t.node.removeEventListener(o,n),0!==Dn.countOf(e)&&(Dn.remove(e,t)&&jn.delete(e),!0)}const Hn=new Map,qn=$n();function Un(t,e){const n=ct(t.inFilters);return`${t.statePathName}::${e}::${n}`}function Vn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}const Gn=new Set(["radio","checkbox"]),Kn=new Set(["value","valueAsNumber","valueAsDate"]);function Jn(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(Gn.has(t)&&"checked"===e)return!0;if(Kn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Ut(n);if(null!==s){const t=Gt(n)?.get(s);void 0===t&&Z(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Jt(n);if(o?.knownProperties.has(e))return!0}return!1}let Qn=1,Xn=1,Yn=1;const Zn=new WeakMap;function to(t,e,n){let o=Zn.get(t);void 0===o&&(o=new Map,Zn.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=Qn++,o.set(s,r)),r}function eo(t,e){return"to-element"===e?2*t:2*t+1}const no=new Set;function oo(t){return{transactionId:Xn++,originBindingId:t,visitedEdges:no,hop:0}}function so(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let ro=null;function io(){return ro}function ao(t,e){const n=ro;ro=t;try{return e()}finally{ro=n}}const lo=[];let co=!1;const uo=new Map,ho=$n(),fo=new WeakMap,po=t=>t.detail,mo=new WeakMap,go=new WeakMap;let yo=0;const bo=new WeakMap;function wo(t){const e=Ut(t.node);if(null!==e){const n=Gt(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&Z(`CustomElementRegistry is unavailable for <${e}>.`))}if(Jn(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const e=function(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Ut(t.node);if(null!==n){const o=Gt(t.node)?.get(n);void 0===o&&Z(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Jt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}(t),n=function(t){if(null!==Ut(t.node)){const e=Jt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??po}return null}(t),s=function(t){if(null===Ut(t.node))return!1;const e=Jt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}(t),r=function(t,e,n,o){const s=ct(t.inFilters);return`${t.propName}::${t.statePathName}::${e}::${s}::${function(t){if(null===t)return"n";let e=go.get(t);return void 0===e&&go.set(t,e=++yo),`g${e}`}(n)}::${o?"o":"s"}`}(t,e,n,s);bo.set(t,{key:r,eventName:e});let i=uo.get(r);void 0===i&&(i=((t,e,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==po||r||function(t,e,n){const o=t[e];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${e} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,e)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${e}" key while element.${e} is ${typeof o}`),null===s)return;let r=mo.get(t);void 0===r&&(r=new Set,mo.set(t,r)),r.has(e)||(r.add(e),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${t.tagName.toLowerCase()}> "${e}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${e}, or (e) => e.target.${e}) on that wcBindable property.`))}(a,t,l);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const t of n)c=t.filterFn(c);const u=fo.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(o.enablePropagationContext){const n=to(a,t,e),s=function(t,e){for(let n=lo.length-1;n>=0;n--){const o=lo[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==_e&&_e({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:eo(n,"to-state"),node:a,member:t}));const r=eo(n,"to-state"),i=io();if(null!==i&&i.visitedEdges.has(r))return void(null!==_e&&_e({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=so(i??oo(n),r)}const h=ga(a.getRootNode());null===h&&Z("No state tree found on this root for two-way binding.");const f=we(a),p=()=>{r&&(co=!0);try{h.createState("writable",t=>{t[Oe](f,()=>{t[e]=c})})}finally{r&&(co=!1)}};null!==d?ao(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),uo.set(r,i)),t.node.addEventListener(e,i),ho.add(r,t)}}const vo=new WeakSet;function _o(t){vo.add(t)}function $o(t){return!!vo.has(t)&&(vo.delete(t),!0)}const So=new WeakMap;function xo(t,e){const n=So.get(t);return!(void 0===n||n<e||(n===e?So.delete(t):So.set(t,n-e),0))}const Po=new WeakSet;function ko(t){Po.add(t)}function Io(t){return!!Po.has(t)&&(Po.delete(t),!0)}let No=0;function Ao(){No--}function Eo(){return No>0}class Co{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.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),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const To=new WeakMap;function Mo(t){let e=To.get(t);return void 0===e&&(e=new Co(t),To.set(t,e)),e}const Oo=new Set([x,P,k,S]);function Lo(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==g&&s!==y&&Z(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&Z(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Ro(t){return t.propModifiers.some(t=>t.includes("="))}const jo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Do=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Wo(t,e){return"state"===t&&"call"===e?jo:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function zo(t){if(!o.enableDirectionalInitialSync)return Ro(t)&&Z("init=/sync= modifiers require enableDirectionalInitialSync."),jo;const e=null===(n=Lo(t,g))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:Z(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":Z(`Invalid sync modifier value "${t}".`)}(Lo(t,y));if("event"===t.bindingType)return null!==e&&"none"!==e&&Z("Event bindings only allow init=none."),"call"===s?Do:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(Oo.has(t.propSegments[0]))return Wo("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&Z(`Binding type "${t.bindingType}" does not support init=${e}.`),Wo(e??"state",s);const r=Jt(t.node);if(null===r)return Wo(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||Z(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||Z(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||Z(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let Bo=0,Fo=0;const Ho=["active","disposed","failed"],qo=new WeakMap,Uo=new WeakMap,Vo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,Jo=new WeakMap;function Qo(t,e){const n=Jo.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Jo.set(t,new Set([n,e]))):Jo.set(t,e)}function Xo(t){return Jo.has(t)}function Yo(t,e){const n=Jo.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Zo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Zo(n,e)}function ts(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class es{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.removedNodes;if(0===r.length||!xo(s.target,r.length))for(let t=0;t<r.length;t++)e.push(r[t]);const i=s.addedNodes;for(let t=0;t<i.length;t++)n.push(i[t])}const o=[];for(const t of e)$o(t)||Zo(t,t=>{Yo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)Io(t)&&!Eo()||Zo(t,t=>{Yo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&na(o)}}const ns=new WeakMap;function os(t){let e=ns.get(t);return void 0===e&&(e=new es(t),ns.set(t,e)),e}function ss(t){const e=ct(t.inFilters),n=ct(t.outFilters);return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function rs(t,e,n){const o=ga(an(t,n));null===o&&Z("No state tree found on this root for binding.");const s=Ve(o,t.statePathInfo);return function(t,e,n){let o=fn.get(t);void 0===o&&(o=new WeakMap,fn.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==_e&&_e({type:"state:binding-added",absoluteAddress:qe(t,e),binding:n})}(s,e,t),s}function is(t,e){const n=ln(t,e);return dn(n,t),n}function as(t,e,n,o){null!==e?hn(e,t):function(t,e,n){const o=fn.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==_e&&_e({type:"state:binding-removed",absoluteAddress:qe(t,e),binding:n}))}(n,o,t),_n(t),cn(t)}function ls(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class cs{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=this.rowOf(t),i=null===o?-1:o.bindings.indexOf(t);if(null!==o&&0===o.phases[i]){const e=o;this.observe(t.replaceNode),s.registerAddress&&null===e.addresses[i]&&null===e.patternPathInfos[i]&&(e.registered=!0,this.registerRowSlot(e,i));continue}const a=Vo.get(t);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(t,s,n),r.push(t)):(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(t=>this.shouldApplyState(t))}activate(t,e){if(ts(e)&&os(e),null===this.rowPlan)for(const n of t){const t=Vo.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return Ro(t)&&zo(t),!0;const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0){if(!e.registered)return!0;if(2===e.phases[n])return!1;const t=e.plan.slots[n];return 1&e.flags[n]?"state"===t.authority||!t.policy.outputOnly:(e.flags[n]|=1,"state"===t.authority)}}const n=Vo.get(t);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(t){const e=this.rowOf(t),n=null===e?-1:e.bindings.indexOf(t);if(null!==e&&n>=0){let o=Uo.get(e);return void 0===o&&Uo.set(e,o=[]),{id:o[n]??(o[n]=++Bo),info:t,generation:e.generation,phase:Ho[e.phases[n]],teardowns:null}}const o=Vo.get(t);return o?.session===this?o:null}addTeardown(t,e){const n=Vo.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(ls(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=Gt(t);null===s&&Z(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Qo(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,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=Mo(s).wait(e,()=>{if(a())try{Kt(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0)return void this.disposeRowSlot(e,n)}const n=Vo.get(t);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(t){for(let e=0;e<t.length;e++)this.disposeBinding(t[e]);if(!(this.rows.size>0))for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}destroyRow(t){const e=t.length>0?this.rowOf(t[0]):null;null!==e?(this.destroyRowRecord(e),this.rows.delete(e)):this.destroyRecords()}destroyRowRecord(t){for(let e=0;e<t.bindings.length;e++){const n=t.addresses[e];null!==n&&(hn(n,t.bindings[e]),t.addresses[e]=null),t.phases[e]=1}}dispose(){for(const t of Array.from(this.rows))for(let e=0;e<t.bindings.length;e++)this.disposeRowSlot(t,e);for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.rows)this.destroyRowRecord(t);this.rows.clear();for(const t of this.records)null!==t.address&&(hn(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.rows)for(let n=0;n<e.bindings.length;n++)0===e.phases[n]&&t(e.bindings[n].node);for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];for(const e of this.rows)for(let n=0;n<e.bindings.length;n++){if(0!==e.phases[n])continue;if(null===e.addresses[n]&&null===e.patternPathInfos[n])continue;const o=e.bindings[n];this.unregisterRowSlot(e,n),this.registerRowSlot(e,n),this.shouldApplyState(o)&&t.push(o)}for(const e of this.records){if("active"!==e.phase)continue;const n=e.info;if(null===e.address&&null===e.patternListIndex)continue;const o="for"===n.bindingType?ln(n):null;if(as(n,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null,this.registerAddress(e),null!==o){const t=ln(n);t!==o&&Pe(o)&&xe(t,Se(o)),t!==o&&Me(o)&&Ee(t,Ae(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return ts(e)?e:null}(t);null!==e&&os(e)}handleMutations(t,e,n){for(const n of e)Zo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Zo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&na(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Vo.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=Ko.get(e);void 0===t&&(t=ss(e),Ko.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Qo(n,this);const o=this.knownMapFor(n);let s=Ko.get(t);void 0===s&&(s=ss(t),Ko.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n=t.slots,o=e.length,s={id:++Bo,session:this,generation:++Fo,plan:t,bindings:e,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 t=0;t<o;t++){const o=e[t],r=o.replaceNode;if(Qo(r,this),this.addKnownRowBinding(r,o,t),qo.set(o,s),n[t].isEvent){let n=!1;try{n=Bn(o)}catch(e){throw s.phases[t]=2,e}n&&(s.flags[t]|=2)}}}activatePlanRows(t,e,n){const o=e.length>0?this.rowOf(e[0]):null;if(null===o||o.bindings!==e){for(const t of e)this.initialize([t],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=t.slots;let r=!1;for(let t=0;t<e.length;t++)if(0===o.phases[t])null===o.addresses[t]&&null===o.patternPathInfos[t]&&this.registerRowSlot(o,t,n);else{if(r||(o.generation=++Fo,r=!0,this.rows.add(o)),o.phases[t]=0,o.flags[t]=0,s[t].isEvent){let n=!1;try{n=Bn(e[t])}catch(e){throw o.phases[t]=2,this.runRowSlotTeardowns(o,t),e}n&&(o.flags[t]|=2)}this.registerRowSlot(o,t,n)}}rowOf(t){const e=qo.get(t);return void 0!==e&&e.session===this?e:null}registerRowSlot(t,e,n){if(null!==t.addresses[e]||null!==t.patternPathInfos[e])return;const o=t.bindings[e],s=sn(o);null!==s?(t.patternPathInfos[e]=rs(o,s,n),t.patternListIndexes[e]=s):t.addresses[e]=is(o,n)}unregisterRowSlot(t,e){const n=t.addresses[e],o=t.patternPathInfos[e];null===n&&null===o||(as(t.bindings[e],n,o,t.patternListIndexes[e]),t.addresses[e]=null,t.patternPathInfos[e]=null,t.patternListIndexes[e]=null)}disposeRowSlot(t,e){if(1!==t.phases[e]){t.phases[e]=1,this.runRowSlotTeardowns(t,e);for(let e=0;e<t.phases.length;e++)if(0===t.phases[e])return;this.rows.delete(t)}}runRowSlotTeardowns(t,e){try{this.unregisterRowSlot(t,e)}catch{}if(2&t.flags[e]){t.flags[e]&=-3;try{Fn(t.bindings[e])}catch{}}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++Bo,info:t,generation:++Fo,phase:"discovered",teardowns:null,session:this,anchor:t.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};Vo.set(t,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(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;Bn(e)?t.eventAttached=!0:e.propSegments[0]!==_?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=Vn(t),s=Un(t,o);let r=Hn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.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 t of n)s=t.filterFn(s);const r=ga(o.getRootNode());null===r&&Z("No state tree found on this root for two-way binding.");const i=we(o);r.createState("writable",t=>{t[Oe](i,()=>{t[e]=s})})},Hn.set(s,r)),t.node.addEventListener(o,r),qn.add(s,t),!0}var e,n;return!1}(e)&&ls(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=Vn(t),n=Un(t,e),o=Hn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==qn.countOf(n)&&(qn.remove(n,t)&&Hn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=kn(t),s=Pn(t,o);let r=Sn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.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 t of n)r=t.filterFn(r);const i=ga(o.getRootNode());null===i&&Z("No state tree found on this root for two-way binding.");const a=we(o);i.createState("writable",t=>{t[Oe](a,()=>{let n=t[e];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(t[e]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(t[e]=n.toSpliced(o,1))}else t[e]=s?[r]:[]})})},Sn.set(s,r)),t.node.addEventListener(o,r),xn.add(s,t),!0}var e,n;return!1}(e)&&ls(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=kn(t),n=Pn(t,e),o=Sn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==xn.countOf(n)&&(xn.remove(n,t)&&Sn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Jn(e.node,e.propName)&&-1===e.propModifiers.indexOf(m)){const n=function(t,e,n){let o=fo.get(t);void 0===o&&(o=new Map,fo.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&fo.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});ls(t,n)}wo(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==_)return!1;const e=t.node,n=Ut(e),o=Gt(e);if(null!==n&&void 0===o?.get(n))return null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(On.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||Z('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Ut(t)?null:Jt(t)}(e);null===r&&Z(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&Z(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${rt(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,c=t.propModifiers,u=t=>{c.includes(f)&&t.preventDefault(),c.includes(p)&&t.stopPropagation();const n=ga(e.getRootNode());null===n&&Z("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||Z(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${rt(l,n.eventTokenNames)}${it}`);const o=we(e);n.createStateAsync("writable",async e=>{An(e[Oe](o,()=>{const s=null!==o?nn(o.listIndex,o.pathInfo.wildcardCount):[];return Mn(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,u),On.set(t,{eventName:a,handler:u}),!0})(e)&&ls(t,()=>function(t){if(t.propSegments[0]!==_)return!1;const e=On.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),On.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Ut(t.info.node);if(null===n)return void e();const o=Gt(t.info.node);if(null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=Mo(o).wait(n,()=>{if(this.isAlive(t,s))try{Kt(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});ls(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=zo(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=ga(t.replaceNode.getRootNode());null===e&&Z("No state tree found on this root for binding.");const n=vn(t);let o=!1;return e.createState("readonly",t=>{o=t[Re](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void No++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,Ao()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=ga(t.node.getRootNode());null===o&&Z("No state tree found on this root for initial binding sync.");const s=we(t.node);o.createState("writable",e=>{e[Oe](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=sn(n);if(null!==o?(t.patternPathInfo=rs(n,o,e),t.patternListIndex=o):t.address=is(n,e),!t.options.registerPathInfo)return;const s=ga(n.replaceNode.getRootNode());null===s&&Z("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Vo.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,Ao());const e=t.info;if(null!==t.address||null!==t.patternListIndex)try{as(e,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=bo.get(t);if(void 0===e)return;bo.delete(t);const n=uo.get(e.key);void 0!==n&&(t.node.removeEventListener(e.eventName,n),ho.remove(e.key,t)&&uo.delete(e.key))}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{Fn(e)}catch{}}}}function us(t){let e=Go.get(t);return void 0===e&&(e=new cs(t),Go.set(t,e)),e}function ds(t){return Vo.get(t)?.session??qo.get(t)?.session??null}let hs=null;function fs(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const ps=Object.freeze([]),ms=new WeakMap,gs=new WeakMap;function ys(t){return gs.get(t)??[]}function bs(t,e){gs.set(t,e)}const ws=new WeakMap;function vs(t){return ws.get(t)??[]}function _s(t,e){ws.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let $s=0;function Ss(){return`u${($s++).toString(36)}`}let xs=0,Ps=0;const ks=Symbol("wcs.listIndex.noValue");class Is{uuid=Ss();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=ks,this._index=e,this._version=xs,this._chainGeneration=Ps}get index(){return this._index}set index(t){this._index=t,this._version=++xs,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(t){this._value=t}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=xs),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Ps||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Ps),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++xs,Ps++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function Ns(t,e,n=t){return new Is(t,e,n)}function As(t,e){t.reparent(e)}function Es(t){return t.homeParentListIndex}function Cs(t,e){t.value=e}function Ts(t,e){const n=t.value;return n!==ks&&n===e.value}const Ms=new WeakMap,Os=new WeakSet;function Ls(t){return Os.has(t)}function Rs(t){const e=Ms.get(t);return void 0===e?null:e}function js(t,e){const n=Ms.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o){const t=function(t,e){const n=Es(t),o=t.parentListIndex;return null===n||n===o||Os.has(n)?function(t,e,n){return null!==t&&null!==n&&n!==e&&!!Os.has(t)&&!Os.has(n)&&n.position===t.position&&Ts(n,t)}(n,o,e)||function(t,e){return t!==e&&null!==t&&null!==e&&t.position===e.position&&Os.has(t)&&!Os.has(e)}(o,e)?e:null:n}(o,e);if(null!==t)for(const e of n)As(e,t)}return n}function Ds(t,e){null!==e?Ms.set(t,e):Ms.delete(t)}const Ws=new WeakMap;function zs(t,e){null===e?Ws.delete(t):Ws.set(t,e)}function Bs(t){const e=Ws.get(t);e&&(e.dirty=!0)}const Fs=Symbol.for("wcstack.transition-runner");function Hs(t){const e=globalThis[Fs];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}function qs(t,e,n){const o=Hs(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const Us=[],Vs=[];function Gs(t){Vs.includes(t)||Vs.push(t)}function Ks(t,e=0){const n=Us.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Us.push(o):Us.splice(n,0,o)}function Js(t){queueMicrotask(()=>{throw t})}const Qs=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){for(let e=0;e<Vs.length;e++)Vs[e](t);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(t){const e=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(t),e&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Ce(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(t,e)})}hasQueuedPath(t,e){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===t&&n.absoluteAddress.absolutePathInfo.pathInfo.path===e)}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t,n=[]){const o=new Map,s=new Set;for(let e=0;e<t.length;e++){const n=t[e],r=o.get(n.absoluteAddress);null!==_e&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&_e({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 t=0;t<n.length;t++){const e=n[t];o.has(e)||o.set(e,null)}const r=[],i=new Map;o.forEach((t,e)=>{if(null!==t&&t.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,transactionId:t.transactionId,hop:t.hop,maxHops:32}),void(null!==_e&&_e({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop}));const n=pn(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(r.push(e),null!==t&&i.set(e,t));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==t&&i.set(n,t))});try{const t=()=>{i.size>0?na(r,i):na(r)};if(e()||0===r.length)t();else{const e=qs("state",t);void 0!==e&&e.catch(Js)}}finally{Te(),function(t){for(const e of Us.slice())e.listener(t)}(s)}}};function Xs(){return Qs}const Ys=new WeakMap,Zs=new WeakMap,tr=new WeakMap,er=new WeakMap;let nr=!1;const or=new WeakMap;function sr(t){const e=t.absolutePathInfo.stateElement;let n=or.get(e);void 0===n&&or.set(e,n=new Set),n.add(t)}function rr(t){const e=or.get(t);return void 0===e?null:(or.delete(t),e)}const ir=new WeakMap,ar=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=[];function hr(t,e){const n=fr(t);if(n.recorded.has(e))return;n.recorded.add(e);const o=nt(e).cumulativePaths;if(o.length<2)return;let s=ur.get(t);void 0===s&&ur.set(t,s=new Map);for(let t=0;t<o.length-1;t++){let n=s.get(o[t]);void 0===n&&s.set(o[t],n=new Set),n.add(e)}}function fr(t){let e=Ys.get(t);return void 0===e&&Ys.set(t,e={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),e}function pr(t,e,n){let o=t.get(e);void 0===o&&t.set(e,o=new Set),o.add(n)}function mr(t,e,n){const o=t.get(e);o.delete(n),0===o.size&&t.delete(e)}function gr(t,e,n,o){const s=function(t,e){let n=t.byPath.get(e);return void 0===n&&t.byPath.set(e,n=new Map),n}(t,e);let r=Zs.get(o);if(void 0===r&&Zs.set(o,r=new Map),r.has(e)){const t=r.get(e);return Object.is(t,n)||(mr(s,t,o),r.set(e,n),pr(s,n,o)),!1}return r.set(e,n),pr(s,n,o),!0}function yr(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):(o.push(n),!1)}function br(t,e,n,o,s,r){t.lastValue.set(e,n),s&&(null!==o.listIndex&&yr(tr,o.listIndex,r)&&function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){let n=lr.get(e);void 0===n&&lr.set(e,n=new Set),n.add(t)}}(o.listIndex),null!==r.levelListIndex&&yr(er,r.levelListIndex,r))}function wr(t,e,n,o,s){nr=!0;const r=fr(t);hr(t,e),br(r,e,s,o,gr(r,e,n,o),{stateElement:t,path:e,absAddress:o,levelListIndex:null})}function vr(t,e){fr(t).tracked.add(e)}function _r(t,e){return!0===Ys.get(t)?.byPath.has(e)||!0===ir.get(t)?.has(e)}function $r(t,e,n){if("number"!=typeof e)return;const o=t.indexes[e];if(void 0!==o)for(const e of t.getters)n.push(Ke(t.stateElement,bn(e,o)))}function Sr(t,e){if(void 0!==t)for(const n of t)e.push(n)}function xr(t,e,n,o,s){const r=Ys.get(t),i=r?.byPath.get(e),a=ir.get(t)?.get(e);if(void 0===r||void 0===i&&void 0===a)return dr;const l=r.lastValue.has(e),c=r.lastValue.get(e);r.lastValue.set(e,s);const u=[],d=!n||!Object.is(o,s),h=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&Sr(i.get(o),u),h&&Sr(i.get(c),u),d&&Sr(i.get(s),u)),void 0!==a)for(const t of a)n&&$r(t,o,u),h&&$r(t,c,u),d&&$r(t,s,u);return u}function Pr(t,e){return!0===ur.get(t)?.has(e)}function kr(t,e){let n=t;for(const t of e){if("object"!=typeof n||null===n)return;n=n[t]}return n}function Ir(t,e,n,o,s=!0){const r=nt(e).segments.length,i=[];for(const a of ur.get(t).get(e)){const e=nt(a).segments.slice(r);if(e.includes(l)){Nr(t,a,i);continue}const c=s?kr(n,e):void 0;for(const n of xr(t,a,s,c,kr(o,e)))i.push(n)}return i}function Nr(t,e,n){const o=Ys.get(t).byPath.get(e);if(void 0!==o)for(const t of o.values())Sr(t,n);const s=ir.get(t)?.get(e);if(void 0!==s)for(const t of s)for(let e=0;e<t.indexes.length;e++)$r(t,e,n)}function Ar(t){const e=er.get(t.levelListIndex),n=e.indexOf(t);e.splice(n,1)}function Er(t){const e=tr.get(t);if(void 0!==e){tr.delete(t),function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){const n=lr.get(e);void 0!==n&&(n.delete(t),0===n.size&&lr.delete(e))}}(t);for(const t of e){const{stateElement:e,path:n,absAddress:o}=t,s=Zs.get(o),r=s.get(n);s.delete(n),mr(Ys.get(e).byPath.get(n),r,o),null!==t.levelListIndex&&Ar(t)}}}function Cr(t){const e=cr.get(t);if(void 0!==e){cr.delete(t);for(const t of e){const e=ir.get(t.stateElement),n=e.get(t.path);n.delete(t),0===n.size&&e.delete(t.path);const o=ar.get(t.indexes);o.splice(o.indexOf(t),1),0===o.length&&ar.delete(t.indexes)}}}function Tr(t){if(!nr)return;Er(t),Cr(t);const e=lr.get(t);if(void 0!==e){lr.delete(t);for(const t of e)Er(t),Cr(t),lr.delete(t)}}function Mr(t,e,n){if(!nr)return;const o=er.get(t);if(void 0!==o)for(const{stateElement:t,path:s,absAddress:r}of o){const o=Ys.get(t),i=o.byPath.get(s);mr(i,e,r),pr(i,n,r),Zs.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,e)||Object.is(a,n))&&(Bs(r),Xs().enqueueAbsoluteAddress(r,null),sr(r))}}const Or=new WeakMap,Lr=Object.freeze([]),Rr=new Set;function jr(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:Lr,s=Array.isArray(n)&&n.length>0?n:Lr,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:Lr,o=Array.isArray(e)&&e.length>0?e:Lr;let s=Or.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=js(o,t)||[],a=i.length>0?Es(i[0]):t;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Rr,deleteIndexSet:new Set(i),addIndexSet:Rr};let e=js(s,t);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=Ns(t,n,a);e.push(o)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:Rr,deleteIndexSet:Rr,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:Rr,deleteIndexSet:Rr,addIndexSet:Rr};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],u=n.get(l),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=Ns(t,o,a);e.push(n),c.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:c}}finally{void 0!==l&&(function(t,e,n){let o=Or.get(t);o||(o=new WeakMap,Or.set(t,o)),o.set(e,n)}(o,s,l),Ds(s,l.newIndexes))}}(t,e,n);!function(t,e){for(let n=0;n<t.length;n++){if(t[n].index!==n){const e=t[n].index;t[n].index=n,Mr(t[n],e,n)}Cs(t[n],e[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Lr),function(t){for(const e of t)Os.add(e)}(o.deleteIndexSet);for(const t of o.deleteIndexSet)Tr(t);return function(t){for(const e of t)Os.delete(e)}(o.newIndexes),function(t,e){if(!nr||t===e)return;const n=ar.get(t);if(void 0===n)return;ar.delete(t);const o=ar.get(e);ar.set(e,void 0===o?n:o.concat(n));for(const o of n){o.indexes=e;const n=fr(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=t[n],r=e[n];if(s!==r)for(const t of[s,r])if(void 0!==t&&!Ls(t))for(const e of o.getters){const n=Ke(o.stateElement,bn(e,t));Bs(n),Xs().enqueueAbsoluteAddress(n,null),sr(n)}}}(o.oldIndexes,o.newIndexes),o}const Dr=new WeakSet,Wr=new WeakMap;function zr(t){return Wr.get(t)??null}function Br(t,e){Wr.set(t,e)}const Fr=new WeakMap;function Hr(t){return Fr.get(t)??[]}function qr(t,e){Fr.set(t,e)}function Ur(t,e){const n=Hr(t);for(const t of n)ve(t,e)}const Vr=new WeakMap,Gr=new WeakMap;function Kr(t,e){for(let n=0;n<t.length;n++)if(e.has(t[n]))return!0;return!1}function Jr(t,e,n){Ur(t,e);const o=ys(t),s=zr(t);if(null!==s&&(s.activate(o,n.rootNode),null!==e&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(t){return Vr.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=Gr.get(t);void 0===o&&Gr.set(t,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=e.map((e,o)=>{const s=t.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=e.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const t of a){if("*"===t)return null;c+="."+t,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(t,e,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let t=0;t<e.length;t++){const u=e[t];if(!n.shouldApplyState(u))continue;const d=r[t];if(null===d||Kr(d.prefixes,i)){ta(u,s);continue}if(s.appliedBindingSet.has(u))continue;c||(l=s.state[Le](o),c=!0);const h=d.tail;let f=l,p=!1;for(let t=0;t<h.length;t++){if(null==f){f=void 0;break}if(a&&!(h[t]in Object(f))){p=!0;break}f=f[h[t]]}p?ta(u,s):(s.appliedBindingSet.add(u),Zi(u,s,f))}}(r,o,s,e,n)}for(const t of o)null===s&&dn(ln(t),t),(null===s||s.shouldApplyState(t))&&ta(t,n)}function Qr(t){if(!t.mounted)return;const e=ys(t),n=zr(t);for(let t=0;t<e.length;t++){const o=e[t];null!==n?n.disposeBinding(o):hn(ln(o),o)}!function(t){const e=Hr(t);for(let t=0;t<e.length;t++)ve(e[t],null)}(t)}const Xr=new WeakMap,Yr=Object.freeze(new Set);function Zr(t,e){const n=Xr.get(t);n?n.add(e):Xr.set(t,new Set([e]))}function ti(t){const e=Xr.get(t);return void 0!==e?e:Yr}function ei(t,e){const n=Xr.get(t);n&&(n.delete(e),0===n.size&&Xr.delete(t))}const ni=new Set(["if","elseif","else","for"]);class oi{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e;const n=[];for(let e=t.firstChild;null!==e;e=e.nextSibling)n.push(e);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(t){const e=this._childNodeArray;for(let n=0;n<e.length;n++){const o=e[n];ko(o),t.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){ko(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=zr(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRow(ys(this));const e=this._childNodeArray;for(let t=0;t<e.length;t++){const n=e[t];null!==n.parentNode&&(_o(n),n.parentNode.removeChild(n))}const n=ys(this);for(let t=0;t<n.length;t++){const e=n[t];ni.has(e.bindingType)&&ti(e.node).forEach(t=>{t.tryDestroy()||t.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const t=zr(this);null!==t&&(t.isRowSession?t.disposeBindings(ys(this)):t.dispose())}this._teardownBindings()}_teardownBindings(){const t=ys(this);for(let e=0;e<t.length;e++){const n=t[e];ni.has(n.bindingType)&&ti(n.node).forEach(t=>{t.unmount()}),_n(n),cn(n)}}unmount(){{const t=zr(this);null!==t&&(t.isRowSession?t.disposeBindings(ys(this)):t.dispose())}for(const t of this._childNodeArray)null!==t.parentNode&&(_o(t),t.parentNode.removeChild(t));const t=ys(this);for(let e=0;e<t.length;e++){const n=t[e];ni.has(n.bindingType)&&ti(n.node).forEach(t=>{t.unmount()}),_n(n),cn(n)}this._mounted=!1}}function si(t){const e=document.createDocumentFragment(),n=new oi(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function ri(t){void 0!==t.uuid&&null!==t.uuid||Z("BindingInfo.uuid is null.");const n=Sa(t.uuid);n||Z(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=oe(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===S||s===_)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ut(r))return null;if("prop"===o&&Jn(r,t.propName))return null;const i=re(t);let a;try{a=zo({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:e,template:i,isEvent:"event"===o,isIndexBinding:t.statePathName in N,policy:a,authority:a.authority})}}return 0===n.length?null:{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=oe(o,s[t].nodePath);null===e&&Z(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),me(e),Ht(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e,n){let o=ra.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new cs,ra.set(n,o)),o.initializeRow(t,e),o}(n,a,t.node),u=new oi(o);return Br(u,c),bs(u,a),function(t,e){Vr.set(t,e)}(u,n),_s(u,l),qr(u,r),Zr(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=oe(t,s.nodePath);if(null===e&&Z(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),he.has(e))continue;const r=fe(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new cs;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new oi(i,s);Br(l,a.bindingSession),bs(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in N&&c.push(t);return _s(l,c),qr(l,a.nodes),Zr(t.node,l),l}const ii=new WeakSet,ai=Symbol.for("wcstack.state.view-transition-naming");function li(){const t=Hs("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function ci(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||ii.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[ai]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(ii.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const ui=new WeakMap,di=new WeakMap,hi=new WeakMap,fi=new WeakMap;function pi(t,e,n){!function(t,e,n){let o=di.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,di.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function mi(t,e){ui.set(t,e)}function gi(t){return t.nodeType===Node.ELEMENT_NODE||(t.nodeType===Node.TEXT_NODE?""!==(t.textContent?.trim()??""):t.nodeType===Node.COMMENT_NODE&&t.data.startsWith("@@wcs-"))}function yi(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const bi=new Set(["if","elseif","else","for"]);function wi(t,e){for(const n of ys(t))if(e.appliedBindingSet.delete(n),bi.has(n.bindingType))for(const t of ti(n.node))wi(t,e)}function vi(t){for(const e of ys(t)){if(!bi.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of ti(e.node))vi(n),t&&n.mounted&&(Qr(n),n.unmount(),ei(e.node,n))}}function _i(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function $i(t,n,s){const r=Boolean(s);let i;const a=ti(t.node);i=0===a.size?ri(t):a.values().next().value;const l=e(),c=t.uuid??"",u=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${_i(t)}`),Qr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${_i(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);Jr(i,we(t.node),n);const e=li();null!==e&&ci(i,"branch",e)}}const Si=new WeakMap;function xi(t){return Si.get(t)??[]}const Pi=new Set;function ki(){Pi.clear()}const Ii=Symbol.for("wcstack.trustedTypes.policy");function Ni(){const t=globalThis[Ii];return null===t||"object"!=typeof t?null:t}let Ai,Ei=!1;const Ci={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}};function Ti(t,n,s){if(1===t.propSegments.length){const e=t.propSegments[0];"textContent"===e||"innerText"===e?s=null==s?"":String(s):void 0===s&&"innerHTML"===e&&(s="")}if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0],u=r[c];if(u!==s){null!==hs&&null!==u&&"object"==typeof u&&null!==s&&"object"==typeof s&&null!==Ut(r)&&hs.rememberOverwrittenObject(r,c,u);const e="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let t=!1;try{r[c]=e?function(t){if("string"!=typeof t)return t;const e=Ni(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(Ei)return;if(!function(){if(void 0!==Ai)return Ai;if(!("trustedTypes"in globalThis))return Ai=!1,Ai;try{document.createElement("div").innerHTML="<i></i>",Ai=!1}catch{Ai=!0}return Ai}())return;Ei=!0;const n="function"==typeof Ni()?.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 "${e}" 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:t,property:e})}(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=Ut(t);if(null===n)return null;const o=Gt(t)?.get(n);if(void 0===o)return null;const s=Jt(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&Jn(r,c)){const e=to(r,c,t.statePathName),o=eo(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??io()??oo(e);if(a.visitedEdges.has(o))null!==_e&&_e({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=so(a,o);ao(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Yn++,writtenValue:n};lo.push({receipt:i,node:t});try{return r()}finally{lo.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=Ci[c];t?t(r,s):(function(t,e,n){let o=Si.get(t);o||(o=[],Si.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,s),a=r,Pi.add(a))}return}var a,l;const c=i[0];let u=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==u)return;u=u[e]}const d=i[i.length-1],h=u[d];if(h!==s){if(Object.isFrozen(u))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:s}));null!==hs&&2===i.length&&"object"==typeof u&&null!==u&&null!==Ut(r)&&(d in u?hs.rememberOverwrittenValue(r,c,d,u[d]):hs.recordInjectedKey(r,c,d));try{u[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:s,error:t})}}}const Mi=new WeakSet;function Oi(t,e,n){}function Li(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function Ri(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),s=e.length>0?e+a:"";for(const t of n){if(s.length>0&&!t.startsWith(s))continue;const e=t.slice(s.length);e.length>0&&-1===e.indexOf(a)&&o.push(e)}return o}const ji={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Di={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Wi(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${it}`}function zi(t,e){return`[wcs/recursion-anchor] "${t}" does not match the declared recursion anchor "${e}". 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 Bi(t,e){return`$setAll("${t}") ${e}`}function Fi(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} 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.${it}`}const Hi=new WeakSet;function qi(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Ui=Object.freeze({[x]:function(t,e,n){const o=t.node,s=t.propSegments[1];null!=n?("boolean"!=typeof n&&Z(`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)},[P]:function(t,e,n){const o=t.node,s=t.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)},[k]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[S]:function(t,e,n){Rn(n)||Z("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ms.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||Z('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Ut(t);if(null===e)return null;const n=Gt(t)?.get(e);return void 0===n&&Z(`Custom element <${e}> is not defined for command binding.`),Jt(t)}(r);null===a&&Z(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||Z(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${rt(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ms.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void ms.delete(t);const o=n[i];return"function"!=typeof o&&Z(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),ms.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Vi={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Mi.has(t.replaceNode)){Mi.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,r=sn(t),i=ln(t),a=Se(i),c=a.length>0&&!di.has(t.node)?[]:a,u=jr(r,c,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let d=di.get(t.node);const h=void 0!==d?function(t,e,n){if(o=e,!Dr.has(o))return null;var o;let s=null;for(let e=0;e<n.newIndexes.length;e++){const o=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?t.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}(d,c,u):null,f=Array.isArray(c)&&c.length===u.deleteIndexSet.size&&u.deleteIndexSet.size>0;if(f&&null===h&&null!==t.node.parentNode){let e=fi.get(t.node);if(void 0===e){const n=ui.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(gi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(gi(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n),fi.set(t.node,e)}if(e){const e=t.node.parentNode;!function(t,e){So.set(t,(So.get(t)??0)+e)}(e,e.childNodes.length),e.textContent="",e.appendChild(t.node)}}let p=f?1e3-function(t){return hi.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==d){const e=d;u.deleteIndexSet.forEach(n=>{const o=e.get(n);void 0!==o&&(null!==h&&h.reused.has(o)?(Qr(o),vi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?ei(t.node,o):(Qr(o),o.unmount(),function(t,e){let n=hi.get(t.node);void 0===n&&(n=[],hi.set(t.node,n)),n.length<1e3?n.push(e):ei(t.node,e)}(t,o),p-=1),f||e.delete(n))}),f&&(di.delete(t.node),d=void 0)}let m=t.node;const g=nt(s.path+"."+l),y=n.stateElement.loopContextStack,b=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.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(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?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 t of i)a.add(n[t]);return a}(u);let w=null;u.newIndexes.length==u.addIndexSet.size&&u.newIndexes.length>0&&m.isConnected&&null===h&&(w=document.createDocumentFragment(),Xe(w,n.rootNode));const v=e(),_=li(),$=t.uuid??"",S=hi.get(t.node);for(const e of u.newIndexes){let o;if(u.addIndexSet.has(e)){const r=bn(g,e);if(y.createLoopContext(r,r=>{if(o=h?.byAddedIndex.get(e)??(void 0!==S?S.pop():void 0),void 0===o?o=ri(t):wi(o,n),null!==w)v&&w.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`)),o.appendTo(w),v&&w.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const t=document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`);m.parentNode.insertBefore(t,m.nextSibling),m=t}o.mountAfter(m)}if(v){const t=document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`),n=o.lastNode??m;n.parentNode.insertBefore(t,n.nextSibling)}}Jr(o,r,n),null!==_&&ci(o,"row",_)}),void 0===o&&Z(`Content not found for ListIndex: ${e.index} at path "${s.path}"`),null!==h&&h.reused.has(o)){const t=n.stateElement.addressHooks;if(t){const e=t.rowReused;for(let t=0;t<e.length;t++)e[t](n.stateElement,o)}}}else{if(o=void 0!==d?d.get(e)??null:null,u.changeIndexSet.has(e)){const t=vs(o);for(const e of t)ta(e,n)}null===o&&Z(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==b&&b.has(e)&&yi(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),t){const t=o,s=bn(g,e);y.createLoopContext(s,e=>{Jr(t,e,n)})}}m=o.lastNode||m,void 0===d&&(d=new WeakMap,di.set(t.node,d)),d.set(e,o)}ui.set(t.node,m),null!==w&&(t.node.parentNode.insertBefore(w,t.node.nextSibling),Xe(w,null))},if:$i,else:$i,elseif:$i,radio:function(t,e,n){const o=t.node,s=fs(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=fs(o.value,t.inFilters),r=Array.isArray(n)?n:ps;o.checked=r.includes(s)}},Gi=new WeakMap,Ki=new WeakMap,Ji=new WeakMap;function Qi(){}function Xi(t){const e=hs;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return Oi;if(e.isDeclared(n,o))return Qi}return Ti}function Yi(t,e){Zi(t,e,function(t,e){const n=vn(e);if(n.pathInfo.path in N){const t=we(e.node);return null===t&&Z(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&Z("ListIndex not found for loopContext:");const n=N[e];void 0===n&&Z(`Invalid index name: ${e}`);const o=en(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&Z(Fi(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Le](n)}(e.state,t))}function Zi(t,e,n){const o=fs(n,t.outFilters);if(!0===Ki.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=Gi.get(t);if(void 0===s){if(Gi.has(t))return s=Xi(t),s===Oi&&Gi.set(t,s),void s(t,e,o);if(s=Vi[t.bindingType],void 0===s){const e=t.propSegments[0];s=Ui[e],Gi.set(t,s),void 0===s&&(Ut(t.replaceNode)?(s=Xi(t),s===Oi&&Gi.set(t,s)):(s=Ti,Gi.set(t,s)))}if(s===Ti&&"SELECT"===t.node.tagName){const n=t.propSegments[0];if("value"===n||"selectedIndex"===n)return e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement}),void Ki.set(t,!0)}s(t,e,o)}else s(t,e,o)}function ta(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=ln(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=ds(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Ji.get(t)){const e=Ut(t.replaceNode);if(e&&void 0===Gt(t.replaceNode)?.get(e))return void function(t,e){if(Hi.has(t))return;Hi.add(t);const n=()=>{Hi.delete(t);const e=ds(t);(null===e||e.shouldApplyState(t))&&na([t])},o=n=>{Hi.delete(t),qi(e,n)},s=ds(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Hi.delete(t),r()})||(Hi.delete(t),r()))}const r=Gt(t.replaceNode);if(null===r)return Hi.delete(t),void qi(e,new Error("CustomElementRegistry is unavailable."));Mo(r).wait(e,()=>{t.replaceNode.isConnected?n():Hi.delete(t)},o)}(t,e);Ji.set(t,!0)}if(!0===e.sameRootVerified)return void Yi(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Ye(o),null===o&&Z("Root node for fragment not found for binding.")),o!==e.rootNode){const n=ga(o);null===n&&Z("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};Yi(t,r)})}else Yi(t,e)}function ea(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==_e&&_e({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function na(t,e,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<t.length;){let n=t[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 u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=Ye(u),null===u&&Z("Root node for fragment not found for binding."));const d=ga(u);null===d&&Z("No state tree found on this root for binding."),d.createState("readonly",o=>{const h={rootNode:u,stateElement:d,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{ta(n,h)}catch(t){ea(n,t,d,c)}s++;const e=t[s];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{Ti(t,{propagationContextByBinding:e},n)}catch(e){ea(t,e,o??null,c)}for(const[t,e]of i.entries())xe(t,e),Ee(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[We](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[ze](n,o)}catch(t){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:t,original:n,node:o.node})}})}function oa(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=ge(o);0!==t.length&&(ve(o.node,e),na(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}function sa(t,e,n){const[o,s,r]=pe(t,n),i=us(t);for(const t of o)ve(t,e);na(i.initialize(s)),oa(r,e,i)}const ra=new WeakMap;async function ia(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Gt(t);null===s&&Z(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(le(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function aa(t){if(t===document)await ia(document),X(document),Fa(document,document),sa(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await Ft(e.host),await ia(e),X(e),Fa(e,e),sa(e,null)}}const la={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function ca(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${la[t]??t}" before the state is defined.`}let ua=null;function da(t){return null===ua&&Z(ca("ssr",t)),ua}const ha=new WeakMap,fa=new WeakMap,pa=new Set,ma=[];function ga(t){return ha.get(t)??null}function ya(t){return fa.get(t)??Promise.resolve()}const ba=new WeakSet;function wa(t){ba.add(t)}function va(t,n){const s=ha.get(t);if(null===n){if(void 0===s)return;ha.delete(t),pa.delete(s),null!==_e&&_e({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{o&&await da('the "enable-ssr" attribute').hydrate(t)||await aa(t),wa(t),Ka(),e()}catch(t){n(t)}})});fa.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await aa(t),wa(t),Ka(),e()}catch(t){n(t)}})});fa.set(t,e)}}void 0!==s&&Z('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),ha.set(t,n),pa.add(n);for(let e=0;e<ma.length;e++)ma[e](t,n);null!==_e&&_e({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}const _a=new Map;function $a(t,e,n){if(null===n)_a.delete(t);else{_a.set(t,n);const o=ga(e);null===o&&Z("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function Sa(t){return _a.get(t)||null}function xa(t){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=Mt(e.getAttribute(o.bindAttributeName)||"");if(e.localName===o.tagNames.state){if(e.hasAttribute("mount"))return n.filter(t=>t.propSegments[0]!==$);const t=n.find(t=>t.propSegments[0]===$);if(void 0!==t){const e=`on a volume element — a <${o.tagNames.state}> with a "mount" attribute`;Z(1===t.propSegments.length?`[wcs/mount-path-invalid] "${t.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${$}.<key>: <path>") ${e}.`:`[wcs/mount-path-invalid] "${t.propName}: ${t.statePathName}" is a volume injection declaration, and it can only be written ${e}. Add mount="<path>", or bind an element property instead.`)}}return n}if(t.nodeType===Node.COMMENT_NODE){const e=jt(t);null===e&&Z("Comment node binding text not found.");const n=Sa(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Dt(e),s=null):s=e,[{...o,uuid:s}]}return[]}let Pa;function ka(){return Pa??={filterName:"not",args:[]}}const Ia=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Na(t,e){const n=e+a+l,o=xt(t,"|");let s,r;if(-1!==o?(s=t.slice(0,o).trim(),r=t.slice(o)):(s=t.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return t;s=n+a+s.slice(1)}return r.length>0?s+r:s}function Aa(t,e){const n=Ia.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+Na(s,e)+r}function Ea(t,e){const n=Pt(t,";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=xt(n,":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Na(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function Ca(t,e){return Ea(t,e)}function Ta(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=Aa(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=Ea(r,e);t!==r&&o.setAttribute(n,t)}}}function Ma(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}const Oa=new WeakMap;function La(t){return Oa.get(t)??null}function Ra(t){const e=[],n=de(t);for(const t of n){const n=xa(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");Oa.set(e,t.data),t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:Ma(o),parseBindTextResults:n})}return e}function ja(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const Da=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Wa=ka();function za(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Wa],bindingType:t}}function Ba(t,e,n,o,s,r=!0){ja(e),"string"==typeof o&&Ta(e,o),Fa(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ra(e)};return void 0!==s&&function(t,e,n){for(const o of t)for(let t=0;t<o.parseBindTextResults.length;t++){const s=o.parseBindTextResults[t];null==s.uuid&&(o.parseBindTextResults[t]=e(s,n))}}(i.nodeInfos,s,o),i}function Fa(t,e,n,s){const r=o.commentElsePrefix,i=ce(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],u=[];for(;a.nextNode();){const t=a.currentNode;u.push(t)}for(const e of u){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=Ca(i,n));let a=Mt(i)[0];const u=Da.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=Ss();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&Z("'else' binding found without preceding 'if' or 'elseif' binding."),a=za("else",l.parseBindTextResult),p=Ba(t,h,a,m,s,!1),$a(f,t,p);const n=c.at(-1),o=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Ma(o),parseBindTextResults:xa(o)})):e.replaceWith(o)}else if("elseif"===d){null===l&&Z("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ba(t,h,a,m,s),$a(f,t,p);const n=document.createComment(`@@${u}:${f}`),o=Ss(),i={fragment:document.createDocumentFragment(),parseBindTextResult:za("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Ma(n),parseBindTextResults:xa(n)}),$a(o,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:Ma(g),parseBindTextResults:xa(g)})):e.replaceWith(g)}else{p=Ba(t,h,a,m,s),$a(f,t,p);const n=document.createComment(`@@${u}:${f}`);e.replaceWith(n)}"if"===d?(c.length=0,l=p):"elseif"===d?l=p:"else"===d&&(l=null,c.length=0)}}const Ha=()=>`[${o.bindAttributeName}]`;function qa(t){if(Xo(t))return!0;if(!Ua(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(Ha());return null!==e&&Xo(e)}function Ua(t){return 1===t.nodeType}function Va(t){if(qa(t))return;X(t),Fa(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);sa(e&&s?n:t,null)}const Ga=[];function Ka(){const t=Ga.splice(0,Ga.length);for(const e of t)Va(e);!function(){const t=function(){const t=globalThis[s];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[r];return void 0===e&&(e=[],t[r]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[i];return void 0===e&&(e=new WeakSet,t[i]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const Ja={protocol:"wcs-binder",version:1,bind:function(t){var e;Ua(t)&&!qa(t)&&(e=t.getRootNode(),ba.has(e)?Va(t):Ga.push(t))}},Qa="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Xa=0;async function Ya(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++Xa}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" 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 ${Qa}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${Qa}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Za(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){Z(`Failed to load script file: ${t}`)}}class tl{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&Z("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=u&&Z("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&Z("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&Z("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&Z(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const el={$updatedCallback:C,$streams:z},nl=new WeakSet;function ol(t,e){let n=t;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,e);)n=Object.getPrototypeOf(n);return n}function sl(t){if((null===t||"object"!=typeof t&&"function"!=typeof t)&&Z(`The state must be an object, got ${null===t?"null":typeof t}. Check the source of the state element (json / src / the inline <script>).`),!nl.has(t)){for(const e of Object.keys(el)){if(!(e in t))continue;const n=el[e];n in t&&Z(`[wcs/declaration-alias] The state declares both "${e}" and "${n}". "${e}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${it}`),Object.isExtensible(t)||Z(`[wcs/declaration-alias] The state is not extensible, so the old name "${e}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${it}`);const o=ol(t,e),s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,n,{...s,configurable:!0}),o===t&&delete t[e]}nl.add(t)}}const rl=new WeakMap;function il(t,e){let n=rl.get(t);void 0===n&&(n=new Map,rl.set(t,n));let o=n.get(e);return void 0===o&&(o=new Ln(e,t),n.set(e,o)),o}const al=new WeakMap;function ll(t){const e=al.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return il(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:il(t,n)}},set(){Z("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){Z("$command namespace is read-only; deleting from it is not allowed.")}});return al.set(t,n),n}const cl=Symbol("wcs.notHandled"),ul=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],dl=new Map;function hl(t,e){dl.set(t,e)}const fl=new Map;let pl=[],ml=[];function gl(t,e){fl.set(t,e),pl=Array.from(fl.values()).sort((t,e)=>t.order-e.order),ml=pl.slice().reverse()}function yl(t){return fl.has(t)}function bl(t,e){for(let n=0;n<pl.length;n++)pl[n].activate?.(t,e)}function wl(t){"readonly"===t.mutability&&Z("This state is readonly.")}const vl=new Map;class _l{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=nt(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function $l(t){let e;return vl.get(t)??(vl.set(t,e=new _l(t)),e)}function Sl(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:en(n.listIndex,o,n.pathInfo.wildcardCount)}function xl(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=tn(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?en(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?en(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}function Pl(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function kl(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](t,e,n,o,s);if(a!==cl)return a}}return cl}function Il(t,e,n,o,s){if(e.pathInfo.segments[0]===j)return function(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}(ll(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){if(null===e.parentAddress){const r=kl(s,e,null,n,o);if(r!==cl)return r;Z(function(t,e,n){return`[${ji.binding}] Path "${t}" does not exist on the state tree.${rt(t,Ri(e,"",n))}${it}`}(e.pathInfo.path,t,s.getterPaths))}const r=Nl(t,e.parentAddress,n,o);if(null==r)return;const i=e.pathInfo.segments[e.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==l&&!(i in Object(r))){const t=kl(s,e,Object(r),n,o);if(t!==cl)return t}if(i===l){const t=e.listIndex?.index??Z(Fi(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(r,t)}return Reflect.get(r,i)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}function Nl(t,e,n,o){xl(o,e),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,e.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const t=r.read;for(let r=0;r<t.length;r++){const i=t[r](s,e,n,o);if(i!==cl)return i}}return Pl(s,e)?function(t,e,n,o,s){const r=Ke(s,e),i=function(t){return Ws.get(t)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Il(t,e,n,o,s);return zs(r,{value:l,dirty:!1,generation:a}),l}(t,e,n,o,s):Il(t,e,n,o,s)}function Al(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,u,d)=>{const h=o[s]??null;if(null===h)return void d.push(u);const f=bn(h,r),p=Ke(n.stateElement,f),m=Ae(p),g=Nl(t,f,e,n),y=jr(r,m,g).newIndexes,b=l[c]??null;if(i.set(p,g),null===b)for(let t=0;t<y.length;t++){const e=y[t];a(o,s+1,e,l,c+1,u.concat(e.index),d)}else{const t=y[b]??Z(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,u.concat(t.index),d):d.push(u.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Ee(t,Array.isArray(e)?e:[]);return l}function El(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=js(Nl(t,bn(a,r),e,n),r);null==l&&Z(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??Z(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Cl(t,e,n,o){"object"==typeof t&&null!==t||Z(`${U} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&Z(`${U} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Tl(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&Z(`${U} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Ml(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];Cl(a,n,o,i);const l=Tl(a,e,n,o,i);r.has(l)&&Z(`${U} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Ol(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function Ll(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const r=Nl(t,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=e.pathInfo.lastSegment;if(i===l){const t=e.listIndex?.index;return"number"==typeof t&&t in r}return i in r}const Rl=new WeakMap;function jl(t,e){null===e?Rl.delete(t):Rl.set(t,e)}function Dl(t,e,n){const s=bn(nt(t.wildcardParentPaths[e]),n),r=Ke(t.stateElement,s),i=Ae(r),a=t.stateProxy[Le](s),l=jr(s.listIndex,i,a);t.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(l,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)Dl(t,e+1,n)}const Wl=[];function zl(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:Wl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Wl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Bl=[];function Fl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Bl;let s=null;const r=e+a;for(const t of o){if(t!==e&&!t.startsWith(r))continue;const o=nt(t);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Bl}function Hl(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,ql(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}function ql(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const r of s){const s=nt(r);if(t.listPathSet.has(o)&&s.lastSegment===l){const i=t.stateProxy[Le](e),a=Ke(t.stateElement,e),l=Ae(a),c=jr(e.listIndex,l,i);t.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const u=zl(t,o,0,0,c);for(const e of u.fullRows){const o=bn(s,e);t.result.add(o),n.push(o)}if(null!==u.movedRows){const e=Fl(t,r,s);if(null===e)for(const e of u.movedRows){const o=bn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of u.movedRows)for(const s of e){const e=bn(s,o);t.result.add(e),n.push(e)}}}else{const o=bn(s,e.listIndex);t.result.add(o),n.push(o)}}const r=t.dynamicMap.get(o);if(r)for(const o of r){const s=nt(o),r=[];if(s.wildcardCount>0){const n=tn(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=en(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Dl(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=en(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=bn(s,e);t.result.add(o),n.push(o)}}}function Ul(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&Z(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),d={ranks:u,stateElement:t,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};Hl(d,e,a),function(t,e){for(let n=0;n<1e3;n++){const n=rr(t.stateElement);if(null===n)return;n.forEach(n=>{Hl(t,bn(n.absolutePathInfo.pathInfo,n.listIndex),e)})}}(d,a);for(const[t,e]of d.observedListValueByAbsAddress)Ee(t,e);return Array.from(d.result)}function Vl(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](t,e,n,o,s)}}function Gl(t,e,n){const o=t.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function Kl(t,e,n){const o=t.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function Jl(t,e,n,o,s,r){const i=_r(t,e),a=Pr(t,e);if(!i&&!a)return null;const l=[],c=Xl(l);return i&&xr(t,e,n,o,s).forEach(c),a&&Ir(t,e,n?o:r(),s).forEach(c),l}function Ql(){return o.enablePropagationContext?io()??null:null}function Xl(t){const e=Xs(),n=Ql();return o=>{Bs(o),e.enqueueAbsoluteAddress(o,n),t.push(o)}}function Yl(t,e,n){if(null===t||0===t.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=Xs(),a=Ql();for(let n=0;n<t.length;n++){const l=t[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const u=bn(l.pathInfo,t[n].listIndex);Ul(o,u,s,r,o.listPaths,e,"new",t=>{if(t===u)return;const e=Ke(o,t);Bs(e),i.enqueueAbsoluteAddress(e,a)},{listExpansion:"diff"})}}function Zl(t,e,n,s,r,i,a="diff"){const l=o.enablePropagationContext?io()??oo(-1):null,c=Xs();c.enqueueAbsoluteAddress(e,l),i&&Bs(e),Ul(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=Ke(s.stateElement,e);Bs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function tc(t,e,n,o,s){s&&(t.getterPaths.has(e)?Bs(n):zs(n,{value:o,dirty:!1,generation:t.stateGeneration}))}function ec(t,e,n,o,s,r,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const i=Nl(t,n,s,r),a=e.pathInfo.segments[e.pathInfo.segments.length-1];if(a===l){const t=e.listIndex?.index??Z(Fi(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(i,t,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);r.pushAddress(e),r.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{Zl(e,n,s,r,i,a)}}function nc(t,e,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(e.pathInfo.path);if(void 0!==i){const r=Nl(t,e,o,s),c=function(t,e,n,o){const s=Ml(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Ml(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,i,r,n);if(null!==c)return function(t,e,n,o,s,r){const i=e.pathInfo.path,c=e.listIndex;null===Rs(o)&&jr(c,null,o);const u=jr(c,o,n.list),d=oc(t,e,n.list,s,r,i),h=nt(i+a+l);for(const e of n.matched){const n=Ol(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const i of n)void 0!==o?nc(t,bn(nt(h.path+a+i.field),o),i.value,s,r):e.oldRow[i.field]=i.value}return d}(t,e,c,r,o,s)}}return oc(t,e,n,o,s,null)}function oc(t,e,n,s,r,i){const c=r.stateElement,u=e.pathInfo.path,d=c.addressHooks;if(d){const t=d.write;for(let o=0;o<t.length;o++){const i=t[o](c,e,n,s,r);if(i!==cl)return i}}const h=!!co&&(co=!1,!0);if(!(u in t)&&null!==e.parentAddress&&!c.elementPaths.has(u)){const a=Nl(t,e.parentAddress,s,r);if("object"==typeof a&&null!==a){const t=e.pathInfo.lastSegment,f=t===l?e.listIndex?.index:t;let p,m=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==f&&f in a,e=void 0!==f?a[f]:void 0;if(t&&Object.is(e,n))return!0;p=e,m=!0}const g=Jl(c,u,m,p,n,()=>a[f]),y=Pl(c,e),b=Ke(c,e);null!==_e&&_e({type:"state:write",absoluteAddress:b,value:n,oldValue:p,hasOldValue:m}),Vl(c,u,b,p,m);let w=!1;try{if(void 0===f&&Z(Fi(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),d&&0!==d.writeMissing.length&&t!==l&&!(f in a)){const t=d.writeMissing;for(let o=0;o<t.length;o++){w=!0;const i=t[o](c,e,a,f,n,s,r);if(i!==cl)return i;w=!1}}return Reflect.set(a,f,n)}finally{Zl(e,b,s,r,i,y),Yl(g,s,r),w?Bs(b):tc(c,u,b,n,y),Gl(c,e.pathInfo,{value:n})}}}let f,p=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Nl(t,e,s,r);if(Ll(t,e,s,r)&&Object.is(o,n))return!0;f=o,p=!0}const m=Jl(c,u,p,f,n,()=>Nl(t,e,s,r)),g=c.elementPaths.has(e.pathInfo.path),y=Pl(c,e),b=Ke(c,e);null!==_e&&_e({type:"state:write",absoluteAddress:b,value:n,oldValue:f,hasOldValue:p}),Vl(c,u,b,f,p);try{return g?function(t,e,n,o,s,r,i,c){const u=e.parentAddress??Z(`address.parentAddress is undefined path: ${e.pathInfo.path}`),d=Nl(t,u,s,r)??[];let h=(f=d,Rl.get(f)??null);var f;if(null===h){const t=Rs(d)??[];h={value:[...d],listIndexes:[...t]},jl(d,h)}try{return ec(t,e,n,o,s,r,i,c)}finally{const n=h.value.indexOf(o),i=Nl(t,u,s,r)??[],c=Array.isArray(i)?Rs(i)??[]:[],f=e.listIndex.index,p=-1!==n?h.listIndexes[n]:Ns(u.listIndex,-1);if(c[f]=p,new Set(i).size===h.value.length){for(let t=0;t<c.length;t++)c[t].index=t;jl(d,null),function(t,e,n,o,s,r){const i=r.stateElement,c=Xs(),u=Ke(i,t);Se(u)===n&&(Ds(e.value,e.listIndexes),xe(u,e.value),function(t){Dr.add(t)}(e.value)),c.enqueueRenderOnlyAddress(u);const d=new Map;e.listIndexes.forEach((t,e)=>d.set(t,e));const h=nt(t.pathInfo.path+a+l);for(let t=0;t<o.length;t++){const n=o[t],a=d.get(n);if(a===t)continue;const l=bn(h,n),u=Ke(i,l);if(void 0===a){const n=Je(i,h,e.listIndexes[t]??null);Kl(i,u,n),Zl(l,u,s,r,null,Pl(i,l),"full");continue}Ul(i,l,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",t=>{const e=Ke(i,t);Bs(e),c.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}}(u,h,i,c,s,r)}}}(t,e,b,n,s,r,i,y):ec(t,e,b,n,s,r,i,y)}finally{Yl(m,s,r),g||tc(c,u,b,n,y),Gl(c,e.pathInfo,{value:n})}}function sc(t,e,n,o){return(e,s,...r)=>{Array.isArray(s)||Z(`$resolve("${e}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&Z(`$resolve("${e}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=nt(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&Z(Wi("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=bn(i,El(t,n,o,i,s));if(0===r.length)return Nl(t,a,n,o);wl(o),nc(t,a,r[0],n,o)}}function rc(t,e,n,o){const s=sc(t,0,n,o);return(e,r)=>{const i=nt(e);if(void 0===r||Array.isArray(r)||Z(`$getAll("${e}") 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 t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&Z(Wi("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Sl(o,i.wildcardPaths[t]);if(e){r=nn(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&Z(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", 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).`}(e,t.pathInfo.path)),r=[]}}const a=Al(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}function ic(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Sl(o,s.wildcardPaths.at(-1)??Z(`lastWildcardPath is null: ${e.pathInfo.path}`))??Z(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??Z(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=js(Nl(t,bn(i,s),n,o),s)??Z(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??Z(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??Z(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":Z(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function ac(t,e,n,o){return(e,s,r,i)=>{wl(o);const a=nt(e);Array.isArray(s)||Z(Bi(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&Z(Wi("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&Z(Bi(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&Z(Bi(e,"requires an array as the value when { spread: true } is set."));const u=Al(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&Z(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,u.length,r.length));const d=[];for(let e=0;e<u.length;e++){const s=El(t,n,o,a,u[e]);d.push(bn(a,s))}let h=0;for(let e=0;e<d.length;e++){const s=d[e];let i;i=c?r(Nl(t,s,n,o),...u[e]):l?r[e]:r,void 0!==i&&(nc(t,s,i,n,o),h++)}return h}}function lc(t,e){const n=t.getterPaths;if(0===n.size)return!1;for(const t of nt(e).cumulativePaths)if(n.has(t))return!0;return!1}const cc=/^\$\d+$/,uc=`${V}${a}`,dc=`${G}${a}`,hc=new WeakMap;function fc(t,e,n,o){const s=N[e];if(void 0===s&&"string"==typeof e&&36===e.charCodeAt(0)&&cc.test(e)&&Z(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&Z(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&Z(`ListIndex not found: ${e.toString()}`);let i=s;const a=t.pathInfo,l=o.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let n=0;n<e.length;n++)i+=e[n](o,t)}const c=en(r,i,a.wildcardCount);return c?.index??Z(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,e,n,t);if(i!==cl)return i}}if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>rc(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>ac(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=$l(e),i=ic(t,r,n,o),a=bn(r.pathInfo,i),l=Ke(s,a),c=Xs();c.enqueueAbsoluteAddress(l),function(t,e,n,o,s){const r=_r(t,e),i=Pr(t,e);if(!r&&!i)return;const a=n(),l=[],c=Xl(l);r&&xr(t,e,!1,void 0,a).forEach(c),i&&Ir(t,e,void 0,a,!1).forEach(c),Yl(l,o,s)}(s,r.pathInfo.path,()=>Nl(t,a,n,o),n,o),Ul(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Ke(s,t);Bs(e),c.enqueueAbsoluteAddress(e)});const u=s.addressHooks;if(u){const t=u.written;for(let e=0;e<t.length;e++)t[e](s,a.pathInfo)}}}(t,0,n,o)(e);case"$resolve":return(e,s,...r)=>sc(t,0,n,o)(e,s,...r);case"$dependOn":case"$trackDependency":return t=>function(t,e,n,o){return t=>{-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] ${String(e)}("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&Z(`No active state reference to track dependency for path "${t}".`);const n=o.lastAddressStack?.pathInfo??Z("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==t&&s.addDynamicDependency(t,n.path)}}(0,e,0,o)(t);case"$eq":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(lc(o.stateElement,t))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&vr(o.stateElement,t),Object.is(n[t],e);let r;o.beginUntrack();try{r=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&wr(o.stateElement,t,e,Ke(o.stateElement,s),r),Object.is(r,e)};case"$eqPath":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=lc(o.stateElement,t);let i,a=r?n[t]:void 0;o.beginUntrack();try{r||(a=n[t]),i=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?vr(o.stateElement,t):wr(o.stateElement,t,i,Ke(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(t,e=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||Z(`$eqIndex("${t}") needs a list row scope.`);const r=en(s.listIndex,e-1,s.pathInfo.wildcardCount);if(null===r&&Z(`$eqIndex("${t}", ${e}): no list index at that level.`),lc(o.stateElement,t))return o.stateElement.getterPaths.has(s.pathInfo.path)&&vr(o.stateElement,t),Object.is(n[t],r.index);const i=e===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[t],i&&(l=n[s.pathInfo.wildcardParentPaths[e-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const e=i?Rs(l):null;null!==e?function(t,e,n,o,s){nr=!0,fr(t).lastValue.set(e,s),hr(t,e);let r=ir.get(t);void 0===r&&ir.set(t,r=new Map);let i=r.get(e);void 0===i&&r.set(e,i=new Set);let a,l=ar.get(o);if(void 0===l?ar.set(o,l=[]):a=l.find(n=>n.stateElement===t&&n.path===e),void 0===a){a={stateElement:t,path:e,indexes:o,getters:new Set},l.push(a),i.add(a);const n=o[0]?.parentListIndex??null;if(null!==n){let t=cr.get(n);void 0===t&&cr.set(n,t=new Set),t.add(a)}}a.getters.add(n)}(o.stateElement,t,s.pathInfo,e,a):function(t,e,n,o,s){nr=!0;const r=fr(t);hr(t,e),br(r,e,s,o,gr(r,e,n.index,o),{stateElement:t,path:e,absAddress:o,levelListIndex:n})}(o.stateElement,t,r,Ke(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untracked":case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case j:return ll(o.stateElement)}if(!e.startsWith(uc)&&!e.startsWith(dc))return}const r=$l(e),i=ic(t,r,n,o),a=bn(r.pathInfo,i);return Nl(t,a,n,o)}if("symbol"==typeof e){const s=function(t){let e=hc.get(t);return void 0===e&&(e=new Map,hc.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case Oe:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&Z("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case Le:i=e=>Nl(t,e,n,o);break;case Re:i=e=>Ll(t,e,n,o);break;case je:i=()=>async function(t,e,n){const o=Reflect.get(t,A);"function"==typeof o&&await o.call(n)}(t,0,n);break;case De:i=()=>function(t,e,n){const o=Reflect.get(t,E);"function"==typeof o&&o.call(n)}(t,0,n);break;case We:i=e=>function(t,e,n,o){const s=Reflect.get(t,C);let r;if("function"==typeof s){const t=new Set,i={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,s=e.path;if(-1===s.indexOf("#")&&(t.add(s),e.wildcardCount>0)){const t=nn(n.listIndex,e.wildcardCount),o=i[s];void 0===o?i[s]=[t]:o.push(t)}}r=s.call(n,Array.from(t),i)}const i=o.stateElement?.addressHooks;if(i){const t=i.updated;for(let s=0;s<t.length;s++)t[s](o.stateElement,e,n)}return r}(t,e,n,o);break;case ze:i=(e,o)=>function(t,e,n,o){const s=Reflect.get(t,T);"function"==typeof s&&s.call(o,e,n)}(t,e,o,n);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}class pc{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=ga(t);null===n&&Z("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&Z("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&Z(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),Z(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const n=this._addressStack[e];if(n){if(t.has(n))return!0;t.add(n)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&Z(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return fc(t,e,n,this)}set(t,e,n,o){return wl(this),function(t,e,n,o,s){if("string"==typeof e){const r=$l(e),i=ic(t,r,o,s);return nc(t,bn(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}deleteProperty(t,e){return wl(this),Reflect.deleteProperty(t,e)}defineProperty(t,e,n){return wl(this),Reflect.defineProperty(t,e,n)}}const mc=Promise.resolve(),gc=new Map;let yc=[];function bc(t,e){gc.set(t,e),yc=Array.from(gc.values()).sort((t,e)=>t.order-e.order)}function wc(t,e){return Z(ca(t,e))}const vc="undefined"==typeof HTMLElement?class{}:HTMLElement;function _c(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}let $c=null;const Sc=new Set(["for","if","elseif","else"]);const xc=[[B,"watch"],[F,"scan"],[z,"streams"],[H,"recursion"]];class Pc extends vc{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return ya(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new tl}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&Z(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){sl(t),function(t){for(let e=0;e<xc.length;e++){const[n,o]=xc[e];n in t&&!yl(o)&&Z(ca(o,`"${n}"`))}}(t);const e=this.__state,n=function(){const t=new Map;return{get:e=>t.get(e),set(e,n){t.set(e,n)}}}();n.set("previousState",e),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].validateEarly?.(t,e,n)}(this,t,n);const o=function(t){const e=new Set,n=t[R];if(void 0===n)return e;Array.isArray(n)||Z(`${R} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Z(`${R} entries must be non-empty strings.`),t===j&&Z(`${R} entry "${t}" conflicts with the reserved namespace name "${j}".`),e.has(t)&&Z(`${R} entry "${t}" is duplicated.`),e.add(t);return e}(t),s=function(t){const e=new Set,n=t[D];if(void 0===n)return e;Array.isArray(n)||Z(`${D} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Z(`${D} entries must be non-empty strings.`),e.has(t)&&Z(`${D} entry "${t}" is duplicated.`),e.add(t);return e}(t),r=function(t){const e=t[U];if(void 0===e)return null;"object"==typeof e&&null!==e||Z(`${U} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&Z(`${U} entry path must be a non-empty string.`);const e=t.split(a);e.some(t=>0===t.length)&&Z(`${U} entry "${t}" must not contain empty path segments.`),e[e.length-1]===l&&Z(`${U} entry "${t}" must be the list path itself, not the element path (drop the trailing "${a}${l}").`),-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] ${U} entry "${t}" uses "${q}", which ${U} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${a}${l}${a}children").`),"function"!=typeof o?("string"!=typeof o&&Z(`${U} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&Z(`${U} entry "${t}" key field name must be a non-empty string.`),(o.includes(a)||o.includes(l))&&Z(`${U} entry "${t}" key field name "${o}" must be a flat property name ("${a}" / "${l}" are not allowed).`),o in Object.prototype&&Z(`${U} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t);n.set("eventTokenNames",s),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].validate?.(t,e,n)}(this,t,n),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].preCommit?.(t,e,n)}(this,t,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=t,void 0!==e&&$c?.reset(this),this._hasUpdatedCallback=C in t,this._hasErrorCallback=T in t,Tn.delete(this),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].applyEarly?.(t,e,n)}(this,t,n),function(t,e,n){const o=e[W];if(void 0!==o){"object"==typeof o&&null!==o||Z(`${W} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||Z(`${W} entry "${e}" is not declared in $eventTokens.${rt(e,n)}`),"function"!=typeof s&&Z(`${W} entry "${e}" must be a function.`),Mn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const i=function(t){const e=new Set,n=new Set,o=_c(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of i.getterPaths)this._getterPaths.add(t);for(const t of i.setterPaths)this._setterPaths.add(t);!function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].apply?.(t,e,n)}(this,t,n),this._listKeys=r,this._rebuildPathInfo(),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].register?.(t,e,n)}(this,t,n),bl(this,null),this._resolveLoading?.()}attributeChangedCallback(t,e,n){this._initialized&&e!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===e?"absent":`"${e}"`}, 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")?da('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){Z("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await Ya(t,o.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||Z(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await Za(t);Z(`Unsupported src file type: ${t}`)}}catch(t){Z(`Failed to initialize state: ${t}`)}}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}return await this._loadingPromise,null!==this._rootNode&&(va(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),Z(t)}_failInitializeLoudly(t,e=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),e&&null!==this._rootNode&&null===ga(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),fa.set(t,n)}(this._rootNode,t),function(t,e,n){for(let o=0;o<yc.length;o++)yc[o].initializeFailed?.(t,e,n)}(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{A in t&&await t[je]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{E in t&&t[De]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(t){for(let e=0;e<yc.length;e++)if(!0===yc[e].reconnecting?.(t))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||ga(this._rootNode)===this||va(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(t){for(let e=0;e<yc.length;e++){const n=yc[e].connecting?.(t);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{wc("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}const n=this.parentNode;if(n instanceof ShadowRoot&&n.host.hasAttribute(K))try{wc("dcc",`a <${o.tagNames.state}> inside a [${K}] host`)}catch(t){this._failInitializeLoudly(t)}let s=!1;try{const t=function(t){for(let e=0;e<yc.length;e++){const n=yc[e].preparing?.(t);if(null!=n)return n}return null}(this);null===t&&this.hasAttribute("bind-component")&&wc("scopes",'the "bind-component" attribute'),s=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(s)return;let r=!1;try{r=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!r)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!e()||t!==this._connectGeneration||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await da('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}bl(this,t),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!function(t){for(let e=0;e<yc.length;e++)if(!0===yc[e].disconnecting?.(t))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(t,e){for(let n=0;n<yc.length;n++)yc[n].initializeFailureCleared?.(t,e)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{va(this.rootNode,null),al.delete(this),function(t){for(let e=0;e<ml.length;e++)ml[e].deactivate?.(t)}(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(t=>(sl(t),t))}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}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(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e,this.attachAddressHooks("watch",B)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&Z(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return Li(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&Z("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const n=function(t,e){const n=dl.get(t);return void 0===n&&Z(ca(t,`"${e}"`)),n}(t,e);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(t,e){for(let n=0;n<ul.length;n++){const o=ul[n],s=e[o];if(void 0===s)continue;const r=t[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",O)}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(t);void 0===o?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:o.bound||"binding"===n})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+l)),!this._pathSet.has(t)){const e=nt(t);if(this._pathSet.add(t),$c?.check(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=nt(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,n){try{const o=function(t,e,n){const o=new pc(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&Z(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);!function(t){for(let e=0;e<yc.length;e++)yc[e].replacingState?.(t)}(this),(this._hasGraftedVolumes||this._hasMounts)&&Z("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const e=this.__state;this._state=t;const n=function(t){const e=new Set;for(const n of t)if(void 0!==n)for(const[t,o]of Object.entries(_c(n)))t.startsWith("$")||t.includes(l)||"function"==typeof o.value||e.add(t);return e}([e,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){!function(t,n,o){const s=new Map;for(const t of o){const e=nt(t);if(null===e.lastWildcardPath)continue;const n=s.get(e.lastWildcardPath);void 0===n?s.set(e.lastWildcardPath,[e]):n.push(e)}const r=[],i=new Set,a=e=>{const n=Ke(t,e);if(i.has(n))return;i.add(n);const o=pn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==e.listIndex){const t=s.get(e.pathInfo.path);if(void 0!==t)for(const n of t)a(bn(n,e.listIndex))}};Ce();try{if(t.createState("readonly",e=>{for(const o of n){const n=bn(nt(o),null);a(n);try{Ul(t,n,t.staticDependency,t.dynamicDependency,t.listPaths,e,"new",a)}catch{}}}),0===r.length)return;const o=function(t){const e=[],n=[];for(const o of t)Sc.has(o.bindingType)?e.push(o):n.push(o);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(n)}(r),s=()=>{na(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=qs("state",s);void 0!==i&&i.catch(Js)}finally{Te()}}(this,t,this._pathRegistrations.keys())}}const kc=[],Ic=[];function Nc(){const t=[];let e=0;for(let n=0;n<Ic.length;n++){const o=Ic[n].deref();void 0!==o&&(t.push(o),Ic[e++]=Ic[n])}return Ic.length=e,t}function Ac(t,e){const r=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(t);var i;r&&((i=r).tagNames&&Object.assign(n.tagNames,i.tagNames),"string"==typeof i.bindAttributeName&&(n.bindAttributeName=i.bindAttributeName),"string"==typeof i.commentTextPrefix&&(n.commentTextPrefix=i.commentTextPrefix),"string"==typeof i.commentForPrefix&&(n.commentForPrefix=i.commentForPrefix),"string"==typeof i.commentIfPrefix&&(n.commentIfPrefix=i.commentIfPrefix),"string"==typeof i.commentElseIfPrefix&&(n.commentElseIfPrefix=i.commentElseIfPrefix),"string"==typeof i.commentElsePrefix&&(n.commentElsePrefix=i.commentElsePrefix),"string"==typeof i.locale&&(n.locale=i.locale),"boolean"==typeof i.debug&&(n.debug=i.debug),"boolean"==typeof i.enableMustache&&(n.enableMustache=i.enableMustache),"boolean"==typeof i.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=i.enableDirectionalInitialSync),"boolean"==typeof i.enablePropagationContext&&(n.enablePropagationContext=i.enablePropagationContext),"boolean"==typeof i.enableContractAnalyzer&&(n.enableContractAnalyzer=i.enableContractAnalyzer),"boolean"==typeof i.sameValueGuard&&(n.sameValueGuard=i.sameValueGuard)),function(t=customElements){Nc().includes(t)||Ic.push(new WeakRef(t));for(let e=0;e<kc.length;e++)kc[e](t);t.get(o.tagNames.state)||t.define(o.tagNames.state,Pc)}(e),function(){const t=globalThis;void 0===t[s]&&(t[s]=Ja)}()}let Ec=null;function Cc(t){return Ec??Z(ca("watch",`"$watch" in <wcs-state mount="${t}">`))}let Tc=null;const Mc=Object.freeze([]),Oc="3.3.0",Lc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Rc(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const jc="__WCSTACK_DEVTOOLS_HOOK__";const Dc=t=>{null!==_e&&_e({type:"state:update-batch",addresses:t})};function Wc(t){const e=null!==_e;!function(t){_e=t}(t);const n=null!==t;n&&!e?Ks(Dc,0):!n&&e&&function(t){const e=Us.findIndex(e=>e.listener===t);-1!==e&&Us.splice(e,1)}(Dc)}function zc(t){return{rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function Bc(t){return ga(t)??Z("devtools: no state tree on this root")}let Fc=null;function Hc(){if(e())return;if(null!==Fc)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Oc,getStateElements(){const t=[];for(const e of pa)t.push(zc(e));return t},overlays(t){return e=Bc(t),null===Tc?Mc:Tc(e);var e},keyedSubscriptions:t=>function(t){const e=function(t){const e=Ys.get(t);return void 0===e?null:{byPath:e.byPath,lastValue:e.lastValue,tracked:e.tracked,watchers:ir.get(t)}}(t);if(null===e)return[];const n=new Set([...e.byPath.keys(),...e.tracked]);if(void 0!==e.watchers)for(const t of e.watchers.keys())n.add(t);const o=[];for(const t of[...n].sort()){const n=e.byPath.get(t);let s=0;if(void 0!==n)for(const t of n.values())s+=t.size;o.push({path:t,tracked:e.tracked.has(t),rows:s,keys:n?.size??0,lists:e.watchers?.get(t)?.size??0,lastValue:e.lastValue.get(t)})}return o}(Bc(t)),keys(t){const e=Bc(t),n=[];return e.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}n.push(e)}}),n},read(t,e,n){let o;return Bc(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){Bc(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=`${ct(t.inFilters)}\0${ct(t.outFilters)}`;return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=Sa(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Rc(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=ne(e,Mt(n));for(const o of t)r(Rc(e,o,"attribute",n))}catch{}continue}const e=Lc.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=Sa(s);if(null===a){if(n===o.commentTextPrefix)try{r(Rc(t,Dt(s),"comment",s))}catch{}}else r(Rc(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:Wc};Fc=t,function(){const t=globalThis,e=t[jc];if(void 0!==e)return 2!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 2. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:2,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[jc]=n,n}().register(t)}const qc={name:"devtools",install(){Hc()}},Uc=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Vc=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])}),Gc=new WeakMap,Kc=new WeakMap,Jc=new WeakSet,Qc=new WeakMap;function Xc(t,e,n,o){console.warn(`[@wcstack/state] [${ji[n]}] ${Di[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${rt(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${it}`),null!==_e&&_e({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const Yc={check:function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=t.addressHooks;if(s){const e=s.suppressPathDiagnostic;for(let o=0;o<e.length;o++)if(e[o](t,n))return}const r=nt(n).segments;if("binding"===o&&r.length<2)return;if(function(t,e){let n=Gc.get(t);return void 0===n&&(n=new Set,Gc.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const i=function(t,e,n){if(void 0!==Li(t,e))return Vc;const o=nt(e).segments;let s=t,r="";for(let e=0;e<o.length;e++){const i=o[e],c=r;if(r=0===e?i:r+a+i,e>0&&e<o.length-1&&void 0!==Li(t,r))return Uc;if(Object(s)!==s)return Uc;if(i===l){if(!Array.isArray(s)||0===s.length)return Uc;s=s[0];continue}const u=Li(s,i);if(void 0===u)return{existence:"missing",missingSegment:i,candidates:Ri(s,c,n)};if("function"==typeof u.get)return e===o.length-1?Vc:Uc;s=u.value}return Vc}(e,n,t.getterPaths);"missing"===i.existence&&(function(t,e){return!0===Qc.get(t)?.has(e)}(t,n)||("binding"!==o?Xc(0,n,o,i):function(t,e,n){let o=Kc.get(t);void 0===o&&(o=new Map,Kc.set(t,o)),o.set(e,n),Jc.has(t)||(Jc.add(t),setTimeout(()=>function(t){Jc.delete(t);const e=Kc.get(t);if(void 0!==e){Kc.delete(t);for(const[t,n]of e)Xc(0,t,"binding",n)}}(t),0))}(t,n,i)))},reset:function(t){Gc.delete(t),Kc.delete(t)},markExported:function(t,e){let n=Qc.get(t);void 0===n&&(n=new Set,Qc.set(t,n)),n.add(e),Kc.get(t)?.delete(e)}};let Zc=!1;const tu={name:"diagnostics",install(){Zc||(Zc=!0,$c=Yc)}};function eu(t){Z(`filter ${t} requires at least one option`)}function nu(t){Z(`filter ${t} requires a number as option`)}function ou(t){Z(`filter ${t} requires a number value`)}function su(t){Z(`filter ${t} requires a date value`)}const ru={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function iu(t){return!(!t||isNaN(Number(t)))}function au(t,e){return iu(t)||nu(e),Number(t)}function lu(t,e,n){return au(t?.[e]??eu(n),n)}const cu=t=>e=>{const n=t(e);return t=>null==t?t:n(t)},uu={eq:(t,e)=>{const n=t?.[0]??eu("eq"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t===o:(iu(n)||nu("eq"),t===Number(n)):"string"==typeof t?t===n:t===o},ne:(t,e)=>{const n=t?.[0]??eu("ne"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t!==o:(iu(n)||nu("ne"),t!==Number(n)):"string"==typeof t?t!==n:t!==o},not:t=>t=>!t,lt:t=>{const e=lu(t,0,"lt");return t=>("number"!=typeof t&&ou("lt"),t<e)},le:t=>{const e=lu(t,0,"le");return t=>("number"!=typeof t&&ou("le"),t<=e)},gt:t=>{const e=lu(t,0,"gt");return t=>("number"!=typeof t&&ou("gt"),t>e)},ge:t=>{const e=lu(t,0,"ge");return t=>("number"!=typeof t&&ou("ge"),t>=e)},add:t=>{const e=lu(t,0,"add");return t=>("number"!=typeof t&&ou("add"),t+e)},sub:t=>{const e=lu(t,0,"sub");return t=>("number"!=typeof t&&ou("sub"),t-e)},mul:t=>{const e=lu(t,0,"mul");return t=>("number"!=typeof t&&ou("mul"),t*e)},div:t=>{const e=lu(t,0,"div");return t=>("number"!=typeof t&&ou("div"),t/e)},mod:t=>{const e=lu(t,0,"mod");return t=>("number"!=typeof t&&ou("mod"),t%e)},abs:t=>t=>("number"!=typeof t&&ou("abs"),Math.abs(t)),clamp:t=>{const e=lu(t,0,"clamp"),n=lu(t,1,"clamp");return t=>("number"!=typeof t&&ou("clamp"),Math.min(Math.max(t,e),n))},toFixed:t=>{const e=au(t?.[0]??"0","toFixed");return t=>("number"!=typeof t&&ou("toFixed"),t.toFixed(e))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&ou("locale"),t.toLocaleString(e??o.locale))},upper:cu(t=>t=>String(t).toUpperCase()),lower:cu(t=>t=>String(t).toLowerCase()),capitalize:cu(t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)}),trim:cu(t=>t=>String(t).trim()),slice:cu(t=>{const e=[lu(t,0,"slice")],n=t?.[1];return void 0!==n&&e.push(au(n,"slice")),t=>String(t).slice(...e)}),substr:cu(t=>{const e=lu(t,0,"substr"),n=lu(t,1,"substr");return t=>String(t).substr(e,n)}),padStart:cu(t=>{const e=lu(t,0,"padStart"),n=t?.[1]??"0";return t=>String(t).padStart(e,n)}),padEnd:cu(t=>{const e=lu(t,0,"padEnd"),n=t?.[1]??" ";return t=>String(t).padEnd(e,n)}),repeat:cu(t=>{const e=lu(t,0,"repeat");return t=>String(t).repeat(e)}),reverse:cu(t=>t=>String(t).split("").reverse().join("")),truncate:cu(t=>{const e=lu(t,0,"truncate"),n=t?.[1]??"…";return t=>{const o=String(t);return o.length<=e?o:o.slice(0,e)+n}}),join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||Z("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=Math.pow(10,au(t?.[0]??"0","round"));return t=>("number"!=typeof t&&ou("round"),Math.round(t*e)/e)},floor:t=>{const e=Math.pow(10,au(t?.[0]??"0","floor"));return t=>("number"!=typeof t&&ou("floor"),Math.floor(t*e)/e)},ceil:t=>{const e=Math.pow(10,au(t?.[0]??"0","ceil"));return t=>("number"!=typeof t&&ou("ceil"),Math.ceil(t*e)/e)},percent:t=>{const e=au(t?.[0]??"0","percent");return t=>("number"!=typeof t&&ou("percent"),`${(100*t).toFixed(e)}%`)},unit:cu(t=>{const e=t?.[0]??eu("unit");return t=>String(t)+e}),date:t=>{const e=t?.[0];return t=>(t instanceof Date||su("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||su("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||su("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||su("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||su("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!t,truthy:t=>t=>!!t,defaults:(t,e)=>{const n=t?.[0]??eu("defaults"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t||o},coalesce:(t,e)=>{const n=t?.[0]??eu("coalesce"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t??o},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),nullIfEmpty:t=>t=>""===t?null:t},du={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]},hu=uu,fu=uu;let pu=!1;const mu={name:"formats",install(){pu||(pu=!0,gt("input",fu,du,ru),gt("output",hu,du,ru))}};function gu(t){return-1!==t.indexOf(q)}function yu(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+a;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(gu(o))return null;const s=o.slice(1).split(a);return s[0]===l||s.some(t=>0===t.length)?null:o}function bu(t){return 0===t.length?t:a+_u(t.slice(1))}function wu(t,e,n){const o=a+t.repeat,s=e.length<=n.length?e:n,r=e.length<=n.length?n:e;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 t=0;t<i.length;t+=o.length)if(!i.startsWith(o,t))return!1;return!0}function vu(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(a,o-1))if(wu(t,e,n.slice(0,o)))return!0;return!1}function _u(t){const e=t.split(a);for(let t=0;t<e.length;t++)e[t]===l||Number.isNaN(Number(e[t]))||(e[t]=l);return e.join(a)}function $u(t,e){const n=t.repeat.split(a),o=a+t.repeat;let s=e;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===a+t.repeatList+a+"length")return!0;for(let t=1;t<n.length;t++)if(s===a+n.slice(0,t).join(a))return!0;return!1}function Su(t,e,n){n<0&&Z(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=a+t.repeat;const s=o+e;let r=0;for(const t of s.split(a))t===l&&r++;return r>c&&Z(`[wcs/recursion-depth-exceeded] Recursion on "${t.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 xu(t,e){return Su(t,"",e)}function Pu(t,e,n){if(!n.startsWith(t.anchor))return null;if(e.length>0&&!n.endsWith(e))return null;if(n.length<t.anchor.length+e.length)return null;const o=n.slice(t.anchor.length,n.length-e.length);if(0===o.length)return 0;const s=a+t.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function ku(t,e,n){const o=t.recursionRegistry,s=yu(o.spec,n);null===s&&Z(zi(n,o.spec.recursiveAnchor));const r=function(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=e.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(t,e){const n=t.spec;if(!e.startsWith(n.anchor))return null;const o=a+n.repeat;let s=0,r=n.anchor.length;for(;e.startsWith(o,r);)r+=o.length,s++;return r!==e.length&&46!==e.charCodeAt(r)?null:s}(e,n.pathInfo.path)}(e,o);return null===r&&Z(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function Iu(t,e,n,o,s){const r=o.spec,i=[],l=new Map,c=[],u=r.repeatList,d=r.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void i.push(bn(t,n));const s=m(o[e],n,null).rows;for(let n=0;n<s.length;n++)p(t,e+1,s[n])};function m(o,s,i){const a=bn(o,s),c=Ke(n.stateElement,a),d=Nl(t,a,e,n),f=null===i?null:((t,e,n)=>{if(!Array.isArray(e)||0===e.length)return null;const o=e;return h.has(o)&&Z(`[wcs/recursion-cycle] "${t}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&Z(`[wcs/recursion-shared-list] "${t}" 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 "${u}" array.`),o})(o.path,d,i),p=jr(s,Ae(c),d);return l.set(c,Array.isArray(d)?d:[]),null!==f&&null!==i&&i.add(f),{rows:p.newIndexes,tracked:f}}const g=(t,e,n)=>{const{rows:r,tracked:l}=m(e,n,f);if(0===r.length)return;const d=(t=>{const e=c[t];if(void 0!==e)return e;const n=o.concretePathAt(s,t),r=0===s.length?n:o.concretePathAt("",t),i={nodePath:r,concretePathInfo:nt(n),childListPathInfo:nt(r+a+u)};return c[t]=i,i})(t),y=l;h.add(y);const b=d.concretePathInfo.wildcardCount===t+1;for(let e=0;e<r.length;e++){const n=r[e];b?i.push(bn(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,nt(d),null);for(const[t,e]of l)Ee(t,e);return i}const Nu={write(t,e){if(!0!==t.hasRecursion)return cl;const n=t.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);return null!==n&&Z(`[wcs/recursion-readonly] "${e.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(t,e,n,o){if(!0!==t.stateElement.hasRecursion)return cl;if("$getAll"===e)return(e,s)=>{if(gu(e)){if(void 0!==s)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=yu(r.spec,o);null===i&&Z(zi(o,r.spec.recursiveAnchor)),Array.isArray(s)||Z(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&Z(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=Iu(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Nl(t,a[o],e,n));return l}(o,n,t,e,s);e=ku(t.stateElement,t,e)}return rc(o,0,n,t)(e,s)};if("$setAll"===e)return(e,s,r,i)=>gu(e)?function(t,e,n,o,s,r,i){wl(n);const a=n.stateElement.recursionRegistry,l=yu(a.spec,o);null===l&&Z(zi(o,a.spec.recursiveAnchor));const c=bu(l);Array.isArray(s)||Z(Bi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&Z(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&Z(Bi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&Z(Bi(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(t,e,n){$u(t,n)&&Z(`[wcs/recursion-structural-write] "${e}" writes the recursion structure itself (a node, its "${t.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 u=a.conflictingRecursiveGetter(c);null!==u&&Z(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${u}", 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 d=Iu(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(nc(t,d[o],r,e,n),h++);return h}(o,n,t,e,s,r,i):ac(o,0,n,t)(e,s,r,i);if(36!==e.charCodeAt(0)&&gu(e)){const s=$l(ku(t.stateElement,t,e)),r=ic(o,s,n,t);return Nl(o,bn(s.pathInfo,r),n,t)}return cl}};let Au=!1;function Eu(t,e){"string"==typeof e&&0!==e.length||Z(`[wcs/recursion-declaration-invalid] ${H} ${t} must be a non-empty string.`);const n=e.split(a);n.some(t=>0===t.length)&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain empty path segments.`),n.length<2&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must name a list element: a property path ending with "${a}${l}" (for example "nodes${a}${l}").`),n[n.length-1]!==l&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must end with "${a}${l}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===l&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must have exactly one "${l}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===q&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain "${q}" — the declaration is what gives "${q}" its meaning.`),isNaN(Number(n[o]))||Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const Cu=new WeakSet;function Tu(t){return"function"==typeof t.get&&Cu.has(t.get)}const Mu="[wcs/recursion-declaration-invalid]";class Ou{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(t,e){this.spec=t;const n=_c(e);for(const[e,o]of Object.entries(n)){if(!gu(e))continue;"function"==typeof o.set&&Z(`${Mu} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&Z(`${Mu} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=yu(t,e);null===n&&Z(zi(e,t.recursiveAnchor)),0===n.length&&Z(`${Mu} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${a}total"), not the node.`),$u(t,bu(n))&&Z(`${Mu} "${e}" names the recursion structure itself (a node, its "${t.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 "${t.recursiveAnchor}${a}total").`),this._definitions.set(e,{recursivePath:e,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(t){for(const[e,n]of Object.entries(t)){if(gu(e)||Tu(n))continue;const t=this._matchExpansion(e);null!==t&&Z(`${Mu} "${e}" is already defined on the state, so the recursive getter "${t}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const t=Array.from(this._definitions.values());for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)wu(this.spec,t[e].suffix,t[n].suffix)&&Z(`${Mu} "${t[e].recursivePath}" and "${t[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(t){for(const e of this._definitions.values())if(vu(this.spec,e.suffix,t))return e.recursivePath;return null}recursiveGetterOwningPath(t){const e=this._ownerByPathInfo.get(t);if(void 0!==e)return e;const n=this.recursiveGetterOwning(t.path);return this._ownerByPathInfo.set(t,n),n}recursiveGetterOwning(t){const e=this._accessors.get(t);if(void 0!==e)return e.recursivePath;const n=_u(t),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 t=n.lastIndexOf(a);null===s&&t>this.spec.anchor.length;t=n.lastIndexOf(a,t-1))s=this._matchExpansion(n.slice(0,t))}return this._ownerByPath.set(n,s),s}_matchExpansion(t){for(const e of this._definitions.values())if(null!==Pu(this.spec,e.suffix,t))return e.recursivePath;return null}materializeForPathInfo(t,e){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(e);if(void 0!==n)return n;const o=this.materializeFor(t,e.path);return this._accessorByPathInfo.set(e,o),o}materializeFor(t,e){const n=this._accessors.get(e);if(void 0!==n)return n;if(!e.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const t of this._definitions.values()){const n=Pu(this.spec,t.suffix,e);null!==n&&(null!==o&&Z(`"${e}" matches both "${o.recursivePath}" and "${t.recursivePath}".`),o=t,s=n)}return null===o?null:this._define(t,o,s,e)}_define(t,e,n,o){const s=t.findStateDescriptor(o);void 0===s||Tu(s)||Z(`"${o}" is already defined on the state, so the recursive getter "${e.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:e.recursivePath,depth:n}),i=e.get,a=function(){return i.call(this)};var l;return l=a,Cu.add(l),t.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(t,n),this._accessors.set(o,r),r}_registerListPaths(t,e){for(const n of function(t,e){const n=[];n.push(t.anchorList);for(let o=0;o<e;o++)n.push(xu(t,o)+a+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){const n=new Set(this._accessors.keys());return function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&Tu(n)&&delete e[t]}for(const e of[t.staticDependency,t.dynamicDependency]){for(const t of n)e.delete(t);for(const[t,o]of e){let s=null;for(let t=0;t<o.length;t++)n.has(o[t])?s??=o.slice(0,t):s?.push(o[t]);null!==s&&(0===s.length?e.delete(t):e.set(t,s))}}}}(t,e,n),n}concretePathAt(t,e){let n=this._concreteBySuffix.get(t);void 0===n&&(n=[],this._concreteBySuffix.set(t,n));let o=n[e];return void 0===o&&(o=Su(this.spec,t,e),n[e]=o),o}accessorFor(t){return this._accessors.get(t)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const Lu="recursionSpec",Ru="recursionRegistry",ju={order:5,validateEarly(t,e,n){const o=function(t){const e=t[H];if(void 0===e)return null;"object"==typeof e&&null!==e||Z(`[wcs/recursion-declaration-invalid] ${H} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(e);0===n.length&&Z(`[wcs/recursion-declaration-invalid] ${H} must declare exactly one anchor; it is empty.`),n.length>1&&Z(`[wcs/recursion-declaration-invalid] ${H} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Eu("anchor",o),"string"!=typeof s&&Z(`[wcs/recursion-declaration-invalid] ${H} entry "${o}" must map to the repeating sub-path as a string (for example "children${a}${l}").`),Eu("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(a)),i=s.slice(0,s.lastIndexOf(a)),c=r+a+q;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:c,anchorList:r,repeatList:i})}(e);n.set(Lu,o),n.set(Ru,null===o?null:new Ou(o,e))},preCommit(t,e,n){const o=t.recursionRegistry;if(null!==o)for(const e of o.forgetGenerated(t,n.get("previousState")))t.addGeneratedPath?.(e);const s=n.get(Ru)??null;t.setRecursionRegistry?.(s),null!==s&&t.attachAddressHooks?.("recursion",H)},apply(t,e,n){const o=n.get(Lu)??null;null!==o&&t.addListPath(o.anchorList)}};let Du=!1;const Wu={name:"recursion",install(){Du||(Du=!0,Au||(Au=!0,hl("recursion",Nu)),gl("recursion",ju))}},zu={written:function(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let Bu=!1;function Fu(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function Hu(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function qu(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function Uu(t){return t.startsWith("$")}function Vu(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function Gu(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||Z(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||Z(`${e} entries must be non-empty strings.`),t.startsWith("$")&&Z(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&Z(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function Ku(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||Z(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Gt(t);null!==r&&"function"==typeof r.define||Z(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&Z(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const t of Array.from(e.childNodes))i.content.appendChild(a.importNode(t,!0));const l=e.mode,{bindables:c,commands:u,streamBackedBindables:d}=function(t){sl(t);const e=Gu(t,O)??[],n=Gu(t,L)??[],o=_c(t),s=function(t){const e=t[z];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}Z(`${O} entry "${t}" is not declared on the state.${rt(t,Vu(o,"value"))}`)}"function"==typeof e.value&&Z(`${O} entry "${t}" is a method. Declare it in ${L} instead.`)}for(const t of n){const e=o[t];void 0===e&&Z(`${L} entry "${t}" is not declared on the state.${rt(t,Vu(o,"method"))}`),"function"!=typeof e.value&&Z(`${L} entry "${t}" is not a method. Declare it in ${O} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||u.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(K))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=Gt(this._shadow);return null!==t&&Kt(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(m.bindableEventMap).length>0){const e=t.querySelector(p);e?(Bu||(Bu=!0,hl("dcc",zu)),e.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${O} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=_c(n);for(const[t,e]of Object.entries(g)){if(Uu(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=qu(t,o)}else n.get=Fu(t),n.set=Hu(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:Fu(t),set:Hu(t)});r.define(s,m)}const Ju={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(K)?async function(t,e,n){const o=t;try{o.hasAttribute("bind-component")&&Z(`"bind-component" cannot be used inside a [${K}] host. DCC state comes from the template, not from a component property.`);const s=await async function(t,e){try{if(t.hasAttribute("src")){const e=t.getAttribute("src");if(e.endsWith(".js"))return await Za(e);Z(`DCC: Unsupported src type: ${e}`)}const n=t.querySelector('script[type="module"]');if(n)return await Ya(n,e.tagName.toLowerCase());Z(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}catch(t){Z(`DCC: Failed to load state: ${t}`)}}(o,e);Ku(e,n,s),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}(t,e.host,e):null}};let Qu=!1;function Xu(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function Yu(t,e){for(const n of t)if(Xu(e,n.innerSegments))return n;return null}function Zu(t,e){const n=e.slice(t.innerSegments.length);return 0===n.length?t.outerPathInfo.path:t.outerPathInfo.path+a+n.join(a)}const td=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function ed(t,e,n){const o=td.get(t);return void 0===o?null:(...t)=>{const s=t.slice();for(let t=0;t<o.length;t++){const n=o[t];"string"==typeof s[n]&&(s[n]=e(s[n]))}return n(s)}}const nd=new WeakMap;function od(t,e,n){let o=nd.get(t);void 0===o&&(o=new Map,nd.set(t,o));null!=o.get(e)&&Z(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function sd(t,e){if(null===t)return!1;const n=nd.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+a)||t.startsWith(e+a))return!0;return!1}const rd=new WeakMap,id=[];function ad(t,e,n,o){if(e.length>0){const s=n.split(a),r=Yu(e,s);if(null!==r)return o&&r.readonly&&Z(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${$}.${r.innerSegments.join(a)}#${m}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${m} from the injection.`),Zu(r,s)}return t+a+n}function ld(t,e,n){let o=-1,s=null;for(const t of e){const e=t.outerPathInfo.path;e.length<=o||(n===e?(o=e.length,s=t.innerSegments.join(a)):n.startsWith(e+a)&&(o=e.length,s=t.innerSegments.join(a)+n.slice(e.length)))}if(t.length>o){if(n===t)return"";if(n.startsWith(t+a))return n.slice(t.length+1)}return s}function cd(t,e,n=id){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)=>e[o](ad(t,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>e.$setAll(ad(t,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>e.$resolve(ad(t,n,o,s.length>1),...s);const o=ed(s,e=>ad(t,n,e,!1),t=>e[s](...t));return null!==o?o:e[s]}return e[ad(t,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(e[s]=r,!0):(e[ad(t,n,s,!0)]=r,!0)),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const ud=new WeakMap,dd=[],hd=new WeakMap,fd=new WeakSet;function pd(t){console.error(`[@wcstack/state] volume "${t.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>.`),t.onGrafted(null)}let md=null,gd=0;const yd=["$watch",z,"$scan","$listKeys",C,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],bd=new Set;function wd(t,e){const n=t.stateObject[e];if("function"==typeof n)try{const o=t.component[t.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function vd(t){const e=t.indexOf(a);return-1===e?t:t.slice(0,e)}function _d(t,e){const n=Yu(t.entries,e);return null===n?null:Zu(n,e)}function $d(t,e){return t.markerBasePath+a+e}function Sd(t,e,n,o){let s=t.accessorBySuffixByMarkerParent.get(e);void 0===s&&(s=new Map,t.accessorBySuffixByMarkerParent.set(e,s));const r=e+a+n;s.set(n,{accessorName:o,indexShift:nt(r).wildcardCount-nt(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(r),t.addedGetterPaths.add(r))}function xd(t,e){return!t.injectedKeys.has(e)&&(!t.getterKeys.has(e)&&"function"==typeof t.stateObject[e]||!t.mappedKeys.has(e)&&Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function Pd(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(a)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${vd(e)}: path") or declare the key on the component state.`}const kd=/^\$(\d+)$/;function Id(t,e){if(!t.hasReadonlyEntries)return null;const n=e[0];if("$"===n||"#"===n)return null;if(t.getterKeys.has(e)||t.setterKeys.has(e))return null;const o=vd(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||xd(t,o))return null;const s=function(t,e){return Yu(t.entries,e)}(t,e.split(a));return null!==s&&s.readonly?s:null}function Nd(t,e){const n=Id(t,e);if(null!==n){const o=0===n.innerSegments.length?"":a+n.innerSegments.join(a);Z(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${m}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${m} from the mount.`)}return Ad(t,e)}function Ad(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(a);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===l){o=t;break}if(-1===o)return Sd(t,t.markerBasePath,e,e),$d(t,e);if(xd(t,n[0]))return Sd(t,t.markerBasePath,e,e),$d(t,e);const s=n.slice(0,o+1),r=n.slice(o+1),i=_d(t,s);null===i&&Z(Pd(t,e)),0===r.length&&Z(`Wildcard-terminal accessor "${e}" on mounted <${t.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 c=i+a+t.marker;return Sd(t,c,r.join(a),e),c+a+r.join(a)}(t,e);const o=vd(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return $d(t,e);if(xd(t,o))return $d(t,e);const s=_d(t,e.split(a));if(null!==s)return s;Z(Pd(t,e))}const Ed=new Set(["prop","radio","checkbox"]);function Cd(t,e,n,o,s){if(void 0===o)return;const r=nt(n).wildcardCount-nt(e).wildcardCount;return 0===r?o:(s.length<r&&Z(`Cannot resolve "${e}" 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 Td=new WeakMap,Md=new WeakMap,Od=new WeakMap,Ld=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)}),Rd=new WeakMap;function jd(t){return Rd.get(t)??null}let Dd=!1;function Wd(t){return zd(t).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join(a),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]}))}function zd(t){const e=Od.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}function Bd(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=Od.get(t);if(void 0===o)return null;const s=e.indexOf(a,n),r=-1===s?e.slice(n):e.slice(n,s),i=o.get(r);if(void 0===i)return null;const l=i.deref();return void 0===l?(o.delete(r),null):l}const Fd=new WeakMap,Hd=new Set;function qd(t,e,n,o){let s=Fd.get(t);if(void 0===s){if(!o)return null;s=new Map,Fd.set(t,s)}let r=s.get(e);if(void 0===r){if(!o)return null;r=new Map,s.set(e,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 Ud(t,e){if(!t.component.isConnected)return!1;const n=we(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function Vd(t,e,n,o){const s=qd(t,e,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&Ud(n,e)?n:null}(r,o);if(null!==t)return{record:t,entry:r.entry}}let i=null,l=null;for(const t of s.holders){const r=t.ref.deref();void 0!==r?Ud(r,o)&&(null!==l&&Z(`[wcs/mount-export-ambiguous] "${e}${a}${n}" is exported by two mounted components on the same instance: <${l.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=t,l=r):s.holders.delete(t)}return null===i||null===l?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:l,entry:i.entry})}function Gd(t){const e=t.parentStateElement,n=we(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[Oe](n,()=>{t.$postUpdate(o.exportedPath)})})}const Kd=new WeakMap;class Jd{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,s,r){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return bn(nt(this.markerParentPath+a+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(Ad(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,s,...r)=>{const i=r.length>0?Nd(t,e):Ad(t,e),a=Cd(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a="$setAll"===s?Nd(t,e):Ad(t,e),l=Cd(0,e,a,r,n);return o[s](a,l,...i)}}const t=this.record,n=this.receiver,o=ed(e,e=>Ad(t,e),t=>n[e](...t));return null!==o?o:this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return xl(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[Ad(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||Z(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),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(t,e)?(t[e]=n,!0):(this.receiver[Nd(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return Ad(this.record,e),!0}catch{return!1}}}function Qd(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=Kd.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Kd.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(i,new Jd(t,s,e.listIndex,r,n,o))}function Xd(t,e){const n=function(t){return Td.get(t)??null}(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&Z(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&us(e).dispose(),function(t,e){Dd||(Dd=!0,be=t=>Td.has(t)?t.host:null),Td.set(t,e),Rd.set(e,t);let n=Od.get(e.parentStateElement);void 0===n&&(n=new Map,Od.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=Md.get(e.component);void 0===o&&(o=new Map,Md.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&Ld.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}(e,t),e instanceof ShadowRoot&&function(t,e){const n=ha.get(t);if(void 0!==n){if(n===e)return;Z("A state tree is already registered on this root.")}ha.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const s=kd.exec(e.statePathName);if(null!==s){const r=function(t,e){return void 0===e?t.delta:nt(Ad(t,e)).wildcardCount-nt(e).wildcardCount}(t,n);o=0===r?e.statePathName:`$${Number(s[1])+r}`}else if(o=Ad(t,e.statePathName),"for"===e.bindingType){const n=nt(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+a+l,n)}const r=e.propModifiers,i=null===s&&Array.isArray(r)&&Ed.has(e.bindingType??"")&&!r.includes(m)&&null!==Id(t,e.statePathName);return o!==e.statePathName||i?{...e,statePathName:o,statePathInfo:nt(o),...i?{propModifiers:[...r,m]}:{}}:e}(t,e,n);X(e);const o=we(t.component);Fa(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),sa(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=Ad(t,n)}catch{continue}const o=e.indexOf(a+t.marker);if(-1===o)continue;const s=e.slice(0,o+1+t.marker.length),r=e.slice(s.length+1),i=e.slice(0,o)+a+r,l=nt(i);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:e,exportedPath:i};t.exports.set(i,c),qd(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,i),$c?.markExported(t.parentStateElement,i)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=we(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const s=`${n}|${o.exportedPath}`;if(Hd.has(s))continue;const r=nt(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[Oe](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Hd.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.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.`))}}(t),Gd(t),o=e,s=Promise.resolve(),fa.set(o,s),s.then(()=>wa(o),()=>{})}function Yd(t,e){const n=us(e),o=we(t.component);n.forEachActiveBindingNode(t=>ve(t,o)),na(n.rebindAddresses()),Gd(t)}function Zd(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const th={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const s=Bd(t,e.pathInfo.path);if(null!==s)return Qd(s,e,n,o)}return cl},readMissing(t,e,n,o,s){if(null===n){if(sd(t.rootNode??null,e.pathInfo.path))return;return cl}if(!0===t.hasMounts){const n=Vd(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s){const r=Qd(t,bn(nt(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(n.record,n.entry,e.listIndex,o,s)}return cl},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=rd.get(t);if(void 0===n||0===n.size)return null;const o=e+a;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&Z(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return cl},writeMissing(t,e,n,o,s,r,i){if(!0===t.hasMounts){const n=Vd(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s,r){const i=Qd(t,bn(nt(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(n.record,n.entry,e.listIndex,s,r,i)}return cl},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=Bd(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(a,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const s=-1===o?e:e.slice(0,o),r=-1===o?"":e.slice(o+1),i=t.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:t.delta}(t,o)}return 0},handlerScope(t,e,n,o,s){if(!0!==t.hasMounts)return s;const r=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=Td.get(n);if(void 0!==t)return t;n=n.parentNode}return Td.get(e)??null}(e,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(t,e,n){const o=function(t){return ud.get(t)??dd}(t);for(const s of o){const o=new Set,r={};for(const n of e){if(n.absolutePathInfo.stateElement!==t)continue;const e=n.absolutePathInfo.pathInfo.path;if(-1!==e.indexOf("#"))continue;const i=ld(s.mountPath,s.injections,e);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const t=nn(n.listIndex,a);(r[i]??=[]).push(t)}}if(o.size>0)try{s.callback.call(cd(s.mountPath,n,s.injections),Array.from(o),r)}catch(t){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>sd(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(function(t){const e=Od.get(t);return void 0!==e&&e.size>0}(e))for(const n of zd(e)){if(!Zd(n.component,t))continue;const e=jd(n);null!==e&&Yd(n,e)}}(e,t)}};let eh=!1;const nh=new WeakMap;function oh(t){let e=nh.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},nh.set(t,e)),e}function sh(t,e){null!==e.slotRootNode&&(function(t,e,n){const o=nd.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function rh(t,e,n){if(e.slotRootNode===n)return!0;const s=e.mountPath;try{od(n,s,t)}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 ga(n)?.markHasVolume?.(),e.slotRootNode=n,!0}const ih={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=oh(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{od(n,e.mountPath,t),ga(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,mc}return async function(t,e){const n=t,s=t.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(t){0===t.length&&Z('"mount" requires a non-empty tree path.');const e=nt(t);for(const n of e.segments)0===n.length&&Z(`"mount" path "${t}" has an empty segment.`),n===l&&Z(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&Z(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),i=function(t,e){const n=[],s=new Set;let r;try{r=Mt(t)}catch(t){Z(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${e}"> has an invalid ${o.bindAttributeName}: ${t instanceof Error?t.message:String(t)}`)}for(const t of r){if(t.propSegments[0]!==$)continue;const r=t.propSegments.slice(1),i=t.statePathInfo,a=n=>Z(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${e}"> "${t.propName}: ${t.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==l&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${$}.<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)."),(t.inFilters.length>0||t.outFilters.length>0)&&a("an injection takes no filters."),t.propModifiers.some(t=>t!==m)&&a(`an injection accepts only #${m}.`),s.has(r[0])&&a(`"${r[0]}" is injected twice.`),s.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:t.propModifiers.includes(m)})}return n.sort((t,e)=>e.innerSegments.length-t.innerSegments.length),n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&Z('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),od(s,r,t),ga(s)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=s}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===ga(s)&&function(t,e){const n=()=>{if(null!==ga(t))return;const n=t.querySelectorAll(o.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> 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=t.ownerDocument??t;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&sh(t,e),t.settleInitialization()};let c;try{await Promise.resolve(),c=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void a(null)}const u=t.connectedRootNode??null;null!==u&&rh(t,e,u)?function(t,e,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};null===e?(Th(),function(t,e){if(fd.has(t))return void pd(e);let n=hd.get(t);void 0===n&&(n=[],hd.set(t,n)),n.push(e)}(t,a)):Eh(e,a)}(u,ga(u),r,c,a,()=>rh(t,e,u),i):a(null)}(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=oh(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&ga(n)===e.graftInfo.rootStateElement&&Nh(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==nh.get(t)?.initializing)return;const e=t.getAttribute("mount");Z(`Cannot replace the state of <${o.tagNames.state} mount="${e}"> 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 "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){fd.add(t);const e=hd.get(t);if(void 0!==e){hd.delete(t);for(const t of e)pd(t)}}(e)},initializeFailureCleared(t,e){!function(t){fd.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=oh(t);return null!==e.graftInfo&&Nh(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,sh(t,e)),t.clearConnectedRootNode(),!0}};let ah=!1;const lh=new WeakMap;function ch(t,e){let n=lh.get(t);n||(n=new Set,lh.set(t,n)),n.add(e)}const uh=new WeakMap,dh=new WeakMap,hh=new WeakMap,fh=new WeakMap,ph={isComplete:function(t,e){return!0===lh.get(t)?.has(e)},isDeclared:function(t,e){return!0===uh.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=dh.get(t);o||(o=new Map,dh.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=hh.get(t);o||(o=new Map,hh.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)},rememberOverwrittenValue:function(t,e,n,o){let s=fh.get(t);s||(s=new Map,fh.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}};const mh=new WeakMap;class gh{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=mh.get(t);return n?n.get(e)??null:null}(t,e)??Z("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const yh=t=>()=>t;function bh(t,e,n,o){!function(t,e,n){let o=mh.get(t);o||(o=new Map,mh.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(function(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}(o));const s=function(t,e){const n=new gh(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:yh(s),enumerable:!0,configurable:!0}),ch(e,n),wh(e,n)}function wh(t,e){if(M in t){const n=t[M];"function"==typeof n?n.call(t,e).catch(t=>{Z(`Error in ${M}: ${t instanceof Error?t.message:String(t)}`)}):Z(`${M} is not a function.`)}}const vh=new Set;function _h(t,e){vh.has(t)||(vh.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function $h(t){const e=t.rootEntry,n=we(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Oe](n,()=>{o=t[e.outerPathInfo.path]})}),o}const Sh=new WeakMap;function xh(t,e){t.landInitialization(),Z(e)}async function Ph(t,e){const n=t;if(n.hasAttribute("bind-component")){const i=n.parentNode,l=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,c=l?Ut(l):null;null!==l&&null!==c||Z(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||l.hasAttribute(o.bindAttributeName)||xh(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const u=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&u.push('<script type="module">'),u.length>0&&Z(`"bind-component" cannot be combined with ${u.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(t,e){let n=uh.get(t);n||(n=new Set,uh.set(t,n)),n.add(e)}(l,d);const h=Gt(l);null===h&&Z(`CustomElementRegistry is unavailable for <${c}>.`),await h.whenDefined(c.toLowerCase()),l.hasAttribute(o.bindAttributeName)&&await Ft(l),d in l||Z(`Component does not have property "${d}" for state binding.`);let f=l[d];"object"==typeof f&&null!==f||Z(`Component property "${d}" is not an object for state binding.`);const p=function(t,e){const n=dh.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(l,d);if(void 0!==p&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=ae(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(l,d)&&(l[d]=p,f=p),e.boundComponent=l,e.boundComponentStateProp=d,t.setBoundComponent(l,d),i instanceof ShadowRoot||(ae(l)??[]).some(t=>t.propSegments[0]===d)||xh(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${d}: path").`),l.hasAttribute(o.bindAttributeName)){const o=(ae(l)??[]).filter(t=>t.propSegments[0]===d);if(o.length>0){const u=ga(l.getRootNode())??xh(t,`No state tree found on this root for mount host <${c}>.`);let h=(s=l,r=d,Md.get(s)?.get(r)??null);const p=null!==h;if(null===h&&(function(t,e,n){const o=fh.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;fh.get(t).delete(e)}}(l,d,f),h=function(t,e,n,o,s,r=new Set){0===n.length&&Z(`Cannot build a mount record without host bindings for "${e}".`),sl(s);const i=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(a);l.has(n)&&Z("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(m)};i.push(o),0===e.length&&(c=o)}i.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++gd,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=_c(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(s),p=new Set;for(const t of i)1===t.innerSegments.length&&p.add(t.innerSegments[0]);const g={};for(const t of Object.keys(s))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof s[t]&&(r.has(t)||p.has(t)||(g[t]=s[t]));return{id:u,marker:d,component:t,stateProp:e,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?d:c.outerPathInfo.path+a+d,stateObject:s,getterKeys:h,setterKeys:f,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(t=>t.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(l,d,o,u,f,function(t,e){return hh.get(t)?.get(e)}(l,d)),function(t){!function(t){const e=t.component.tagName.toLowerCase(),n=t.stateProp;let o=null;for(const s of t.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=_c(t.stateObject);const i=o[r];let l;if(t.getterKeys.has(r)||t.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)l="an accessor";else if("function"==typeof i?.value)l="a method";else{if(t.mappedKeys.has(r)||t.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(t.stateObject,r))continue;l="an own data key"}const c=s.innerSegments.join(a);_h(`${e}|${n}|${c}|entry`,`<${e}>.${n} declares "${r}" as ${l}, which hides the mounted entry "${n}.${c}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(t);const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp;let s,r=!1;for(const i of e){if(null===t.rootEntry)continue;if(r||(s=$h(t),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const e=t.rootEntry.outerPathInfo.path;_h(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${e}.${i}" (${o}: ${e}). Remove the default to read the tree, or rename it to keep it private.`)}}(h)),e.mountRecord=h,n.parentNode!==i)return;try{Xd(h,i instanceof ShadowRoot?i:l)}catch(e){throw t.landInitialization(),e}if(!p){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=we(t.component);let s;return e[Oe](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(t,e,n){const o=t.parentStateElement,s=(t,e)=>{let s;return o.createState(t,t=>{s=n(t,()=>e(t))}),s};return"$postUpdate"===e?e=>s("readonly",n=>n.$postUpdate(Ad(t,e))):(n,o,...r)=>{const i="$setAll"===e||"$resolve"===e&&r.length>0,a=i?Nd(t,n):Ad(t,n),l=we(t.component)?.listIndex.indexes??[],c=Cd(0,n,a,"$resolve"===e?o??[]:o,l);return s(i?"writable":"readonly",t=>t[e](a,c,...r))}}(t,s,n);const r=ed(s,e=>Ad(t,e),t=>{let o;return e.createState("readonly",e=>{o=n(e,()=>e[s](...t))}),o});if(null!==r)return r;let i;return e.createState("readonly",e=>{i=n(e,()=>e["$"===s[0]?s:Ad(t,s)])}),i},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:Nd(t,s)]=r})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return Ad(t,n),!0}catch{return!1}}})}(h);Object.defineProperty(l,d,{get:()=>t,enumerable:!0,configurable:!0}),ch(l,d)}return wh(l,d),function(t){const e=yd.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(q)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;bd.has(n)||(bd.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.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.`))}(h),void wd(h,"$connectedCallback")}}bh(t,e.boundComponent,e.boundComponentStateProp,f)}var s,r}const kh={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=Sh.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Sh.set(t,e)),e}(t);return Ph(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=Sh.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&Yd(n,o)}),wd(n,"$connectedCallback"),!0},disconnecting(t){const e=Sh.get(t);return void 0!==e&&null!==e.mountRecord&&(wd(e.mountRecord,"$disconnectedCallback"),Gd(e.mountRecord),t.clearConnectedRootNode(),!0)}};let Ih=!1;function Nh(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(cd(t.mountPath,o,t.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function Ah(t,e,n,o=[]){sl(n),function(t,e,n,o){const s=0===o.length?null:_c(n);for(const t of o){const n=t.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||Z(`[wcs/mount-path-invalid] Volume "${e}" declares "${n}" as an accessor or a method and also injects it ("${$}.${n}: ${t.outerPathInfo.path}"). Rename one of them.`)}const r=n[B];if(void 0!==r){"object"==typeof r&&null!==r||Z(`${B} must be an object mapping state paths to handler functions.`);const t=Cc(e);for(const[e,n]of Object.entries(r))"function"!=typeof n&&Z(`${B} entry "${e}" must be a function.`),t.assertValidPath(e)}const i=n[U];if(void 0!==i){"object"==typeof i&&null!==i||Z(`${U} 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)&&Z(`${U} entry "${n}" must map a list path to a field name or a key function.`);const r=ad(e,o,n,!1);t.listKeys?.has(r)&&Z(`${U} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[z]&&Z(`Volume "${e}" declares ${z}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&Z(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[H]&&Z(`Volume "${e}" declares ${H}, 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 t of Object.keys(_c(n)))-1!==t.indexOf(q)&&Z(`Volume "${e}" declares "${t}", which uses "${q}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n,o);const{data:s,accessors:r}=function(t,e){const n={},o=new Map;for(const[s,r]of Object.entries(_c(t)))s.startsWith("$")||e.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(t=>t.innerSegments[0]))),i=nt(e),l=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(l)return;Z(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],s=""===n?o in t:void 0!==t[n+a+o];n=""===n?o:n+a+o,s||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(l)return;Z(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=s}),function(t,e){let n=rd.get(t);void 0===n&&(n=new Set,rd.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,s]of r){const r=e+a+n,i=s.get,l=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(cd(e,this,o))}),"function"==typeof l&&(c.set=function(t){l.call(cd(e,this,o),t)}),t.defineTreeAccessor(r,c)}!function(t,e,n,o){const s=n[B];if(void 0!==s){const n=Cc(e),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=ad(e,o,n,!1),c=function(t,n,...s){l.call(cd(e,this,o),t,n,...s)};r.push({path:s,pathInfo:nt(s),handler:c,order:1e6+a++}),i.add(s),t.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(t,r),t.addVolumeWatchPaths?.(i),n.start(t))}const r=n[U];if(void 0!==r){const n=new Map;for(const[t,s]of Object.entries(r))n.set(ad(e,o,t,!1),s);t.mergeVolumeListKeys?.(n)}const i=n[C];"function"==typeof i&&(function(t,e){let n=ud.get(t);void 0===n&&(n=[],ud.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,injections:o,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}(t,e,n,o);const c=n.$connectedCallback;return"function"==typeof c&&t.createState("writable",t=>{let n;try{n=c.call(cd(e,t,o))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n,injections:o}}function Eh(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=Ah(t,e.mountPath,e.volumeState,e.injections)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}let Ch=!1;function Th(){var t;Ch||(Ch=!0,eh||(eh=!0,hl("scopes",th),Tc=Wd),ah||(ah=!0,bc("scopes",ih)),Ih||(Ih=!0,bc("bindComponent",kh),hs=ph),md=Eh,t=Mh,ma.includes(t)||ma.push(t))}function Mh(t,e){(function(t){const e=nd.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){fd.delete(t);const n=hd.get(t);if(void 0===n||0===n.length||null===md)return;hd.delete(t);const o=md;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const Oh={name:"scopes",install(){Th(),Qu||(Qu=!0,bc("dcc",Ju))}},Lh=/^@@wcs-(?:for|if|elseif|else):[^-]/,Rh=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,jh=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Dh=/^@@wcs-text-start:(.+)$/;function Wh(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function zh(t,e){const n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const t=n.currentNode;e(t.data)&&o.push(t)}return o}const Bh=t=>Lh.test(t),Fh=t=>Rh.test(t);function Hh(t){const e=t.fragment.cloneNode(!0);for(const n of t.nodeInfos){const o=La(oe(t.fragment,n.nodePath));if(null===o)continue;const s=oe(e,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return e}class qh extends vc{_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(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=Oc.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=o.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(e,t);if(void 0!==o&&"function"==typeof o.get)continue;const s=e[t];"function"!=typeof s&&(n[t]=s)}return n}static buildContent(t,e,n){const s=n??t.ownerDocument,r=document.createElement("script");r.setAttribute("type","application/json"),r.textContent=Wh(JSON.stringify(e)),t.appendChild(r);for(const[e,n]of function(t){const e=new Map,n=[t];for(;n.length>0;)for(const t of zh(n.shift(),Bh)){const o=t.data,s=o.slice(o.indexOf(":")+1);if(e.has(s))continue;const r=Sa(s);null!==r&&(e.set(s,r),n.push(r.fragment))}return e}(s)){const s=document.createElement("template");s.setAttribute("id",e);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i),s.content.appendChild(Hh(n)),t.appendChild(s)}const i=t.ownerDocument,a=Array.from(Pi);if(a.length>0){const e={};for(let t=0;t<a.length;t++){const n=a[t];if(!n.isConnected||n.ownerDocument!==i)continue;const o=xi(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const t of o)r[t.propName]=t.value;e[s]=r}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=Wh(JSON.stringify(e)),t.appendChild(n)}}ki()}static removeBlockBoundaryComments(t){for(const e of zh(t,t=>Rh.test(t)||jh.test(t)))e.remove()}static removeStructuralComments(t){for(const e of zh(t,Bh))e.remove()}static restoreTextBindings(t){for(const e of zh(t,t=>Dh.test(t))){const t=Dh.exec(e.data)[1],n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}for(const t of zh(e,Fh)){const e=Rh.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}qh.restoreTextBindings(e);for(const t of zh(e,Bh)){const e=s.get(t.data.split(":")[1]);if(e){const n=document.createElement("template"),s=e.getAttribute(o.bindAttributeName);s&&n.setAttribute(o.bindAttributeName,s);const r=document.importNode(e.content,!0);if(r.childNodes.length>0)n.content.appendChild(r);else for(const t of Array.from(e.childNodes))n.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(n,t)}}const r=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of r)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const Uh={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of s){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Oc),qh.buildContent(o,qh.extractStateData(t),t.getRootNode()),t.parentNode?.insertBefore(o,t)}ki()},reset:function(){_a.clear(),ki()}},Vh=new Set(["for","if","elseif","else"]);function Gh(t){const e=new cs;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e,deferredSpreads:[]};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i,a]=pe(s),l=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:l,subscriberNodes:r,bindingSession:e,deferredSpreads:a}}const Kh=/^\s*@@\s*(?:wcs-text)?\s*:/;function Jh(t,e,n){for(const o of e)"event"===o.bindingType||Vh.has(o.bindingType)||(o.node.nodeType!==Node.COMMENT_NODE||"text"===o.bindingType&&Kh.test(o.node.data))&&(o.statePathName in N||nt(o.statePathName).wildcardCount>n||t.push(o))}function Qh(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`;return zh(t,t=>t===r)[0]??null}function Xh(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Mt(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,ka()],bindingType:"else"}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;ja(a),"string"==typeof l&&Ta(a,l),Fa(n,a,l),$a(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:Ra(a)})}}const Yh={hydrate:async function(t){await ia(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${Oc}". Falling back to full render.`),qh.cleanupDom(t),!1}for(const n of e)Xh(t,n);qh.restoreTextBindings(document.body);const n=function(t){const e=[];for(const n of zh(t,Fh)){const t=Rh.exec(n.data),o=t[1],s=t[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 u=n.nextSibling;const d=`@@wcs-${o}-end:${s}`;for(;u&&(u.nodeType!==Node.COMMENT_NODE||u.data!==d);)c.push(u),u=u.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body),s=function(t,e){const n=new Map,o=[];for(const s of e){if(0===s.nodes.length)continue;const e=si(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a,deferredSpreads:c}=Gh(s.nodes);Br(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");bs(e,r),qr(e,i);const u=[];for(const t of r)t.statePathName in N&&u.push(t);if(_s(e,u),"for"===s.type&&null!==s.index){const i=Qh(t,"for",s.uuid);if(i){const t=Ns(null,s.index);pi(i,t,e),mi(i,s.nodes[s.nodes.length-1]),Zr(i,e);const u=nt(s.path+"."+l),d=bn(u,t);Ur(e,d),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Jh(o,r,u.wildcardCount),oa(c,d,a);let h=n.get(s.uuid);h||(h=[],n.set(s.uuid,h)),h.push(t)}}else{const n=Qh(t,s.type,s.uuid);n&&(Zr(n,e),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Jh(o,r,0),oa(c,null,a))}}for(const[e,o]of n){const n=Qh(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Sa(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ga(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&Ds(e,o)})}return o}(document.body,n);qh.removeBlockBoundaryComments(document.body);const r=[];for(const t of e)t.parentNode&&(r.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());const[i,a,c]=pe(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(ve(t,null),e.setAttribute("data-wcs-completed",""))}else ve(t,null);const u=[],d=[],h=us(document.body),f=h.initialize(a);oa(c,null,h);for(const t of f)if("event"!==t.bindingType)if(Vh.has(t.bindingType))d.push(t);else{if(t.statePathName.includes(l))continue;u.push(t)}for(const t of d)if("for"===t.bindingType){const e=ln(t),n=ga(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&(xe(e,o),Ee(e,o))})}na([...u,...s]);for(const{el:t,parent:e,next:n}of r)e.insertBefore(t,n);const p=new Map;for(const e of t.querySelectorAll("[data-wcs-ssr-id]"))p.set(e.getAttribute("data-wcs-ssr-id"),e);for(const e of t.querySelectorAll(o.tagNames.ssr))for(const[t,n]of Object.entries(e.hydrateProps)){const e=p.get(t);if(e)for(const[t,o]of Object.entries(n))e[t]=o}for(const e of t.querySelectorAll("[data-wcs-completed],[data-wcs-ssr-id]"))e.removeAttribute("data-wcs-completed"),e.removeAttribute("data-wcs-ssr-id");return!0},loadState(t){const e=t.parentNode;if(!e)return null;const n=qh.find(e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(t){await ya(t.rootNode);const e=qh.extractStateData(t),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",Oc),qh.buildContent(n,e,t.rootNode),t.parentNode?.insertBefore(n,t)}};let Zh=!1;const tf={name:"ssr",install(){Zh||(Zh=!0,ua=Yh,function(t){if(!kc.includes(t)){kc.push(t);for(const e of Nc())t(e)}}(t=>{t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,qh)}),function(){const e=globalThis;void 0===e[t]&&(e[t]=Uh)}())}},ef=new WeakMap,nf=new Set,of=new Set;function sf(t){return t.byFromPath.size>0||t.byResetPath.size>0}function rf(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function af(t){return ef.get(t)}function lf(t){cf(t),ef.delete(t)}function cf(t){nf.delete(t),of.delete(t)}const uf=new WeakSet;let df=0;function hf(t){return af(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function ff(t){if(0===of.size)return;if(e=t.absolutePathInfo.stateElement,!of.has(e))return;var e;const n=hf(t);if(void 0!==n)for(const t of n)pf(t)}function pf(t){uf.has(t)||(uf.add(t),df++)}function mf(t){return!!uf.delete(t)&&(df--,!0)}const gf=/^(?:0|[1-9]\d*)$/;function yf(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function bf(t){if("object"!=typeof t||null===t||Object.isFrozen(t))return null;const e=Object.getPrototypeOf(t);return Array.isArray(t)?e===Array.prototype&&Reflect.ownKeys(t).every(e=>"length"===e||"string"==typeof e&&gf.test(e)&&yf(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&yf(t,e))?null:"object"}function wf(t,e){const n=bf(t);if(null===n)return t;const o=t,s=e.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(t.length):null===Object.getPrototypeOf(t)?Object.create(null):{},e.set(o,r);for(const t of Object.keys(o))r[t]=wf(o[t],e);return r}function vf(t){return wf(t,new Map)}function _f(t,e,n){if(Object.is(t,e))return!0;const o=bf(e);if(null===o||"object"!=typeof t||null===t)return!1;const s=t,r=e;if("array"===o){if(!Array.isArray(t)||t.length!==e.length)return!1}else if(Array.isArray(t)||Object.keys(s).length!==Object.keys(r).length)return!1;if(bf(t)!==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 e=0;e<t.length;e++)if(!_f(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&_f(s[t],r[t],n))}function $f(t,e){return _f(t,e,new Map)}const Sf=new WeakMap;function xf(t,e){if("function"!=typeof e)return;const n=Sf.get(e);void 0===n?Sf.set(e,new Set([t])):n.add(t)}function Pf(t,e){return"function"==typeof e&&!0===Sf.get(e)?.has(t)}const kf={"read-source":t=>`${F} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-rows":t=>`${F} could not read the rows of "from" for "${t}". Nothing was folded or written.`,"read-output":t=>`${F} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${F} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${F} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${F} could not write the output "${t}".`},If={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Nf(t,e,n){null!==_e&&_e({type:"state:watch-error",phase:e,path:`${F}.${t}`,error:n})}function Af(t,e,n){console.error(`[@wcstack/state] ${kf[n](t)}`,e),Nf(t,If[n],e)}function Ef(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function Cf(t,e){e.then(void 0,()=>{}),Af(t,new TypeError(`${F} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Tf=new WeakSet,Mf="[wcs/scan-declaration-invalid]",Of=Object.freeze([]);function Lf(t){return`${F} entry "${t}"`}function Rf(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function jf(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${l}${l}`)?`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.${it}`}function Df(t,e,n){0===n.length&&Z(`${Mf} ${t} "${e}" must be a non-empty state path.${it}`),n.startsWith("$")&&Z(`${Mf} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${it}`),n.includes("@")&&Z(`${Mf} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${it}`),n in Object.prototype&&Z(`${Mf} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${it}`);const o=nt(n);for(const s of o.segments)0===s.length&&Z(`${Mf} ${t} ${e} "${n}" has an empty path segment.${it}`);return o.wildcardCount>c&&Z(`${Mf} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function Wf(t,e,n,o){const s=Lf(t);0===t.length&&Z(`${Mf} ${F} entry name must be a non-empty string.${it}`),(t.includes(a)||t.includes(l))&&Z(`${Mf} ${s} must be a flat property name ("${a}" and "${l}" are not allowed). The output is a property the runtime owns.${it}`),t.startsWith("$")&&Z(`${Mf} ${s} must not start with "$" (reserved namespace).${it}`),t in Object.prototype&&Z(`${Mf} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${it}`),e.has(t)&&Z(`${Mf} ${s} conflicts with a getter declared on the state.${it}`),n.has(t)&&Z(`${Mf} ${s} conflicts with a setter declared on the state.${it}`),o.has(t)&&Z(`${Mf} ${s} conflicts with the ${z} entry of the same name — each output has exactly one owner.${it}`)}function zf(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!Pf(t,o)&&Z(`${Mf} ${Lf(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${it}`)}function Bf(t,e,n,o,s,r){const i=Lf(t),l=void 0!==e.from,c=void 0!==e.on;if(l===c&&Z(`${Mf} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${it}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||Z(`${Mf} ${i} "on" must be a non-empty event-token name.${it}`),n.has(t)||Z(`${Mf} ${i} on "${t}" is not declared in ${D}.${rt(t,n)}${it}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&Z(`${Mf} ${i} "from" must be a state path string.${it}`);const d=Df(i,"from",u),h=Rf(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&Z(jf(i,"from",u,h));const f=Rf(d,s);return null!==f&&Z(function(t,e,n){return`${Mf} ${t} from "${e}" ${n===e?"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.${it}`}(i,u,f)),(u===t||u.startsWith(t+a))&&Z(`${Mf} ${i} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${it}`),{kind:"path",path:u,pathInfo:d}}function Ff(t,e,n,o){if(void 0===e)return Of;const s=Lf(t);Array.isArray(e)||Z(`${Mf} ${s} "resetOn" must be an array of state paths.${it}`);const r=[];for(const t of e){"string"!=typeof t&&Z(`${Mf} ${s} "resetOn" must contain only state path strings.${it}`);const e=Df(s,"resetOn",t);e.wildcardCount>0&&Z(`${Mf} ${s} resetOn "${t}" must not contain "${l}" — a reset returns the whole output to "initial".${it}`);const i=Rf(e,o);null!==i&&Z(jf(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&Z(`${Mf} ${s} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${it}`),"path"===n.kind&&t.startsWith(n.path+a)&&Z(`${Mf} ${s} resetOn "${t}" 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.${it}`),r.push(t)}return r}function Hf(t){const e=t.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[t.name];i="threw";const a=function(t){return uf.has(t)}(t),l=a&&!$f(n,t.initial)?vf(t.initial):n,c=e(l,o,...s);if(Ef(c))return void Cf(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,xf(t.name,c)),a&&mf(t)}catch(e){Af(t.name,e,i)}}}const qf="scanEntries",Uf={order:8,validate(t,e,n){const o=function(t,e,n=null){const o=t[F];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&Z(`${Mf} ${F} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${it}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(_c(t)))"function"==typeof n.get?s.add(e):"function"==typeof n.set&&i.add(e),"function"==typeof n.set&&r.add(e),"function"==typeof n.value&&a.set(e,n.value);const l=function(t){sl(t);const e=t[z];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];let u=0;for(const[t,d]of Object.entries(o)){Wf(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&Z(`${Mf} ${Lf(t)} must be an object ({ from | on, initial, fold, resetOn? }).${it}`);const o=d;zf(t,a,o);const h=Bf(t,o,e,s,i,n);"initial"in o||Z(`${Mf} ${Lf(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${it}`),"function"!=typeof o.fold&&Z(`${Mf} ${Lf(t)} fold must be a function.${it}`);const f=Ff(t,o.resetOn,h,s);c.push({name:t,source:h,fold:o.fold,initial:o.initial,resetOn:f,order:u++})}return function(t){const e=new Set(t.map(t=>t.name)),n=new Map;for(const o of t){for(const t of o.resetOn){const n=nt(t).segments[0];e.has(n)&&Z(`${Mf} ${Lf(o.name)} resetOn "${t}" reads the ${F} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${it}`)}if("path"===o.source.kind){const t=o.source.pathInfo.segments[0];e.has(t)&&n.set(o.name,t)}}for(const t of n.keys()){const o=[t];let s=n.get(t);for(;void 0!==s&&o.length<=e.size;)s===t&&Z(`${Mf} ${F} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${it}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}(e,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(qf,o)},applyEarly(t,e,n){const o=n.get(qf)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=vf(n.initial);t[n.name]=e,xf(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&Mn(t,n.source.tokenName).subscribe(Hf(n))}(t,o))},register(t,e,n){const o=n.get(qf)??null,s=function(t){const e=new Map,n=af(t);if(void 0!==n)for(const t of n.entries)mf(t)&&e.set(t.name,t.resetOn);return lf(t),e}(t);t.setScanPaths?.(null===o?null:function(t,e,n){const o=function(t,e){lf(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&rf(n,t.source.path,t);for(const e of t.resetOn)rf(o,e,t),"event"===t.source.kind&&rf(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return ef.set(t,r),r}(t,e);for(const o of e){const e=n.get(o.name);"event"===o.source.kind&&void 0!==e&&o.resetOn.some(n=>e.includes(n)&&Xs().hasQueuedPath(t,n))&&pf(o)}const s=new Set;for(const e of o.byFromPath.keys())s.add(e),t.setPathInfo(e,"prop","scan");for(const e of o.byResetPath.keys())t.setPathInfo(e,"prop","scan");return s.size>0?s:null}(t,o,s))}};let Vf=!1;const Gf=Object.freeze([]),Kf=Object.freeze([]);function Jf(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Gf,i=t.dynamicDependency.get(n)??Gf,a=e.byFromPath.get(n)??Kf;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const Qf=Symbol("wcs-stream-last-notified-uncertain"),Xf=new WeakMap;function Yf(t,e){const n=Xf.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Zf(t,e){const n=Xf.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Qf,error:Object.is(o.error,null)?null:Qf})}const tp=new Set;function ep(t){tp.delete(t)}const np=new WeakMap;function op(t){return np.get(t)??new Map}function sp(t){ep(t);const e=np.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Zf(t,n.name)}const rp=(t,e)=>e,ip=new Set;const ap=new WeakMap,lp=new WeakMap;function cp(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=op(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&op(t).has(n),ownKeys:()=>Array.from(op(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=op(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){Z(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){Z(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function up(t){const e=ap.get(t);if(void 0!==e)return e;const n=cp(t,V,t=>t.status);return ap.set(t,n),n}function dp(t){const e=lp.get(t);if(void 0!==e)return e;const n=cp(t,G,t=>t.error);return lp.set(t,n),n}function hp(t){ap.delete(t),lp.delete(t)}let fp=null;function pp(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}const mp={read(t,e){!function(t,e){null!==fp&&fp.add(Ke(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===V?pp(up(t),e.pathInfo.segments):n===G?pp(dp(t),e.pathInfo.segments):cl},get:(t,e)=>e===V?up(t.stateElement):e===G?dp(t.stateElement):cl};function gp(t){Sp();const e=op(t);if(0!==e.size){!function(t){tp.add(t)}(t);for(const n of e.values())yp(t,n)}}function yp(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=fp,s=new Set;let r;fp=s;try{t.createState("readonly",t=>{r=n(t)})}finally{fp=o}r instanceof Promise&&Z(`${z} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${V}${a}${e.name}`,l=`${G}${a}${e.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==i&&o.path!==l||Z(`${z} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&Z(`${z} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=s,r}(t,e);!function(t,e){const n=af(t);if(void 0!==n&&0!==e.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==e.name)continue;const s=Jf(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&Z(`[wcs/scan-feedback-loop] ${z} entry "${e.name}" args read "${n}", which is derived from the ${F} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,e),t.createState("writable",t=>{t[e.name]=e.definition.initial}),xf(e.name,e.definition.initial),bp(t,e,"active",null);const s=e.definition,r={fold(n){t.createState("writable",t=>{const o=s.fold(t[e.name],n);t[e.name]=o,xf(e.name,o)})},done(){bp(t,e,"done",null)},fail(o){bp(t,e,"error",o),n.abort()}};!async function(t,e,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 t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError(`[@wcstack/state] ${z}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",r)}}(s.source,o,n.signal,r)}function bp(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return Xf.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(function(t,e,n,o){let s=Xf.get(t);void 0===s&&(s=new Map,Xf.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${V}${a}${e.name}`),i&&t.$postUpdate(`${G}${a}${e.name}`)}))}function wp(t){const e=tp;if(0===e.size)return;const n=[];for(const o of e)for(const e of op(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&op(t).get(o.name)===o)try{yp(t,o)}catch(n){o.controller?.abort(),e.has(t)&&op(t).get(o.name)===o&&bp(t,o,"error",n)}}let vp=!1;const _p=new WeakMap,$p={order:20,apply(t,e){var n;hp(t),sp(n=t),ep(n),np.delete(n),function(t,e){sl(e);const n=e[z];if(void 0===n)return void Yf(t,ip);"object"==typeof n&&null!==n||Z(`${z} must be an object mapping stream names to stream definitions.`);const o=new Map,s=_c(e);for(const[r,i]of Object.entries(n)){0===r.length&&Z(`${z} entry name must be a non-empty string.`),r.includes(a)&&Z(`${z} entry "${r}" must be a flat property name ("${a}" is not allowed).`),r.includes(l)&&Z(`${z} entry "${r}" must be a flat property name ("${l}" is not allowed).`),r.startsWith("$")&&Z(`${z} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&Z(`${z} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(r)&&Z(`${z} entry "${r}" conflicts with a getter declared on the state.`),t.setterPaths.has(r)&&Z(`${z} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||Z(`${z} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,c=s[r]?.value;"function"!=typeof c||c===n.initial||Pf(r,c)||Z(`${z} 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&&Z(`${z} entry "${r}" source must be a function.`);const u=void 0!==n.fold;u&&"function"!=typeof n.fold&&Z(`${z} entry "${r}" fold must be a function.`),u&&!("initial"in n)&&Z(`${z} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&Z(`${z} entry "${r}" args must be a function.`);const d={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??rp,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in e||(e[r]=d.definition.initial,xf(r,d.definition.initial)),o.set(r,d)}!function(t,e){np.set(t,e)}(t,o),Yf(t,new Set(o.keys()))}(t,e),void 0!==e[z]&&t.attachAddressHooks?.("streams",z)},activate(t,n){if(!e()&&null!=t.connectedRootNode){if(null===n){if(!0!==t.initialized)return;return gp(t),void _p.set(t,t.connectGeneration??0)}n===t.connectGeneration&&_p.get(t)!==n&&gp(t)}},deactivate(t){sp(t),hp(t)}};function Sp(){vp||(vp=!0,hl("streams",mp),gl("streams",$p),Ks(wp,20))}let xp=0,Pp=0;function kp(t){xp=t+1}function Ip(){xp=0}function Np(){xp>Pp&&(Pp=xp)}const Ap=new WeakMap;function Ep(t,e,n){let o=Ap.get(t);void 0===o&&(o=new Map,Ap.set(t,o)),o.set(e,n)}const Cp=new Map;function Tp(t,e){Cp.has(t)||Cp.set(t,e)}function Mp(t){return Cp.get(t)}const Op=new WeakMap,Lp=new WeakMap,Rp=new Set,jp=new Map;function Dp(t){return Op.get(t)??jp}function Wp(t,e){let n=Lp.get(t);void 0===n&&(n=new Map,Lp.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}const zp=new Map;function Bp(t){return Lp.get(t)??zp}function Fp(t){0===t.length&&Z(`[wcs/watch-declaration-invalid] ${B} entry name must be a non-empty state path.`),t.startsWith("$")&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not start with "$" (reserved namespace).${it}`),t.includes("@")&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${it}`),t in Object.prototype&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=nt(t);for(const n of e.segments)0===n.length&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" has an empty path segment.${it}`);return e.wildcardCount>c&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const Hp={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||Tp(n,o)},swapped(t,e,n){var o;o=n,Cp.has(o)&&Tp(e,Mp(n))}};function qp(t){for(let e=t;null!==e;e=e.parentListIndex)if(Ls(e))return!0;return!1}function Up(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[Le](bn(e.wildcardParentPathInfos[i],r)),l=Rs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=en(o,i,e.wildcardCount);if(l!==c&&!Ts(l,c)){if(Ls(c))return"gone";s="replaced"}r=l}return s}function Vp(t,e,n){const o=new Map;for(const s of n){const n=Up(t,e,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(),t=>t.row)}const Gp=Object.freeze([]);function Kp(t,e,n){let o=t.get(n);return void 0===o&&(o={stateElement:e,entry:n,rows:[],reset:!1},t.set(n,o)),o}function Jp(t,e){let n=0;for(;n<t.indexes.length-1&&t.indexes[n]===e.indexes[n];)n++;return t.indexes[n]-e.indexes[n]}function Qp(t,e){return e.has(t.stateElement)&&!0===af(t.stateElement)?.entries.has(t.entry)}function Xp(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Yp(n,t))||mf(e)}function Yp(t,e){return Xs().hasQueuedPath(t,e)}function Zp(t,e){!function(t,e,n){if(0!==df)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=hf(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||mf(e)}}(t,e,Yp)}function tm(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function em(t,e,n){if(!Qp(t,n))return Xp(t),null;const{stateElement:o,entry:s}=t;if(t.reset)return{group:t,next:s.initial};const r=s.source;if(function(t,e){for(const n of e.pathInfo.cumulativePaths)if(t.getterPaths.has(n))return!0;return!1}(o,r))return function(t,e,n){if(Tf.has(t))return;Tf.add(t);const o=`[wcs/scan-source-computed] ${F} entry "${e}" 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}`),Nf(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=op(t).get(e);if(void 0===o)return!1;for(const t of o.depAddresses)if(n.has(t))return!0;return!1}(o,r.pathInfo.segments[0],e))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",e=>{const n=e[s.name];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?t.rows:Vp(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(Jp)){let n;try{n=tm(e,r,t)}catch(t){Af(s.name,t,"read-source");continue}const o=a(l,n,Mp(t.absAddress),...t.indexes);if(Ef(o))return void Cf(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){Af(s.name,t,i.failure)}return i.plan}function nm(t,e){const{group:n}=t;if(!Qp(n,e))return void Xp(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||mf(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!$f(o,s.initial):!Object.is(o,t.next)){const o=n.reset?vf(s.initial):t.next;e[s.name]=o,xf(s.name,o)}})}catch(t){Af(s.name,t,"write")}}function om(t){hm(),(0!==Dp(t).size||0!==Bp(t).size||function(t){const e=ef.get(t);return void 0!==e&&sf(e)}(t))&&(function(t){Rp.add(t),function(t){const e=ef.get(t);void 0!==e&&(sf(e)&&nf.add(t),function(t){return t.eventResetByPath.size>0}(e)&&of.add(t))}(t)}(t),function(t){const e=[];for(const n of Dp(t).values())sm(t,n)&&e.push(n);for(const n of Bp(t).values())for(const o of n)sm(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{Ep(t,Je(t,o.pathInfo,null),n[o.path])}catch(e){im(t,o.path,"prime",e)}})}(t))}function sm(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const rm={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function im(t,e,n,o){console.error(`[@wcstack/state] $watch ${rm[n]} "${e}" threw.`,o),null!==_e&&_e({type:"state:watch-error",phase:n,path:e,error:o})}function am(t){const e=Rp;try{if(0===e.size)return void Zp(t,e);const n=function(){const t=Pp;return Pp=0,t}();if(n>32){Zp(t,null);const e=Array.from(t,t=>t.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:e}),void(null!==_e&&_e({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}!function(t,e,n){if(0!==t.length){kp(n);try{for(const n of t)nm(n,e)}finally{Ip()}}}(function(t,e,n){if(Zp(t,e),0===nf.size)return Gp;const o=new Map;for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=af(t);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let e=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;e=nn(n.listIndex,r.wildcardCount)}for(const s of i)Kp(o,t,s).rows.push({absAddress:n,indexes:e})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const e of a)Kp(o,t,e).reset=!0}if(0===o.size)return Gp;const s=Array.from(o.values()).sort((t,e)=>t.entry.order-e.entry.order),r=[];kp(n);try{for(const n of s){const o=em(n,t,e);null!==o&&r.push(o)}}finally{Ip()}return r}(t,e,n),e,n),function(t,e,n){const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=Dp(t).get(s),i=Bp(t).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const e of a){let s=[];if(e.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=nn(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(cm);const s=function(t){let e=null;for(let n=0;n<t.length;n++){const o=t[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=t[n-1];(qp(o.absAddress.listIndex)||s?.entry===o.entry&&lm(s.indexes,o.indexes))&&(e??=new Set).add(o.entry)}if(null===e)return t;const n=new Set;for(const o of e){const e=t.filter(t=>t.entry===o),s=e[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(Vp(t,o.pathInfo,e));for(const t of e)s.has(t)||n.add(t)})}catch(t){im(0,o.path,"evaluate",t);for(const t of e)n.add(t)}}return t.filter(t=>!n.has(t))}(o);kp(n);try{for(const t of s){if(!e.has(t.stateElement))continue;const n=Dp(t.stateElement).get(t.entry.path)===t.entry,o=!0===Bp(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&um(t)}}finally{Ip()}}(t,e,n)}finally{Cp.clear()}}function lm(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function cm(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function um(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=sm(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void im(0,n.path,"evaluate",t)}const a=r?function(t,e){return Ap.get(t)?.get(e)}(e,o):Mp(o);r&&Ep(e,o,i),null!==_e&&_e({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){im(0,n.path,"handler",t)}}let dm=!1;function hm(){dm||(dm=!0,hl("watch",Hp),gl("watch",fm),Ks(am,10),Gs(Np),Ec={assertValidPath:Fp,addEntries:Wp,start:om})}const fm={order:10,register(t,e){var n;n=t,Rp.delete(n),cf(n),Op.delete(n),function(t){Ap.delete(t)}(t);const o=function(t,e){const n=e[B];if(void 0===n)return null;"object"==typeof n&&null!==n||Z(`[wcs/watch-declaration-invalid] ${B} must be an object mapping state paths to handler functions.${it}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${e}" must be a function.${it}`);const n=Fp(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){Op.set(t,e)}(t,o),s.size>0?s:null}(t,e);t.setWatchPaths?.(o),null===o&&null==t.scanPaths||t.attachAddressHooks?.("watch",null!==o?B:F)},activate(t,n){e()||null==t.connectedRootNode||(null===n?!0===t.initialized:n===t.connectGeneration)&&om(t)},deactivate(t){var e;e=t,Rp.delete(e),cf(e)}},pm=[mu,{name:"temporal",install(){hm(),Vf||(Vf=!0,gl("scan",Uf),Gs(ff)),Sp()}},Wu,Oh,tf,qc,tu];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(pm),void Ac(void 0,void 0));const mm={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},gm=!1,ym=[".html"];function bm(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function wm(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let vm=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const _m={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function $m(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function Sm(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}const xm={static:2,param:1,"catch-all":0};let Pm=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&wm(`${mm.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&wm(`${mm.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=xm[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(_m).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||wm(`${mm.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath,o=await this._guardHandler(e,n,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:$m(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new vm("Navigation cancelled by guard.",o);if(!o)throw new vm("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new vm("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},km=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=bm();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new Pm(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||wm(`${mm.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):wm(`${mm.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&wm(`${mm.route} with fallback attribute must be a direct child of ${mm.router}.`),t.fallbackRoute&&wm(`${mm.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const Im=Symbol.for("wcstack.trustedTypes.policy"),Nm=Symbol.for("wcstack.trustedTypes.internal"),Am="wcstack";function Em(){const t=globalThis[Im];return null===t||"object"!=typeof t?null:t}let Cm=!1;function Tm(t){const e=function(){const t=globalThis,e=t[Nm];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Am,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof Em()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Am}". Allow it in the CSP (\`trusted-types ${Am};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[Nm]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Em(),s=o?.createHTML;return"function"==typeof s?(Cm||(Cm=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Am}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Am};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Mm=new Map;let Om=class extends HTMLElement{_uuid=bm();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||wm(`${mm.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Mm.set(t,n),n}catch(e){wm(`${mm.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${mm.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Mm.has(t)?n.innerHTML=Tm(Mm.get(t)||""):n.innerHTML=Tm(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Tm(t):console.warn(`${mm.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&gm}get name(){return this.getAttribute("name")||""}},Lm=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||wm(`${mm.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&gm}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Rm=new Set(["props","states","attr",""]);function jm(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function Dm(t,e){t.hasAttribute("data-bind")||wm(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Rm.has(n)||wm(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&jm(t,e,o)}).catch(()=>{wm(`Failed to define custom element: ${s}`)}):jm(t,e,o)}let Wm=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||wm(`${mm.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${mm.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{Dm(e,t)}),e.hasAttribute("data-bind")&&Dm(e,t))}};function zm(){return document.createElement(mm.layoutOutlet)}const Bm="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Fm(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){wm(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${Bm}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${Bm}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function Hm(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function qm(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===mm.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),Hm(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===mm.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Fm(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===mm.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=zm();o.layout=n,i=o,a=e}}const c=await qm(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function Um(t){const e=new Map;return await qm(t,t.template.content,[],e)}function Vm(t){return!1!==t.checkVisibility?.()}function Gm(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",n=_m[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)Gm(s,e,n,o)}function Km(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)Gm(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let Jm=null,Qm=null;function Xm(){const t=ym;return 0===t.length?null:(Jm===t&&Qm||(Jm=t,Qm=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Qm)}function Ym(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=Xm();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Zm(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function tg(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=Xm();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function eg(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function ng(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{Dm(e,t.typedParams)}),n.hasAttribute("data-bind")&&Dm(n,t.typedParams),n.querySelectorAll(mm.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===mm.layoutOutlet&&n.assignParams(t.typedParams)}}function og(t,e){ng(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const sg=Symbol.for("wcstack.transition-runner");const rg=Symbol.for("wcstack.binder");function ig(){const t=globalThis[rg];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const ag=Symbol.for("wcstack.binder.pending"),lg=Symbol.for("wcstack.binder.taken");function cg(){const t=globalThis;let e=t[lg];return void 0===e&&(e=new WeakSet,t[lg]=e),e}function ug(t){const e=ig();return null===e?(function(){const t=globalThis;let e=t[ag];return void 0===e&&(e=[],t[ag]=e),e}().push(t),!1):(cg().add(t),e.bind(t),!0)}const dg=new WeakSet,hg="data-wcs";function fg(t,e,n){!dg.has(t)&&function(t){return t.hasAttribute(hg)||null!==t.querySelector(`[${hg}]`)}(t)&&(dg.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==ig()||(o=t,cg().has(o))||console.warn(`[@wcstack/router] ${e} contains ${hg} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function pg(t){for(const e of t.childNodeArray)1===e.nodeType&&(ug(e)||fg(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.'))}async function mg(t,e){try{let t=null;for(const n of e.routes){const o=await n.guardCheck(e);o&&(t=null===t?o:Object.assign({},t,o))}e.data=t}catch(e){if(e instanceof vm)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function gg(t,e,n,o,s=""){const r=Zm(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:s,path:r}),!0;let i=Km(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:wm(`${mm.router} No route matched for path: ${r}`)),i.lastPath=o,i.search=s;const a=e.lastRoutes,l=await async function(t,e,n){if(!await mg(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||eg(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=og(o,e),n.length>0&&!s.has(o)&&pg(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[sg];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",data:i.data??null,search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(Vm(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(Vm(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(t,i),!0)}function yg(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function bg(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function wg(t){return"?"===t?"":t}function vg(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function _g(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const $g="data-wcs-ssr",Sg="data-wcs-ssr-link",xg="@@wcs-route-ph:",Pg="@@wcs-route-start:",kg="@@wcs-route-end:",Ig=Object.freeze({});class Ng extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Ig;_typedParams=Ig;_searchParams=Ig;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return Ym(t)}_normalizeBasename(t){return tg(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(mm.outlet))return t;const e=document.createElement(mm.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||wm(`${mm.router} has no outlet.`),this._outlet}get template(){return this._template||wm(`${mm.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=$m(t.search),s=t.data??null,r=this._data!==s,i=!Sm(this._params,e),a=this._routeName!==t.routeName,l=!Sm(this._searchParams,o),c=this._path!==t.path;r&&(this._data=s),i&&(this._params=e,this._typedParams=n),a&&(this._routeName=t.routeName),l&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,r&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${mm.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${mm.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=bg(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+wg(n.search)+n.hash,r=yg();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(Zm(t,this._basename));await gg(this,this.outlet,t,this._path,wg(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(Zm(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await gg(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${mm.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await gg(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=_g();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||wm(`${mm.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||wm(`${mm.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await Um(this),r=!t&&this._outlet.hasAttribute($g);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&wm(`${mm.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute($g);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await gg(this,this.outlet,i,this._path,window.location.search||""),(r||null!==ig())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(mm.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(xg)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Pg)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith(kg)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=Zm(t,this._basename);let d=Km(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of d.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(Pg)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===mm.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute($g);for(const t of d.routes)ng(t,d);return this.outlet.lastRoutes=d.routes,!await mg(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(t){const e=Zm(t,this._basename),n=Km(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&wm(`${mm.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await gg(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${xg}${t.absolutePath}`}),this.outlet.setAttribute($g,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${Pg}${t.absolutePath}`),s=document.createComment(`${kg}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&ug(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!vg(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),_g()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=yg();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(yg()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Ag=["title","rel","target","download","hreflang","lang","dir"];class Eg extends HTMLElement{static get observedAttributes(){return["to",...Ag]}_childNodeArray=[];_uuid=bm();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(mm.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(mm.router);if(n)return this._router=n;wm(`${mm.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return Ym(t)}_joinInternalPath(t,e){const n=tg(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=bg(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+wg(o)+s}else try{t.href=new URL(e).toString()}catch{wm(`[${mm.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){_g()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Sg)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(Sg),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||Ag.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,_g())return this._updateActiveState(),void n.setAttribute(Sg,"");yg()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!yg()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){yg()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Ag.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=bg(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Cg=[],Tg=new Map;let Mg=!1;const Og=new WeakMap;class Lg extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Mg||(this._captureInitialHead(),Mg=!0),Cg.push(this),this._reapplyHead()}disconnectedCallback(){const t=Cg.indexOf(this);-1!==t&&Cg.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||wm("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Og.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Og.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Tg.has(t)||Tg.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Cg)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Tg.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=Cg.length-1;e>=0;e--){const o=Cg[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Tg.has(n)&&(t=Tg.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),ug(t)||fg(t,`<${t.tagName.toLowerCase()}> inside <${mm.head}>`,`<${mm.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(mm.layout)||t.define(mm.layout,Om),t.get(mm.layoutOutlet)||t.define(mm.layoutOutlet,Wm),t.get(mm.outlet)||t.define(mm.outlet,Lm),t.get(mm.route)||t.define(mm.route,km),t.get(mm.router)||t.define(mm.router,Ng),t.get(mm.link)||t.define(mm.link,Eg),t.get(mm.head)||t.define(mm.head,Lg)}(void 0);const Rg="data-fetchtarget",jg={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Dg=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function Wg(t,e){return e.every(e=>"available"===t.availability.get(e))}const zg=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Bg=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new Dg("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return Wg(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),u=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",d=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:u,userActivation:d},epoch:e.epoch??0,lastError:e.lastError}}(zg,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!Wg(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:u="auto",timeout:d=0}=e;let h=null;d>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},d));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===u)s=await n.blob();else if("arrayBuffer"===u)s=await n.arrayBuffer();else if("text"===u)s=await n.text();else if("json"===u)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,d)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},Fg=!1;function Hg(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Rg}]`);if(!n)return;const o=n.getAttribute(Rg);if(!o)return;const s=customElements.get(jg.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function qg(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}const Ug=Symbol.for("wcstack.trustedTypes.policy");function Vg(){const t=globalThis[Ug];return null===t||"object"!=typeof t?null:t}let Gg,Kg=!1;let Jg=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Bg.wcBindable,properties:[...Bg.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new Bg(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(jg.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(jg.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&function(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=Vg(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Gg)return Gg;if(!("trustedTypes"in globalThis))return Gg=!1,Gg;try{document.createElement("div").innerHTML="<i></i>",Gg=!1}catch{Gg=!0}return Gg}())return void function(){if(Kg)return;Kg=!0;const t="function"==typeof Vg()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}(t,s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!qg(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Fg||(Fg=!0,document.addEventListener("click",Hg)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Qg extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class Xg extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Yg=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof Jg&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(jg.fetch)||t.define(jg.fetch,Jg),t.get(jg.fetchHeader)||t.define(jg.fetchHeader,Qg),t.get(jg.fetchBody)||t.define(jg.fetchBody,Xg),t.get(jg.infiniteScroll)||t.define(jg.infiniteScroll,Yg)}(void 0);const Zg="data-storagetarget",ty={storage:"wcs-storage"},ey="wcs-storage:value-changed",ny="wcs-storage:loading-changed",oy="wcs-storage:error",sy="wcs-storage:error-info-changed",ry="wcs-storage:trigger-changed";let iy=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:ey,semantics:"state",getter:t=>t.detail},{name:"loading",event:ny,semantics:"state"},{name:"error",event:oy,semantics:"state"},{name:"errorInfo",event:sy,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(ny,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(oy,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(sy,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(ey,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},ay=!1;function ly(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Zg}]`);if(!n)return;const o=n.getAttribute(Zg);if(!o)return;const s=customElements.get(ty.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function cy(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let uy=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...iy.wcBindable,properties:[...iy.wcBindable.properties,{name:"trigger",event:ry,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new iy(this),this._internals=this._initInternals(),this._wireStates({[ny]:t=>({loading:!0===t}),[oy]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(ry,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!cy(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",ay||(ay=!0,document.addEventListener("click",ly)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(ty.storage)||t.define(ty.storage,uy)}(void 0);const dy="*",hy="vanilla",fy={scanImportmap:!0,loaders:{[hy]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[dy]:hy},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function py(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function my(t,e,n){let o;if(null===e||e===dy||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===dy)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[dy],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const gy=new Set,yy=new Map;let by=new WeakMap;function wy(t){if(t===globalThis.customElements)return yy;let e=by.get(t);return void 0===e&&(e=new Map,by.set(t,e)),e}const vy=new Map;async function _y(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of vy)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){gy.has(e)||(console.error(`Failed to eager load component '${e}':`,t),gy.add(e))}}function $y(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function Sy(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&vy.set(t,e)});const xy=new WeakSet,Py=new WeakSet;async function ky(t,e,n){t.shadowRoot&&(xy.has(t)||await async function(t,e,n){xy.add(t),await Ey(t.shadowRoot,e,n)}(t,e,n))}async function Iy(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=wy(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=my("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),gy.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Ny(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=Sy(t);void 0===o.get(s.name)?(Py.has(t)||(Py.add(t),o.whenDefined(s.name).then(async()=>{await ky(t,e,n)})),a.has(s.name)||gy.has(s.name)||(a.add(s.name),i.push(s))):await ky(t,e,n)}let l=0;for(const t of i)await Iy(t,e,n,o),l++;return l}async function Ay(t,e,n,o){for(;await Ny(t,e,n,o)>0;);}async function Ey(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return $y(e)}return $y(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Ay(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await Ay(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Cy extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Cy._instance)throw new Error(`${fy.tagNames.autoloader} can only be instantiated once.`);Cy._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=py(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=my(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(_y(s,o,r))}await Promise.all(n)}(n,fy.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await Ey(document,fy,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Cy._instance===this&&(Cy._instance=null)}}!function(t=customElements){t.get(fy.tagNames.autoloader)||t.define(fy.tagNames.autoloader,Cy)}(void 0);
2
2
  //# sourceMappingURL=auto.min.js.map