@wcstack/state 2.0.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +85 -17
- package/README.md +88 -19
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.d.ts +22 -3
- package/dist/index.esm.js +89 -22
- package/dist/index.esm.js.map +1 -1
- package/package.json +1 -1
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;const s=".",r="*",i=128,a="|",l="prevent",c="stop",d="ro",u="init",f="sync",h="else",p="...",m="on",g="eventToken",y="command",b="class",w="attr",v="style",$={};for(let t=0;t<128;t++)$[`$${t+1}`]=t;const S=Object.freeze($),N="$connectedCallback",x="$disconnectedCallback",I="$updatedCallback",P="$stateReadyCallback",k="$bindables",_="$commands",A="$commandTokens",C="$command",E="$eventTokens",M="$on",T="$streams",O="$watch",R="$listKeys",D="$streamStatus",j="$streamError",L="data-wc-definition",W=new WeakMap,B=new WeakSet;let F=0;async function z(t){const e=function(t){let e,n=W.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++F,promise:o,resolve:e},W.set(t,n),B.has(t)&&n.resolve(),n}(t);await e.promise}function q(t){const e=W.get(t);void 0===e?B.add(t):e.resolve()}const V=new Map;let U=0;function K(t){let e=V.get(t);return void 0!==e||(e=Object.freeze(new G(t)),V.set(t,e)),e}class G{id=++U;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:K(e),n=t.split("."),o=[],s=[],i=[],a={},l=[],c=[],d=[],u=[];let f="",h="",p=0;for(let t=0;t<n.length;t++)f+=n[t],n[t]===r&&(i.push(f),a[f]=p,l.push(e(f)),c.push(h),d.push(e(h)),u.push(t),p++),o.push(f),s.push(e(f)),h=f,f+=".";const m=i.length>0?i[i.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=i,this.wildcardPathSet=new Set(i),this.indexByWildcardPath=a,this.wildcardPathInfos=l,this.wildcardPathInfoSet=new Set(l),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}}const H=new WeakMap;function J(t){const e=H.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{H.set(t,n)}}function X(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Y(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return X(e);if(void 0!==n)return X(n)}return X(globalThis.customElements)}function Q(t,e){t.upgrade?.(e)}function Z(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=ot(s.properties,tt);if(null===r)return null;const i=void 0===s.inputs?new Map:ot(s.inputs,et);if(null===i)return null;const a=void 0===s.commands?new Map:ot(s.commands,nt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function tt(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 et(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 nt(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 ot(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 st(t){throw new Error(`[@wcstack/state] ${t}`)}function rt(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:K(n),inFilters:[],outFilters:[],bindingType:"prop"}}function it(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function at(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&&st("Spread binding requires an element node.");const e=t,o=J(e);null===o&&st(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Y(e);null===a&&st(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||st(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Q(a,e);const l=Z(e);null===l&&st(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const t of l.knownProperties.keys()){if(d.has(t))continue;d.add(t);const e=rt(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(d.has(t))continue;d.add(t);const e=rt(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=it(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=it(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 lt(t,e){let n=t;if(0===e.length)return n;for(let t=0;t<e.length&&(n=n?.childNodes[e[t]]??null,null!==n);t++);return n}const ct=new WeakMap;function dt(t){return ct.get(t)||null}function ut(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 ft(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=ut(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const ht=" Validate statically: npx @wcstack/lint <file>.",pt=new Set(["if","elseif","else","for"]);function mt(t){st(`filter ${t} requires at least one option`)}function gt(t){st(`filter ${t} requires a number as option`)}function yt(t){st(`filter ${t} requires a number value`)}function bt(t){st(`filter ${t} requires a date value`)}function wt(t){return!(!t||isNaN(Number(t)))}const vt={eq:t=>{const e=t?.[0]??mt("eq");return t=>"number"==typeof t?(wt(e)||gt("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??mt("ne");return t=>"number"==typeof t?(wt(e)||gt("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&st(`filter ${"not"} requires a boolean value`),!t),lt:t=>{const e=t?.[0]??mt("lt");return wt(e)||gt("lt"),t=>("number"!=typeof t&&yt("lt"),t<Number(e))},le:t=>{const e=t?.[0]??mt("le");return wt(e)||gt("le"),t=>("number"!=typeof t&&yt("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??mt("gt");return wt(e)||gt("gt"),t=>("number"!=typeof t&&yt("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??mt("ge");return wt(e)||gt("ge"),t=>("number"!=typeof t&&yt("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??mt("inc");return wt(e)||gt("inc"),t=>("number"!=typeof t&&yt("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??mt("dec");return wt(e)||gt("dec"),t=>("number"!=typeof t&&yt("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??mt("mul");return wt(e)||gt("mul"),t=>("number"!=typeof t&&yt("mul"),t*Number(e))},div:t=>{const e=t?.[0]??mt("div");return wt(e)||gt("div"),t=>("number"!=typeof t&&yt("div"),t/Number(e))},mod:t=>{const e=t?.[0]??mt("mod");return wt(e)||gt("mod"),t=>("number"!=typeof t&&yt("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&yt("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??mt("clamp");wt(e)||gt("clamp");const n=t?.[1]??mt("clamp");wt(n)||gt("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&yt("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return wt(e)||gt("fix"),t=>("number"!=typeof t&&yt("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&yt("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]??mt("slice");wt(n)||gt("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(wt(o)||gt("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??mt("substr");wt(e)||gt("substr");const n=t?.[1]??mt("substr");return wt(n)||gt("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??mt("pad");wt(e)||gt("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??mt("rep");return wt(e)||gt("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??mt("truncate");wt(e)||gt("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)||st(`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 wt(e)||gt("round"),t=>{"number"!=typeof t&&yt("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return wt(e)||gt("floor"),t=>{"number"!=typeof t&&yt("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return wt(e)||gt("ceil"),t=>{"number"!=typeof t&&yt("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return wt(e)||gt("percent"),t=>("number"!=typeof t&&yt("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??mt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||bt("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||bt("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=>!1===t||null==t||0===t||""===t||Number.isNaN(t),truthy:t=>t=>!1!==t&&null!=t&&0!==t&&""!==t&&!Number.isNaN(t),defaults:t=>{const e=t?.[0]??mt("defaults");return t=>!1===t||null==t||0===t||""===t||Number.isNaN(t)?e:t},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),null:t=>t=>""===t?null:t},$t=vt,St={input:vt,output:$t},Nt=(t,e)=>n=>{const o=n[t];return o||st(`[wcs/filter-unknown] filter not found: ${t}.${ft(t,Object.keys(n))}${ht}`),o(e)};function xt(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 It=new Map;function Pt(t,e){const n=St[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&st(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&st(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=It.get(s);return void 0===r&&(r=Nt(o,[])(n),It.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=t.substring(o+1,s),i=t.substring(0,o).trim(),a=function(t){const e=[];let n="",o=null,s=!1,r=-1,i=-1;const a=()=>{e.push(xt(n,r,i)),n="",s=!1,r=-1,i=-1};for(let e=0;e<t.length;e++){const l=t[e];o?l===o?o=null:(-1===r&&(r=n.length),n+=l,i=n.length):'"'===l||"'"===l?(o=l,s=!0):","===l?a():n+=l}const l=xt(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=It.get(l);return void 0===c&&(c=Nt(i,a)(n),It.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const kt=t=>t.trim(),_t=new Map;const At=new Map;function Ct(t){const e=t.indexOf(a);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=s.split(a).map(kt),r=Pt(o,"output"),At.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&st(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);return{statePathName:n,statePathInfo:K(n),outFilters:r}}function Et(t){const[...e]=t.split(";").map(kt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&st(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===h){const t=K("#else");return{propName:h,propSegments:[h],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===p){const e=Ct(o);return e.outFilters.length>0&&st(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&st(`Invalid spread binding "${t}": spread target path is required.`),{propName:p,propSegments:[p],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ct(o),bindingType:n}}{const t=Ct(o),e=function(t){const e=t.indexOf(a);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),_t.has(r)?i=_t.get(r):(o=r.split(a).map(kt),i=Pt(o,"input"),_t.set(r,i))):n=t.trim();const[l,c]=n.split("#").map(kt),d=l.split(s).map(kt);return{propName:l,propSegments:d,propModifiers:c?c.split(",").map(kt):[],inFilters:i}}(n);return e.propSegments[0]===g||e.propSegments[0].startsWith(m)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});if(n.length>1){n.some(t=>pt.has(t.bindingType))&&st(`[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">).${ht}`)}return n}const Mt=new WeakMap,Tt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Ot=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Rt(t){const e=Mt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Ot.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Tt.has(r)?(Mt.set(t,s[2]),s[2]):null}function Dt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ct(t),bindingType:"text"}}const jt=new Map;function Lt(t,e,n){if(null===n)jt.delete(t);else{jt.set(t,n);const o=zi(e);null===o&&st("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 Wt(t){return jt.get(t)||null}function Bt(t){if(t.nodeType===Node.ELEMENT_NODE){return Et(t.getAttribute(o.bindAttributeName)||"")}if(t.nodeType===Node.COMMENT_NODE){const e=Rt(t);null===e&&st("Comment node binding text not found.");const n=Wt(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Dt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function Ft(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function zt(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Ft(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function qt(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 Vt(t){const e=[],n=zt(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(t){if(t.nodeType===Node.ELEMENT_NODE){return t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==Rt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const t=s.currentNode;n.length>0&&qt(t,n)||e.push(t)}return e}const Ut=new WeakSet;function Kt(t,e,n,o){const s=at(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?J(t):null;return null===n&&st("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}Ut.add(t);const r=function(t,e){const n=[];for(const o of e)if("text"!==o.bindingType)n.push({...o,node:t,replaceNode:t});else{const e=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,node:t,replaceNode:e})}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){ct.set(t,e)}(t,r),q(t),{bindings:r,deferred:null}}function Gt(t,e){const n=Vt(t),o=[],s=[];for(const t of n){if(Ut.has(t))continue;const n=Kt(t,Bt(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Ht(t){Ut.add(t)}function Jt(t){const{node:e,parseResults:n,transform:o}=t;!function(t){Ut.delete(t)}(e);return Kt(e,n,{allowDeferred:!1},o).bindings}let Xt=0;const Yt=["$watch","$streams","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on"],Qt=new Set;function Zt(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 te(t,e,n,o,r,i=new Set){0===n.length&&st(`Cannot build a mount record without host bindings for "${e}".`);const a=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(s);l.has(n)&&st("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo};a.push(o),0===e.length&&(c=o)}a.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const d=++Xt,u=`#m${d}`,{getterKeys:f,setterKeys:h}=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}}(r),p={};for(const t of Object.keys(r))t.startsWith("$")||f.has(t)||h.has(t)||"function"!=typeof r[t]&&(i.has(t)||(p[t]=r[t]));return{id:d,marker:u,component:t,stateProp:e,parentStateElement:o,entries:a,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+s+u,stateObject:r,getterKeys:f,setterKeys:h,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set}}function ee(t){const e=t.indexOf(s);return-1===e?t:t.slice(0,e)}function ne(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 oe(t,e){for(const n of t.entries)if(ne(e,n.innerSegments)){const t=e.slice(n.innerSegments.length);return 0===t.length?n.outerPathInfo.path:n.outerPathInfo.path+s+t.join(s)}return null}function se(t,e){return t.markerBasePath+s+e}function re(t,e,n,o){let r=t.accessorBySuffixByMarkerParent.get(e);void 0===r&&(r=new Map,t.accessorBySuffixByMarkerParent.set(e,r));const i=e+s+n;r.set(n,{accessorName:o,indexShift:K(i).wildcardCount-K(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(i),t.addedGetterPaths.add(i))}function ie(t,e){return!t.injectedKeys.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 ae(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(s)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${ee(e)}: path") or declare the key on the component state.`}const le=/^\$(\d+)$/;function ce(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(s);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===r){o=t;break}if(-1===o)return re(t,t.markerBasePath,e,e),se(t,e);if(ie(t,n[0]))return re(t,t.markerBasePath,e,e),se(t,e);const i=n.slice(0,o+1),a=n.slice(o+1),l=oe(t,i);null===l&&st(ae(t,e)),0===a.length&&st(`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=l+s+t.marker;return re(t,c,a.join(s),e),c+s+a.join(s)}(t,e);const o=ee(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return se(t,e);if(ie(t,o))return se(t,e);const i=oe(t,e.split(s));if(null!==i)return i;st(ae(t,e))}function de(t,e,n){let o;const i=le.exec(e.statePathName);if(null!==i){const s=function(t,e){return void 0===e?t.delta:K(ce(t,e)).wildcardCount-K(e).wildcardCount}(t,n);o=0===s?e.statePathName:`$${Number(i[1])+s}`}else if(o=ce(t,e.statePathName),"for"===e.bindingType){const n=K(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+s+r,n)}return o===e.statePathName?e:{...e,statePathName:o,statePathInfo:K(o)}}function ue(t,e,n,o,s){if(void 0===o)return;const r=K(n).wildcardCount-K(e).wildcardCount;return 0===r?o:(s.length<r&&st(`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 fe=new WeakMap,he=new WeakMap;const pe=new WeakMap;const me=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)});function ge(t){return fe.get(t)??null}function ye(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=pe.get(t);if(void 0===o)return null;const r=e.indexOf(s,n),i=-1===r?e.slice(n):e.slice(n,r),a=o.get(i);if(void 0===a)return null;const l=a.deref();return void 0===l?(o.delete(i),null):l}const be=new WeakMap;function we(t){let e=t;for(;e;){const t=be.get(e);if(t)return t;let n=e.parentNode;null===n&&e instanceof ShadowRoot&&null!==ge(e)&&(n=e.host),e=n}return null}function ve(t,e){null!==e?be.set(t,e):be.delete(t)}let $e=null;const Se=new WeakMap;function Ne(t){return Se.get(t)??[]}function xe(t,e){Se.set(t,e)}function Ie(t){return Se.has(t)}const Pe=Symbol("$$setLoopContext"),ke=Symbol("$$getByAddress"),_e=Symbol("$$hasByAddress"),Ae=Symbol("$$setByAddress"),Ce=Symbol("$$connectedCallback"),Ee=Symbol("$$disconnectedCallback"),Me=Symbol("$$updatedCallback"),Te=new WeakMap;function Oe(t,e){if(Te.has(t)){const n=Te.get(t);if(n.has(e))return n.get(e)}else Te.set(t,new WeakMap);const n=Object.freeze(new Re(t,e));return Te.get(t).set(e,n),n}class Re{pathInfo;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Oe(t,e.parentPathInfo)}}const De=new WeakMap,je=new WeakMap;class Le{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const t=this.absolutePathInfo.parentAbsolutePathInfo;if(null===t)return null;let e=null;return e=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=We(t,e)}}function We(t,e){if(null===e){let e=je.get(t);return void 0!==e||(e=new Le(t,null),je.set(t,e)),e}{let n=De.get(e);void 0===n&&(n=new WeakMap,De.set(e,n));let o=n.get(t);return void 0!==o||(o=new Le(t,e),n.set(t,o)),o}}const Be=new WeakMap;function Fe(t,e){null===e?Be.delete(t):Be.set(t,e)}function ze(t){return Be.get(t)||null}const qe=new Map;function Ve(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=qe.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,qe.set(s,r),r}function Ue(t,e,n){return e<0||e>=n?null:t.at(e-n)}function Ke(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const Ge=new WeakMap;function He(t){const e=we(t.node);if(null===e)return null;let n=Ge.get(e);if(void 0===n)n=new WeakMap,Ge.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Ve(e.pathInfo,t.statePathInfo);return n>0&&(o=Ue(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const Je=new WeakMap;function Xe(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=ze(n);null===e?st(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function Ye(t,e){let n=null;if(n=Je.get(t)||null,null!==n)return n;const o=Xe(t,e),s=He(t),r=zi(o);null===r&&st("No state tree found on this root for binding.");return n=We(Oe(r,t.statePathInfo),s),Je.set(t,n),n}function Qe(t){Je.delete(t)}const Ze=new WeakMap;function tn(t,e){const n=Ze.get(t);void 0===n?Ze.set(t,e):n instanceof Set?n.add(e):n!==e&&Ze.set(t,new Set([n,e])),null!==$e&&$e({type:"state:binding-added",absoluteAddress:t,binding:e})}function en(t,e){const n=Ze.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&Ze.delete(t),null!==$e&&$e({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const nn=new WeakMap;function on(t,e,n){const o=nn.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:We(t,e),binding:n}))}function sn(t){const e=Ze.get(t);return void 0!==e?e:null!==t.listIndex?nn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const rn=new WeakMap,an=new WeakMap;class ln{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]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=cn(t,e)}}function cn(t,e){if(null===e){let e=an.get(t);return void 0!==e||(e=new ln(t,null),an.set(t,e)),e}{let n=rn.get(e);void 0===n&&(n=new WeakMap,rn.set(e,n));let o=n.get(t);return void 0!==o||(o=new ln(t,e),n.set(t,o)),o}}const dn=new WeakMap;function un(t){let e=null;if(e=dn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=He(t);null===n&&st(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=cn(t.statePathInfo,n)}else e=cn(t.statePathInfo,null);return dn.set(t,e),e}function fn(t){dn.delete(t)}function hn(){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 pn=new Map,mn=hn();function gn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function yn(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function bn(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=yn(t),s=gn(t,o);let r=pn.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&&st("No state tree found on this root for two-way binding.");const a=we(o);i.createState("writable",t=>{t[Pe](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]:[]})})},pn.set(s,r)),t.node.addEventListener(o,r),mn.add(s,t),!0}var e,n;return!1}function wn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function vn(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)wn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class $n{_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 Sn extends $n{constructor(t){super(t)}emit(...t){return null!==$e&&$e({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}const Nn=new WeakMap;function xn(t,e){let n=Nn.get(t);void 0===n&&(n=new Map,Nn.set(t,n));let o=n.get(e);return void 0===o&&(o=new Sn(e),n.set(e,o)),o}function In(t){Nn.delete(t)}const Pn=new WeakMap;function kn(t){if(t.propSegments[0]!==g)return!1;const e=t.node,n=J(e),o=Y(e);if(null!==n&&void 0===o?.get(n))return null===o&&st(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Pn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||st('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===J(t)?null:Z(t)}(e);null===r&&st(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&st(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${ft(s,r.knownProperties.keys())}`);const a=i.event,d=t.statePathName,u=t.propModifiers,f=t=>{u.includes(l)&&t.preventDefault(),u.includes(c)&&t.stopPropagation();const n=zi(e.getRootNode());null===n&&st("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(d)||st(`[wcs/token-undeclared] eventToken "${d}" is not declared in $eventTokens.${ft(d,n.eventTokenNames)}${ht}`);const o=we(e);n.createStateAsync("writable",async e=>{vn(e[Pe](o,()=>{const s=null!==o?Ke(o.listIndex,o.pathInfo.wildcardCount):[];return xn(n,d).emit(e,t,...s)}),`$on."${d}"`)})};return e.addEventListener(a,f),Pn.set(t,{eventName:a,handler:f}),!0}class _n extends $n{constructor(t){super(t)}emit(...t){return null!==$e&&$e({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}function An(t){return t instanceof _n}const Cn=new Map,En=hn();function Mn(t){const e=t.propModifiers.filter(t=>t===l||t===c).sort().join(",");return`${t.statePathName}::${e}`}const Tn=(t,e,n)=>o=>{e.includes(l)&&o.preventDefault(),e.includes(c)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=zi(r);null===i&&st("No state tree found on this root for event handler.");const a=we(s),d=t.startsWith(C+".");i.createStateAsync("writable",async e=>{const l=e[Pe](a,()=>{let l=null!==a?a.pathInfo.wildcardCount:0;if(null!==a&&!0===i.hasMounts){const t=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=fe.get(n);if(void 0!==t)return t;n=n.parentNode}return fe.get(e)??null}(s,r);if(null!==t){const e=t.indexShiftByLoopElementPath.get(a.pathInfo.path);l=void 0!==e?l-e:0}}const c=null!==a?Ke(a.listIndex,l):[];if(d){const s=e[ke](cn(n,null));return An(s)||st(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...c)}const u=e[t];return"function"!=typeof u&&st(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(u,e,[o,...c])});vn(l,`"${t}"`)})};function On(t){if(!t.propName.startsWith(m))return!1;const e=Mn(t);let n=Cn.get(e);void 0===n&&(n=Tn(t.statePathName,t.propModifiers,t.statePathInfo),Cn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),En.add(e,t),!0}const Rn=new Map,Dn=hn();function jn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Ln(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function Wn(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=Ln(t),s=jn(t,o);let r=Rn.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&&st("No state tree found on this root for two-way binding.");const i=we(o);r.createState("writable",t=>{t[Pe](i,()=>{t[e]=s})})},Rn.set(s,r)),t.node.addEventListener(o,r),Dn.add(s,t),!0}var e,n;return!1}const Bn=new Set(["radio","checkbox"]),Fn=new Set(["value","valueAsNumber","valueAsDate"]);function zn(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=J(n);if(null!==s){const t=Y(n)?.get(s);void 0===t&&st(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Z(n);if(o?.knownProperties.has(e))return!0}return!1}let qn=1,Vn=1,Un=1;const Kn=new WeakMap;function Gn(t,e,n){let o=Kn.get(t);void 0===o&&(o=new Map,Kn.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 Hn(t,e){return"to-element"===e?2*t:2*t+1}const Jn=new Set;function Xn(t){return{transactionId:Vn++,originBindingId:t,visitedEdges:Jn,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 Qn=null;function Zn(){return Qn}function to(t,e){const n=Qn;Qn=t;try{return e()}finally{Qn=n}}const eo=[];let no=!1;const oo=new Map,so=hn(),ro=new WeakMap,io=t=>t.detail;function ao(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 lo(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=J(t.node);if(null!==n){const o=Y(t.node)?.get(n);void 0===o&&st(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Z(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function co(t){if(null!==J(t.node)){const e=Z(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??io}return null}function uo(t){if(null===J(t.node))return!1;const e=Z(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const fo=(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);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 d=ro.get(a)?.get(t);if(void 0!==d)for(const t of d)t(c);let u=null;if(o.enablePropagationContext){const n=Gn(a,t,e),s=function(t,e){for(let n=eo.length-1;n>=0;n--){const o=eo[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:Hn(n,"to-state"),node:a,member:t}));const r=Hn(n,"to-state"),i=Zn();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}));u=Yn(i??Xn(n),r)}const f=zi(a.getRootNode());null===f&&st("No state tree found on this root for two-way binding.");const h=we(a),p=()=>{r&&(no=!0);try{f.createState("writable",t=>{t[Pe](h,()=>{t[e]=c})})}finally{r&&(no=!1)}};null!==u?to(u,p):p()};const ho=new WeakSet;function po(t){ho.add(t)}function mo(t){return!!ho.has(t)&&(ho.delete(t),!0)}const go=new WeakSet;function yo(t){go.add(t)}function bo(t){return!!go.has(t)&&(go.delete(t),!0)}let wo=0;function vo(){wo--}function $o(){return wo>0}class So{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 xo(t){let e=No.get(t);return void 0===e&&(e=new So(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!==u&&s!==f&&st(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&st(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Po(t){return t.propModifiers.some(t=>t.includes("="))}const ko=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),_o=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Ao(t,e){return"state"===t&&"call"===e?ko:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Co(t){if(!o.enableDirectionalInitialSync)return Po(t)&&st("init=/sync= modifiers require enableDirectionalInitialSync."),ko;const e=null===(n=Io(t,u))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:st(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":st(`Invalid sync modifier value "${t}".`)}(Io(t,f));if("event"===t.bindingType)return null!==e&&"none"!==e&&st("Event bindings only allow init=none."),"call"===s?_o:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===y)return Ao("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&st(`Binding type "${t.bindingType}" does not support init=${e}.`),Ao(e??"state",s);const r=Z(t.node);if(null===r)return Ao(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||st(`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)||st(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||st(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Eo(t,e){return"auto"!==e?e:function(t){const e=zi(t.replaceNode.getRootNode());null===e&&st("No state tree found on this root for binding.");const n=un(t);let o=!1;return e.createState("readonly",t=>{o=t[_e](n)}),o}(t)?"state":"element"}let Mo=0,To=0;const Oo=new WeakMap,Ro=new WeakMap,Do=new WeakMap,jo=new WeakMap;function Lo(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 Wo(t){return jo.has(t)}function Bo(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 Fo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Fo(n,e)}function zo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class qo{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(const o of t)e.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));const o=[];for(const t of e)mo(t)||Fo(t,t=>{Bo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)bo(t)&&!$o()||Fo(t,t=>{Bo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&Kr(o)}}const Vo=new WeakMap;function Uo(t){let e=Vo.get(t);return void 0===e&&(e=new qo(t),Vo.set(t,e)),e}function Ko(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 Go(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class Ho{records=new Set;rowPlan=null;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=Oo.get(t);void 0===o||"disposed"===o.phase||"failed"===o.phase?(this.start(t,s,n),r.push(t)):(this.observe(o.anchor),s.registerAddress&&null===o.address&&null===o.patternListIndex&&(o.options.registerAddress=!0,this.registerAddress(o)),"active"===o.phase&&this.settleInitialRecord(o),this.settleConnectedSnapshot(o))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(zo(e)&&Uo(e),null===this.rowPlan)for(const n of t){const t=Oo.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 Po(t)&&Co(t),!0;const e=Oo.get(t);return void 0===e||e.session!==this||(!e.options.registerAddress||"waiting-definition"===e.phase||"failed"!==e.phase&&("active"===e.phase&&this.settleInitialRecord(e),e.initialApplyDone?"state"===e.resolvedAuthority||!e.outputOnlyMember&&!e.observationPending:(e.initialApplyDone=!0,"state"===e.resolvedAuthority)))}getRecord(t){const e=Oo.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=Oo.get(t);return!(void 0===n||!this.isAlive(n,n.generation))&&(Go(n,e),!0)}deferUntilDefined(t,e,n,o=()=>{}){const s=Y(t);null===s&&st(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Lo(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=xo(s).wait(e,()=>{if(a())try{Q(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=Oo.get(t);void 0!==e&&e.session===this&&this.disposeRecord(e)}dispose(){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;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.records)null!==t.address&&(en(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];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?Ye(n):null;if(null!==e.address?(en(e.address,n),e.address=null):(on(e.patternPathInfo,e.patternListIndex,n),e.patternPathInfo=null,e.patternListIndex=null),fn(n),Qe(n),this.registerAddress(e),null!==o){const t=Ye(n);t!==o&&Ie(o)&&xe(t,Ne(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return zo(e)?e:null}(t);null!==e&&Uo(e)}handleMutations(t,e,n){for(const n of e)Fo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Fo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&Kr(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=Oo.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=Do.get(e);void 0===t&&(t=Ko(e),Do.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Lo(n,this);const o=this.knownMapFor(n);let s=Do.get(t);void 0===s&&(s=Ko(t),Do.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={registerAddress:!1,registerPathInfo:!1,applyOnReconnect:!1},o=t.slots;for(let t=0;t<e.length;t++){const s=e[t],r=o[t],i=s.replaceNode;Lo(i,this),this.addKnownRowBinding(i,s,t),this.optionsByBinding.set(s,n);const a={id:++Mo,info:s,generation:++To,phase:"active",teardowns:null,session:this,anchor:i,options:n,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:r.policy,resolvedAuthority:r.authority,initialSettled:!0,initialApplyDone:!1,outputOnlyMember:r.policy.outputOnly,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};if(Oo.set(s,a),this.records.add(a),r.isEvent){try{On(s)}catch(t){throw a.phase="failed",this.runTeardowns(a),this.records.delete(a),t}a.eventAttached=!0}}}activatePlanRows(t,e,n){const o=t.slots;for(let t=0;t<e.length;t++){const s=e[t],r=Oo.get(s);if(void 0!==r&&r.session===this){if(r.options.registerAddress=!0,"disposed"===r.phase||"failed"===r.phase){const e=o[t];if(r.generation=++To,r.phase="active",r.initialPolicy=e.policy,r.resolvedAuthority=e.authority,r.initialSettled=!0,r.initialApplyDone=!1,r.outputOnlyMember=e.policy.outputOnly,this.records.add(r),e.isEvent){try{On(s)}catch(t){throw r.phase="failed",this.runTeardowns(r),this.records.delete(r),t}r.eventAttached=!0}this.registerAddress(r,n);continue}null===r.address&&null===r.patternListIndex&&this.registerAddress(r,n)}else this.initialize([s],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}}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:++Mo,info:t,generation:++To,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};Oo.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;On(e)?t.eventAttached=!0:e.propSegments[0]!==g?(Wn(e)&&Go(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=Ln(t),n=jn(t,e),o=Rn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Dn.countOf(n)&&(Dn.remove(n,t)&&Rn.delete(n),!0))}return!1}(e)),bn(e)&&Go(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=yn(t),n=gn(t,e),o=pn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==mn.countOf(n)&&(mn.remove(n,t)&&pn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const n=function(t,e,n){let o=ro.get(t);void 0===o&&(o=new Map,ro.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&&ro.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});Go(t,n)}!function(t){const e=J(t.node);if(null!==e){const n=Y(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&st(`CustomElementRegistry is unavailable for <${e}>.`))}if(zn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=lo(t),n=co(t),o=uo(t),s=ao(t,e,null!==n,o);let r=oo.get(s);void 0===r&&(r=fo(t.propName,t.statePathName,t.inFilters,n,o),oo.set(s,r)),t.node.addEventListener(e,r),so.add(s,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{kn(e)&&Go(t,()=>function(t){if(t.propSegments[0]!==g)return!1;const e=Pn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),Pn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=J(t.info.node);if(null===n)return void e();const o=Y(t.info.node);if(null===o&&st(`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=xo(o).wait(n,()=>{if(this.isAlive(t,s))try{Q(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))});Go(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Co(t.info),n=Eo(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 wo++;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,vo()),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&&st("No state tree found on this root for initial binding sync.");const s=we(t.node);o.createState("writable",e=>{e[Pe](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=He(n);if(null!==o){const s=zi(Xe(n,e));null===s&&st("No state tree found on this root for binding.");const r=Oe(s,n.statePathInfo);!function(t,e,n){let o=nn.get(t);void 0===o&&(o=new WeakMap,nn.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:We(t,e),binding:n})}(r,o,n),t.patternPathInfo=r,t.patternListIndex=o}else{const o=Ye(n,e);tn(o,n),t.address=o}if(!t.options.registerPathInfo)return;const s=zi(n.replaceNode.getRootNode());null===s&&st("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&&Oo.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,vo());const e=t.info;if(null!==t.address)try{en(t.address,e),t.address=null,fn(e),Qe(e)}catch{}else if(null!==t.patternListIndex)try{on(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,fn(e),Qe(e)}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=J(t.node);if(null!==e){const n=Y(t.node),o=n?.get(e);if(void 0===o)return}if(zn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=lo(t),n=ao(t,e,null!==co(t),uo(t)),o=oo.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),so.remove(n,t)&&oo.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{!function(t){if(!t.propName.startsWith(m))return!1;const e=Mn(t),n=Cn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==En.countOf(e)&&(En.remove(e,t)&&Cn.delete(e))}(e)}catch{}}}}function Jo(t){let e=Ro.get(t);return void 0===e&&(e=new Ho(t),Ro.set(t,e)),e}function Xo(t){return Oo.get(t)?.session??null}const Yo=new WeakMap;function Qo(t,e){let n=Yo.get(t);n||(n=new Set,Yo.set(t,n)),n.add(e)}const Zo=new WeakMap;function ts(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const es=Object.freeze([]);const ns=new WeakMap;const os=new WeakMap;function ss(t){return os.get(t)??[]}function rs(t,e){os.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 is=0;function as(){return`u${(is++).toString(36)}`}let ls=0;class cs{uuid=as();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(t,e){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._index=e,this._version=ls}get index(){return this._index}set index(t){this._index=t,this._version=++ls,this.indexes[this.position]=t}get version(){return this._version}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=ls),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0===this._listIndexes&&(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)]),this._listIndexes}get varName(){return`$${this.position+1}`}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function ds(t,e){return new cs(t,e)}const us=new WeakMap;function fs(t){return us.get(t)||null}function hs(t,e){null!==e?us.set(t,e):us.delete(t)}const ps=new WeakMap,ms=Object.freeze([]),gs=new Set;function ys(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:ms,s=Array.isArray(n)&&n.length>0?n:ms,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:ms,o=Array.isArray(e)&&e.length>0?e:ms;let s=ps.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=fs(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:gs,deleteIndexSet:new Set(i),addIndexSet:gs};let e=fs(s);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=ds(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:gs,deleteIndexSet:gs,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 a={oldIndexes:i,newIndexes:i,changeIndexSet:gs,deleteIndexSet:gs,addIndexSet:gs};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,l=new Set;for(let o=0;o<s.length;o++){const a=s[o],c=n.get(a),d=c&&c.length>0?c.shift():void 0;if(void 0===d){const n=ds(t,o);e.push(n),l.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(!function(t,e,n){let o=ps.get(t);o||(o=new WeakMap,ps.set(t,o)),o.set(e,n)}(o,s,a),hs(s,a.newIndexes))}}(t,e,n);return function(t){for(let e=0;e<t.length;e++)t[e].index!==e&&(t[e].index=e)}(o.newIndexes),o}function bs(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}const ws=new WeakMap;function vs(t){return ws.get(t)??[]}function $s(t,e){ws.set(t,e)}const Ss=new WeakMap;function Ns(t){return Ss.get(t)??null}function xs(t,e){Ss.set(t,e)}const Is=new WeakMap;function Ps(t){return Is.get(t)??[]}function ks(t,e){Is.set(t,e)}function _s(t,e){const n=Ps(t);for(const t of n)ve(t,e)}function As(t,e,n){_s(t,e);const o=vs(t),s=Ns(t);null!==s&&s.activate(o,n.rootNode);for(const t of o){if(null===s){tn(Ye(t),t)}(null===s||s.shouldApplyState(t))&&Vr(t,n)}}function Cs(t){if(!t.mounted)return;const e=vs(t),n=Ns(t);for(const t of e)if(null!==n)n.disposeBinding(t);else{en(Ye(t),t)}!function(t){const e=Ps(t);for(const t of e)ve(t,null)}(t)}const Es=new WeakMap,Ms=Object.freeze(new Set);function Ts(t,e){const n=Es.get(t);n?n.add(e):Es.set(t,new Set([e]))}function Os(t){const e=Es.get(t);return void 0!==e?e:Ms}function Rs(t,e){const n=Es.get(t);n&&(n.delete(e),0===n.size&&Es.delete(t))}const Ds=new Set(["if","elseif","else","for"]);class js{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e,this._childNodeArray=Array.from(this._content.childNodes),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){for(const e of this._childNodeArray)yo(e),t.appendChild(e);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){yo(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=Ns(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)po(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=vs(this);for(const t of e)if(Ds.has(t.bindingType)){const e=Os(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){Ns(this)?.dispose();for(const t of this._childNodeArray)po(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=vs(this);for(const e of t){if(Ds.has(e.bindingType)){const t=Os(e.node);for(const e of t)e.unmount()}fn(e),Qe(e)}this._mounted=!1}}function Ls(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}function Ws(t){const e=document.createDocumentFragment(),n=new js(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 Bs(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=lt(o,s[t].nodePath);null===e&&st(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Ht(e),q(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){const n=new Ho;return n.initializeRow(t,e),n}(n,a),d=new js(o);return xs(d,c),$s(d,a),rs(d,l),ks(d,r),Ts(t.node,d),d}function Fs(t){void 0!==t.uuid&&null!==t.uuid||st("BindingInfo.uuid is null.");const n=Wt(t.uuid);n||st(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&Ls(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=lt(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===y||s===g)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==J(r))return null;if("prop"===o&&zn(r,t.propName))return null;let i;try{i=Co({...t,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;n.push({nodeIndex:e,template:t,isEvent:"event"===o,isIndexBinding:t.statePathName in S,policy:i,authority:i.authority})}}return{directional:e,slots:n}}(n)),null!==r)return Bs(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=lt(t,s.nodePath);if(null===e&&st(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Ut.has(e))continue;const r=Kt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new Ho,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new js(i,s);xs(l,a.bindingSession),$s(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in S&&c.push(t);return rs(l,c),ks(l,a.nodes),Ts(t.node,l),l}const zs=Symbol.for("wcstack.transition-runner");function qs(t){const e=globalThis[zs];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}const Vs=new WeakSet,Us=Symbol.for("wcstack.state.view-transition-naming");function Ks(){const t=qs("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Gs(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||Vs.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[Us]??={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.`)):(Vs.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 Hs=new WeakMap,Js=new WeakMap,Xs=new WeakMap,Ys=new WeakMap;function Qs(t,e,n){!function(t,e,n){let o=Js.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Js.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Zs(t,e){Hs.set(t,e)}function tr(t,e){let n=Xs.get(t.node);void 0===n&&(n=[],Xs.set(t.node,n)),n.length<1e3?n.push(e):Rs(t.node,e)}function er(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)}function nr(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function or(t,n,s){const r=Boolean(s);let i;const a=Os(t.node);i=0===a.size?Fs(t):a.values().next().value;const l=e(),c=t.uuid??"",d=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${nr(t)}`),Cs(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${nr(t)}`),l){const e=document.createComment(`@@wcs-${d}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);As(i,we(t.node),n);const e=Ks();null!==e&&Gs(i,"branch",e)}}const sr=new WeakMap,rr=new WeakMap;const ir=new WeakMap;const ar=new WeakMap;function lr(t){return ar.get(t)??[]}const cr=new Set;const dr={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 ur(t,n,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 l=i[0],c=r[l];if(c!==s){null!==c&&"object"==typeof c&&null!==s&&"object"==typeof s&&null!==J(r)&&function(t,e,n){let o=sr.get(t);o||(o=new Map,sr.set(t,o)),o.has(e)||o.set(e,n)}(r,l,c);const e=()=>{let t=!1;try{r[l]=s,t=!0}catch(t){o.debug&&console.warn(`Failed to set property '${l}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=J(t);if(null===n)return null;const o=Y(t)?.get(n);if(void 0===o)return null;const s=Z(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,l);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&&zn(r,l)){const o=Gn(r,l,t.statePathName),i=Hn(o,"to-element"),a=n?.propagationContextByBinding?.get(t)??Zn()??Xn(o);if(a.visitedEdges.has(i))null!==$e&&$e({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:r,member:l});else{const t=Yn(a,i);to(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Un++,writtenValue:n};eo.push({receipt:i,node:t});try{return r()}finally{eo.pop()}}(r,l,s,o,t.transactionId,e))}}else e()}if(e()){const t=dr[l];t?t(r,s):(!function(t,e,n){let o=ar.get(t);o||(o=[],ar.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,l,s),a=r,cr.add(a))}return}var a;const l=i[0];let c=r[l];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==c)return;c=c[e]}const d=i[i.length-1],u=c[d];if(u!==s){if(Object.isFrozen(c))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:u,newValue:s}));2===i.length&&"object"==typeof c&&null!==c&&null!==J(r)&&(d in c?function(t,e,n,o){let s=ir.get(t);s||(s=new Map,ir.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}(r,l,d,c[d]):function(t,e,n){let o=rr.get(t);o||(o=new Map,rr.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)}(r,l,d));try{c[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:u,newValue:s,error:t})}}}const fr=new WeakSet;function hr(t,e,n){}const pr=new WeakMap;function mr(t,e){if(null===t)return!1;const n=pr.get(t);if(void 0===n||0===n.size)return!1;for(const t of n)if(e===t||e.startsWith(t+s)||t.startsWith(e+s))return!0;return!1}const gr=new WeakMap;function yr(t,e){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{e.$postUpdate(t+s+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...r)=>e[n](t+s+o,...r)}return e[o]}return e[t+s+o]}},set:(n,o,r)=>("string"!=typeof o||(e[t+s+o]=r),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const br=new WeakMap,wr=[];const vr=new WeakMap;let $r=null;const Sr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Nr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function xr(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 Ir(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),r=e.length>0?e+s:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(s)&&o.push(e)}return o}const Pr={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},kr={binding:"Bound path",watch:"$watch path"};function _r(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}.${ht}`}function Ar(t,e){return`$setAll("${t}") ${e}`}function Cr(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.${ht}`}const Er=new WeakMap;function Mr(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(mr(t.rootNode??null,n))return;const i=K(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=Er.get(t);return void 0===n&&(n=new Set,Er.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;const a=function(t,e,n){if(void 0!==xr(t,e))return Nr;const o=K(e).segments;let i=t,a="";for(let e=0;e<o.length;e++){const l=o[e],c=a;if(a=0===e?l:a+s+l,e>0&&e<o.length-1&&void 0!==xr(t,a))return Sr;if(Object(i)!==i)return Sr;if(l===r){if(!Array.isArray(i)||0===i.length)return Sr;i=i[0];continue}const d=xr(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:Ir(i,c,n)};if("function"==typeof d.get)return e===o.length-1?Nr:Sr;i=d.value}return Nr}(e,n,t.getterPaths);"missing"===a.existence&&(console.warn(`[@wcstack/state] [${Pr[o]}] ${kr[o]} "${n}" does not resolve on the state tree: "${a.missingSegment}" is not declared.${ft(a.missingSegment,a.candidates)} Updates to this path will be silently dropped.${ht}`),null!==$e&&$e({type:"state:path-unresolved",source:o,path:n,missingSegment:a.missingSegment}))}function Tr(t,e){const n=un(e);if(n.pathInfo.path in S){const t=we(e.node);return null===t&&st(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&st("ListIndex not found for loopContext:");const n=S[e];void 0===n&&st(`Invalid index name: ${e}`);const o=Ue(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&st(Cr(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[ke](n)}const Or=new WeakSet;function Rr(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Dr=Object.freeze({[b]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&st("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[w]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[v]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[y]:function(t,e,n){An(n)||st("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ns.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||st('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=J(t);if(null===e)return null;const n=Y(t)?.get(e);return void 0===n&&st(`Custom element <${e}> is not defined for command binding.`),Z(t)}(r);null===a&&st(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||st(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ft(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ns.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 ns.delete(t);const o=n[i];return"function"!=typeof o&&st(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),ns.set(t,{token:o,unsubscribe:c,elementRef:l})}}),jr={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!fr.has(t.replaceNode)){fr.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,i=He(t),a=Ye(t),l=Ne(a),c=l.length>0&&!Js.has(t.node)?[]:l,d=ys(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);const u=Array.isArray(c)&&c.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(u&&null!==t.node.parentNode){let e=Ys.get(t.node);if(void 0===e){const n=Hs.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(n.nodeType===Node.ELEMENT_NODE||n.nodeType===Node.TEXT_NODE&&""!==(n.textContent?.trim()??"")){s=!1;break}n=n.previousSibling}for(;null!==o;){if(o.nodeType===Node.ELEMENT_NODE||o.nodeType===Node.TEXT_NODE&&""!==(o.textContent?.trim()??"")){s=!1;break}o=o.nextSibling}return s}(t.node,n),Ys.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let f=Js.get(t.node),h=u?1e3-function(t){return Xs.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==f){for(const e of d.deleteIndexSet){const n=f.get(e);void 0!==n&&(h<=0&&n.tryDestroy()?Rs(t.node,n):(Cs(n),n.unmount(),tr(t,n),h-=1),u||f.delete(e))}u&&(Js.delete(t.node),f=void 0)}let p=t.node;const m=K(s.path+"."+r),g=n.stateElement.loopContextStack,y=bs(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&p.isConnected&&(b=document.createDocumentFragment(),Fe(b,n.rootNode));const w=e(),v=Ks(),$=t.uuid??"",S=Xs.get(t.node);for(const e of d.newIndexes){let o;if(d.addIndexSet.has(e)){const r=cn(m,e);g.createLoopContext(r,r=>{if(o=void 0!==S?S.pop():void 0,void 0===o&&(o=Fs(t)),null!==b)w&&b.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`)),o.appendTo(b),w&&b.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`));else{if(p.nextSibling!==o.firstNode){if(w){const t=document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`);p.parentNode.insertBefore(t,p.nextSibling),p=t}o.mountAfter(p)}if(w){const t=document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`),n=o.lastNode??p;n.parentNode.insertBefore(t,n.nextSibling)}}As(o,r,n),null!==v&&Gs(o,"row",v)}),void 0===o&&st(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=void 0!==f?f.get(e)??null:null,d.changeIndexSet.has(e)){const t=ss(o);for(const e of t)Vr(e,n)}null===o&&st(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==y&&y.has(e)&&er(p,o.firstNode)||p.nextSibling===o.firstNode||o.mountAfter(p),t){const t=o,s=cn(m,e);g.createLoopContext(s,e=>{As(t,e,n)})}}p=o.lastNode||p,void 0===f&&(f=new WeakMap,Js.set(t.node,f)),f.set(e,o)}Hs.set(t.node,p),null!==b&&(t.node.parentNode.insertBefore(b,t.node.nextSibling),Fe(b,null))},if:or,else:or,elseif:or,radio:function(t,e,n){const o=t.node,s=ts(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=ts(o.value,t.inFilters),r=Array.isArray(n)?n:es;o.checked=r.includes(s)}},Lr=new WeakMap,Wr=new WeakMap,Br=new WeakMap;function Fr(){}function zr(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===Yo.get(t)?.has(e)}(e,n)?hr:function(t,e){return!0===Zo.get(t)?.has(e)}(e,n)?Fr:ur}function qr(t,e){const n=ts(Tr(e.state,t),t.outFilters);if(!0===Wr.get(t))return void e.deferredSelectBindings.push({binding:t,value:n});let o=Lr.get(t);if(void 0===o){if(Lr.has(t))return o=zr(t),o===hr&&Lr.set(t,o),void o(t,e,n);if(o=jr[t.bindingType],void 0===o){const e=t.propSegments[0];if(o=Dr[e],Lr.set(t,o),void 0===o){J(t.replaceNode)?(o=zr(t),o===hr&&Lr.set(t,o)):(o=ur,Lr.set(t,o))}}if(o===ur){if("SELECT"===t.node.tagName){const o=t.propSegments[0];if("value"===o||"selectedIndex"===o)return e.deferredSelectBindings.push({binding:t,value:n}),void Wr.set(t,!0)}}o(t,e,n)}else o(t,e,n)}function Vr(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=Ye(t);if(e.updatedAbsAddressSetByStateElement.has(e.stateElement)){e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n)}else e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=Xo(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Br.get(t)){const e=J(t.replaceNode);if(e&&void 0===Y(t.replaceNode)?.get(e))return void function(t,e){if(Or.has(t))return;Or.add(t);const n=()=>{Or.delete(t);const e=Xo(t);(null===e||e.shouldApplyState(t))&&Kr([t])},o=n=>{Or.delete(t),Rr(e,n)},s=Xo(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Or.delete(t),r()})||(Or.delete(t),r()))}const r=Y(t.replaceNode);if(null===r)return Or.delete(t),void Rr(e,new Error("CustomElementRegistry is unavailable."));xo(r).wait(e,()=>{t.replaceNode.isConnected?n():Or.delete(t)},o)}(t,e);Br.set(t,!0)}if(!0===e.sameRootVerified)return void qr(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=ze(o),null===o&&st("Root node for fragment not found for binding.")),o!==e.rootNode){const n=zi(o);null===n&&st("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};qr(t,r)})}else qr(t,e)}function Ur(t,e){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 Kr(t,e){let n=0;const s=new Set,r=new Map,i=new Map,a=[];for(;n<t.length;){let l=t[n];if(!1===l.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${l.bindingType} ${l.statePathName} on ${l.node.nodeName}`,l),n++;continue}let c=l.replaceNode.getRootNode();c instanceof DocumentFragment&&!(c instanceof ShadowRoot)&&(c=ze(c),null===c&&st("Root node for fragment not found for binding."));const d=zi(c);null===d&&st("No state tree found on this root for binding."),d.createState("readonly",o=>{const u={rootNode:c,stateElement:d,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Vr(l,u)}catch(t){Ur(l,t)}n++;const e=t[n];if(!e)break;if(e.replaceNode.getRootNode()!==u.rootNode)break;l=e}})}for(const{binding:t,value:n}of a)try{ur(t,{propagationContextByBinding:e},n)}catch(e){Ur(t,e)}for(const[t,e]of r.entries())xe(t,e);for(const[t,e]of i.entries())t.createState("writable",t=>{t[Me](Array.from(e))})}function Gr(t,e,n){const[o,s,r]=Gt(t,n),i=Jo(t);for(const t of o)ve(t,e);Kr(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=Jt(o);0!==t.length&&(ve(o.node,e),Kr(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const Hr=/\{\{\s*(.+?)\s*\}\}/g,Jr=new Set(["SCRIPT","STYLE"]);function Xr(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&&Jr.has(t.parentElement.tagName)||Yr(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),Xr(e.content)}else Xr(t.content)}function Yr(t){const e=t.data;if(Hr.lastIndex=0,!Hr.test(e))return;Hr.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Hr.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)}let Qr;function Zr(){if(Qr)return Qr;const t=[],e=Nt("not",t)($t);return Qr={filterName:"not",args:t,filterFn:e},Qr}const ti=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function ei(t,e){const n=e+s+r,o=t.indexOf("|");let i,a;if(-1!==o?(i=t.slice(0,o).trim(),a=t.slice(o)):(i=t.trim(),a=""),"."===i)i=n;else{if(!i.startsWith("."))return t;i=n+s+i.slice(1)}return a.length>0?i+a:i}function ni(t,e){const n=ti.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+ei(s,e)+r}function oi(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=ei(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function si(t,e){return oi(t,e)}function ri(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=ni(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=oi(r,e);t!==r&&o.setAttribute(n,t)}}}function ii(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 ai(t){const e=[],n=Vt(t);for(const t of n){const n=Bt(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:ii(o),parseBindTextResults:n})}return e}function li(t){const e=Array.from(t.childNodes);for(const n of e)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&t.removeChild(n)}}const ci=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),di=Zr();function ui(t,e){const n=e.outFilters;return{...e,outFilters:[...n,di],bindingType:t}}function fi(t,e,n,o,s,r=!0){li(e),"string"==typeof o&&ri(e,o),hi(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:ai(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 hi(t,e,n,s){const r=o.commentElsePrefix,i=zt(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;if(i.length>0&&-1!==i.indexOf(e))return NodeFilter.FILTER_REJECT;if("template"===e.tagName.toLowerCase()){if((e.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const t=a.currentNode;d.push(t)}for(const e of d){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=si(i,n));let a=Et(i)[0];const d=ci.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=e.content,h=as();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&st("'else' binding found without preceding 'if' or 'elseif' binding."),a=ui("else",l.parseBindTextResult),p=fi(t,f,a,m,s,!1),Lt(h,t,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:ii(o),parseBindTextResults:Bt(o)})):e.replaceWith(o)}else if("elseif"===u){null===l&&st("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=fi(t,f,a,m,s),Lt(h,t,p);const n=document.createComment(`@@${d}:${h}`),o=as(),i={fragment:document.createDocumentFragment(),parseBindTextResult:ui("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ii(n),parseBindTextResults:Bt(n)}),Lt(o,t,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(e.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:ii(g),parseBindTextResults:Bt(g)})):e.replaceWith(g)}else{p=fi(t,f,a,m,s),Lt(h,t,p);const n=document.createComment(`@@${d}:${h}`);e.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}async function pi(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Y(t);null===s&&st(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(Ft(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function mi(t){if(t===document)await pi(document),Xr(document),hi(document,document),Gr(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await z(e.host),await pi(e),Xr(e),hi(e,e),Gr(e,null)}}const gi="2.0.0",yi="undefined"==typeof HTMLElement?class{}:HTMLElement,bi=/^@@wcs-(?:for|if|elseif|else):[^-]/,wi=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,vi=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,$i=/^@@wcs-text-start:(.+)$/;function Si(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Ni extends yi{_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=gi.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;if(!n)return null;return n.querySelector(e)}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const[t,o]of Object.entries(e))t.startsWith("$")||"function"==typeof o||(n[t]=o);return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=Si(JSON.stringify(e)),t.appendChild(n);const s=Array.from(jt.keys());for(const e of s){const n=Wt(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(cr);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=lr(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=Si(JSON.stringify(e)),t.appendChild(n)}}cr.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(wi.test(t.data)||vi.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;bi.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=$i.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;wi.test(t.data)&&i.push(t)}for(const t of i){const e=wi.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()}Ni.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(bi.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 xi=new Set(["for","if","elseif","else"]);function Ii(t){const e=new Ho;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]=Gt(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 Pi(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 ki(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Et(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,Zr()],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;li(a),"string"==typeof l&&ri(a,l),hi(n,a,l);Lt(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:ai(a)})}}async function _i(t){await pi(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="${gi}". Falling back to full render.`),Ni.cleanupDom(t),!1}for(const n of e)ki(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=wi.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 d=t.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body);!function(t,e){const n=new Map;for(const o of e){if(0===o.nodes.length)continue;const e=Ws(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=Ii(o.nodes);xs(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");$s(e,s),ks(e,i);const l=[];for(const t of s)t.statePathName in S&&l.push(t);if(rs(e,l),"for"===o.type&&null!==o.index){const i=Pi(t,"for",o.uuid);if(i){const t=ds(null,o.index);Qs(i,t,e),Zs(i,o.nodes[o.nodes.length-1]),Ts(i,e),_s(e,cn(K(o.path+"."+r),t)),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let l=n.get(o.uuid);l||(l=[],n.set(o.uuid,l)),l.push(t)}}else{const n=Pi(t,o.type,o.uuid);n&&(Ts(n,e),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=Pi(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Wt(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=zi(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&hs(e,o)})}}(document.body,n),Ni.removeBlockBoundaryComments(document.body);const s=[];for(const t of e)t.parentNode&&(s.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());Ni.restoreTextBindings(document.body);const[i,a]=Gt(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 l=[],c=[],d=Jo(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(xi.has(t.bindingType))c.push(t);else{if(t.statePathName.includes(r))continue;l.push(t)}for(const t of c)if("for"===t.bindingType){const e=Ye(t),n=zi(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&xe(e,o)})}Kr(l);for(const{el:t,parent:e,next:n}of s)e.insertBefore(t,n);const u=t.querySelectorAll(o.tagNames.ssr);for(const e of u){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}const Ai=Symbol.for("wcstack.binder");const Ci=Symbol.for("wcstack.binder.pending"),Ei=Symbol.for("wcstack.binder.taken");function Mi(){const t=function(){const t=globalThis[Ai];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[Ci];return void 0===e&&(e=[],t[Ci]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[Ei];return void 0===e&&(e=new WeakSet,t[Ei]=e),e}();for(const e of n)o.add(e),t.bind(e)}function Ti(t){if(Wo(t))return!0;if(!Oi(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Wo(e)}function Oi(t){return 1===t.nodeType}function Ri(t){if(Ti(t))return;Xr(t),hi(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Gr(e&&s?n:t,null)}const Di=[];function ji(){const t=Di.splice(0,Di.length);for(const e of t)Ri(e);Mi()}const Li={protocol:"wcs-binder",version:1,bind:function(t){var e;Oi(t)&&!Ti(t)&&(e=t.getRootNode(),Vi.has(e)?Ri(t):Di.push(t))}};const Wi=new WeakMap,Bi=new WeakMap,Fi=new Set;function zi(t){return Wi.get(t)??null}function qi(t){return Bi.get(t)??Promise.resolve()}const Vi=new WeakSet;function Ui(t){Vi.add(t)}function Ki(t,n){const s=Wi.get(t);if(null===n){if(void 0===s)return;Wi.delete(t),Fi.delete(s),null!==$e&&$e({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{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{if(o){await _i(t)||await mi(t)}else await mi(t);Ui(t),ji(),e()}catch(t){n(t)}})});Bi.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await mi(t),Ui(t),ji(),e()}catch(t){n(t)}})});Bi.set(t,e)}}void 0!==s&&st('A state tree is already registered on this root — one <wcs-state> per root in v2. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Wi.set(t,n),Fi.add(n),function(t,e){const n=vr.get(t);if(void 0===n||0===n.length||null===$r)return;vr.delete(t);const o=$r;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,n),null!==$e&&$e({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}let Gi=0,Hi=0;const Ji=[];function Xi(t,e=0){const n=Ji.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Ji.push(o):Ji.splice(n,0,o)}function Yi(t){queueMicrotask(()=>{throw t})}const Qi=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){Gi>Hi&&(Hi=Gi);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&queueMicrotask(()=>{const t=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(t)})}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t){const n=new Map;for(const e of t){const t=n.get(e.absoluteAddress);null!==$e&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&$e({type:"propagation:coalesced",absoluteAddress:e.absoluteAddress,droppedTransactionId:t.transactionId,winnerTransactionId:e.context.transactionId}),n.set(e.absoluteAddress,e.context)}const o=[],s=new Map;for(const[t,e]of n){if(null!==e&&e.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),null!==$e&&$e({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=sn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(o.push(t),null!==e&&s.set(t,e));else!1!==n.replaceNode.isConnected&&(o.push(n),null!==e&&s.set(n,e))}try{const t=()=>{s.size>0?Kr(o,s):Kr(o)};if(e()||0===o.length)t();else{const e=function(t,e,n){const o=qs(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("state",t);void 0!==e&&e.catch(Yi)}}finally{!function(t){for(const e of Ji.slice())e.listener(t)}(new Set(n.keys()))}}};function Zi(){return Qi}const ta=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function ea(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 na="__WCSTACK_DEVTOOLS_HOOK__";function oa(){const t=globalThis,e=t[na];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[na]=n,n}const sa=t=>{null!==$e&&$e({type:"state:update-batch",addresses:t})};function ra(t){const e=null!==$e;!function(t){$e=t}(t);const n=null!==t;n&&!e?Xi(sa,0):!n&&e&&function(t){const e=Ji.findIndex(e=>e.listener===t);-1!==e&&Ji.splice(e,1)}(sa)}function ia(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 aa(t){return zi(t)??st("devtools: no state tree on this root")}let la=null;function ca(){if(e())return;if(null!==la)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:gi,getStateElements(){const t=[];for(const e of Fi)t.push(ia(e));return t},overlays:t=>function(t){const e=pe.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}(aa(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]})),keys(t){const e=aa(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 aa(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){aa(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=Wt(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(ea(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=at(e,Et(n));for(const o of t)r(ea(e,o,"attribute",n))}catch{}continue}const e=ta.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=Wt(s);if(null===a){if(n===o.commentTextPrefix)try{r(ea(t,Dt(s),"comment",s))}catch{}}else r(ea(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:ra};la=t,oa().register(t)}const da={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",gi),Ni.buildContent(o,Ni.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}};const ua="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let fa=0;async function ha(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++fa}\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 ${ua}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${ua}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function pa(t){try{const e=await import(function(t){return new URL(t,document.baseURI).href}(t));return e.default||{}}catch(t){st(`Failed to load script file: ${t}`)}}class ma{_loopContextStack=Array(i).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&st("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=i&&st("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&&st("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&&st("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&&st(`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 ga=new WeakMap;function ya(t,e){let n=ga.get(t);void 0===n&&(n=new Map,ga.set(t,n));let o=n.get(e);return void 0===o&&(o=new _n(e),n.set(e,o)),o}const ba=new WeakMap;function wa(t){const e=ba.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 ya(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:ya(t,n)}},set(){st("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){st("$command namespace is read-only; deleting from it is not allowed.")}});return ba.set(t,n),n}const va=Symbol("wcs-stream-last-notified-uncertain"),$a=new WeakMap;function Sa(t,e){const n=$a.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Na(t,e){const n=$a.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:va,error:Object.is(o.error,null)?null:va})}const xa=new Set;function Ia(t){xa.delete(t)}const Pa=new WeakMap;function ka(t){return Pa.get(t)??new Map}function _a(t){Ia(t);const e=Pa.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Na(t,n.name)}const Aa=(t,e)=>e,Ca=new Set;function Ea(t,e){const n=e[T];if(void 0===n)return void Sa(t,Ca);"object"==typeof n&&null!==n||st(`${T} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[i,a]of Object.entries(n)){0===i.length&&st(`${T} entry name must be a non-empty string.`),i.includes(s)&&st(`${T} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&st(`${T} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&st(`${T} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&st(`${T} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&st(`${T} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&st(`${T} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||st(`${T} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&st(`${T} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&st(`${T} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&st(`${T} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&st(`${T} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??Aa,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};i in e||(e[i]=c.definition.initial),o.set(i,c)}!function(t,e){Pa.set(t,e)}(t,o),Sa(t,new Set(o.keys()))}const Ma=new WeakMap,Ta=new WeakMap;function Oa(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=ka(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&ka(t).has(n),ownKeys:()=>Array.from(ka(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=ka(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){st(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){st(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Ra(t){const e=Ma.get(t);if(void 0!==e)return e;const n=Oa(t,D,t=>t.status);return Ma.set(t,n),n}function Da(t){const e=Ta.get(t);if(void 0!==e)return e;const n=Oa(t,j,t=>t.error);return Ta.set(t,n),n}function ja(t){Ma.delete(t),Ta.delete(t)}let La=null;async function Wa(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)}}function Ba(t){const e=ka(t);if(0!==e.size){!function(t){xa.add(t)}(t);for(const n of e.values())Fa(t,n)}}function Fa(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=La,r=new Set;let i;La=r;try{t.createState("readonly",t=>{i=n(t)})}finally{La=o}i instanceof Promise&&st(`${T} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${D}${s}${e.name}`,l=`${j}${s}${e.name}`;for(const n of r){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==a&&o.path!==l||st(`${T} 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&&st(`${T} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=r,i}(t,e);t.createState("writable",t=>{t[e.name]=e.definition.initial}),za(t,e,"active",null);const r=e.definition,i={fold(n){t.createState("writable",t=>{t[e.name]=r.fold(t[e.name],n)})},done(){za(t,e,"done",null)},fail(o){za(t,e,"error",o),n.abort()}};Wa(r.source,o,n.signal,i)}function za(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return $a.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),i=r.status!==n,a=!Object.is(r.error,o);(i||a)&&(!function(t,e,n,o){let s=$a.get(t);void 0===s&&(s=new Map,$a.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${D}${s}${e.name}`),a&&t.$postUpdate(`${j}${s}${e.name}`)}))}Xi(function(t){const e=xa;if(0===e.size)return;const n=[];for(const o of e)for(const e of ka(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)&&ka(t).get(o.name)===o)try{Fa(t,o)}catch(n){o.controller?.abort(),e.has(t)&&ka(t).get(o.name)===o&&za(t,o,"error",n)}},20);const qa=new WeakMap,Va=new WeakMap,Ua=new Set,Ka=new Map;function Ga(t){return qa.get(t)??Ka}function Ha(){return Ua}const Ja=new Map;function Xa(t){return Va.get(t)??Ja}function Ya(t){0===t.length&&st(`[wcs/watch-declaration-invalid] ${O} entry name must be a non-empty state path.`),t.startsWith("$")&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not start with "$" (reserved namespace).${ht}`),t.includes("@")&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ht}`),t in Object.prototype&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=K(t);for(const n of e.segments)0===n.length&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" has an empty path segment.${ht}`);return e.wildcardCount>128&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" exceeds the maximum wildcard depth (128).`),e}function Qa(t,e){const n=e[O];if(void 0===n)return null;"object"==typeof n&&null!==n||st(`[wcs/watch-declaration-invalid] ${O} must be an object mapping state paths to handler functions.${ht}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&st(`[wcs/watch-declaration-invalid] ${O} entry "${e}" must be a function.${ht}`);const n=Ya(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){qa.set(t,e)}(t,o),s.size>0?s:null}const Za=new WeakMap;function tl(t,e,n){let o=Za.get(t);void 0===o&&(o=new Map,Za.set(t,o)),o.set(e,n)}const el=new Map;function nl(t){0===Ga(t).size&&0===Xa(t).size||(function(t){Ua.add(t)}(t),function(t){const e=[];for(const n of Ga(t).values())sl(t,n)&&e.push(n);for(const n of Xa(t).values())for(const o of n)sl(t,o)&&e.push(o);if(0===e.length)return;t.createState("readonly",n=>{for(const o of e)try{tl(t,ol(t,o),n[o.path])}catch(e){il(t,o.path,"prime",e)}})}(t))}function ol(t,e){return We(Oe(t,e.pathInfo),null)}function sl(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const rl={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function il(t,e,n,o){console.error(`[@wcstack/state] $watch ${rl[n]} "${e}" threw.`,o),null!==$e&&$e({type:"state:watch-error",phase:n,path:e,error:o})}function al(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 ll(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=sl(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){if(0===e.pathInfo.wildcardCount)return t[e.path];return t.$resolve(e.path,n)}(t,n,s)}catch(t){return void il(0,n.path,"evaluate",t)}const a=r?function(t,e){return Za.get(t)?.get(e)}(e,o):function(t){return el.get(t)}(o);r&&tl(e,o,i),null!==$e&&$e({type:"state:watch-fired",path:n.path}),n.handler.call(t,i,a,...s)})}catch(t){il(0,n.path,"handler",t)}}function cl(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 dl(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 ul(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 fl(t){return t.startsWith("$")}function hl(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}function pl(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 ml(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||st(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||st(`${e} entries must be non-empty strings.`),t.startsWith("$")&&st(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&st(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function gl(t){const e=ml(t,k)??[],n=ml(t,_)??[],o=hl(t),s=function(t){const e=t[T];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}st(`${k} entry "${t}" is not declared on the state.${ft(t,pl(o,"value"))}`)}"function"==typeof e.value&&st(`${k} entry "${t}" is a method. Declare it in ${_} instead.`)}for(const t of n){const e=o[t];void 0===e&&st(`${_} entry "${t}" is not declared on the state.${ft(t,pl(o,"method"))}`),"function"!=typeof e.value&&st(`${_} entry "${t}" is not a method. Declare it in ${k} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}Xi(function(t){const e=Ha();try{if(0===e.size)return;const n=function(){const t=Hi;return Hi=0,t}();if(n>32){const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==$e&&$e({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=Ga(t).get(s),i=Xa(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=Ke(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(al),function(t){Gi=t+1}(n);try{for(const t of o){if(!e.has(t.stateElement))continue;const n=Ga(t.stateElement).get(t.entry.path)===t.entry,o=!0===Xa(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&ll(t)}}finally{Gi=0}}finally{el.clear()}},10);const yl=new Map;class bl{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=K(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 wl(t){let e;return yl.get(t)??(yl.set(t,e=new bl(t)),e)}function vl(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:Ue(n.listIndex,o,n.pathInfo.wildcardCount)}const $l=new WeakMap;function Sl(t,e){null===e?$l.delete(t):$l.set(t,e)}function Nl(t){const e=$l.get(t);e&&(e.dirty=!0)}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=Ve(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?Ue(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?Ue(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}const Il=new WeakMap;class Pl{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 cn(K(this.markerParentPath+s+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(ce(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=ce(t,e),a=ue(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a=ce(t,e),l=ue(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 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[ce(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)||st(`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[ce(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 ce(this.record,e),!0}catch{return!1}}}function kl(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=Il.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Il.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 Pl(t,s,e.listIndex,r,n,o))}function _l(t){const e=t.parentStateElement,n=(e,n)=>{const o=we(t.component);let s;return e[Pe](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(ce(t,e))):(n,o,...r)=>{const i=ce(t,n),a=we(t.component)?.listIndex.indexes??[],l=ue(0,n,i,"$resolve"===e?o??[]:o,a),c="$setAll"===e||"$resolve"===e&&r.length>0?"writable":"readonly";return s(c,t=>t[e](i,l,...r))}}(t,s,n);let r;return e.createState("readonly",e=>{r=n(e,()=>e["$"===s[0]?s:ce(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:ce(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 ce(t,n),!0}catch{return!1}}})}function Al(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Cl(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}function El(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===C)return Cl(wa(s),e.pathInfo.segments);if(i===D)return Cl(Ra(s),e.pathInfo.segments);if(i===j)return Cl(Da(s),e.pathInfo.segments);if(!0===s.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const t=ye(s,e.pathInfo.path);if(null!==t)return kl(t,e,n,o)}if(!(e.pathInfo.path in t)){if(null===e.parentAddress&&mr(function(t){return t.rootNode??null}(s),e.pathInfo.path))return;const i=e.parentAddress??st(function(t,e,n){return`[${Pr.binding}] Path "${t}" does not exist on the state tree.${ft(t,Ir(e,"",n))}${ht}`}(e.pathInfo.path,t,s.getterPaths)),a=Tl(t,i,n,o);if(null==a)return;const l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??st(Cr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(a,t)}return Reflect.get(a,l)}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 Ml(t,e,n,o,s){const r=We(Oe(s,e.pathInfo),e.listIndex),i=function(t){return $l.get(t)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=El(t,e,n,o,s);return Sl(r,{value:a,dirty:!1}),a}function Tl(t,e,n,o){xl(o,e),function(t,e){if(null===La)return;const n=Oe(t,e.pathInfo);La.add(We(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return Al(s,e)?Ml(t,e,n,o,s):El(t,e,n,o,s)}const Ol=new WeakMap;function Rl(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=cn(f,r),p=Ol.get(h),m=Tl(t,h,e,n),g=ys(r,p,m).newIndexes,y=l[c]??null;if(i.set(h,m),null===y)for(let t=0;t<g.length;t++){const e=g[t];a(o,s+1,e,l,c+1,d.concat(e.index),u)}else{const t=g[y]??st(`ListIndex not found at index ${y} of ${f.path}`);s+1<o.length?a(o,s+1,t,l,c+1,d.concat(t.index),u):u.push(d.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Ol.set(t,e);return l}function Dl(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=fs(Tl(t,cn(a,r),e,n));null==l&&st(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??st(`ListIndex not found at index ${c} of ${a.path}`)}return r}function jl(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}))}function Ll(t,e,n,o){"object"==typeof t&&null!==t||st(`${R} 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&&st(`${R} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Wl(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&st(`${R} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Bl(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];Ll(a,n,o,i);const l=Wl(a,e,n,o,i);r.has(l)&&st(`${R} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Fl(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 zl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=Tl(t,s,n,o);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=e.pathInfo.lastSegment;if(a===r){const t=e.listIndex?.index;return"number"==typeof t&&t in i}return a in i}const ql=new WeakMap;function Vl(t,e){null===e?ql.delete(t):ql.set(t,e)}function Ul(t,e,n){const s=K(t.wildcardParentPaths[e]),r=Oe(t.stateElement,s),i=cn(s,n),a=Ne(We(r,n)),l=t.stateProxy[ke](i),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}`),[]}}(ys(i.listIndex,a,l),t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)Ul(t,e+1,n)}const Kl=[];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:Kl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Kl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Hl=[];function Jl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Hl;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=K(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??Hl}function Xl(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=K(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[ke](e),a=Ne(We(Oe(t.stateElement,e.pathInfo),e.listIndex)),l=Gl(t,o,0,0,ys(e.listIndex,a,r));for(const e of l.fullRows){const o=cn(s,e);t.result.add(o),n.push(o)}if(null!==l.movedRows){const e=Jl(t,i,s);if(null===e)for(const e of l.movedRows){const o=cn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of l.movedRows)for(const s of e){const e=cn(s,o);t.result.add(e),n.push(e)}}}else{const o=cn(s,e.listIndex);t.result.add(o),n.push(o)}}const i=t.dynamicMap.get(o);if(i)for(const o of i){const s=K(o),r=[];if(s.wildcardCount>0){const n=Ve(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&st(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=Ue(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Ul(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&st(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=Ue(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=cn(s,e);t.result.add(o),n.push(o)}}}function Yl(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 d=function(t,e,n,o){const s=new Map,r=new Map,i=[t];for(r.set(t,0);i.length>0;){const t=i.pop();if(s.has(t))continue;const o=e.get(t),a=n.get(t);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];r.set(e,(r.get(e)??0)+1),s.has(e)||i.push(e)}}const a=new Map,l=new Set,c=[];for(const[t,e]of r)0===e&&(a.set(t,0),l.add(t),c.push(t));for(let t=0;t<c.length;t++){const e=c[t],n=a.get(e)+1;n>o&&st(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${e}`);const i=s.get(e);for(let t=0;t<i.length;t++){const e=i[t];n>(a.get(e)??-1)&&a.set(e,n);const o=r.get(e)-1;r.set(e,o),0===o&&(l.add(e),c.push(e))}}if(l.size!==s.size){let t=-1;for(const e of l){const n=a.get(e);n>t&&(t=n)}const e=t+1;for(const t of s.keys())l.has(t)||a.set(t,e)}return a}(c,n,o,1e3),u={ranks:d,stateElement:t,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};return 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,Xl(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(u,e,a),Array.from(u.result)}function Ql(t,e,n,o,s){const r=t.watchPaths;null!=r&&s&&r.has(e)&&function(t,e){el.has(t)||el.set(t,e)}(n,o)}function Zl(t,e,n,s,r){const i=o.enablePropagationContext?Zn()??Xn(-1):null,a=Zi();a.enqueueAbsoluteAddress(e,i),Yl(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=We(Oe(s.stateElement,e.pathInfo),e.listIndex);Nl(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function tc(t,e,n,o,s,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 a=Tl(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??st(Cr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(a,t,o)}return Reflect.set(a,l,o)}if(!i.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);i.pushAddress(e),i.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}finally{Zl(e,n,s,i,a)}}function ec(t,e,n,o,s,r,i){let a=e.parentAddress??st(`address.parentAddress is undefined path: ${e.pathInfo.path}`),l=function(t){return ql.get(t)??null}(a);if(null===l){const e=Tl(t,a,s,r)??[],n=fs(e)??[];l={value:[...e],listIndexes:[...n]},Vl(a,l)}try{return tc(t,e,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=Tl(t,a,s,r)??[],c=Array.isArray(i)?fs(i)??[]:[],d=e.listIndex.index,u=-1!==n?l.listIndexes[n]:ds(a.listIndex,-1);c[d]=u;if(new Set(i).size===l.value.length){for(let t=0;t<c.length;t++)c[t].index=t;Vl(a,null)}}}function nc(t,e,n,o,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(n)){const l=a.get(e.pathInfo.path);if(void 0!==l){const a=Tl(t,e,o,i),c=function(t,e,n,o){const s=Bl(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Bl(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,l,a,n);if(null!==c)return function(t,e,n,o,i,a){const l=e.pathInfo.path,c=e.listIndex;null===fs(o)&&ys(c,null,o);const d=ys(c,o,n.list),u=oc(t,e,n.list,i,a,l),f=K(l+s+r);for(const e of n.matched){const n=Fl(e.oldRow,e.newRow);if(0===n.length)continue;const o=d.newIndexes[e.position];for(const r of n)void 0!==o?nc(t,cn(K(f.path+s+r.field),o),r.value,i,a):e.oldRow[r.field]=r.value}return u}(t,e,c,a,o,i)}}return oc(t,e,n,o,i,null)}function oc(t,e,n,i,a,l){const c=a.stateElement,d=e.pathInfo.path;if(!0===c.hasGraftedVolumes){const t=function(t,e){const n=gr.get(t);if(void 0===n||0===n.size)return null;const o=e+s;for(const t of n)if(t.startsWith(o))return t;return null}(c,d);null!==t&&st(`Cannot replace "${d}" wholesale: a volume is mounted at "${t}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${t}" itself, or individual fields inside "${d}", instead.`)}const u=!!no&&(no=!1,!0);if(!(d in t)&&null!==e.parentAddress&&!c.elementPaths.has(d)){const s=Tl(t,e.parentAddress,i,a);if("object"==typeof s&&null!==s){const t=e.pathInfo.lastSegment,f=t===r?e.listIndex?.index:t;let h,p=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==f&&f in s,e=void 0!==f?s[f]:void 0;if(t&&Object.is(e,n))return!0;h=e,p=!0}const m=Al(c,e),g=We(Oe(c,e.pathInfo),e.listIndex);null!==$e&&$e({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:p}),Ql(c,d,g,h,p);try{return void 0===f&&st(Cr(`path "${d}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),Reflect.set(s,f,n)}finally{Zl(e,g,i,a,l),m&&Sl(g,{value:n,dirty:!1}),jl(c,e.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Tl(t,e,i,a);if(zl(t,e,i,a)&&Object.is(o,n))return!0;f=o,h=!0}const p=c.elementPaths.has(e.pathInfo.path),m=Al(c,e),g=We(Oe(c,e.pathInfo),e.listIndex);null!==$e&&$e({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),Ql(c,d,g,f,h);try{return p?ec(t,e,g,n,i,a,l):tc(t,e,g,n,i,a,l)}finally{m&&Sl(g,{value:n,dirty:!1}),jl(c,e.pathInfo,{value:n})}}function sc(t,e,n,o){return(e,s,r)=>{const i=K(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&&st(_r("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=cn(i,Dl(t,n,o,i,s));if(!(void 0!==r))return Tl(t,a,n,o);nc(t,a,r,n,o)}}function rc(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return vl(o,s.wildcardPaths.at(-1)??st(`lastWildcardPath is null: ${e.pathInfo.path}`))??st(`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]??st(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=fs(Tl(t,cn(i,s),n,o))??st(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??st(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??st(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":st(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function ic(t,e,n,o){const r=Reflect.get(t,I);let i;if("function"==typeof r){const t=new Set,s={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,r=e.path;if(t.add(r),e.wildcardCount>0){const t=Ke(n.listIndex,e.wildcardCount),o=s[r];void 0===o?s[r]=[t]:o.push(t)}}i=r.call(n,Array.from(t),s)}const a=o.stateElement?(l=o.stateElement,br.get(l)??wr):[];var l;if(a.length>0)for(const t of a){const r=t.mountPath+s,i=new Set,a={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo.path;if(e!==t.mountPath&&!e.startsWith(r))continue;const s=e===t.mountPath?"":e.slice(r.length);if(""===s)continue;i.add(s);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const t=Ke(n.listIndex,l);(a[s]??=[]).push(t)}}if(i.size>0)try{t.callback.call(yr(t.mountPath,n),Array.from(i),a)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" $updatedCallback threw.`,e)}}return i}const ac=`${D}${s}`,lc=`${j}${s}`,cc=new WeakMap;function dc(t,e,n,o){const r=S[e];if(void 0!==r){0===o.addressStackLength&&st(`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 i=t?.listIndex;null==i&&st(`ListIndex not found: ${e.toString()}`);let a=r;const l=t.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const t=ye(o.stateElement,l.path);null!==t&&(a=r+function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(s,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const r=-1===o?e:e.slice(0,o),i=-1===o?"":e.slice(o+1),a=t.accessorBySuffixByMarkerParent.get(r)?.get(i);return void 0!==a?a.indexShift:t.delta}(t,l.path))}const c=Ue(i,a,l.wildcardCount);return c?.index??st(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>function(t,e,n,o){const s=sc(t,0,n,o);return(e,r)=>{const i=K(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)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&st(_r("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=vl(o,i.wildcardPaths[t]);if(e){r=Ke(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&&st(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}}(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>function(t,e,n,o){return(e,s,r,i)=>{const a=K(e);Array.isArray(s)||st(Ar(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&st(_r("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&st(Ar(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&st(Ar(e,"requires an array as the value when { spread: true } is set."));const d=Rl(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&st(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,d.length,r.length));const u=[];for(let e=0;e<d.length;e++){const s=Dl(t,n,o,a,d[e]);u.push(cn(a,s))}let f=0;for(let e=0;e<u.length;e++){const s=u[e];let i;i=c?r(Tl(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(nc(t,s,i,n,o),f++)}return f}}(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=wl(e),i=rc(t,r,n,o),a=cn(r.pathInfo,i),l=We(Oe(s,a.pathInfo),a.listIndex),c=Zi();c.enqueueAbsoluteAddress(l),Yl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=We(Oe(s,t.pathInfo),t.listIndex);Nl(e),c.enqueueAbsoluteAddress(e)}),jl(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>sc(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{0===o.addressStackLength&&st(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??st("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"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case C:return wa(o.stateElement);case D:return Ra(o.stateElement);case j:return Da(o.stateElement)}if(!e.startsWith(ac)&&!e.startsWith(lc))return}const s=wl(e),r=rc(t,s,n,o),i=cn(s.pathInfo,r);return Tl(t,i,n,o)}if("symbol"==typeof e){const s=function(t){let e=cc.get(t);return void 0===e&&(e=new Map,cc.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case Pe:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&st("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 ke:i=e=>Tl(t,e,n,o);break;case _e:i=e=>zl(t,e,n,o);break;case Ae:i=(e,s)=>nc(t,e,s,n,o);break;case Ce:i=()=>async function(t,e,n){const o=Reflect.get(t,N);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Ee:i=()=>function(t,e,n){const o=Reflect.get(t,x);"function"==typeof o&&o.call(n)}(t,0,n);break;case Me:i=e=>ic(t,e,n,o);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}class uc{_stateElement;_addressStack=Array(i).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=zi(t);null===n&&st("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&st("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=i&&st(`Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_describeAddressCycle(){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`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&st(`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 dc(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&st("This state is readonly."),function(t,e,n,o,s){if("string"==typeof e){const r=wl(e),i=rc(t,r,o,s);return nc(t,cn(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)}}function fc(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)}const hc=new WeakMap;class pc{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=hc.get(t);return n?n.get(e)??null:null}(t,e)??st("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 mc=t=>()=>t;function gc(t,e,n,o){!function(t,e,n){let o=hc.get(t);o||(o=new Map,hc.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(fc(o));const s=function(t,e){const n=new pc(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:mc(s),enumerable:!0,configurable:!0}),Qo(e,n),yc(e,n)}function yc(t,e){if(P in t){const n=t[P];"function"==typeof n?n.call(t,e).catch(t=>{st(`Error in ${P}: ${t instanceof Error?t.message:String(t)}`)}):st(`${P} is not a function.`)}}function bc(t,e){const n=ge(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&st(`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&&Jo(e).dispose(),function(t,e){fe.set(t,e);let n=pe.get(e.parentStateElement);void 0===n&&(n=new Map,pe.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=he.get(e.component);void 0===o&&(o=new Map,he.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&me.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=Wi.get(t);if(void 0!==n){if(n===e)return;st("A state tree is already registered on this root.")}Wi.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>de(t,e,n);Xr(e);const o=we(t.component);hi(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),Gr(e,o,n)}(t,e),o=e,s=Promise.resolve(),Bi.set(o,s),s.then(()=>Ui(o),()=>{})}const wc=new Set;function vc(t,e){wc.has(t)||(wc.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function $c(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[Pe](n,()=>{o=t[e.outerPathInfo.path]})}),o}function Sc(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(yr(t.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function Nc(t,e,n){const o=n[O];if(void 0!==o){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(o)){const o=e+s+a,c=function(t,n,...o){l.call(yr(e,this),t,n,...o)};n.push({path:o,pathInfo:K(o),handler:c,order:1e6+i++}),r.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(!function(t,e){let n=Va.get(t);void 0===n&&(n=new Map,Va.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),nl(t))}const r=n[R];if(void 0!==r){const n=new Map;for(const[t,o]of Object.entries(r))n.set(e+s+t,o);t.mergeVolumeListKeys?.(n)}const i=n[I];"function"==typeof i&&(!function(t,e){let n=br.get(t);void 0===n&&(n=[],br.set(t,n)),n.push(e)}(t,{mountPath:e,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}function xc(t,e,n){!function(t,e,n){const o=n[O];if(void 0!==o){"object"==typeof o&&null!==o||st(`${O} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&st(`${O} entry "${t}" must be a function.`),Ya(t)}const r=n[R];if(void 0!==r){"object"==typeof r&&null!==r||st(`${R} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(r))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&st(`${R} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+s+n)&&st(`${R} entry "${e+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&st(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`)}(t,e,n);const{data:o,accessors:r}=function(t){const e={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(t)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(e[o]=s.value):n.set(o,s));return{data:e,accessors:n}}(n),i=K(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;st(`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],r=""===n?o in t:void 0!==t[n+s+o];n=""===n?o:n+s+o,r||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(a)return;st(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=o}),function(t,e){let n=gr.get(t);void 0===n&&(n=new Set,gr.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,o]of r){const r=e+s+n,i=o.get,a=o.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(yr(e,this))}),"function"==typeof a&&(l.set=function(t){a.call(yr(e,this),t)}),t.defineTreeAccessor(r,l)}Nc(t,e,n);const l=n.$connectedCallback;return"function"==typeof l&&t.createState("writable",t=>{const n=l.call(yr(e,t));n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function Ic(t,e){let n=null;try{n=xc(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}function Pc(t,e,n,o,s){null===e?function(t,e){let n=vr.get(t);void 0===n&&(n=[],vr.set(t,n)),n.push(e)}(t,{mountPath:n,volumeState:o,onGrafted:s}):Ic(e,{mountPath:n,volumeState:o,onGrafted:s})}$r=Ic;class kc extends yi{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return qi(t)}__state;_hasUpdatedCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_name="default";_initialized=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new ma}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_watchPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_volumeGraftInfo=null;_volumeInitializing=!1;_mountRecord=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_dcc=!1;_connectGeneration=0;_streamsStartedGeneration=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&&st(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){this._commandTokenNames=function(t){const e=new Set,n=t[A];if(void 0===n)return e;Array.isArray(n)||st(`${A} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||st(`${A} entries must be non-empty strings.`),t===C&&st(`${A} entry "${t}" conflicts with the reserved namespace name "${C}".`),e.has(t)&&st(`${A} entry "${t}" is duplicated.`),e.add(t);return e}(t),this._eventTokenNames=function(t){const e=new Set,n=t[E];if(void 0===n)return e;Array.isArray(n)||st(`${E} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||st(`${E} entries must be non-empty strings.`),e.has(t)&&st(`${E} entry "${t}" is duplicated.`),e.add(t);return e}(t),this.__state=t,this._hasUpdatedCallback=I in t,In(this),function(t,e,n){const o=e[M];if(void 0!==o){"object"==typeof o&&null!==o||st(`${M} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||st(`${M} entry "${e}" is not declared in $eventTokens.${ft(e,n)}`),"function"!=typeof s&&st(`${M} entry "${e}" must be a function.`),xn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const n=function(t){const e=new Set,n=new Set,o=hl(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 n.getterPaths)this._getterPaths.add(t);for(const t of n.setterPaths)this._setterPaths.add(t);var o;ja(this),_a(o=this),Ia(o),Pa.delete(o),Ea(this,t),this._listKeys=function(t){const e=t[R];if(void 0===e)return null;"object"==typeof e&&null!==e||st(`${R} 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&&st(`${R} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&st(`${R} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&st(`${R} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),"function"!=typeof o?("string"!=typeof o&&st(`${R} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&st(`${R} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&st(`${R} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&st(`${R} 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),function(t){Ua.delete(t),qa.delete(t)}(this),function(t){Za.delete(t)}(this),this._watchPaths=Qa(this,t),this._initialized&&null!==this._rootNode&&!e()&&(nl(this),Ba(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}get name(){return this._name}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const t=this.parentNode;if(!t)return null;const e=Ni.find(t);if(!e)return null;const n=e.stateData;return Object.keys(n).length>0?n: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){st("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 ha(t,`${this._name}`);{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||st(`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 pa(t);st(`Unsupported src file type: ${t}`)}}catch(t){st(`Failed to initialize state: ${t}`)}}async _initializeVolume(){const t=this._rootNode,e=this.getAttribute("mount");try{!function(t){0===t.length&&st('"mount" requires a non-empty tree path.');const e=K(t);for(const n of e.segments)0===n.length&&st(`"mount" path "${t}" has an empty segment.`),n===r&&st(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&st(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(e),this.hasAttribute("bind-component")&&st('"mount" cannot be combined with "bind-component".'),this.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),function(t,e){let n=pr.get(t);void 0===n&&(n=new Set,pr.set(t,n)),n.has(e)&&st(`Volume slot "${e}" is already mounted on this tree.`),n.add(e)}(t,e)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}this._volumeInitializing=!0,null===zi(t)&&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)}(t,e);const n=t=>{this._volumeGraftInfo=t,this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()};let s;try{s=await this._loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${e}" failed to load.`,t),void n(null)}null!==this._rootNode?Pc(t,zi(t),e,s,n):n(null)}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}await this._loadingPromise,Ki(this.rootNode,this)}_failInitialization(t){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),st(t)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const r=this.parentNode,i=r instanceof ShadowRoot?r.host:r instanceof Element?r:null,a=i?J(i):null;null!==i&&null!==a||st(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),r instanceof ShadowRoot||i.hasAttribute(o.bindAttributeName)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${a}>, or mount it from the host (data-wcs="${this.getAttribute("bind-component")}: path").`);const l=["state","src","json"].filter(t=>this.hasAttribute(t));null!==this.querySelector('script[type="module"]')&&l.push('<script type="module">'),l.length>0&&st(`"bind-component" cannot be combined with ${l.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const c=this.getAttribute("bind-component");!function(t,e){let n=Zo.get(t);n||(n=new Set,Zo.set(t,n)),n.add(e)}(i,c);const d=Y(i);null===d&&st(`CustomElementRegistry is unavailable for <${a}>.`),await d.whenDefined(a.toLowerCase()),i.hasAttribute(o.bindAttributeName)&&await z(i),c in i||st(`Component does not have property "${c}" for state binding.`);let u=i[c];"object"==typeof u&&null!==u||st(`Component property "${c}" is not an object for state binding.`);const f=function(t,e){const n=sr.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(i,c);if(void 0!==f&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=dt(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(i,c)&&(i[c]=f,u=f),this._boundComponent=i,this._boundComponentStateProp=c,r instanceof ShadowRoot||(dt(i)??[]).some(t=>t.propSegments[0]===c)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${a}>, or mount it from the host (data-wcs="${c}: path").`),i.hasAttribute(o.bindAttributeName)){const o=(dt(i)??[]).filter(t=>t.propSegments[0]===c);if(o.length>0){const l=zi(i.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${a}>.`);let d=(n=i,s=c,he.get(n)?.get(s)??null);const f=null!==d;if(null===d&&(function(t,e,n){const o=ir.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;ir.get(t).delete(e)}}(i,c,u),d=te(i,c,o,l,u,(t=i,e=c,rr.get(t)?.get(e))),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp,s=new Map;for(const e of t.entries)1===e.innerSegments.length&&s.set(e.innerSegments[0],e.outerPathInfo.path);let r,i=!1;for(const a of e){const e=s.get(a);if(void 0!==e){vc(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted entry "${o}.${a}: ${e}" (the host value no longer reaches it). Remove the default to read the tree, or rename it to keep it private.`);continue}if(null===t.rootEntry)continue;if(i||(r=$c(t),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=t.rootEntry.outerPathInfo.path;vc(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted tree key "${l}.${a}" (${o}: ${l}). Remove the default to read the tree, or rename it to keep it private.`)}}(d)),this._mountRecord=d,this.parentNode!==r)return;try{bc(d,r instanceof ShadowRoot?r:i)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}if(!f){const t=_l(d);Object.defineProperty(i,c,{get:()=>t,enumerable:!0,configurable:!0}),Qo(i,c)}return yc(i,c),function(t){const e=Yt.filter(e=>void 0!==t.stateObject[e]);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Qt.has(n)||(Qt.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). See docs/state-mount-design.md §4-6.`))}(d),void Zt(d,"$connectedCallback")}}gc(this,this._boundComponent,this._boundComponentStateProp,u)}var t,e,n,s}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{N in t&&await t[Ce]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await pa(t):st(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await ha(e,t.tagName.toLowerCase()):st(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){st(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||st(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Y(t);null!==r&&"function"==typeof r.define||st(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&st(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template");i.innerHTML=e.innerHTML;const a=e.mode,{bindables:l,commands:c,streamBackedBindables:d}=gl(n),u=l.length>0||c.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,l,c):null,f=l.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,l):{},h=o.tagNames.state,p=class extends HTMLElement{static template=i;static shadowRootMode=a;static wcBindable=u;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(L))return null;this._shadow=this.attachShadow({mode:p.shadowRootMode}),this._shadow.appendChild(p.template.content.cloneNode(!0));const t=Y(this._shadow);return null!==t&&Q(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(p.bindableEventMap).length>0){const e=t.querySelector(h);e?e.setBindableEventMap(p.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${k} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(h)??null}},m=hl(n);for(const[t,e]of Object.entries(m)){if(fl(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=ul(t,o)}else n.get=cl(t),n.set=dl(t);Object.defineProperty(p.prototype,t,n)}for(const t of d)Object.defineProperty(p.prototype,t,{configurable:!0,enumerable:!0,get:cl(t),set:dl(t)});r.define(s,p)}(t,e,n),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",t=>{x in t&&t[Ee]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&zi(this._rootNode)===this._volumeGraftInfo.rootStateElement&&Sc(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const t=this._mountRecord,e=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&function(t,e){const n=Jo(e),o=we(t.component);n.forEachActiveBindingNode(t=>ve(t,o)),Kr(n.rebindAddresses())}(t,e)}),Zt(t,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||zi(this._rootNode)===this||Ki(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 t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(L))return this.hasAttribute("bind-component")&&st(`"bind-component" cannot be used inside a [${L}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(t.host,t);if(this.hasAttribute("mount")){if(this._volumeInitializing)return;return void await this._initializeVolume()}if(await this._initializeBindWebComponent(),null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await qi(this.rootNode);const t=Ni.extractStateData(this),e=document.createElement(o.tagNames.ssr);e.setAttribute("version",gi),Ni.buildContent(e,t),this.parentNode?.insertBefore(e,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||nl(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||Ba(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Sc(this._volumeGraftInfo,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._mountRecord)return Zt(this._mountRecord,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Ki(this.rootNode,null),t=this,ga.delete(t),function(t){ba.delete(t)}(this),In(this),_a(this),ja(this),function(t){Ua.delete(t)}(this),this._rootNode=null}}var t}get initialized(){return this._initialized}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get watchPaths(){return this._watchPaths}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}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&st(`$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}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 rootNode(){return null===this._rootNode&&st("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0}get hasGraftedVolumes(){return this._hasGraftedVolumes}markHasGraftedVolumes(){this._hasGraftedVolumes=!0}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t}_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("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+r)),!this._pathSet.has(t)){const e=K(t);if(this._pathSet.add(t),Mr(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=K(t.parentPath)}}}_createState(t,e,n){try{const o=function(t,e,n){const o=new uc(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 crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){this._initialized?((this._hasGraftedVolumes||this._hasMounts)&&st("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."),this._state=t):this._resolveSetState?.(t)}}function _c(t=customElements){t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,Ni),t.get(o.tagNames.state)||t.define(o.tagNames.state,kc)}function Ac(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}}await function(e,o){const s=Ac(e);var r;s&&((r=s).tagNames&&Object.assign(n.tagNames,r.tagNames),"string"==typeof r.bindAttributeName&&(n.bindAttributeName=r.bindAttributeName),"string"==typeof r.commentTextPrefix&&(n.commentTextPrefix=r.commentTextPrefix),"string"==typeof r.commentForPrefix&&(n.commentForPrefix=r.commentForPrefix),"string"==typeof r.commentIfPrefix&&(n.commentIfPrefix=r.commentIfPrefix),"string"==typeof r.commentElseIfPrefix&&(n.commentElseIfPrefix=r.commentElseIfPrefix),"string"==typeof r.commentElsePrefix&&(n.commentElsePrefix=r.commentElsePrefix),"string"==typeof r.locale&&(n.locale=r.locale),"boolean"==typeof r.debug&&(n.debug=r.debug),"boolean"==typeof r.enableMustache&&(n.enableMustache=r.enableMustache),"boolean"==typeof r.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=r.enableDirectionalInitialSync),"boolean"==typeof r.enablePropagationContext&&(n.enablePropagationContext=r.enablePropagationContext),"boolean"==typeof r.enableContractAnalyzer&&(n.enableContractAnalyzer=r.enableContractAnalyzer),"boolean"==typeof r.sameValueGuard&&(n.sameValueGuard=r.sameValueGuard)),_c(o),function(){const t=globalThis;void 0===t[Ai]&&(t[Ai]=Li)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=da)}(),ca()}();
|
|
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;const s=".",r="*",i=128,a="|",l="prevent",c="stop",d="ro",u="init",f="sync",h="else",p="...",m="on",g="eventToken",y="command",b="class",w="attr",v="style",$={};for(let t=0;t<128;t++)$[`$${t+1}`]=t;const S=Object.freeze($),N="$connectedCallback",x="$disconnectedCallback",I="$updatedCallback",P="$stateReadyCallback",k="$bindables",_="$commands",A="$commandTokens",C="$command",E="$eventTokens",M="$on",T="$streams",O="$watch",R="$listKeys",D="$streamStatus",j="$streamError",L="data-wc-definition",W=new WeakMap,B=new WeakSet;let z=0;async function F(t){const e=function(t){let e,n=W.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++z,promise:o,resolve:e},W.set(t,n),B.has(t)&&n.resolve(),n}(t);await e.promise}function q(t){const e=W.get(t);void 0===e?B.add(t):e.resolve()}const V=new Map;let U=0;function K(t){let e=V.get(t);return void 0!==e||(e=Object.freeze(new G(t)),V.set(t,e)),e}class G{id=++U;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:K(e),n=t.split("."),o=[],s=[],i=[],a={},l=[],c=[],d=[],u=[];let f="",h="",p=0;for(let t=0;t<n.length;t++)f+=n[t],n[t]===r&&(i.push(f),a[f]=p,l.push(e(f)),c.push(h),d.push(e(h)),u.push(t),p++),o.push(f),s.push(e(f)),h=f,f+=".";const m=i.length>0?i[i.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=i,this.wildcardPathSet=new Set(i),this.indexByWildcardPath=a,this.wildcardPathInfos=l,this.wildcardPathInfoSet=new Set(l),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}}const H=new WeakMap;function J(t){const e=H.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{H.set(t,n)}}function X(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Y(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return X(e);if(void 0!==n)return X(n)}return X(globalThis.customElements)}function Q(t,e){t.upgrade?.(e)}function Z(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=ot(s.properties,tt);if(null===r)return null;const i=void 0===s.inputs?new Map:ot(s.inputs,et);if(null===i)return null;const a=void 0===s.commands?new Map:ot(s.commands,nt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function tt(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 et(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 nt(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 ot(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 st(t){throw new Error(`[@wcstack/state] ${t}`)}function rt(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:K(n),inFilters:[],outFilters:[],bindingType:"prop"}}function it(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function at(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&&st("Spread binding requires an element node.");const e=t,o=J(e);null===o&&st(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Y(e);null===a&&st(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||st(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Q(a,e);const l=Z(e);null===l&&st(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const t of l.knownProperties.keys()){if(d.has(t))continue;d.add(t);const e=rt(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(d.has(t))continue;d.add(t);const e=rt(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=it(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=it(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 lt(t,e){let n=t;if(0===e.length)return n;for(let t=0;t<e.length&&(n=n?.childNodes[e[t]]??null,null!==n);t++);return n}const ct=new WeakMap;function dt(t){return ct.get(t)||null}function ut(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 ft(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=ut(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const ht=" Validate statically: npx @wcstack/lint <file>.",pt=new Set(["if","elseif","else","for"]);function mt(t){st(`filter ${t} requires at least one option`)}function gt(t){st(`filter ${t} requires a number as option`)}function yt(t){st(`filter ${t} requires a number value`)}function bt(t){st(`filter ${t} requires a date value`)}function wt(t){return!(!t||isNaN(Number(t)))}const vt={eq:t=>{const e=t?.[0]??mt("eq");return t=>"number"==typeof t?(wt(e)||gt("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??mt("ne");return t=>"number"==typeof t?(wt(e)||gt("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&st(`filter ${"not"} requires a boolean value`),!t),lt:t=>{const e=t?.[0]??mt("lt");return wt(e)||gt("lt"),t=>("number"!=typeof t&&yt("lt"),t<Number(e))},le:t=>{const e=t?.[0]??mt("le");return wt(e)||gt("le"),t=>("number"!=typeof t&&yt("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??mt("gt");return wt(e)||gt("gt"),t=>("number"!=typeof t&&yt("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??mt("ge");return wt(e)||gt("ge"),t=>("number"!=typeof t&&yt("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??mt("inc");return wt(e)||gt("inc"),t=>("number"!=typeof t&&yt("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??mt("dec");return wt(e)||gt("dec"),t=>("number"!=typeof t&&yt("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??mt("mul");return wt(e)||gt("mul"),t=>("number"!=typeof t&&yt("mul"),t*Number(e))},div:t=>{const e=t?.[0]??mt("div");return wt(e)||gt("div"),t=>("number"!=typeof t&&yt("div"),t/Number(e))},mod:t=>{const e=t?.[0]??mt("mod");return wt(e)||gt("mod"),t=>("number"!=typeof t&&yt("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&yt("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??mt("clamp");wt(e)||gt("clamp");const n=t?.[1]??mt("clamp");wt(n)||gt("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&yt("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return wt(e)||gt("fix"),t=>("number"!=typeof t&&yt("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&yt("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]??mt("slice");wt(n)||gt("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(wt(o)||gt("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??mt("substr");wt(e)||gt("substr");const n=t?.[1]??mt("substr");return wt(n)||gt("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??mt("pad");wt(e)||gt("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??mt("rep");return wt(e)||gt("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??mt("truncate");wt(e)||gt("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)||st(`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 wt(e)||gt("round"),t=>{"number"!=typeof t&&yt("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return wt(e)||gt("floor"),t=>{"number"!=typeof t&&yt("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return wt(e)||gt("ceil"),t=>{"number"!=typeof t&&yt("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return wt(e)||gt("percent"),t=>("number"!=typeof t&&yt("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??mt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||bt("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||bt("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||bt("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=>!1===t||null==t||0===t||""===t||Number.isNaN(t),truthy:t=>t=>!1!==t&&null!=t&&0!==t&&""!==t&&!Number.isNaN(t),defaults:t=>{const e=t?.[0]??mt("defaults");return t=>!1===t||null==t||0===t||""===t||Number.isNaN(t)?e:t},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),null:t=>t=>""===t?null:t},$t=vt,St={input:vt,output:$t},Nt=(t,e)=>n=>{const o=n[t];return o||st(`[wcs/filter-unknown] filter not found: ${t}.${ft(t,Object.keys(n))}${ht}`),o(e)};function xt(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 It=new Map;function Pt(t,e){const n=St[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&st(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&st(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=It.get(s);return void 0===r&&(r=Nt(o,[])(n),It.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=t.substring(o+1,s),i=t.substring(0,o).trim(),a=function(t){const e=[];let n="",o=null,s=!1,r=-1,i=-1;const a=()=>{e.push(xt(n,r,i)),n="",s=!1,r=-1,i=-1};for(let e=0;e<t.length;e++){const l=t[e];o?l===o?o=null:(-1===r&&(r=n.length),n+=l,i=n.length):'"'===l||"'"===l?(o=l,s=!0):","===l?a():n+=l}const l=xt(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=It.get(l);return void 0===c&&(c=Nt(i,a)(n),It.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const kt=t=>t.trim(),_t=new Map;const At=new Map;function Ct(t){const e=t.indexOf(a);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=s.split(a).map(kt),r=Pt(o,"output"),At.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&st(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);return{statePathName:n,statePathInfo:K(n),outFilters:r}}function Et(t){const[...e]=t.split(";").map(kt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&st(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===h){const t=K("#else");return{propName:h,propSegments:[h],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===p){const e=Ct(o);return e.outFilters.length>0&&st(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&st(`Invalid spread binding "${t}": spread target path is required.`),{propName:p,propSegments:[p],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ct(o),bindingType:n}}{const t=Ct(o),e=function(t){const e=t.indexOf(a);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),_t.has(r)?i=_t.get(r):(o=r.split(a).map(kt),i=Pt(o,"input"),_t.set(r,i))):n=t.trim();const[l,c]=n.split("#").map(kt),d=l.split(s).map(kt);return{propName:l,propSegments:d,propModifiers:c?c.split(",").map(kt):[],inFilters:i}}(n);return e.propSegments[0]===g||e.propSegments[0].startsWith(m)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});if(n.length>1){n.some(t=>pt.has(t.bindingType))&&st(`[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">).${ht}`)}return n}const Mt=new WeakMap,Tt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Ot=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Rt(t){const e=Mt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Ot.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Tt.has(r)?(Mt.set(t,s[2]),s[2]):null}function Dt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ct(t),bindingType:"text"}}const jt=new Map;function Lt(t,e,n){if(null===n)jt.delete(t);else{jt.set(t,n);const o=Fi(e);null===o&&st("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 Wt(t){return jt.get(t)||null}function Bt(t){if(t.nodeType===Node.ELEMENT_NODE){return Et(t.getAttribute(o.bindAttributeName)||"")}if(t.nodeType===Node.COMMENT_NODE){const e=Rt(t);null===e&&st("Comment node binding text not found.");const n=Wt(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Dt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function zt(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function Ft(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!zt(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function qt(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 Vt(t){const e=[],n=Ft(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(t){if(t.nodeType===Node.ELEMENT_NODE){return t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==Rt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const t=s.currentNode;n.length>0&&qt(t,n)||e.push(t)}return e}const Ut=new WeakSet;function Kt(t,e,n,o){const s=at(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?J(t):null;return null===n&&st("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}Ut.add(t);const r=function(t,e){const n=[];for(const o of e)if("text"!==o.bindingType)n.push({...o,node:t,replaceNode:t});else{const e=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,node:t,replaceNode:e})}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){ct.set(t,e)}(t,r),q(t),{bindings:r,deferred:null}}function Gt(t,e){const n=Vt(t),o=[],s=[];for(const t of n){if(Ut.has(t))continue;const n=Kt(t,Bt(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Ht(t){Ut.add(t)}function Jt(t){const{node:e,parseResults:n,transform:o}=t;!function(t){Ut.delete(t)}(e);return Kt(e,n,{allowDeferred:!1},o).bindings}let Xt=0;const Yt=["$watch","$streams","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on"],Qt=new Set;function Zt(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 te(t,e,n,o,r,i=new Set){0===n.length&&st(`Cannot build a mount record without host bindings for "${e}".`);const a=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(s);l.has(n)&&st("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo};a.push(o),0===e.length&&(c=o)}a.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const d=++Xt,u=`#m${d}`,{getterKeys:f,setterKeys:h}=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}}(r),p={};for(const t of Object.keys(r))t.startsWith("$")||f.has(t)||h.has(t)||"function"!=typeof r[t]&&(i.has(t)||(p[t]=r[t]));return{id:d,marker:u,component:t,stateProp:e,parentStateElement:o,entries:a,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+s+u,stateObject:r,getterKeys:f,setterKeys:h,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set}}function ee(t){const e=t.indexOf(s);return-1===e?t:t.slice(0,e)}function ne(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 oe(t,e){for(const n of t.entries)if(ne(e,n.innerSegments)){const t=e.slice(n.innerSegments.length);return 0===t.length?n.outerPathInfo.path:n.outerPathInfo.path+s+t.join(s)}return null}function se(t,e){return t.markerBasePath+s+e}function re(t,e,n,o){let r=t.accessorBySuffixByMarkerParent.get(e);void 0===r&&(r=new Map,t.accessorBySuffixByMarkerParent.set(e,r));const i=e+s+n;r.set(n,{accessorName:o,indexShift:K(i).wildcardCount-K(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(i),t.addedGetterPaths.add(i))}function ie(t,e){return!t.injectedKeys.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 ae(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(s)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${ee(e)}: path") or declare the key on the component state.`}const le=/^\$(\d+)$/;function ce(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(s);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===r){o=t;break}if(-1===o)return re(t,t.markerBasePath,e,e),se(t,e);if(ie(t,n[0]))return re(t,t.markerBasePath,e,e),se(t,e);const i=n.slice(0,o+1),a=n.slice(o+1),l=oe(t,i);null===l&&st(ae(t,e)),0===a.length&&st(`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=l+s+t.marker;return re(t,c,a.join(s),e),c+s+a.join(s)}(t,e);const o=ee(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return se(t,e);if(ie(t,o))return se(t,e);const i=oe(t,e.split(s));if(null!==i)return i;st(ae(t,e))}function de(t,e,n){let o;const i=le.exec(e.statePathName);if(null!==i){const s=function(t,e){return void 0===e?t.delta:K(ce(t,e)).wildcardCount-K(e).wildcardCount}(t,n);o=0===s?e.statePathName:`$${Number(i[1])+s}`}else if(o=ce(t,e.statePathName),"for"===e.bindingType){const n=K(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+s+r,n)}return o===e.statePathName?e:{...e,statePathName:o,statePathInfo:K(o)}}function ue(t,e,n,o,s){if(void 0===o)return;const r=K(n).wildcardCount-K(e).wildcardCount;return 0===r?o:(s.length<r&&st(`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 fe=new WeakMap,he=new WeakMap;const pe=new WeakMap;const me=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)});function ge(t){return fe.get(t)??null}function ye(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=pe.get(t);if(void 0===o)return null;const r=e.indexOf(s,n),i=-1===r?e.slice(n):e.slice(n,r),a=o.get(i);if(void 0===a)return null;const l=a.deref();return void 0===l?(o.delete(i),null):l}const be=new WeakMap;function we(t){let e=t;for(;e;){const t=be.get(e);if(t)return t;let n=e.parentNode;null===n&&e instanceof ShadowRoot&&null!==ge(e)&&(n=e.host),e=n}return null}function ve(t,e){null!==e?be.set(t,e):be.delete(t)}let $e=null;const Se=new WeakMap;function Ne(t){return Se.get(t)??[]}function xe(t,e){Se.set(t,e)}function Ie(t){return Se.has(t)}const Pe=Symbol("$$setLoopContext"),ke=Symbol("$$getByAddress"),_e=Symbol("$$hasByAddress"),Ae=Symbol("$$setByAddress"),Ce=Symbol("$$connectedCallback"),Ee=Symbol("$$disconnectedCallback"),Me=Symbol("$$updatedCallback"),Te=new WeakMap;function Oe(t,e){if(Te.has(t)){const n=Te.get(t);if(n.has(e))return n.get(e)}else Te.set(t,new WeakMap);const n=Object.freeze(new Re(t,e));return Te.get(t).set(e,n),n}class Re{pathInfo;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Oe(t,e.parentPathInfo)}}const De=new WeakMap,je=new WeakMap;class Le{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const t=this.absolutePathInfo.parentAbsolutePathInfo;if(null===t)return null;let e=null;return e=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=We(t,e)}}function We(t,e){if(null===e){let e=je.get(t);return void 0!==e||(e=new Le(t,null),je.set(t,e)),e}{let n=De.get(e);void 0===n&&(n=new WeakMap,De.set(e,n));let o=n.get(t);return void 0!==o||(o=new Le(t,e),n.set(t,o)),o}}const Be=new WeakMap;function ze(t,e){null===e?Be.delete(t):Be.set(t,e)}function Fe(t){return Be.get(t)||null}const qe=new Map;function Ve(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=qe.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,qe.set(s,r),r}function Ue(t,e,n){return e<0||e>=n?null:t.at(e-n)}function Ke(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const Ge=new WeakMap;function He(t){const e=we(t.node);if(null===e)return null;let n=Ge.get(e);if(void 0===n)n=new WeakMap,Ge.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Ve(e.pathInfo,t.statePathInfo);return n>0&&(o=Ue(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const Je=new WeakMap;function Xe(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Fe(n);null===e?st(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function Ye(t,e){let n=null;if(n=Je.get(t)||null,null!==n)return n;const o=Xe(t,e),s=He(t),r=Fi(o);null===r&&st("No state tree found on this root for binding.");return n=We(Oe(r,t.statePathInfo),s),Je.set(t,n),n}function Qe(t){Je.delete(t)}const Ze=new WeakMap;function tn(t,e){const n=Ze.get(t);void 0===n?Ze.set(t,e):n instanceof Set?n.add(e):n!==e&&Ze.set(t,new Set([n,e])),null!==$e&&$e({type:"state:binding-added",absoluteAddress:t,binding:e})}function en(t,e){const n=Ze.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&Ze.delete(t),null!==$e&&$e({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const nn=new WeakMap;function on(t,e,n){const o=nn.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:We(t,e),binding:n}))}function sn(t){const e=Ze.get(t);return void 0!==e?e:null!==t.listIndex?nn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const rn=new WeakMap,an=new WeakMap;class ln{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]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=cn(t,e)}}function cn(t,e){if(null===e){let e=an.get(t);return void 0!==e||(e=new ln(t,null),an.set(t,e)),e}{let n=rn.get(e);void 0===n&&(n=new WeakMap,rn.set(e,n));let o=n.get(t);return void 0!==o||(o=new ln(t,e),n.set(t,o)),o}}const dn=new WeakMap;function un(t){let e=null;if(e=dn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=He(t);null===n&&st(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=cn(t.statePathInfo,n)}else e=cn(t.statePathInfo,null);return dn.set(t,e),e}function fn(t){dn.delete(t)}function hn(){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 pn=new Map,mn=hn();function gn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function yn(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function bn(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=yn(t),s=gn(t,o);let r=pn.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=Fi(o.getRootNode());null===i&&st("No state tree found on this root for two-way binding.");const a=we(o);i.createState("writable",t=>{t[Pe](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]:[]})})},pn.set(s,r)),t.node.addEventListener(o,r),mn.add(s,t),!0}var e,n;return!1}function wn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function vn(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)wn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class $n{_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 Sn extends $n{_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 Nn=new WeakMap;function xn(t,e){let n=Nn.get(t);void 0===n&&(n=new Map,Nn.set(t,n));let o=n.get(e);return void 0===o&&(o=new Sn(e,t),n.set(e,o)),o}function In(t){Nn.delete(t)}const Pn=new WeakMap;function kn(t){if(t.propSegments[0]!==g)return!1;const e=t.node,n=J(e),o=Y(e);if(null!==n&&void 0===o?.get(n))return null===o&&st(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Pn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||st('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===J(t)?null:Z(t)}(e);null===r&&st(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&st(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${ft(s,r.knownProperties.keys())}`);const a=i.event,d=t.statePathName,u=t.propModifiers,f=t=>{u.includes(l)&&t.preventDefault(),u.includes(c)&&t.stopPropagation();const n=Fi(e.getRootNode());null===n&&st("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(d)||st(`[wcs/token-undeclared] eventToken "${d}" is not declared in $eventTokens.${ft(d,n.eventTokenNames)}${ht}`);const o=we(e);n.createStateAsync("writable",async e=>{vn(e[Pe](o,()=>{const s=null!==o?Ke(o.listIndex,o.pathInfo.wildcardCount):[];return xn(n,d).emit(e,t,...s)}),`$on."${d}"`)})};return e.addEventListener(a,f),Pn.set(t,{eventName:a,handler:f}),!0}class _n extends $n{_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 An(t){return t instanceof _n}const Cn=new Map,En=hn();function Mn(t){const e=t.propModifiers.filter(t=>t===l||t===c).sort().join(",");return`${t.statePathName}::${e}`}const Tn=(t,e,n)=>o=>{e.includes(l)&&o.preventDefault(),e.includes(c)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Fi(r);null===i&&st("No state tree found on this root for event handler.");const a=we(s),d=t.startsWith(C+".");i.createStateAsync("writable",async e=>{const l=e[Pe](a,()=>{let l=null!==a?a.pathInfo.wildcardCount:0;if(null!==a&&!0===i.hasMounts){const t=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=fe.get(n);if(void 0!==t)return t;n=n.parentNode}return fe.get(e)??null}(s,r);if(null!==t){const e=t.indexShiftByLoopElementPath.get(a.pathInfo.path);l=void 0!==e?l-e:0}}const c=null!==a?Ke(a.listIndex,l):[];if(d){const s=e[ke](cn(n,null));return An(s)||st(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...c)}const u=e[t];return"function"!=typeof u&&st(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(u,e,[o,...c])});vn(l,`"${t}"`)})};function On(t){if(!t.propName.startsWith(m))return!1;const e=Mn(t);let n=Cn.get(e);void 0===n&&(n=Tn(t.statePathName,t.propModifiers,t.statePathInfo),Cn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),En.add(e,t),!0}const Rn=new Map,Dn=hn();function jn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Ln(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function Wn(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=Ln(t),s=jn(t,o);let r=Rn.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=Fi(o.getRootNode());null===r&&st("No state tree found on this root for two-way binding.");const i=we(o);r.createState("writable",t=>{t[Pe](i,()=>{t[e]=s})})},Rn.set(s,r)),t.node.addEventListener(o,r),Dn.add(s,t),!0}var e,n;return!1}const Bn=new Set(["radio","checkbox"]),zn=new Set(["value","valueAsNumber","valueAsDate"]);function Fn(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(zn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=J(n);if(null!==s){const t=Y(n)?.get(s);void 0===t&&st(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Z(n);if(o?.knownProperties.has(e))return!0}return!1}let qn=1,Vn=1,Un=1;const Kn=new WeakMap;function Gn(t,e,n){let o=Kn.get(t);void 0===o&&(o=new Map,Kn.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 Hn(t,e){return"to-element"===e?2*t:2*t+1}const Jn=new Set;function Xn(t){return{transactionId:Vn++,originBindingId:t,visitedEdges:Jn,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 Qn=null;function Zn(){return Qn}function to(t,e){const n=Qn;Qn=t;try{return e()}finally{Qn=n}}const eo=[];let no=!1;const oo=new Map,so=hn(),ro=new WeakMap,io=t=>t.detail;function ao(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 lo(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=J(t.node);if(null!==n){const o=Y(t.node)?.get(n);void 0===o&&st(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Z(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function co(t){if(null!==J(t.node)){const e=Z(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??io}return null}function uo(t){if(null===J(t.node))return!1;const e=Z(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const fo=(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);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 d=ro.get(a)?.get(t);if(void 0!==d)for(const t of d)t(c);let u=null;if(o.enablePropagationContext){const n=Gn(a,t,e),s=function(t,e){for(let n=eo.length-1;n>=0;n--){const o=eo[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:Hn(n,"to-state"),node:a,member:t}));const r=Hn(n,"to-state"),i=Zn();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}));u=Yn(i??Xn(n),r)}const f=Fi(a.getRootNode());null===f&&st("No state tree found on this root for two-way binding.");const h=we(a),p=()=>{r&&(no=!0);try{f.createState("writable",t=>{t[Pe](h,()=>{t[e]=c})})}finally{r&&(no=!1)}};null!==u?to(u,p):p()};const ho=new WeakSet;function po(t){ho.add(t)}function mo(t){return!!ho.has(t)&&(ho.delete(t),!0)}const go=new WeakSet;function yo(t){go.add(t)}function bo(t){return!!go.has(t)&&(go.delete(t),!0)}let wo=0;function vo(){wo--}function $o(){return wo>0}class So{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 xo(t){let e=No.get(t);return void 0===e&&(e=new So(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!==u&&s!==f&&st(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&st(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Po(t){return t.propModifiers.some(t=>t.includes("="))}const ko=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),_o=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Ao(t,e){return"state"===t&&"call"===e?ko:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Co(t){if(!o.enableDirectionalInitialSync)return Po(t)&&st("init=/sync= modifiers require enableDirectionalInitialSync."),ko;const e=null===(n=Io(t,u))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:st(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":st(`Invalid sync modifier value "${t}".`)}(Io(t,f));if("event"===t.bindingType)return null!==e&&"none"!==e&&st("Event bindings only allow init=none."),"call"===s?_o:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===y)return Ao("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&st(`Binding type "${t.bindingType}" does not support init=${e}.`),Ao(e??"state",s);const r=Z(t.node);if(null===r)return Ao(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||st(`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)||st(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||st(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Eo(t,e){return"auto"!==e?e:function(t){const e=Fi(t.replaceNode.getRootNode());null===e&&st("No state tree found on this root for binding.");const n=un(t);let o=!1;return e.createState("readonly",t=>{o=t[_e](n)}),o}(t)?"state":"element"}let Mo=0,To=0;const Oo=new WeakMap,Ro=new WeakMap,Do=new WeakMap,jo=new WeakMap;function Lo(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 Wo(t){return jo.has(t)}function Bo(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 Fo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class qo{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(const o of t)e.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));const o=[];for(const t of e)mo(t)||zo(t,t=>{Bo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)bo(t)&&!$o()||zo(t,t=>{Bo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&Kr(o)}}const Vo=new WeakMap;function Uo(t){let e=Vo.get(t);return void 0===e&&(e=new qo(t),Vo.set(t,e)),e}function Ko(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 Go(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class Ho{records=new Set;rowPlan=null;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=Oo.get(t);void 0===o||"disposed"===o.phase||"failed"===o.phase?(this.start(t,s,n),r.push(t)):(this.observe(o.anchor),s.registerAddress&&null===o.address&&null===o.patternListIndex&&(o.options.registerAddress=!0,this.registerAddress(o)),"active"===o.phase&&this.settleInitialRecord(o),this.settleConnectedSnapshot(o))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(Fo(e)&&Uo(e),null===this.rowPlan)for(const n of t){const t=Oo.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 Po(t)&&Co(t),!0;const e=Oo.get(t);return void 0===e||e.session!==this||(!e.options.registerAddress||"waiting-definition"===e.phase||"failed"!==e.phase&&("active"===e.phase&&this.settleInitialRecord(e),e.initialApplyDone?"state"===e.resolvedAuthority||!e.outputOnlyMember&&!e.observationPending:(e.initialApplyDone=!0,"state"===e.resolvedAuthority)))}getRecord(t){const e=Oo.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=Oo.get(t);return!(void 0===n||!this.isAlive(n,n.generation))&&(Go(n,e),!0)}deferUntilDefined(t,e,n,o=()=>{}){const s=Y(t);null===s&&st(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Lo(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=xo(s).wait(e,()=>{if(a())try{Q(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=Oo.get(t);void 0!==e&&e.session===this&&this.disposeRecord(e)}dispose(){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;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.records)null!==t.address&&(en(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];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?Ye(n):null;if(null!==e.address?(en(e.address,n),e.address=null):(on(e.patternPathInfo,e.patternListIndex,n),e.patternPathInfo=null,e.patternListIndex=null),fn(n),Qe(n),this.registerAddress(e),null!==o){const t=Ye(n);t!==o&&Ie(o)&&xe(t,Ne(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return Fo(e)?e:null}(t);null!==e&&Uo(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&&Kr(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=Oo.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=Do.get(e);void 0===t&&(t=Ko(e),Do.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Lo(n,this);const o=this.knownMapFor(n);let s=Do.get(t);void 0===s&&(s=Ko(t),Do.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={registerAddress:!1,registerPathInfo:!1,applyOnReconnect:!1},o=t.slots;for(let t=0;t<e.length;t++){const s=e[t],r=o[t],i=s.replaceNode;Lo(i,this),this.addKnownRowBinding(i,s,t),this.optionsByBinding.set(s,n);const a={id:++Mo,info:s,generation:++To,phase:"active",teardowns:null,session:this,anchor:i,options:n,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:r.policy,resolvedAuthority:r.authority,initialSettled:!0,initialApplyDone:!1,outputOnlyMember:r.policy.outputOnly,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};if(Oo.set(s,a),this.records.add(a),r.isEvent){try{On(s)}catch(t){throw a.phase="failed",this.runTeardowns(a),this.records.delete(a),t}a.eventAttached=!0}}}activatePlanRows(t,e,n){const o=t.slots;for(let t=0;t<e.length;t++){const s=e[t],r=Oo.get(s);if(void 0!==r&&r.session===this){if(r.options.registerAddress=!0,"disposed"===r.phase||"failed"===r.phase){const e=o[t];if(r.generation=++To,r.phase="active",r.initialPolicy=e.policy,r.resolvedAuthority=e.authority,r.initialSettled=!0,r.initialApplyDone=!1,r.outputOnlyMember=e.policy.outputOnly,this.records.add(r),e.isEvent){try{On(s)}catch(t){throw r.phase="failed",this.runTeardowns(r),this.records.delete(r),t}r.eventAttached=!0}this.registerAddress(r,n);continue}null===r.address&&null===r.patternListIndex&&this.registerAddress(r,n)}else this.initialize([s],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}}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:++Mo,info:t,generation:++To,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};Oo.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;On(e)?t.eventAttached=!0:e.propSegments[0]!==g?(Wn(e)&&Go(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=Ln(t),n=jn(t,e),o=Rn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Dn.countOf(n)&&(Dn.remove(n,t)&&Rn.delete(n),!0))}return!1}(e)),bn(e)&&Go(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=yn(t),n=gn(t,e),o=pn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==mn.countOf(n)&&(mn.remove(n,t)&&pn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Fn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const n=function(t,e,n){let o=ro.get(t);void 0===o&&(o=new Map,ro.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&&ro.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});Go(t,n)}!function(t){const e=J(t.node);if(null!==e){const n=Y(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&st(`CustomElementRegistry is unavailable for <${e}>.`))}if(Fn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=lo(t),n=co(t),o=uo(t),s=ao(t,e,null!==n,o);let r=oo.get(s);void 0===r&&(r=fo(t.propName,t.statePathName,t.inFilters,n,o),oo.set(s,r)),t.node.addEventListener(e,r),so.add(s,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{kn(e)&&Go(t,()=>function(t){if(t.propSegments[0]!==g)return!1;const e=Pn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),Pn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=J(t.info.node);if(null===n)return void e();const o=Y(t.info.node);if(null===o&&st(`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=xo(o).wait(n,()=>{if(this.isAlive(t,s))try{Q(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))});Go(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Co(t.info),n=Eo(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 wo++;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,vo()),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=Fi(t.node.getRootNode());null===o&&st("No state tree found on this root for initial binding sync.");const s=we(t.node);o.createState("writable",e=>{e[Pe](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=He(n);if(null!==o){const s=Fi(Xe(n,e));null===s&&st("No state tree found on this root for binding.");const r=Oe(s,n.statePathInfo);!function(t,e,n){let o=nn.get(t);void 0===o&&(o=new WeakMap,nn.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:We(t,e),binding:n})}(r,o,n),t.patternPathInfo=r,t.patternListIndex=o}else{const o=Ye(n,e);tn(o,n),t.address=o}if(!t.options.registerPathInfo)return;const s=Fi(n.replaceNode.getRootNode());null===s&&st("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&&Oo.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,vo());const e=t.info;if(null!==t.address)try{en(t.address,e),t.address=null,fn(e),Qe(e)}catch{}else if(null!==t.patternListIndex)try{on(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,fn(e),Qe(e)}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=J(t.node);if(null!==e){const n=Y(t.node),o=n?.get(e);if(void 0===o)return}if(Fn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=lo(t),n=ao(t,e,null!==co(t),uo(t)),o=oo.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),so.remove(n,t)&&oo.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{!function(t){if(!t.propName.startsWith(m))return!1;const e=Mn(t),n=Cn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==En.countOf(e)&&(En.remove(e,t)&&Cn.delete(e))}(e)}catch{}}}}function Jo(t){let e=Ro.get(t);return void 0===e&&(e=new Ho(t),Ro.set(t,e)),e}function Xo(t){return Oo.get(t)?.session??null}const Yo=new WeakMap;function Qo(t,e){let n=Yo.get(t);n||(n=new Set,Yo.set(t,n)),n.add(e)}const Zo=new WeakMap;function ts(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const es=Object.freeze([]);const ns=new WeakMap;const os=new WeakMap;function ss(t){return os.get(t)??[]}function rs(t,e){os.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 is=0;function as(){return`u${(is++).toString(36)}`}let ls=0;class cs{uuid=as();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(t,e){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._index=e,this._version=ls}get index(){return this._index}set index(t){this._index=t,this._version=++ls,this.indexes[this.position]=t}get version(){return this._version}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=ls),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0===this._listIndexes&&(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)]),this._listIndexes}get varName(){return`$${this.position+1}`}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function ds(t,e){return new cs(t,e)}const us=new WeakMap;function fs(t){return us.get(t)||null}function hs(t,e){null!==e?us.set(t,e):us.delete(t)}const ps=new WeakMap,ms=Object.freeze([]),gs=new Set;function ys(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:ms,s=Array.isArray(n)&&n.length>0?n:ms,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:ms,o=Array.isArray(e)&&e.length>0?e:ms;let s=ps.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=fs(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:gs,deleteIndexSet:new Set(i),addIndexSet:gs};let e=fs(s);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=ds(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:gs,deleteIndexSet:gs,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 a={oldIndexes:i,newIndexes:i,changeIndexSet:gs,deleteIndexSet:gs,addIndexSet:gs};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,l=new Set;for(let o=0;o<s.length;o++){const a=s[o],c=n.get(a),d=c&&c.length>0?c.shift():void 0;if(void 0===d){const n=ds(t,o);e.push(n),l.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(!function(t,e,n){let o=ps.get(t);o||(o=new WeakMap,ps.set(t,o)),o.set(e,n)}(o,s,a),hs(s,a.newIndexes))}}(t,e,n);return function(t){for(let e=0;e<t.length;e++)t[e].index!==e&&(t[e].index=e)}(o.newIndexes),o}function bs(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}const ws=new WeakMap;function vs(t){return ws.get(t)??[]}function $s(t,e){ws.set(t,e)}const Ss=new WeakMap;function Ns(t){return Ss.get(t)??null}function xs(t,e){Ss.set(t,e)}const Is=new WeakMap;function Ps(t){return Is.get(t)??[]}function ks(t,e){Is.set(t,e)}function _s(t,e){const n=Ps(t);for(const t of n)ve(t,e)}function As(t,e,n){_s(t,e);const o=vs(t),s=Ns(t);null!==s&&s.activate(o,n.rootNode);for(const t of o){if(null===s){tn(Ye(t),t)}(null===s||s.shouldApplyState(t))&&Vr(t,n)}}function Cs(t){if(!t.mounted)return;const e=vs(t),n=Ns(t);for(const t of e)if(null!==n)n.disposeBinding(t);else{en(Ye(t),t)}!function(t){const e=Ps(t);for(const t of e)ve(t,null)}(t)}const Es=new WeakMap,Ms=Object.freeze(new Set);function Ts(t,e){const n=Es.get(t);n?n.add(e):Es.set(t,new Set([e]))}function Os(t){const e=Es.get(t);return void 0!==e?e:Ms}function Rs(t,e){const n=Es.get(t);n&&(n.delete(e),0===n.size&&Es.delete(t))}const Ds=new Set(["if","elseif","else","for"]);class js{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e,this._childNodeArray=Array.from(this._content.childNodes),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){for(const e of this._childNodeArray)yo(e),t.appendChild(e);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){yo(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=Ns(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)po(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=vs(this);for(const t of e)if(Ds.has(t.bindingType)){const e=Os(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){Ns(this)?.dispose();for(const t of this._childNodeArray)po(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=vs(this);for(const e of t){if(Ds.has(e.bindingType)){const t=Os(e.node);for(const e of t)e.unmount()}fn(e),Qe(e)}this._mounted=!1}}function Ls(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}function Ws(t){const e=document.createDocumentFragment(),n=new js(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 Bs(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=lt(o,s[t].nodePath);null===e&&st(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Ht(e),q(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){const n=new Ho;return n.initializeRow(t,e),n}(n,a),d=new js(o);return xs(d,c),$s(d,a),rs(d,l),ks(d,r),Ts(t.node,d),d}function zs(t){void 0!==t.uuid&&null!==t.uuid||st("BindingInfo.uuid is null.");const n=Wt(t.uuid);n||st(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&Ls(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=lt(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===y||s===g)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==J(r))return null;if("prop"===o&&Fn(r,t.propName))return null;let i;try{i=Co({...t,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;n.push({nodeIndex:e,template:t,isEvent:"event"===o,isIndexBinding:t.statePathName in S,policy:i,authority:i.authority})}}return{directional:e,slots:n}}(n)),null!==r)return Bs(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=lt(t,s.nodePath);if(null===e&&st(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Ut.has(e))continue;const r=Kt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new Ho,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new js(i,s);xs(l,a.bindingSession),$s(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in S&&c.push(t);return rs(l,c),ks(l,a.nodes),Ts(t.node,l),l}const Fs=Symbol.for("wcstack.transition-runner");function qs(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}const Vs=new WeakSet,Us=Symbol.for("wcstack.state.view-transition-naming");function Ks(){const t=qs("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Gs(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||Vs.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[Us]??={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.`)):(Vs.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 Hs=new WeakMap,Js=new WeakMap,Xs=new WeakMap,Ys=new WeakMap;function Qs(t,e,n){!function(t,e,n){let o=Js.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Js.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Zs(t,e){Hs.set(t,e)}function tr(t,e){let n=Xs.get(t.node);void 0===n&&(n=[],Xs.set(t.node,n)),n.length<1e3?n.push(e):Rs(t.node,e)}function er(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)}function nr(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function or(t,n,s){const r=Boolean(s);let i;const a=Os(t.node);i=0===a.size?zs(t):a.values().next().value;const l=e(),c=t.uuid??"",d=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${nr(t)}`),Cs(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${nr(t)}`),l){const e=document.createComment(`@@wcs-${d}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);As(i,we(t.node),n);const e=Ks();null!==e&&Gs(i,"branch",e)}}const sr=new WeakMap,rr=new WeakMap;const ir=new WeakMap;const ar=new WeakMap;function lr(t){return ar.get(t)??[]}const cr=new Set;const dr={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 ur(t,n,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 l=i[0],c=r[l];if(c!==s){null!==c&&"object"==typeof c&&null!==s&&"object"==typeof s&&null!==J(r)&&function(t,e,n){let o=sr.get(t);o||(o=new Map,sr.set(t,o)),o.has(e)||o.set(e,n)}(r,l,c);const e=()=>{let t=!1;try{r[l]=s,t=!0}catch(t){o.debug&&console.warn(`Failed to set property '${l}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=J(t);if(null===n)return null;const o=Y(t)?.get(n);if(void 0===o)return null;const s=Z(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,l);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&&Fn(r,l)){const o=Gn(r,l,t.statePathName),i=Hn(o,"to-element"),a=n?.propagationContextByBinding?.get(t)??Zn()??Xn(o);if(a.visitedEdges.has(i))null!==$e&&$e({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:r,member:l});else{const t=Yn(a,i);to(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Un++,writtenValue:n};eo.push({receipt:i,node:t});try{return r()}finally{eo.pop()}}(r,l,s,o,t.transactionId,e))}}else e()}if(e()){const t=dr[l];t?t(r,s):(!function(t,e,n){let o=ar.get(t);o||(o=[],ar.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,l,s),a=r,cr.add(a))}return}var a;const l=i[0];let c=r[l];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==c)return;c=c[e]}const d=i[i.length-1],u=c[d];if(u!==s){if(Object.isFrozen(c))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:u,newValue:s}));2===i.length&&"object"==typeof c&&null!==c&&null!==J(r)&&(d in c?function(t,e,n,o){let s=ir.get(t);s||(s=new Map,ir.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}(r,l,d,c[d]):function(t,e,n){let o=rr.get(t);o||(o=new Map,rr.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)}(r,l,d));try{c[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:u,newValue:s,error:t})}}}const fr=new WeakSet;function hr(t,e,n){}const pr=new WeakMap;function mr(t,e){if(null===t)return!1;const n=pr.get(t);if(void 0===n||0===n.size)return!1;for(const t of n)if(e===t||e.startsWith(t+s)||t.startsWith(e+s))return!0;return!1}const gr=new WeakMap;function yr(t,e){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{e.$postUpdate(t+s+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...r)=>e[n](t+s+o,...r)}return e[o]}return e[t+s+o]}},set:(n,o,r)=>("string"!=typeof o||(e[t+s+o]=r),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const br=new WeakMap,wr=[];const vr=new WeakMap;let $r=null;const Sr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Nr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function xr(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 Ir(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),r=e.length>0?e+s:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(s)&&o.push(e)}return o}const Pr={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},kr={binding:"Bound path",watch:"$watch path"};function _r(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}.${ht}`}function Ar(t,e){return`$setAll("${t}") ${e}`}function Cr(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.${ht}`}const Er=new WeakMap;function Mr(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(mr(t.rootNode??null,n))return;const i=K(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=Er.get(t);return void 0===n&&(n=new Set,Er.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;const a=function(t,e,n){if(void 0!==xr(t,e))return Nr;const o=K(e).segments;let i=t,a="";for(let e=0;e<o.length;e++){const l=o[e],c=a;if(a=0===e?l:a+s+l,e>0&&e<o.length-1&&void 0!==xr(t,a))return Sr;if(Object(i)!==i)return Sr;if(l===r){if(!Array.isArray(i)||0===i.length)return Sr;i=i[0];continue}const d=xr(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:Ir(i,c,n)};if("function"==typeof d.get)return e===o.length-1?Nr:Sr;i=d.value}return Nr}(e,n,t.getterPaths);"missing"===a.existence&&(console.warn(`[@wcstack/state] [${Pr[o]}] ${kr[o]} "${n}" does not resolve on the state tree: "${a.missingSegment}" is not declared.${ft(a.missingSegment,a.candidates)} Updates to this path will be silently dropped.${ht}`),null!==$e&&$e({type:"state:path-unresolved",source:o,path:n,missingSegment:a.missingSegment}))}function Tr(t,e){const n=un(e);if(n.pathInfo.path in S){const t=we(e.node);return null===t&&st(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&st("ListIndex not found for loopContext:");const n=S[e];void 0===n&&st(`Invalid index name: ${e}`);const o=Ue(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&st(Cr(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[ke](n)}const Or=new WeakSet;function Rr(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Dr=Object.freeze({[b]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&st("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[w]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[v]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[y]:function(t,e,n){An(n)||st("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ns.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||st('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=J(t);if(null===e)return null;const n=Y(t)?.get(e);return void 0===n&&st(`Custom element <${e}> is not defined for command binding.`),Z(t)}(r);null===a&&st(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||st(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ft(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ns.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 ns.delete(t);const o=n[i];return"function"!=typeof o&&st(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),ns.set(t,{token:o,unsubscribe:c,elementRef:l})}}),jr={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!fr.has(t.replaceNode)){fr.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,i=He(t),a=Ye(t),l=Ne(a),c=l.length>0&&!Js.has(t.node)?[]:l,d=ys(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);const u=Array.isArray(c)&&c.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(u&&null!==t.node.parentNode){let e=Ys.get(t.node);if(void 0===e){const n=Hs.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(n.nodeType===Node.ELEMENT_NODE||n.nodeType===Node.TEXT_NODE&&""!==(n.textContent?.trim()??"")){s=!1;break}n=n.previousSibling}for(;null!==o;){if(o.nodeType===Node.ELEMENT_NODE||o.nodeType===Node.TEXT_NODE&&""!==(o.textContent?.trim()??"")){s=!1;break}o=o.nextSibling}return s}(t.node,n),Ys.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let f=Js.get(t.node),h=u?1e3-function(t){return Xs.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==f){for(const e of d.deleteIndexSet){const n=f.get(e);void 0!==n&&(h<=0&&n.tryDestroy()?Rs(t.node,n):(Cs(n),n.unmount(),tr(t,n),h-=1),u||f.delete(e))}u&&(Js.delete(t.node),f=void 0)}let p=t.node;const m=K(s.path+"."+r),g=n.stateElement.loopContextStack,y=bs(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&p.isConnected&&(b=document.createDocumentFragment(),ze(b,n.rootNode));const w=e(),v=Ks(),$=t.uuid??"",S=Xs.get(t.node);for(const e of d.newIndexes){let o;if(d.addIndexSet.has(e)){const r=cn(m,e);g.createLoopContext(r,r=>{if(o=void 0!==S?S.pop():void 0,void 0===o&&(o=zs(t)),null!==b)w&&b.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`)),o.appendTo(b),w&&b.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`));else{if(p.nextSibling!==o.firstNode){if(w){const t=document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`);p.parentNode.insertBefore(t,p.nextSibling),p=t}o.mountAfter(p)}if(w){const t=document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`),n=o.lastNode??p;n.parentNode.insertBefore(t,n.nextSibling)}}As(o,r,n),null!==v&&Gs(o,"row",v)}),void 0===o&&st(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=void 0!==f?f.get(e)??null:null,d.changeIndexSet.has(e)){const t=ss(o);for(const e of t)Vr(e,n)}null===o&&st(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==y&&y.has(e)&&er(p,o.firstNode)||p.nextSibling===o.firstNode||o.mountAfter(p),t){const t=o,s=cn(m,e);g.createLoopContext(s,e=>{As(t,e,n)})}}p=o.lastNode||p,void 0===f&&(f=new WeakMap,Js.set(t.node,f)),f.set(e,o)}Hs.set(t.node,p),null!==b&&(t.node.parentNode.insertBefore(b,t.node.nextSibling),ze(b,null))},if:or,else:or,elseif:or,radio:function(t,e,n){const o=t.node,s=ts(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=ts(o.value,t.inFilters),r=Array.isArray(n)?n:es;o.checked=r.includes(s)}},Lr=new WeakMap,Wr=new WeakMap,Br=new WeakMap;function zr(){}function Fr(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===Yo.get(t)?.has(e)}(e,n)?hr:function(t,e){return!0===Zo.get(t)?.has(e)}(e,n)?zr:ur}function qr(t,e){const n=ts(Tr(e.state,t),t.outFilters);if(!0===Wr.get(t))return void e.deferredSelectBindings.push({binding:t,value:n});let o=Lr.get(t);if(void 0===o){if(Lr.has(t))return o=Fr(t),o===hr&&Lr.set(t,o),void o(t,e,n);if(o=jr[t.bindingType],void 0===o){const e=t.propSegments[0];if(o=Dr[e],Lr.set(t,o),void 0===o){J(t.replaceNode)?(o=Fr(t),o===hr&&Lr.set(t,o)):(o=ur,Lr.set(t,o))}}if(o===ur){if("SELECT"===t.node.tagName){const o=t.propSegments[0];if("value"===o||"selectedIndex"===o)return e.deferredSelectBindings.push({binding:t,value:n}),void Wr.set(t,!0)}}o(t,e,n)}else o(t,e,n)}function Vr(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=Ye(t);if(e.updatedAbsAddressSetByStateElement.has(e.stateElement)){e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n)}else e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=Xo(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Br.get(t)){const e=J(t.replaceNode);if(e&&void 0===Y(t.replaceNode)?.get(e))return void function(t,e){if(Or.has(t))return;Or.add(t);const n=()=>{Or.delete(t);const e=Xo(t);(null===e||e.shouldApplyState(t))&&Kr([t])},o=n=>{Or.delete(t),Rr(e,n)},s=Xo(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Or.delete(t),r()})||(Or.delete(t),r()))}const r=Y(t.replaceNode);if(null===r)return Or.delete(t),void Rr(e,new Error("CustomElementRegistry is unavailable."));xo(r).wait(e,()=>{t.replaceNode.isConnected?n():Or.delete(t)},o)}(t,e);Br.set(t,!0)}if(!0===e.sameRootVerified)return void qr(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Fe(o),null===o&&st("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Fi(o);null===n&&st("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};qr(t,r)})}else qr(t,e)}function Ur(t,e){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 Kr(t,e){let n=0;const s=new Set,r=new Map,i=new Map,a=[];for(;n<t.length;){let l=t[n];if(!1===l.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${l.bindingType} ${l.statePathName} on ${l.node.nodeName}`,l),n++;continue}let c=l.replaceNode.getRootNode();c instanceof DocumentFragment&&!(c instanceof ShadowRoot)&&(c=Fe(c),null===c&&st("Root node for fragment not found for binding."));const d=Fi(c);null===d&&st("No state tree found on this root for binding."),d.createState("readonly",o=>{const u={rootNode:c,stateElement:d,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Vr(l,u)}catch(t){Ur(l,t)}n++;const e=t[n];if(!e)break;if(e.replaceNode.getRootNode()!==u.rootNode)break;l=e}})}for(const{binding:t,value:n}of a)try{ur(t,{propagationContextByBinding:e},n)}catch(e){Ur(t,e)}for(const[t,e]of r.entries())xe(t,e);for(const[t,e]of i.entries())t.createState("writable",t=>{t[Me](Array.from(e))})}function Gr(t,e,n){const[o,s,r]=Gt(t,n),i=Jo(t);for(const t of o)ve(t,e);Kr(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=Jt(o);0!==t.length&&(ve(o.node,e),Kr(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const Hr=/\{\{\s*(.+?)\s*\}\}/g,Jr=new Set(["SCRIPT","STYLE"]);function Xr(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&&Jr.has(t.parentElement.tagName)||Yr(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),Xr(e.content)}else Xr(t.content)}function Yr(t){const e=t.data;if(Hr.lastIndex=0,!Hr.test(e))return;Hr.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Hr.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)}let Qr;function Zr(){if(Qr)return Qr;const t=[],e=Nt("not",t)($t);return Qr={filterName:"not",args:t,filterFn:e},Qr}const ti=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function ei(t,e){const n=e+s+r,o=t.indexOf("|");let i,a;if(-1!==o?(i=t.slice(0,o).trim(),a=t.slice(o)):(i=t.trim(),a=""),"."===i)i=n;else{if(!i.startsWith("."))return t;i=n+s+i.slice(1)}return a.length>0?i+a:i}function ni(t,e){const n=ti.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+ei(s,e)+r}function oi(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=ei(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function si(t,e){return oi(t,e)}function ri(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=ni(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=oi(r,e);t!==r&&o.setAttribute(n,t)}}}function ii(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 ai(t){const e=[],n=Vt(t);for(const t of n){const n=Bt(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:ii(o),parseBindTextResults:n})}return e}function li(t){const e=Array.from(t.childNodes);for(const n of e)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&t.removeChild(n)}}const ci=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),di=Zr();function ui(t,e){const n=e.outFilters;return{...e,outFilters:[...n,di],bindingType:t}}function fi(t,e,n,o,s,r=!0){li(e),"string"==typeof o&&ri(e,o),hi(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:ai(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 hi(t,e,n,s){const r=o.commentElsePrefix,i=Ft(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;if(i.length>0&&-1!==i.indexOf(e))return NodeFilter.FILTER_REJECT;if("template"===e.tagName.toLowerCase()){if((e.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const t=a.currentNode;d.push(t)}for(const e of d){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=si(i,n));let a=Et(i)[0];const d=ci.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=e.content,h=as();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&st("'else' binding found without preceding 'if' or 'elseif' binding."),a=ui("else",l.parseBindTextResult),p=fi(t,f,a,m,s,!1),Lt(h,t,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:ii(o),parseBindTextResults:Bt(o)})):e.replaceWith(o)}else if("elseif"===u){null===l&&st("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=fi(t,f,a,m,s),Lt(h,t,p);const n=document.createComment(`@@${d}:${h}`),o=as(),i={fragment:document.createDocumentFragment(),parseBindTextResult:ui("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ii(n),parseBindTextResults:Bt(n)}),Lt(o,t,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(e.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:ii(g),parseBindTextResults:Bt(g)})):e.replaceWith(g)}else{p=fi(t,f,a,m,s),Lt(h,t,p);const n=document.createComment(`@@${d}:${h}`);e.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}async function pi(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Y(t);null===s&&st(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(zt(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function mi(t){if(t===document)await pi(document),Xr(document),hi(document,document),Gr(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await F(e.host),await pi(e),Xr(e),hi(e,e),Gr(e,null)}}const gi="2.1.1",yi="undefined"==typeof HTMLElement?class{}:HTMLElement,bi=/^@@wcs-(?:for|if|elseif|else):[^-]/,wi=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,vi=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,$i=/^@@wcs-text-start:(.+)$/;function Si(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Ni extends yi{_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=gi.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;if(!n)return null;return n.querySelector(e)}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const[t,o]of Object.entries(e))t.startsWith("$")||"function"==typeof o||(n[t]=o);return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=Si(JSON.stringify(e)),t.appendChild(n);const s=Array.from(jt.keys());for(const e of s){const n=Wt(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(cr);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=lr(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=Si(JSON.stringify(e)),t.appendChild(n)}}cr.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(wi.test(t.data)||vi.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;bi.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=$i.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;wi.test(t.data)&&i.push(t)}for(const t of i){const e=wi.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()}Ni.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(bi.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 xi=new Set(["for","if","elseif","else"]);function Ii(t){const e=new Ho;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]=Gt(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 Pi(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 ki(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Et(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,Zr()],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;li(a),"string"==typeof l&&ri(a,l),hi(n,a,l);Lt(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:ai(a)})}}async function _i(t){await pi(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="${gi}". Falling back to full render.`),Ni.cleanupDom(t),!1}for(const n of e)ki(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=wi.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 d=t.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body);!function(t,e){const n=new Map;for(const o of e){if(0===o.nodes.length)continue;const e=Ws(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=Ii(o.nodes);xs(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");$s(e,s),ks(e,i);const l=[];for(const t of s)t.statePathName in S&&l.push(t);if(rs(e,l),"for"===o.type&&null!==o.index){const i=Pi(t,"for",o.uuid);if(i){const t=ds(null,o.index);Qs(i,t,e),Zs(i,o.nodes[o.nodes.length-1]),Ts(i,e),_s(e,cn(K(o.path+"."+r),t)),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let l=n.get(o.uuid);l||(l=[],n.set(o.uuid,l)),l.push(t)}}else{const n=Pi(t,o.type,o.uuid);n&&(Ts(n,e),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=Pi(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Wt(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Fi(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&hs(e,o)})}}(document.body,n),Ni.removeBlockBoundaryComments(document.body);const s=[];for(const t of e)t.parentNode&&(s.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());Ni.restoreTextBindings(document.body);const[i,a]=Gt(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 l=[],c=[],d=Jo(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(xi.has(t.bindingType))c.push(t);else{if(t.statePathName.includes(r))continue;l.push(t)}for(const t of c)if("for"===t.bindingType){const e=Ye(t),n=Fi(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&xe(e,o)})}Kr(l);for(const{el:t,parent:e,next:n}of s)e.insertBefore(t,n);const u=t.querySelectorAll(o.tagNames.ssr);for(const e of u){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}const Ai=Symbol.for("wcstack.binder");const Ci=Symbol.for("wcstack.binder.pending"),Ei=Symbol.for("wcstack.binder.taken");function Mi(){const t=function(){const t=globalThis[Ai];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[Ci];return void 0===e&&(e=[],t[Ci]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[Ei];return void 0===e&&(e=new WeakSet,t[Ei]=e),e}();for(const e of n)o.add(e),t.bind(e)}function Ti(t){if(Wo(t))return!0;if(!Oi(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Wo(e)}function Oi(t){return 1===t.nodeType}function Ri(t){if(Ti(t))return;Xr(t),hi(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Gr(e&&s?n:t,null)}const Di=[];function ji(){const t=Di.splice(0,Di.length);for(const e of t)Ri(e);Mi()}const Li={protocol:"wcs-binder",version:1,bind:function(t){var e;Oi(t)&&!Ti(t)&&(e=t.getRootNode(),Vi.has(e)?Ri(t):Di.push(t))}};const Wi=new WeakMap,Bi=new WeakMap,zi=new Set;function Fi(t){return Wi.get(t)??null}function qi(t){return Bi.get(t)??Promise.resolve()}const Vi=new WeakSet;function Ui(t){Vi.add(t)}function Ki(t,n){const s=Wi.get(t);if(null===n){if(void 0===s)return;Wi.delete(t),zi.delete(s),null!==$e&&$e({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{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{if(o){await _i(t)||await mi(t)}else await mi(t);Ui(t),ji(),e()}catch(t){n(t)}})});Bi.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await mi(t),Ui(t),ji(),e()}catch(t){n(t)}})});Bi.set(t,e)}}void 0!==s&&st('A state tree is already registered on this root — one <wcs-state> per root in v2. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Wi.set(t,n),zi.add(n),function(t,e){const n=vr.get(t);if(void 0===n||0===n.length||null===$r)return;vr.delete(t);const o=$r;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,n),null!==$e&&$e({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}let Gi=0,Hi=0;const Ji=[];function Xi(t,e=0){const n=Ji.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Ji.push(o):Ji.splice(n,0,o)}function Yi(t){queueMicrotask(()=>{throw t})}const Qi=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){Gi>Hi&&(Hi=Gi);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&queueMicrotask(()=>{const t=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(t)})}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t){const n=new Map;for(const e of t){const t=n.get(e.absoluteAddress);null!==$e&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&$e({type:"propagation:coalesced",absoluteAddress:e.absoluteAddress,droppedTransactionId:t.transactionId,winnerTransactionId:e.context.transactionId}),n.set(e.absoluteAddress,e.context)}const o=[],s=new Map;for(const[t,e]of n){if(null!==e&&e.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),null!==$e&&$e({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=sn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(o.push(t),null!==e&&s.set(t,e));else!1!==n.replaceNode.isConnected&&(o.push(n),null!==e&&s.set(n,e))}try{const t=()=>{s.size>0?Kr(o,s):Kr(o)};if(e()||0===o.length)t();else{const e=function(t,e,n){const o=qs(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("state",t);void 0!==e&&e.catch(Yi)}}finally{!function(t){for(const e of Ji.slice())e.listener(t)}(new Set(n.keys()))}}};function Zi(){return Qi}const ta=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function ea(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 na="__WCSTACK_DEVTOOLS_HOOK__";function oa(){const t=globalThis,e=t[na];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[na]=n,n}const sa=t=>{null!==$e&&$e({type:"state:update-batch",addresses:t})};function ra(t){const e=null!==$e;!function(t){$e=t}(t);const n=null!==t;n&&!e?Xi(sa,0):!n&&e&&function(t){const e=Ji.findIndex(e=>e.listener===t);-1!==e&&Ji.splice(e,1)}(sa)}function ia(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 aa(t){return Fi(t)??st("devtools: no state tree on this root")}let la=null;function ca(){if(e())return;if(null!==la)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:gi,getStateElements(){const t=[];for(const e of zi)t.push(ia(e));return t},overlays:t=>function(t){const e=pe.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}(aa(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]})),keys(t){const e=aa(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 aa(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){aa(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=Wt(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(ea(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=at(e,Et(n));for(const o of t)r(ea(e,o,"attribute",n))}catch{}continue}const e=ta.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=Wt(s);if(null===a){if(n===o.commentTextPrefix)try{r(ea(t,Dt(s),"comment",s))}catch{}}else r(ea(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:ra};la=t,oa().register(t)}const da={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",gi),Ni.buildContent(o,Ni.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}};const ua="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let fa=0;async function ha(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++fa}\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 ${ua}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${ua}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function pa(t){try{const e=await import(function(t){return new URL(t,document.baseURI).href}(t));return e.default||{}}catch(t){st(`Failed to load script file: ${t}`)}}class ma{_loopContextStack=Array(i).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&st("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=i&&st("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&&st("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&&st("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&&st(`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 ga=new WeakMap;function ya(t,e){let n=ga.get(t);void 0===n&&(n=new Map,ga.set(t,n));let o=n.get(e);return void 0===o&&(o=new _n(e,t),n.set(e,o)),o}const ba=new WeakMap;function wa(t){const e=ba.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 ya(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:ya(t,n)}},set(){st("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){st("$command namespace is read-only; deleting from it is not allowed.")}});return ba.set(t,n),n}const va=Symbol("wcs-stream-last-notified-uncertain"),$a=new WeakMap;function Sa(t,e){const n=$a.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Na(t,e){const n=$a.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:va,error:Object.is(o.error,null)?null:va})}const xa=new Set;function Ia(t){xa.delete(t)}const Pa=new WeakMap;function ka(t){return Pa.get(t)??new Map}function _a(t){Ia(t);const e=Pa.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Na(t,n.name)}const Aa=(t,e)=>e,Ca=new Set;function Ea(t,e){const n=e[T];if(void 0===n)return void Sa(t,Ca);"object"==typeof n&&null!==n||st(`${T} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[i,a]of Object.entries(n)){0===i.length&&st(`${T} entry name must be a non-empty string.`),i.includes(s)&&st(`${T} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&st(`${T} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&st(`${T} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&st(`${T} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&st(`${T} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&st(`${T} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||st(`${T} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&st(`${T} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&st(`${T} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&st(`${T} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&st(`${T} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??Aa,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};i in e||(e[i]=c.definition.initial),o.set(i,c)}!function(t,e){Pa.set(t,e)}(t,o),Sa(t,new Set(o.keys()))}const Ma=new WeakMap,Ta=new WeakMap;function Oa(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=ka(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&ka(t).has(n),ownKeys:()=>Array.from(ka(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=ka(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){st(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){st(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Ra(t){const e=Ma.get(t);if(void 0!==e)return e;const n=Oa(t,D,t=>t.status);return Ma.set(t,n),n}function Da(t){const e=Ta.get(t);if(void 0!==e)return e;const n=Oa(t,j,t=>t.error);return Ta.set(t,n),n}function ja(t){Ma.delete(t),Ta.delete(t)}let La=null;async function Wa(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)}}function Ba(t){const e=ka(t);if(0!==e.size){!function(t){xa.add(t)}(t);for(const n of e.values())za(t,n)}}function za(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=La,r=new Set;let i;La=r;try{t.createState("readonly",t=>{i=n(t)})}finally{La=o}i instanceof Promise&&st(`${T} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${D}${s}${e.name}`,l=`${j}${s}${e.name}`;for(const n of r){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==a&&o.path!==l||st(`${T} 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&&st(`${T} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=r,i}(t,e);t.createState("writable",t=>{t[e.name]=e.definition.initial}),Fa(t,e,"active",null);const r=e.definition,i={fold(n){t.createState("writable",t=>{t[e.name]=r.fold(t[e.name],n)})},done(){Fa(t,e,"done",null)},fail(o){Fa(t,e,"error",o),n.abort()}};Wa(r.source,o,n.signal,i)}function Fa(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return $a.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),i=r.status!==n,a=!Object.is(r.error,o);(i||a)&&(!function(t,e,n,o){let s=$a.get(t);void 0===s&&(s=new Map,$a.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${D}${s}${e.name}`),a&&t.$postUpdate(`${j}${s}${e.name}`)}))}Xi(function(t){const e=xa;if(0===e.size)return;const n=[];for(const o of e)for(const e of ka(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)&&ka(t).get(o.name)===o)try{za(t,o)}catch(n){o.controller?.abort(),e.has(t)&&ka(t).get(o.name)===o&&Fa(t,o,"error",n)}},20);const qa=new WeakMap,Va=new WeakMap,Ua=new Set,Ka=new Map;function Ga(t){return qa.get(t)??Ka}function Ha(){return Ua}const Ja=new Map;function Xa(t){return Va.get(t)??Ja}function Ya(t){0===t.length&&st(`[wcs/watch-declaration-invalid] ${O} entry name must be a non-empty state path.`),t.startsWith("$")&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not start with "$" (reserved namespace).${ht}`),t.includes("@")&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ht}`),t in Object.prototype&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=K(t);for(const n of e.segments)0===n.length&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" has an empty path segment.${ht}`);return e.wildcardCount>128&&st(`[wcs/watch-declaration-invalid] ${O} entry "${t}" exceeds the maximum wildcard depth (128).`),e}function Qa(t,e){const n=e[O];if(void 0===n)return null;"object"==typeof n&&null!==n||st(`[wcs/watch-declaration-invalid] ${O} must be an object mapping state paths to handler functions.${ht}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&st(`[wcs/watch-declaration-invalid] ${O} entry "${e}" must be a function.${ht}`);const n=Ya(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){qa.set(t,e)}(t,o),s.size>0?s:null}const Za=new WeakMap;function tl(t,e,n){let o=Za.get(t);void 0===o&&(o=new Map,Za.set(t,o)),o.set(e,n)}const el=new Map;function nl(t){0===Ga(t).size&&0===Xa(t).size||(function(t){Ua.add(t)}(t),function(t){const e=[];for(const n of Ga(t).values())sl(t,n)&&e.push(n);for(const n of Xa(t).values())for(const o of n)sl(t,o)&&e.push(o);if(0===e.length)return;t.createState("readonly",n=>{for(const o of e)try{tl(t,ol(t,o),n[o.path])}catch(e){il(t,o.path,"prime",e)}})}(t))}function ol(t,e){return We(Oe(t,e.pathInfo),null)}function sl(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const rl={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function il(t,e,n,o){console.error(`[@wcstack/state] $watch ${rl[n]} "${e}" threw.`,o),null!==$e&&$e({type:"state:watch-error",phase:n,path:e,error:o})}function al(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 ll(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=sl(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){if(0===e.pathInfo.wildcardCount)return t[e.path];return t.$resolve(e.path,n)}(t,n,s)}catch(t){return void il(0,n.path,"evaluate",t)}const a=r?function(t,e){return Za.get(t)?.get(e)}(e,o):function(t){return el.get(t)}(o);r&&tl(e,o,i),null!==$e&&$e({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){il(0,n.path,"handler",t)}}function cl(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 dl(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 ul(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 fl(t){return t.startsWith("$")}function hl(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}function pl(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 ml(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||st(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||st(`${e} entries must be non-empty strings.`),t.startsWith("$")&&st(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&st(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function gl(t){const e=ml(t,k)??[],n=ml(t,_)??[],o=hl(t),s=function(t){const e=t[T];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}st(`${k} entry "${t}" is not declared on the state.${ft(t,pl(o,"value"))}`)}"function"==typeof e.value&&st(`${k} entry "${t}" is a method. Declare it in ${_} instead.`)}for(const t of n){const e=o[t];void 0===e&&st(`${_} entry "${t}" is not declared on the state.${ft(t,pl(o,"method"))}`),"function"!=typeof e.value&&st(`${_} entry "${t}" is not a method. Declare it in ${k} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}Xi(function(t){const e=Ha();try{if(0===e.size)return;const n=function(){const t=Hi;return Hi=0,t}();if(n>32){const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==$e&&$e({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=Ga(t).get(s),i=Xa(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=Ke(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(al),function(t){Gi=t+1}(n);try{for(const t of o){if(!e.has(t.stateElement))continue;const n=Ga(t.stateElement).get(t.entry.path)===t.entry,o=!0===Xa(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&ll(t)}}finally{Gi=0}}finally{el.clear()}},10);const yl=new Map;class bl{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=K(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 wl(t){let e;return yl.get(t)??(yl.set(t,e=new bl(t)),e)}function vl(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:Ue(n.listIndex,o,n.pathInfo.wildcardCount)}const $l=new WeakMap;function Sl(t,e){null===e?$l.delete(t):$l.set(t,e)}function Nl(t){const e=$l.get(t);e&&(e.dirty=!0)}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=Ve(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?Ue(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?Ue(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}const Il=new WeakMap;class Pl{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 cn(K(this.markerParentPath+s+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(ce(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=ce(t,e),a=ue(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a=ce(t,e),l=ue(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 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[ce(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)||st(`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[ce(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 ce(this.record,e),!0}catch{return!1}}}function kl(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=Il.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Il.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 Pl(t,s,e.listIndex,r,n,o))}function _l(t){const e=t.parentStateElement,n=(e,n)=>{const o=we(t.component);let s;return e[Pe](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(ce(t,e))):(n,o,...r)=>{const i=ce(t,n),a=we(t.component)?.listIndex.indexes??[],l=ue(0,n,i,"$resolve"===e?o??[]:o,a),c="$setAll"===e||"$resolve"===e&&r.length>0?"writable":"readonly";return s(c,t=>t[e](i,l,...r))}}(t,s,n);let r;return e.createState("readonly",e=>{r=n(e,()=>e["$"===s[0]?s:ce(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:ce(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 ce(t,n),!0}catch{return!1}}})}function Al(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Cl(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}function El(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===C)return Cl(wa(s),e.pathInfo.segments);if(i===D)return Cl(Ra(s),e.pathInfo.segments);if(i===j)return Cl(Da(s),e.pathInfo.segments);if(!0===s.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const t=ye(s,e.pathInfo.path);if(null!==t)return kl(t,e,n,o)}if(!(e.pathInfo.path in t)){if(null===e.parentAddress&&mr(function(t){return t.rootNode??null}(s),e.pathInfo.path))return;const i=e.parentAddress??st(function(t,e,n){return`[${Pr.binding}] Path "${t}" does not exist on the state tree.${ft(t,Ir(e,"",n))}${ht}`}(e.pathInfo.path,t,s.getterPaths)),a=Tl(t,i,n,o);if(null==a)return;const l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??st(Cr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(a,t)}return Reflect.get(a,l)}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 Ml(t,e,n,o,s){const r=We(Oe(s,e.pathInfo),e.listIndex),i=function(t){return $l.get(t)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=El(t,e,n,o,s);return Sl(r,{value:a,dirty:!1}),a}function Tl(t,e,n,o){xl(o,e),function(t,e){if(null===La)return;const n=Oe(t,e.pathInfo);La.add(We(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return Al(s,e)?Ml(t,e,n,o,s):El(t,e,n,o,s)}const Ol=new WeakMap;function Rl(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=cn(f,r),p=Ol.get(h),m=Tl(t,h,e,n),g=ys(r,p,m).newIndexes,y=l[c]??null;if(i.set(h,m),null===y)for(let t=0;t<g.length;t++){const e=g[t];a(o,s+1,e,l,c+1,d.concat(e.index),u)}else{const t=g[y]??st(`ListIndex not found at index ${y} of ${f.path}`);s+1<o.length?a(o,s+1,t,l,c+1,d.concat(t.index),u):u.push(d.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Ol.set(t,e);return l}function Dl(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=fs(Tl(t,cn(a,r),e,n));null==l&&st(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??st(`ListIndex not found at index ${c} of ${a.path}`)}return r}function jl(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}))}function Ll(t,e,n,o){"object"==typeof t&&null!==t||st(`${R} 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&&st(`${R} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Wl(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&st(`${R} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Bl(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];Ll(a,n,o,i);const l=Wl(a,e,n,o,i);r.has(l)&&st(`${R} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function zl(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 Fl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=Tl(t,s,n,o);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=e.pathInfo.lastSegment;if(a===r){const t=e.listIndex?.index;return"number"==typeof t&&t in i}return a in i}const ql=new WeakMap;function Vl(t,e){null===e?ql.delete(t):ql.set(t,e)}function Ul(t,e,n){const s=K(t.wildcardParentPaths[e]),r=Oe(t.stateElement,s),i=cn(s,n),a=Ne(We(r,n)),l=t.stateProxy[ke](i),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}`),[]}}(ys(i.listIndex,a,l),t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)Ul(t,e+1,n)}const Kl=[];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:Kl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Kl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Hl=[];function Jl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Hl;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=K(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??Hl}function Xl(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=K(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[ke](e),a=Ne(We(Oe(t.stateElement,e.pathInfo),e.listIndex)),l=Gl(t,o,0,0,ys(e.listIndex,a,r));for(const e of l.fullRows){const o=cn(s,e);t.result.add(o),n.push(o)}if(null!==l.movedRows){const e=Jl(t,i,s);if(null===e)for(const e of l.movedRows){const o=cn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of l.movedRows)for(const s of e){const e=cn(s,o);t.result.add(e),n.push(e)}}}else{const o=cn(s,e.listIndex);t.result.add(o),n.push(o)}}const i=t.dynamicMap.get(o);if(i)for(const o of i){const s=K(o),r=[];if(s.wildcardCount>0){const n=Ve(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&st(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=Ue(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Ul(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&st(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=Ue(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=cn(s,e);t.result.add(o),n.push(o)}}}function Yl(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 d=function(t,e,n,o){const s=new Map,r=new Map,i=[t];for(r.set(t,0);i.length>0;){const t=i.pop();if(s.has(t))continue;const o=e.get(t),a=n.get(t);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];r.set(e,(r.get(e)??0)+1),s.has(e)||i.push(e)}}const a=new Map,l=new Set,c=[];for(const[t,e]of r)0===e&&(a.set(t,0),l.add(t),c.push(t));for(let t=0;t<c.length;t++){const e=c[t],n=a.get(e)+1;n>o&&st(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${e}`);const i=s.get(e);for(let t=0;t<i.length;t++){const e=i[t];n>(a.get(e)??-1)&&a.set(e,n);const o=r.get(e)-1;r.set(e,o),0===o&&(l.add(e),c.push(e))}}if(l.size!==s.size){let t=-1;for(const e of l){const n=a.get(e);n>t&&(t=n)}const e=t+1;for(const t of s.keys())l.has(t)||a.set(t,e)}return a}(c,n,o,1e3),u={ranks:d,stateElement:t,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};return 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,Xl(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(u,e,a),Array.from(u.result)}function Ql(t,e,n,o,s){const r=t.watchPaths;null!=r&&s&&r.has(e)&&function(t,e){el.has(t)||el.set(t,e)}(n,o)}function Zl(t,e,n,s,r){const i=o.enablePropagationContext?Zn()??Xn(-1):null,a=Zi();a.enqueueAbsoluteAddress(e,i),Yl(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=We(Oe(s.stateElement,e.pathInfo),e.listIndex);Nl(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function tc(t,e,n,o,s){s&&(t.getterPaths.has(e)?Nl(n):Sl(n,{value:o,dirty:!1}))}function ec(t,e,n,o,s,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 a=Tl(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??st(Cr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(a,t,o)}return Reflect.set(a,l,o)}if(!i.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);i.pushAddress(e),i.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}finally{Zl(e,n,s,i,a)}}function nc(t,e,n,o,s,r,i){let a=e.parentAddress??st(`address.parentAddress is undefined path: ${e.pathInfo.path}`),l=function(t){return ql.get(t)??null}(a);if(null===l){const e=Tl(t,a,s,r)??[],n=fs(e)??[];l={value:[...e],listIndexes:[...n]},Vl(a,l)}try{return ec(t,e,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=Tl(t,a,s,r)??[],c=Array.isArray(i)?fs(i)??[]:[],d=e.listIndex.index,u=-1!==n?l.listIndexes[n]:ds(a.listIndex,-1);c[d]=u;if(new Set(i).size===l.value.length){for(let t=0;t<c.length;t++)c[t].index=t;Vl(a,null)}}}function oc(t,e,n,o,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(n)){const l=a.get(e.pathInfo.path);if(void 0!==l){const a=Tl(t,e,o,i),c=function(t,e,n,o){const s=Bl(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Bl(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,l,a,n);if(null!==c)return function(t,e,n,o,i,a){const l=e.pathInfo.path,c=e.listIndex;null===fs(o)&&ys(c,null,o);const d=ys(c,o,n.list),u=sc(t,e,n.list,i,a,l),f=K(l+s+r);for(const e of n.matched){const n=zl(e.oldRow,e.newRow);if(0===n.length)continue;const o=d.newIndexes[e.position];for(const r of n)void 0!==o?oc(t,cn(K(f.path+s+r.field),o),r.value,i,a):e.oldRow[r.field]=r.value}return u}(t,e,c,a,o,i)}}return sc(t,e,n,o,i,null)}function sc(t,e,n,i,a,l){const c=a.stateElement,d=e.pathInfo.path;if(!0===c.hasGraftedVolumes){const t=function(t,e){const n=gr.get(t);if(void 0===n||0===n.size)return null;const o=e+s;for(const t of n)if(t.startsWith(o))return t;return null}(c,d);null!==t&&st(`Cannot replace "${d}" wholesale: a volume is mounted at "${t}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${t}" itself, or individual fields inside "${d}", instead.`)}const u=!!no&&(no=!1,!0);if(!(d in t)&&null!==e.parentAddress&&!c.elementPaths.has(d)){const s=Tl(t,e.parentAddress,i,a);if("object"==typeof s&&null!==s){const t=e.pathInfo.lastSegment,f=t===r?e.listIndex?.index:t;let h,p=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==f&&f in s,e=void 0!==f?s[f]:void 0;if(t&&Object.is(e,n))return!0;h=e,p=!0}const m=Al(c,e),g=We(Oe(c,e.pathInfo),e.listIndex);null!==$e&&$e({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:p}),Ql(c,d,g,h,p);try{return void 0===f&&st(Cr(`path "${d}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),Reflect.set(s,f,n)}finally{Zl(e,g,i,a,l),tc(c,d,g,n,m),jl(c,e.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Tl(t,e,i,a);if(Fl(t,e,i,a)&&Object.is(o,n))return!0;f=o,h=!0}const p=c.elementPaths.has(e.pathInfo.path),m=Al(c,e),g=We(Oe(c,e.pathInfo),e.listIndex);null!==$e&&$e({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),Ql(c,d,g,f,h);try{return p?nc(t,e,g,n,i,a,l):ec(t,e,g,n,i,a,l)}finally{tc(c,d,g,n,m),jl(c,e.pathInfo,{value:n})}}function rc(t,e,n,o){return(e,s,r)=>{const i=K(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&&st(_r("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=cn(i,Dl(t,n,o,i,s));if(!(void 0!==r))return Tl(t,a,n,o);oc(t,a,r,n,o)}}function ic(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return vl(o,s.wildcardPaths.at(-1)??st(`lastWildcardPath is null: ${e.pathInfo.path}`))??st(`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]??st(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=fs(Tl(t,cn(i,s),n,o))??st(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??st(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??st(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":st(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function ac(t,e,n,o){const r=Reflect.get(t,I);let i;if("function"==typeof r){const t=new Set,s={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,r=e.path;if(-1===r.indexOf("#")&&(t.add(r),e.wildcardCount>0)){const t=Ke(n.listIndex,e.wildcardCount),o=s[r];void 0===o?s[r]=[t]:o.push(t)}}i=r.call(n,Array.from(t),s)}const a=o.stateElement?(l=o.stateElement,br.get(l)??wr):[];var l;if(a.length>0)for(const t of a){const r=t.mountPath+s,i=new Set,a={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo.path;if(e!==t.mountPath&&!e.startsWith(r))continue;if(-1!==e.indexOf("#"))continue;const s=e===t.mountPath?"":e.slice(r.length);if(""===s)continue;i.add(s);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const t=Ke(n.listIndex,l);(a[s]??=[]).push(t)}}if(i.size>0)try{t.callback.call(yr(t.mountPath,n),Array.from(i),a)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" $updatedCallback threw.`,e)}}return i}const lc=`${D}${s}`,cc=`${j}${s}`,dc=new WeakMap;function uc(t,e,n,o){const r=S[e];if(void 0!==r){0===o.addressStackLength&&st(`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 i=t?.listIndex;null==i&&st(`ListIndex not found: ${e.toString()}`);let a=r;const l=t.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const t=ye(o.stateElement,l.path);null!==t&&(a=r+function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(s,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const r=-1===o?e:e.slice(0,o),i=-1===o?"":e.slice(o+1),a=t.accessorBySuffixByMarkerParent.get(r)?.get(i);return void 0!==a?a.indexShift:t.delta}(t,l.path))}const c=Ue(i,a,l.wildcardCount);return c?.index??st(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>function(t,e,n,o){const s=rc(t,0,n,o);return(e,r)=>{const i=K(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)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&st(_r("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=vl(o,i.wildcardPaths[t]);if(e){r=Ke(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&&st(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}}(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>function(t,e,n,o){return(e,s,r,i)=>{const a=K(e);Array.isArray(s)||st(Ar(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&st(_r("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&st(Ar(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&st(Ar(e,"requires an array as the value when { spread: true } is set."));const d=Rl(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&st(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,d.length,r.length));const u=[];for(let e=0;e<d.length;e++){const s=Dl(t,n,o,a,d[e]);u.push(cn(a,s))}let f=0;for(let e=0;e<u.length;e++){const s=u[e];let i;i=c?r(Tl(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(oc(t,s,i,n,o),f++)}return f}}(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=wl(e),i=ic(t,r,n,o),a=cn(r.pathInfo,i),l=We(Oe(s,a.pathInfo),a.listIndex),c=Zi();c.enqueueAbsoluteAddress(l),Yl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=We(Oe(s,t.pathInfo),t.listIndex);Nl(e),c.enqueueAbsoluteAddress(e)}),jl(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>rc(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{0===o.addressStackLength&&st(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??st("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"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case C:return wa(o.stateElement);case D:return Ra(o.stateElement);case j:return Da(o.stateElement)}if(!e.startsWith(lc)&&!e.startsWith(cc))return}const s=wl(e),r=ic(t,s,n,o),i=cn(s.pathInfo,r);return Tl(t,i,n,o)}if("symbol"==typeof e){const s=function(t){let e=dc.get(t);return void 0===e&&(e=new Map,dc.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case Pe:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&st("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 ke:i=e=>Tl(t,e,n,o);break;case _e:i=e=>Fl(t,e,n,o);break;case Ae:i=(e,s)=>oc(t,e,s,n,o);break;case Ce:i=()=>async function(t,e,n){const o=Reflect.get(t,N);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Ee:i=()=>function(t,e,n){const o=Reflect.get(t,x);"function"==typeof o&&o.call(n)}(t,0,n);break;case Me:i=e=>ac(t,e,n,o);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}class fc{_stateElement;_addressStack=Array(i).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Fi(t);null===n&&st("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&st("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=i&&st(`Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_describeAddressCycle(){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`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&st(`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 uc(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&st("This state is readonly."),function(t,e,n,o,s){if("string"==typeof e){const r=wl(e),i=ic(t,r,o,s);return oc(t,cn(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)}}function hc(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)}const pc=new WeakMap;class mc{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=pc.get(t);return n?n.get(e)??null:null}(t,e)??st("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 gc=t=>()=>t;function yc(t,e,n,o){!function(t,e,n){let o=pc.get(t);o||(o=new Map,pc.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(hc(o));const s=function(t,e){const n=new mc(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:gc(s),enumerable:!0,configurable:!0}),Qo(e,n),bc(e,n)}function bc(t,e){if(P in t){const n=t[P];"function"==typeof n?n.call(t,e).catch(t=>{st(`Error in ${P}: ${t instanceof Error?t.message:String(t)}`)}):st(`${P} is not a function.`)}}function wc(t,e){const n=ge(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&st(`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&&Jo(e).dispose(),function(t,e){fe.set(t,e);let n=pe.get(e.parentStateElement);void 0===n&&(n=new Map,pe.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=he.get(e.component);void 0===o&&(o=new Map,he.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&me.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=Wi.get(t);if(void 0!==n){if(n===e)return;st("A state tree is already registered on this root.")}Wi.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>de(t,e,n);Xr(e);const o=we(t.component);hi(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),Gr(e,o,n)}(t,e),o=e,s=Promise.resolve(),Bi.set(o,s),s.then(()=>Ui(o),()=>{})}const vc=new Set;function $c(t,e){vc.has(t)||(vc.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Sc(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[Pe](n,()=>{o=t[e.outerPathInfo.path]})}),o}function Nc(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(yr(t.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function xc(t,e,n){const o=n[O];if(void 0!==o){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(o)){const o=e+s+a,c=function(t,n,...o){l.call(yr(e,this),t,n,...o)};n.push({path:o,pathInfo:K(o),handler:c,order:1e6+i++}),r.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(!function(t,e){let n=Va.get(t);void 0===n&&(n=new Map,Va.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),nl(t))}const r=n[R];if(void 0!==r){const n=new Map;for(const[t,o]of Object.entries(r))n.set(e+s+t,o);t.mergeVolumeListKeys?.(n)}const i=n[I];"function"==typeof i&&(!function(t,e){let n=br.get(t);void 0===n&&(n=[],br.set(t,n)),n.push(e)}(t,{mountPath:e,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}function Ic(t,e,n){!function(t,e,n){const o=n[O];if(void 0!==o){"object"==typeof o&&null!==o||st(`${O} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&st(`${O} entry "${t}" must be a function.`),Ya(t)}const r=n[R];if(void 0!==r){"object"==typeof r&&null!==r||st(`${R} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(r))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&st(`${R} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+s+n)&&st(`${R} entry "${e+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&st(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`)}(t,e,n);const{data:o,accessors:r}=function(t){const e={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(t)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(e[o]=s.value):n.set(o,s));return{data:e,accessors:n}}(n),i=K(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;st(`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],r=""===n?o in t:void 0!==t[n+s+o];n=""===n?o:n+s+o,r||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(a)return;st(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=o}),function(t,e){let n=gr.get(t);void 0===n&&(n=new Set,gr.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,o]of r){const r=e+s+n,i=o.get,a=o.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(yr(e,this))}),"function"==typeof a&&(l.set=function(t){a.call(yr(e,this),t)}),t.defineTreeAccessor(r,l)}xc(t,e,n);const l=n.$connectedCallback;return"function"==typeof l&&t.createState("writable",t=>{const n=l.call(yr(e,t));n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function Pc(t,e){let n=null;try{n=Ic(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}function kc(t,e,n,o,s){null===e?function(t,e){let n=vr.get(t);void 0===n&&(n=[],vr.set(t,n)),n.push(e)}(t,{mountPath:n,volumeState:o,onGrafted:s}):Pc(e,{mountPath:n,volumeState:o,onGrafted:s})}$r=Pc;class _c extends yi{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return qi(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new ma}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_watchPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_volumeGraftInfo=null;_volumeInitializing=!1;_mountRecord=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_dcc=!1;_connectGeneration=0;_streamsStartedGeneration=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&&st(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){this._commandTokenNames=function(t){const e=new Set,n=t[A];if(void 0===n)return e;Array.isArray(n)||st(`${A} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||st(`${A} entries must be non-empty strings.`),t===C&&st(`${A} entry "${t}" conflicts with the reserved namespace name "${C}".`),e.has(t)&&st(`${A} entry "${t}" is duplicated.`),e.add(t);return e}(t),this._eventTokenNames=function(t){const e=new Set,n=t[E];if(void 0===n)return e;Array.isArray(n)||st(`${E} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||st(`${E} entries must be non-empty strings.`),e.has(t)&&st(`${E} entry "${t}" is duplicated.`),e.add(t);return e}(t),this.__state=t,this._hasUpdatedCallback=I in t,In(this),function(t,e,n){const o=e[M];if(void 0!==o){"object"==typeof o&&null!==o||st(`${M} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||st(`${M} entry "${e}" is not declared in $eventTokens.${ft(e,n)}`),"function"!=typeof s&&st(`${M} entry "${e}" must be a function.`),xn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const n=function(t){const e=new Set,n=new Set,o=hl(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 n.getterPaths)this._getterPaths.add(t);for(const t of n.setterPaths)this._setterPaths.add(t);var o;ja(this),_a(o=this),Ia(o),Pa.delete(o),Ea(this,t),this._listKeys=function(t){const e=t[R];if(void 0===e)return null;"object"==typeof e&&null!==e||st(`${R} 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&&st(`${R} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&st(`${R} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&st(`${R} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),"function"!=typeof o?("string"!=typeof o&&st(`${R} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&st(`${R} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&st(`${R} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&st(`${R} 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),function(t){Ua.delete(t),qa.delete(t)}(this),function(t){Za.delete(t)}(this),this._watchPaths=Qa(this,t),this._initialized&&null!==this._rootNode&&!e()&&(nl(this),Ba(this),this._streamsStartedGeneration=this._connectGeneration),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(){if(!this.hasAttribute("enable-ssr"))return null;const t=this.parentNode;if(!t)return null;const e=Ni.find(t);if(!e)return null;const n=e.stateData;return Object.keys(n).length>0?n: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){st("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 ha(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||st(`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 pa(t);st(`Unsupported src file type: ${t}`)}}catch(t){st(`Failed to initialize state: ${t}`)}}async _initializeVolume(){const t=this._rootNode,e=this.getAttribute("mount");try{!function(t){0===t.length&&st('"mount" requires a non-empty tree path.');const e=K(t);for(const n of e.segments)0===n.length&&st(`"mount" path "${t}" has an empty segment.`),n===r&&st(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&st(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(e),this.hasAttribute("bind-component")&&st('"mount" cannot be combined with "bind-component".'),this.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),function(t,e){let n=pr.get(t);void 0===n&&(n=new Set,pr.set(t,n)),n.has(e)&&st(`Volume slot "${e}" is already mounted on this tree.`),n.add(e)}(t,e)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}this._volumeInitializing=!0,null===Fi(t)&&function(t,e){const n=()=>{if(null!==Fi(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)}(t,e);const n=t=>{this._volumeGraftInfo=t,this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()};let s;try{s=await this._loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${e}" failed to load.`,t),void n(null)}null!==this._rootNode?kc(t,Fi(t),e,s,n):n(null)}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}await this._loadingPromise,Ki(this.rootNode,this)}_failInitialization(t){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),st(t)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const r=this.parentNode,i=r instanceof ShadowRoot?r.host:r instanceof Element?r:null,a=i?J(i):null;null!==i&&null!==a||st(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),r instanceof ShadowRoot||i.hasAttribute(o.bindAttributeName)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${a}>, or mount it from the host (data-wcs="${this.getAttribute("bind-component")}: path").`);const l=["state","src","json"].filter(t=>this.hasAttribute(t));null!==this.querySelector('script[type="module"]')&&l.push('<script type="module">'),l.length>0&&st(`"bind-component" cannot be combined with ${l.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const c=this.getAttribute("bind-component");!function(t,e){let n=Zo.get(t);n||(n=new Set,Zo.set(t,n)),n.add(e)}(i,c);const d=Y(i);null===d&&st(`CustomElementRegistry is unavailable for <${a}>.`),await d.whenDefined(a.toLowerCase()),i.hasAttribute(o.bindAttributeName)&&await F(i),c in i||st(`Component does not have property "${c}" for state binding.`);let u=i[c];"object"==typeof u&&null!==u||st(`Component property "${c}" is not an object for state binding.`);const f=function(t,e){const n=sr.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(i,c);if(void 0!==f&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=dt(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(i,c)&&(i[c]=f,u=f),this._boundComponent=i,this._boundComponentStateProp=c,r instanceof ShadowRoot||(dt(i)??[]).some(t=>t.propSegments[0]===c)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${a}>, or mount it from the host (data-wcs="${c}: path").`),i.hasAttribute(o.bindAttributeName)){const o=(dt(i)??[]).filter(t=>t.propSegments[0]===c);if(o.length>0){const l=Fi(i.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${a}>.`);let d=(n=i,s=c,he.get(n)?.get(s)??null);const f=null!==d;if(null===d&&(function(t,e,n){const o=ir.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;ir.get(t).delete(e)}}(i,c,u),d=te(i,c,o,l,u,(t=i,e=c,rr.get(t)?.get(e))),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp,s=new Map;for(const e of t.entries)1===e.innerSegments.length&&s.set(e.innerSegments[0],e.outerPathInfo.path);let r,i=!1;for(const a of e){const e=s.get(a);if(void 0!==e){$c(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted entry "${o}.${a}: ${e}" (the host value no longer reaches it). Remove the default to read the tree, or rename it to keep it private.`);continue}if(null===t.rootEntry)continue;if(i||(r=Sc(t),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=t.rootEntry.outerPathInfo.path;$c(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted tree key "${l}.${a}" (${o}: ${l}). Remove the default to read the tree, or rename it to keep it private.`)}}(d)),this._mountRecord=d,this.parentNode!==r)return;try{wc(d,r instanceof ShadowRoot?r:i)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}if(!f){const t=_l(d);Object.defineProperty(i,c,{get:()=>t,enumerable:!0,configurable:!0}),Qo(i,c)}return bc(i,c),function(t){const e=Yt.filter(e=>void 0!==t.stateObject[e]);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Qt.has(n)||(Qt.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). See docs/state-mount-design.md §4-6.`))}(d),void Zt(d,"$connectedCallback")}}yc(this,this._boundComponent,this._boundComponentStateProp,u)}var t,e,n,s}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{N in t&&await t[Ce]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await pa(t):st(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await ha(e,t.tagName.toLowerCase()):st(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){st(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||st(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Y(t);null!==r&&"function"==typeof r.define||st(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&st(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template");i.innerHTML=e.innerHTML;const a=e.mode,{bindables:l,commands:c,streamBackedBindables:d}=gl(n),u=l.length>0||c.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,l,c):null,f=l.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,l):{},h=o.tagNames.state,p=class extends HTMLElement{static template=i;static shadowRootMode=a;static wcBindable=u;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(L))return null;this._shadow=this.attachShadow({mode:p.shadowRootMode}),this._shadow.appendChild(p.template.content.cloneNode(!0));const t=Y(this._shadow);return null!==t&&Q(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(p.bindableEventMap).length>0){const e=t.querySelector(h);e?e.setBindableEventMap(p.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${k} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(h)??null}},m=hl(n);for(const[t,e]of Object.entries(m)){if(fl(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=ul(t,o)}else n.get=cl(t),n.set=dl(t);Object.defineProperty(p.prototype,t,n)}for(const t of d)Object.defineProperty(p.prototype,t,{configurable:!0,enumerable:!0,get:cl(t),set:dl(t)});r.define(s,p)}(t,e,n),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",t=>{x in t&&t[Ee]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Fi(this._rootNode)===this._volumeGraftInfo.rootStateElement&&Nc(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const t=this._mountRecord,e=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&function(t,e){const n=Jo(e),o=we(t.component);n.forEachActiveBindingNode(t=>ve(t,o)),Kr(n.rebindAddresses())}(t,e)}),Zt(t,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||Fi(this._rootNode)===this||Ki(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 t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(L))return this.hasAttribute("bind-component")&&st(`"bind-component" cannot be used inside a [${L}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(t.host,t);if(this.hasAttribute("mount")){if(this._volumeInitializing)return;return void await this._initializeVolume()}if(await this._initializeBindWebComponent(),null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await qi(this.rootNode);const t=Ni.extractStateData(this),e=document.createElement(o.tagNames.ssr);e.setAttribute("version",gi),Ni.buildContent(e,t),this.parentNode?.insertBefore(e,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||nl(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||Ba(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Nc(this._volumeGraftInfo,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._mountRecord)return Zt(this._mountRecord,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Ki(this.rootNode,null),t=this,ga.delete(t),function(t){ba.delete(t)}(this),In(this),_a(this),ja(this),function(t){Ua.delete(t)}(this),this._rootNode=null}}var t}get initialized(){return this._initialized}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get watchPaths(){return this._watchPaths}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}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&st(`$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}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 rootNode(){return null===this._rootNode&&st("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0}get hasGraftedVolumes(){return this._hasGraftedVolumes}markHasGraftedVolumes(){this._hasGraftedVolumes=!0}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t}_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("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+r)),!this._pathSet.has(t)){const e=K(t);if(this._pathSet.add(t),Mr(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=K(t.parentPath)}}}_createState(t,e,n){try{const o=function(t,e,n){const o=new fc(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 crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){this._initialized?((this._hasGraftedVolumes||this._hasMounts)&&st("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."),this._state=t):this._resolveSetState?.(t)}}function Ac(t=customElements){t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,Ni),t.get(o.tagNames.state)||t.define(o.tagNames.state,_c)}function Cc(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}}await function(e,o){const s=Cc(e);var r;s&&((r=s).tagNames&&Object.assign(n.tagNames,r.tagNames),"string"==typeof r.bindAttributeName&&(n.bindAttributeName=r.bindAttributeName),"string"==typeof r.commentTextPrefix&&(n.commentTextPrefix=r.commentTextPrefix),"string"==typeof r.commentForPrefix&&(n.commentForPrefix=r.commentForPrefix),"string"==typeof r.commentIfPrefix&&(n.commentIfPrefix=r.commentIfPrefix),"string"==typeof r.commentElseIfPrefix&&(n.commentElseIfPrefix=r.commentElseIfPrefix),"string"==typeof r.commentElsePrefix&&(n.commentElsePrefix=r.commentElsePrefix),"string"==typeof r.locale&&(n.locale=r.locale),"boolean"==typeof r.debug&&(n.debug=r.debug),"boolean"==typeof r.enableMustache&&(n.enableMustache=r.enableMustache),"boolean"==typeof r.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=r.enableDirectionalInitialSync),"boolean"==typeof r.enablePropagationContext&&(n.enablePropagationContext=r.enablePropagationContext),"boolean"==typeof r.enableContractAnalyzer&&(n.enableContractAnalyzer=r.enableContractAnalyzer),"boolean"==typeof r.sameValueGuard&&(n.sameValueGuard=r.sameValueGuard)),Ac(o),function(){const t=globalThis;void 0===t[Ai]&&(t[Ai]=Li)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=da)}(),ca()}();
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|